text:
Q: How to handle errors using sscanf in a loop to get inputs from stdin? I am writing a code to read inputs from the keyboard (stdin) and print them. The standard inputs are like the following.
(6, 10) (6, 12) (6, 20) (6, 25) (9, 25) (10,25)

The code is as below:
void main()
{
    int key, value;

    char input[1000]; //assume the input is than 1000 bits and initiate the inputs as strings
    char *pointer;
    int offset;

    printf("enter key-value pairs of integer numbers like (a,b)(c,d): ");
    fgets(input, sizeof(input), stdin);
    pointer = input;

    //read the pairs of values one at a time until the last pair
    //                       leave space before and after value and brackets to skip spaces
    while (sscanf(pointer, " ( %d , %d ) %n", &key, &value, &offset) == 2)
    {
        printf("key is %d, value is %d", key, value);
        pointer = pointer + offset
    }
}

I also want to improve the code for error handling. For example, if the user inputs were like:
(6, 10) (6, 12) (6, ABC) (DEF, 25) (9, 25) (10,25)

I tried to add a scanResult after the while loop finishes, and clearly, it would not work as scanResult will be -1 once the last pair of values have been scanned.
void main()
{
    int key, value;

    char input[1000]; //assume the input is than 1000 bits and initiate the inputs as strings
    char *pointer;
    int offset;
    int scanResult;

    printf("enter key-value pairs of integer numbers like (a,b)(c,d): ");
    fgets(input, sizeof(input), stdin);
    pointer = input;

    //read the pairs of values one at a time until the last pair
    //                       leave space before and after value and brackets to skip spaces
    while ((scanResult = sscanf(pointer, " ( %d , %d ) %n", &key, &value, &offset)) == 2)
    {
        printf("key is %d, value is %d", key, value);
        pointer = pointer + offset
    }

    if (scanfResult != 2)
    {
        printf("invalid input");
    }
return;
}

Could someone let me how to write the code for error handling?

A: You can just do:
char *end = input + strlen(input);

and
while ( pointer < end && (2 == sscanf(pointer, " ( %d , %d ) %n", &key, &value, &offset)) )


text:
Q: R: Webscraping irregular blocks of values So I am attempting to webscrape a webpage that has irregular blocks of data that is organized in a manner easy to spot with the eye. Let's imagine we are looking at wikipedia. If I am scraping the text from articles of the following link I end up with 33 entries. If I instead grab just the headers, I end up with only 7 (see code below). This result does not surprise us as we know that some sections of articles have multiple paragraphs while others have only one or no paragraph text.
My question though is, how do I associate my headers with my texts. If there were the same number of paragraphs per header or some multiple, this would be trivial.
library(rvest)
wiki <- html("https://en.wikipedia.org/wiki/Web_scraping")

wikitext <- wiki %>%
  html_nodes('p+ ul li , p') %>%
  html_text(trim=TRUE)

wikiheading <- wiki %>%
  html_nodes('.mw-headline') %>%
  html_text(trim=TRUE)

A: This will give you a list called content whose elements are named according to the headings and contain the corresponding text.
library(rvest) # Assumes version 0.2.0.9 is installed not currently on CRAN
wiki <- html("https://en.wikipedia.org/wiki/Web_scraping")

# This node set contains the headings and text
wikicontent <- wiki %>%
  html_nodes("div[id='mw-content-text']") %>%
  xml_children()

# Locates the positions of the headings
headings <- sapply(wikicontent,xml_name)
headings <- c(grep("h2",headings),length(headings)-1)

# Loop through the headings keeping the stuff in-between them as content
content <- list()
for (i in 1:(length(headings)-1)) {
  foo <- wikicontent[headings[i]:(headings[i+1]-1)]
  foo.title <- xml_text(foo[[1]])
  foo.content <- xml_text(foo[-c(1)])
  content[[i]] <- foo.content
  names(content)[i] <- foo.title
}

The key was spotting the mw-content-text node which has all the things you want as children.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Sum input fields values after save in cakephp?
Good afternoon, first of all a cordial greetings to all forum. I have
  a problem and need help. Please would be so kind to help me with
  information, text, illustrations, to perform mathematical operations
  in cakephp, the problem is that I am still a newbie and I was a bit
  complicated all this, to get a better idea this is my view

Form view:
http://www.subirimagenes.com/imagedata.php?url=http://s2.subirimagenes.com/otros/9234902vistaprevia.jpg
Example:
form:
    3 * 7.50  = 22.50
form:
    4 * 5.50  = 22
form:
    1 * 4.90  = 4.90
form:
    2 * 12.90 = 25.8
total:          72.50

What I want to do is take the amounts written on the forms and then do
  the calculation and place in the total field

DB view
http://www.subirimagenes.com/imagedata.php?url=http://s2.subirimagenes.com/otros/9234906db.jpg
----------view/add.ctp.........
<div class="ventas form">
   <?php echo $this->Form->create('Venta'); ?>
   <fieldset>
    <legend><?php echo __('PROCESO DE COMPRA'); ?></legend>
    <?php
    echo $this->Form->input('nombre');
    echo $this->Form->input('apellido');
    echo $this->Form->input('cedula');
    echo $this->Form->input('direccion');
    echo $this->Form->input('mail');
    echo $this->Form->input('telefono');
    echo $this->Form->input('tarjeta');
    echo $this->Form->input('numtarjeta');
    echo __('<legend>SELECCIONE SU PELICULA</legend>');
    echo $this->Form->input('cartelera_id',array('label' => 'Seleccione su pelicula'));
    echo $this->Form->input('cant_adulto', array('label' => 'Cantidad de boletos - Precio normal $ 7,50'));
    echo $this->Form->input('cant_niño', array('label' => 'Cantidad de boletos - Precio niños/ancianos $ 5,50'));
    echo $this->Form->input('cant_discapacitado', array('label' => 'Cantidad de boletos - Precio discapacitados $ 4,90'));

echo __('<legend>SELECCIONE SU COMBO</legend>');
    echo $this->Form->input('combo_id');
    echo $this->Form->input('numcombo', array('label' => 'Cantidad de combos - Precio discapacitados $ 12,90'));
    echo $this->Form->input('total');
    ?>
   </fieldset>

<?php echo $this->Form->end(__('Guardar')); ?>

</div>

.......Controller.......
   class VentasController extends AppController {
/** * Components
 * * @var array
 */ public $components = array('Paginator');
/** * index method
 * * @return void
 */
    public function index() {
        $this->Venta->recursive = 0;
        $this->set('ventas', $this->Paginator->paginate());
    }/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
    public function view($id = null) {
        if (!$this->Venta->exists($id)) {
            throw new NotFoundException(__('Invalid venta'));
        }
        $options = array('conditions' => array('Venta.' . $this->Venta->primaryKey => $id));
        $this->set('venta', $this->Venta->find('first', $options));
    }
/**
 * add method *
 * @return void */
    public function add() {
        if ($this->request->is('post')) {
            $this->Venta->create();
            if ($this->Venta->save($this->request->data)) {
                $this->Session->setFlash(__('La venta se almacenó correctamente.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('La venta no se almacenó correctamente. Por favor, Intente de nuevo.'));
            }
        }
        $carteleras = $this->Venta->Cartelera->find('list',array('fields'=>'pelicula'));
        $this->set(compact('carteleras'));
        $combos = $this->Venta->Combo->find('list',array('fields'=>'nombre'));
        $this->set(compact('combos'));
    }
/** * edit method
 * * @throws NotFoundException
 * @param string $id
 * @return void
 */ public function edit($id = null) {
        if (!$this->Venta->exists($id)) {
            throw new NotFoundException(__('Invalid venta'));
        }
        if ($this->request->is(array('post', 'put'))) {
            if ($this->Venta->save($this->request->data)) {
                $this->Session->setFlash(__('La venta se almacenó correctamente.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('La venta no se almacenó correctamente. Por favor, Intente de nuevo.'));
            }
        } else {
            $options = array('conditions' => array('Venta.' . $this->Venta->primaryKey => $id));
            $this->request->data = $this->Venta->find('first', $options);
        }
        $carteleras = $this->Venta->Cartelera->find('list');
        $this->set(compact('carteleras'));
        $combos = $this->Venta->Combo->find('list');
        $this->set(compact('combos'));
    }
/**
 * delete method *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */ public function delete($id = null) {
        $this->Venta->id = $id;
        if (!$this->Venta->exists()) {
            throw new NotFoundException(__('Invalid venta'));
        }

Thank you very much for your attention

A: Use the beforeSave() callback of the model. Do your calculation there and write to the field.
Example taken from the book:
public function beforeSave($options = array()) {
    if (!empty($this->data['Event']['begindate']) &&
        !empty($this->data['Event']['enddate'])
    ) {

        $this->data['Event']['begindate'] = $this->dateFormatBeforeSave(
            $this->data['Event']['begindate']
        );
        $this->data['Event']['enddate'] = $this->dateFormatBeforeSave(
            $this->data['Event']['enddate']
        );
    }
    return true;
}

public function dateFormatBeforeSave($dateString) {
    return date('Y-m-d', strtotime($dateString));
}

A: public function vent() {
   if ($this->request->is('post')) {
       $this->Venta->create();
       $this->request->data['Venta']['total'] = ($this->request->data['Venta']
        ['cant_adulto'] * 7.5) + ($this->request->data['Venta']['cant_niño'] *
        5.5) +  ($this->request->data['Venta']['cant_discapacitado'] * 4.9)+
        ($this->request->data['Venta']['numcombo'] * 12.9) ;
   if ($this->Venta->save($this->request->data)) {

   $this->Session->setFlash(__('La venta se almacenó correctamente.'));
   $inserted_id=$this->Venta->id;
   return $this->redirect(array('action' => 'view', $inserted_id));
   } else {
   $this->Session->setFlash(__('La venta no se almacenó correctamente. Por
   favor, Intente de nuevo.'));
   }}
   $carteleras = $this->Venta->Cartelera-
                 >find('list',array('fields'=>'pelicula'));
   $this->set(compact('carteleras'));
   $combos = $this->Venta->Combo->find('list',array('fields'=>'nombre'));
   $this->set(compact('combos'));
}


text:
Q: Own controls similar to TextBox in C# Windows application Create own TextBox, Button etc control as own control using User control in C# Windows application, is this good idea?
I wanted make consistency for through out the application. Suppose if I want to change the Textbox border color then all forms textbox updated with this changes. It's just an example.
Please suggest me.

A: I don't recommend using UserControl just for consistency. If application skinning is what you are after, look into WPF. It makes it relatively simple to skin an application (or even a window, or smaller groups)
Here is an article on skinning with WPF: http://www.codeproject.com/Articles/19782/Creating-a-Skinned-User-Interface-in-WPF
Another alternative, staying within Windows Forms, is creating a class that inherits from TextBox, and using that class throughout the application. The Factory pattern would work well here. You could even adapt it to multiple skins.

A: It's not a bad idea to provide custom controls that match your "User Experience" (UX). It really just depends on what you are trying to accomplish with your program.


text:
Q: Issue with primefaces dynamic dialog I have a dynamic Dialog with a CommandButton or an OutputLabel inside, using a value that takes time to generate. To avoid loosing time when loading the page, I used the dynamic param of the dialog. Unfortunately, my function is still called and the necessary time to display the page is very long.
<p:dialog dynamic="true">
  <h:outputText value="#{myBean.myFunction()}"/>
</p:dialog>

Any idea what the issue could be?
Using PF Version 11.0.7

A: Add appendTo="@(body)" to p:dialog, that should help.
<p:dialog appendTo="@(body)" dynamic="true">
  <h:outputText value="#{myBean.myFunction()}"/>
</p:dialog>

visit: https://primefaces.github.io/primefaces/12_0_0/#/core/dialogframework


text:
Q: How to calculate $x,n$ for $x^n=400$ Basically, what I'm trying to figure out is:
If I have a directory tree, and each level of the directory tree has $x$ directories, and there are $n$ levels, then the number of directories at level $n$ is $x^n$.
So, If I want to generate a structure, that at level $n$ has 400 directories, then I need to figure out $x, n$ for $x^n = 400$
At this point, I think I'm basically trying to get $x = \sqrt[n]{400}$
Is it possible to figure this out with just these terms? I'm not super great at math, so any help would be appreciated!

A: You can do better since you know that $x$ and $n$ are integers. Since $400=4\times 10^2 = 2^4 5^2$, then $x^n=2^4 5^2$ implies that $n$ is a common divisor of $4$ and $2$. So $n=2$ or $n=1$.
If $n=1$, then $x=400$ and if $n=2$, then $x=20$ (since $x^2=2^4 5^2 \iff x=(2^4 5^2)^{1/2}=2^2 5^1=20$).


text:
Q: How to know the origins of some data loaded in a google map with java? is possible to know the location of the file who have the data loaded on this map? http://www.comune.monza.it/portale/mappe/mappa_giardini.html
Thanks for any help!

A: The Lat and Lng of the markers on this map is located within the view source.  Take a look at the Gmarker created from approximately line 741-1126.  Seems like it's all there within the page.
Furthermore, seems like they use jquery, markermanager, pano_layer, and pano map control.
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js" type="text/javascript"></script>
<script src="/system/modules/it.tecnoteca.googlemap/resources/script/pano_layer.js" type="text/javascript"></script>
<script src="/system/modules/it.tecnoteca.googlemap/resources/script/pano_maptypecontrol.js" type="text/javascript"></script>
<script src="/system/modules/it.mi.monza.comune.monza_partecipa/resources/script/jquery.js" type="text/javascript"></script>

A: All the datapoints for that are hard coded in the javascript in the html for the mappa_giardini.html file.  Search the file for
point = new GLatLng(45.55889209225004,9.266018271446228);

Look at a couple of the lines and you'll see how its set up.


text:
Q: How to pull value out of promise I have this code below: How can i pull the value out of this promise?
  var value = Auth.loggedinUser().then(function (user){
    return user.id
  });

  console.log(value)

This is my promise below:
Promise {$$state: Object}
    $$state:Object
    status:1
    value:2
__proto__:Object
__proto__:Object

I am trying to just get the value out and set it to my value variable. Which should be 2 or whatever it would return.
My goal is to set the value of the promise to a global variable if possible

A: The whole concept of a promise is that you obtain and use the value of a promise only in the .then() handler or with await.  You cannot fetch the value directly from the promise and should not be trying to because if you are, it is likely because you don't actually grasp how asynchronous code works and how promises work and how the timing of when the value will be available is unknown and thus you have to use the promise notification system to know when the value is available.
So, in your code, you need to consume the user.id inside the .then() handler or in some function that you pass it to that is called from inside the .then() handler.
Auth.currentUser().then(function (user){
    // use user.id here
    // or call some other function here and pass it the id myFunc(user.id)
});

// You do not use user.id here

The code that fetches the user object is asynchronous.  That means that it is non-blocking and that it completes some unknown time in the future.  The ONLY place you can possibly know that the user or user.id value is now valid is INSIDE the .then() handler.
Here's an analogy.  You take your car into service.  They say they have no idea when it will be ready for pickup because they don't yet know what's wrong and how long it will take them to diagnose, get parts and to fix it.  They say they will call you when its done.  So, at this point, you can't make any plans that include using your car because you literally don't know when it will be ready.  The service center has given you a "promise" that they will call you when it's ready and then (and only then) can you come in to pick it up or make plans about when you will have your car.  So, the only places you can make plans for your car are situations that come after they've called you back and told you when it would be ready.  That callback from the service center is like the promise's .then() handler.  Only in code that stems from that .then() handler can you do anything with the resolved value.
Promises are purposely opaque so you cannot look inside of them.  They've defined a standard interface for being notified of completion with .then() or error with .catch().  That's how you use promises.  Asynchronous coding in general takes some getting used to (a different paradigm than used in most other programming environments) and promises are built on top of that to give asynchronous operations a standard way of notifying, coordinating, chaining and propagating errors that also takes a bit of learning.

My goal is to set the value of the promise to a global variable if possible

This is pretty much never the correct way to use a value obtained via an asynchronous operation for several reasons.  Besides the usual reasons to avoid global variables, any code that might want to use this value simply never have any idea when it's actually a valid value.  That info is only known inside the .then() handler or after using await (or in case of errors in a .catch() handler).


text:
Q: Send post via CXF I'm building webservice based on CXF and now I'm sending variables into some URL by code:
url = new URL(urlSSO + "/user");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

connection.setRequestProperty("Content-Length","" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-EN");

connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);

// Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
    response.append(line);
    response.append('\r');
}
rd.close();

userInfo = response.toString();
if (userInfo != null) {
    //do something
} else {
    // some problem with user
    return "home";
}

But I'm wondering if there is some more easy way to do this with CXF?
I mean, maybe CXF has something built-in?
I think that this code can take a lot of time to send and get response from other servlet... This CXF webservice will be put on servicemix, so I need something very fast to send variables


text:
Q: Getting timeout exception when requesting to remote actor I am using below code for requesting and getting response from remote actor.  But sometime Iam getting right response but sometime getting timeout exception. Testing both the actor on the same machine. Don't know what I am doing wrong
final Timeout timeout = new Timeout(15, TimeUnit.SECONDS);
final Future<Object> future = Patterns.ask(remoteControllerActor, com, timeout);
final String result = (String) Await.result(future, timeout.duration());

Below Exception:
java.util.concurrent.TimeoutException: Futures timed out after [15 seconds]
at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:219)
at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:223)
at scala.concurrent.Await$$anonfun$result$1.apply(package.scala:116)
at scala.concurrent.BlockContext$DefaultBlockContext$.blockOn(BlockContext.scala:53)
at scala.concurrent.Await$.result(package.scala:116)
at scala.concurrent.Await.result(package.scala)

A: I got the solution about it. Actually from remoteControllerActor I was making another async request to another remote actor, and in that remote actor, I was running linux command to get disk details, but was not able to parse output properly. That's why I was getting the timeout exception.


text:
Q: React: cannot read document.body.style.marginRight I am having trouble reading the margin-right css property of the body. It seems to fail on initial render, but a few times it seemed to work when I was manually setting the margin-right. I expect it has something to do when when the component is rendering. Tried in useEffect and useLayoutEffect without success.
Pertinent CSS:
body {
    margin-right: 10px;
}

Simple create-react-app:
function App() {
  const [marginRight, setmarginRight] = useState(
    document.body.style.marginRight
  );

  return (

BODY Right margin is: {marginRight}

  );
}

A: HTMLelement.style only returns inline styles. To access style from your css file, you should use:
window.getComputedStyle(document.body).marginRight


text:
Q: C++ Access violation calling function from dll I am developing an application that will access smart cards using the standard PKCS#11. At this moment the application is working very well both on Ubuntu and OS X. Now I am porting it to Windows, but I am getting an "access violation" exception whenever I call functions from the pkcs#11 library, which is linked at runtime.
Below I tried to reproduce a SSCCE of my code (The place where the exception is happening is identified with a comment).
void * libraryHandle = NULL;
CK_RV   rv;
CK_C_GetFunctionList pC_GetFunctionList;
CK_FUNCTION_LIST_PTR functions;

libraryHandle = LoadLibrary(L"C:\\WINDOWS\\system32\\pteidpkcs11.dll");
if (libraryHandle == NULL)
{
    printf("Library not loaded\n");
    exit(1);
}

pC_GetFunctionList = (CK_C_GetFunctionList) GetProcAddress((HMODULE)libraryHandle, "C_GetFunctionList");

if (pC_GetFunctionList == NULL)
{
    printf("Function not loaded\n");
    FreeLibrary((HMODULE)libraryHandle);
    exit(1);
}

rv = (*pC_GetFunctionList) (&functions);
assert(rv == CKR_OK);
printf("Point A\n");

if(functions == NULL)
{
    printf("Functions not loaded\n");
    FreeLibrary((HMODULE)libraryHandle);
    exit(1);
}

printf("%u - %u\n",functions->version.major, functions->version.minor); // Prints without problems
rv = (*functions->C_Initialize) (NULL_PTR); //THIS IS THE PLACE WHERE I AM GETTING THE ACCESS VIOLATION
assert(rv == CKR_OK);

//printf("Point B\n");

FreeLibrary((HMODULE)libraryHandle);

When I debug the application the structure "CK_FUNCTION_LIST_PTR functions" seems to be valid.
Does anyone know what is causing this exception?
I am using Visual Studio 2010 Ultimate and Windows XP SP3.
Thanks!
(PS: I have already tried to load the function "C_Initialize" using "GetProcAddress" from the library, and it worked)
--- Edit
CK_FUNCTION_LIST definition
struct CK_FUNCTION_LIST {

  CK_VERSION    version;  /* Cryptoki version */

/* Pile all the function pointers into the CK_FUNCTION_LIST. */
/* pkcs11f.h has all the information about the Cryptoki
 * function prototypes. */
#include "pkcs11f.h"

};

Full headers in:
  http://www.rsa.com/rsalabs/node.asp?id=2133

A: From that image, it looks like you either have some sort of disagreement on the layout of your CK_FUNCTION_LIST_PTR structure between the executable and the DLL.  Make sure the executable and DLL are both compiled with the same compiler settings etc.
What is the definition (including any surrounding pragmas/macros) of CK_FUNCTION_LIST_PTR?  Is sizeof(CK_FUNCTION_LIST_PTR) the same if you print out its value from both your executable and from inside the DLL (in, say, C_GetFunctionList())?


text:
Q: Best way to analyze ~500K keys in Redis? I have a database system which processes read operations against logical objects that are identified by OIDs (object identifiers). Example is 1.2.4.3.544. There are users identified by GUIDs. API gets results from DB and puts them into Redis. Key example is
SomePrefix_<oid>1.2.4.3.544</oid>_somedetails_<user>1f0c6cfe-ee9d-472c-b320-190df55f9527</user>

There are about a couple of hundreds unique OIDs in the system and about a hundred registered users. Also keys could not have user part for anonymous requests. Number of keys could vary from 80K to.. I suppose 500k.
I need to provide per-OID and per-user statistics to the UI and implement the possibility to delete-per-OID (the same for user). So the task is splitted into two. First version I had implemented was unsuccessful - I used .Keys("*") method in c# app which turns into Redis SCAN * to get all keys to the app to run through them, collect and distinct OIDs/users and show them on the UI. This operation was taking too much time to extract all keys to the app so I switched to another approach - on every save/delete key I incremented/decremented counters stored in Redis in another DB. Counters are simply integers with keys. This was almost okay but I got a requirement to set TTL for every cached request, so I faced with a dilemma how to store/track my statistics to keep it up-to-date with actually stored keys. Options I think
A) run LUA script to scan all keys and get all unique OIDS and unique users with counts, and return them to app. For deletion option - run SCAN inside LUA script and DEL all keys matched with pattern. Pros - no need for separate stats tracking. Cons - need to scan for all keys on every call. I have Zabbix dashboard to show statistics requested through my app and it could be painful to scan keys on every N seconds. These are cons.
B) In separate Redis DB store keys with sets where key is OID (or for users - key is GUID) and inside set store keys to cached requests. But how I could delete them when keys to cached requests are expired? Can I somehow link a value stored in a set with a key from another DB and make this value disappear from a set when key expires?


text:
Q: ASP.Net Core MVC - Ajax form submission with ModelState validation on few ViewModel properties THE PROBLEM
I have a client view model with some required properties and non-required properties. The view contains different sections for updating different view model properties. If i am updating a part of the view with required client details such as FirstName, LastName, DOB, etc then i can wrap the input types into an ajax form and the controller will pick up these properties from the view model and validate accordingly using ModelState.IsValid and validation will be successful. However if I have another section on the same view that needs to update a non required property on the viewmodel (ie Notes) and pass this through from an ajax form post then ModelState validation fails because the other required properties are null as they were never submitted as part of the ajax form. Note that the required fields should always have data populated prior to loading the client details page and therefore should never be null.
THE CODE
ViewModel
public class ClientDetailViewModel
{

    public int ID { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 2)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 2)]
    public string LastName { get; set; }

    [Required]
    [Display(Name = "Date of Birth")]
    [DataType(DataType.Date)]
    public DateTime DOB { get; set; }

    [Required]
    public string Gender { get; set; }

    public string Notes { get; set; }
}

View
@model MSIC.Models.ClientViewModels.ClientDetailViewModel
@inject MSIC.Services.Custom.IGenderService GenderService;

    <form asp-controller="Client" asp-action="Edit" class="form-horizontal">

                <input asp-for="FirstName" class="form-control" />

                <input asp-for="LastName" class="form-control" />

                <input asp-for="DOB" class="form-control" />

                <select asp-for="Gender" asp-items="@(new SelectList(GenderService.GetAll(),"Code","Name"))" class="form-control">
                </select>

    </form>

@Model.Notes

Edit Notes
<form asp-controller="Client" asp-action="EditNotes" class="form-horizontal" data-ajax="true" data-ajax-method="POST" data-ajax-update="#divNotes" data-ajax-mode="replace" data-ajax-success="CloseModal('#notesModal')" data-ajax-failure="AjaxOnFailure(xhr, status, error)">

                    <button type="button" class="close" data-dismiss="modal">×Close</button>

edit Reason

                    <input type="hidden" asp-for="ID" />

                            <textarea asp-for="Notes" class="form-control" autofocus></textarea>

                    <button type="submit" class="btn btn-primary">Save</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

</form>

Controller
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult EditNotes(ClientDetailViewModel model)
{
    //validation fails because required fields in model are null since they were not submitted with this ajax form
    if (ModelState.IsValid)
    {
        //update database with client notes and return notes to screen
        return Content(model.Notes);
    }

    return Content("i haven't coded this yet");
}

THE QUESTIONS

*

*How can I perform ModelState validation inside the controller for only some fields in an efficient way without duplicating code? I searched this issue and am aware of options like ModelState[].Errors.Clear(); but since this will be a big view with many different sections available for update I would like to avoid duplicating those statements in different Action methods for all the small ajax posts I will need to perform. Basically I would like to use ModelState validation so i can just store my validation logic inside the ViewModel and not separate and/or duplicate any validation logic inside the controller too.

*The other option I can see would be to include all the required properties as hidden input types in each ajax form i have but this seems horribly unecessary and would surely be a nightmare to maintain. Is there a better way to pass all ViewModel properties for an ajax post and if so would it be expensive to send ViewModel properties that are not used other than for taking advantage of the ModelState.IsValid check?

*I am new to asp.net and have started with asp.net core mvc (which i'm enjoying a lot) and have been learning via all the tutorials, SO questions, etc. However is it possible that I am approaching this the wrong way and if so what would be the right way to tackle this issue using asp.net core and Microsoft.jQuery.Unobtrusive.Ajax or some other ajax tool? Note that I have only posted this question because none of the other similar issues posted seem to deal with sharing ViewModel properties on a View but only submitting some of the properties but taking advantage of out-of-the-box validation.
Thanks in advance.

A: Although I could not get the recommended approach to behave as suggested I did use the advice given about separating out the view models for rendering and submitting. I think I was led astray by the Movie tutorial on the Microsoft ASP.NET Core site which uses the same Movie model for both the detail and edit pages.
To resolve my issue going forward I have adopted a large view model for the detail page and I will use View Components for the various parts of my page that need updating. This allows me to have a separate View Model for each View Component and my controller post action can accept just the View Model that relates to the corresponding View Component so it can perform only the necessary ModelState validation.
This server side validation from a jQuery ajax post has led me to the next problem about returning the ModelState errors to the client for display but I have submitted a new question for that...
Returning BadRequest in ASP.Net Core MVC to Microsoft jQuery Unobtrusive Ajax post has ModelState undefined

A: It's not expensive to send everything back for all calls (by using hidden fields), but it's hacky and not a direct solution.
The view models in MVC don't have to be the same class for rendering the page and submitting forms. In your case you could define a viewmodel for rendering like this:
public class ClientDetailViewModel {
    public ClientBasicViewModel Basics {get;set;}
    public ClientNotesViewModel Notes {get;set;}
}

Then put the fields (name, gender, etc) in each of the two new classes. Use two separate controller methods to handle form submissions. Tracing how FirstName gets sent and received:

*

*When rendering, you would use Model.Basics.FirstName to show the existing value.

*For the field name in the form, make it input name="FirstName"...

*When submitting the form back, the controller method accepts an argument of type ClientBasicViewModel.


text:
Q: Arduino Function Execution Time I have an Arduino and an APC220 wireless transceiver. I'm writing a library that reads in data from the APC using the SoftwareSerial class. I originally started with the (incorrect) code below that was causing a seg fault because the i variable is incremented even when there is no data available to read. In cases where it happened to work (by chance when the data was immediately available), this function took approximately 6 milliseconds to execute. When I put the i++; statement in its proper place (above the closing brace immediately above it), the function takes over 270 ms to run. Speed is crucial for this function, so I'm wondering what it is about that statement's placement that causes such a dramatic increase in time.
For the code below, buff is declared as char buff[10]; and sSerial is an instance of SoftwareSerial
unsigned long updateLocation(Marker* marker) {
    this->sSerial->print('~');
    //initiate request from vision system
    this->sSerial->flush();
    this->sSerial->print('#');
    this->sSerial->print(marker->num);
    this->sSerial->print('*');
    this->sSerial->flush();
    unsigned long start = millis();
    int state = 0, i = 0;
    while((millis() - start) < 600) {
        if(this->sSerial->available()) {
            buff[i] = this->sSerial->read();
            if(buff[i] == ',') {
                buff[i] = 0;
                switch(state) {
                    case 0:
                        i = -1;
                        state++;
                        break;
                    case 1:
                        marker->x = atof(buff);
                        i = -1;
                        state++;
                        break;
                    case 2:
                        marker->y = atof(buff);
                        i = -1;
                        state++;
                        break;
                    case 3:
                        marker->theta = atof(buff);
                        i = -1;
                        return (millis() - start);
                        break;
                    default:
                        return 0;
                        break;
                }
            }
            // Correct location for i++; takes 270 ms to execute
        }
        // Incorrect location for i++; Takes 6 ms to execute
        i++;
    }
    this->sSerial->print('~');
    this->sSerial->flush();
    return 0;
}

A: Assuming that there's data ready and waiting from sSerial, there's no effective difference in the placement of i++.
You said yourself, in most cases the data isn't ready.  With the incorrect placement of i++, i quickly grows to greater than the size of buff which causes the segfault.
With the correct placement, your code blocks for up to 600ms waiting for enough data to come in to reach case 3 and return.  On average, you're seeing that it takes 270ms for that to happen.
You can test this theory yourself by timing the same function operating directly on a string rather than reading in from serial.
You may want to a) increase your baud rate b) check to see if there's a more efficient software serial implementation you can use c) switch to hardware serial.  If you are only using hardware serial currently for debugging output, you can switch that around. Use an FTDI adapter ($6-10 on eBay) to pipe software serial to USB and reserve the hardware serial for your time sensitive function.
You might also be able to reconfigure your code so it doesn't block the whole time waiting.  You can read in what's available, store it in a global and go back to your main loop to do something else until there's data available again.
edit: I see now that the APC220 is 9600 baud max.  That's pretty slow, so the bottle neck may not be software serial (but you should test it).  If the bottle neck is simply the baud rate, you will need to look at optimizing your code not to block waiting for input if there are other things your system can work on while it's waiting.


text:
Q: Horizontal bar charts with min and max data in pgfplots I am trying to create a horizontal bar chart like the one in the picture below. For that I want to use data stored in a table like this:
\pgfplotstableread[col sep=comma]{
system,   Tmin, Tmax, limitmin, limitmax
{a},      20,     50,     10,      30
{b},     10,     60,     15,      60
{c},      15,     78,     0,       0

}\datatable

The closest I came to a result was by manually typing in the coordinates. But the stacked bar chart keeps adding/ subtracting the values and I cant figure out how to let a bar start from a value different to zero.
\begin{tikzpicture}
\begin{axis}[
xbar stacked,
stack negative=on previous ,
xlabel={Temperature $^{\circ}C$},
symbolic y coords={%
    {A},
    {B},
    {C}},
ytick=data,
%nodes near coords,
%nodes near coords align={horizontal},
ytick=data,
xmajorgrids,
legend
]

\addplot+[blue, fill=blue, bar shift =-5pt] coordinates {
    (14,{A})
    (5,{B})
    (14,{C})
};
\addplot+[blue, fill=blue, bar shift =-5pt] coordinates {
    (-20,{A})
    (-10,{B})
    (14,{C})
};
\addplot+[red, fill=red, bar shift =5pt] coordinates {
    (20,{A})
    (5,{B})
    (14,{C})
};

\addplot+[red, fill=red, bar shift =5pt] coordinates {
    (-20,{A})
    (-10,{B})
    (14,{C})
};

\end{axis}
\end{tikzpicture}

There is probably a proper way to do this but I am still new to tikz and pgfplots and could not find a good example.
Thanks for your help!


text:
Q: How to center-align 2 objects in Tinkercad without moving one of them? How can I align one object to the center of another - without moving that second one?
When I select 2 objects in any order and then align them via the center button, it moves BOTH objects.
I want however to move only one of them. Locking the reference object does not help though.

A: So I found this out finally:
You select 2 objects, click on the "align" button and then on the object that you want to align TO. Then align and the object you selected will not move.


text:
Q: "Public APIs are forever: Only one chance to get it right"? In an OS book I just read that, "Public APIs are forever: Only one chance to get it right". Is it true? Is it applicable only in APIs of Operating Systems or other APIs too? For example, will this be true for the APIs of Android Applications such as Tasker, Locale and Pushover?

A: It is generally true for any public API, yes.  Once you expose an API to the public and people start to build applications that depend on that API, it becomes extremely difficult to change the API because doing so will break all those applications.  That tends to be both a difficult technical problem and a difficult political problem.
Of course, it is possible to change a public API.  It does happen, for example, that projects will depricate an API in one release, introduce a new API, and then remove the old API in some future release.  But that assumes that every (important) application that uses the old API will be rewritten to use the new API before the old API is removed.  That often takes multiple years.  And that means that the owner of the public API is imposing a cost on every other project that consumes the API.  Since there are generally far more consumers of an API, those consumers tend to be a relatively powerful political lobby.

A: APIs always change, otherwise what would be the point of system upgrade? Changing internals only?
Each version of system brings new APIs, old APIs become obsolete and obsolete APIs disappear.
API change only has to be very careful both technically and in terms of communication.

A: My opinion would be that once released, that 'version' of the API is forever, but you can deprecate it by releasing a '2.0' API (there are several examples where this is happening - currently, I can think of Strava who have released a 2.0 version of an API for development against to consume their services).
The problem is supporting that original API ad infinitum... I guess it depends on the usage of the old API, and what the value of those API consumers hold to you.
Going back to 'the old days' of say Windows 3.x and 9x etc., once release, those OS APIs were done and set.  Now, OS updates are pushed all the time, so new APIs can be released, but I think so long as you are running a particular OS flavor (major release), those APIs would only be added to, never removed... may not be the case for the 'next' major release though.
Hmm, maybe I strayed from the original question intent.

A: Quote author is Joshua Bloch, the statement is from his Bumper-Sticker API Design article:

Public APIs, like diamonds, are forever. You have one chance to get it right so give it your best.

For more details on that, author refers readers to his conference session presentation, "How to Design a Good API and Why it Matters". Slide Why is API Design Important to You states it pretty clearly that this is relevant to any programming activity (operating systems or not, doesn't matter to author):

*

*If you program, you are an API designer

*

*Good code is modular - each module has an API

*Useful modules tend to get reused

*

*Once module has users, can't change API at will

*Good reusable modules are corporate assets

*Thinking in terms of APIs improves code quality

Slide Conclusion also stresses this as a general approach:

*

*API design is a noble and rewarding craft

*

*Improves the lot of programmers, end-users, companies...

A: It depends on what kind of API it is (and I am assuming breaking changes, otherwise the statement is obviously not true).
If the caller can choose what version they're using (e.g. with libraries/frameworks that are bundled with the calling application), then changing the API is not a huge problem - but still bad for the reputation of the software. People like to to upgrade seamlessly.
On the other hand, when people cannot keep using the old version of the API (such as with an online service, or things like a browser or OS where running old versions is very undesirable), then changing APIs in an incompatible way is very bad indeed, since it will break all software that uses it and is not updated as well. This imposes a maintenance cost on developers, and they'll hate you for it. And software that isn't maintained and breaks will reflect badly on you as well.
On the gripping hand, there is at least one API provider who constantly introduces breaking changes in the API and is ridiculously successful anyway: Facebook. But they do manage the changes very carefully: there is a published policy, breaking changes are announced and explained at least 90 days beforehand, and developers can choose to activate them early within that timeframe.

A: If you have the foresight to include a version number in the API itself. Either on the connection/initialisation call, or, somewhere near the beginning of the parameter list on each call, then your API can evolve and mutate over time without disrupting existing clients.

A: Although all what we do is to make 'em best at one go, but since time change and improvement comes, sometimes we need to update the information, as many of giant providors have been doing, (like face book several update, twitter one major turning to oAuth and several major, but at most possible all comes with improvement so no frequent changes. And Yes please don't stop supporting older one, It hurts!! :)

A: Anytime that you release any sort of communications protocol, which would obviously include an API, you have one chance to get it right in the sense that the protocol/interface must be backwards-compatible and extensible.
This allows you to add new functionality and release new versions without having to worry about breaking people who are using older versions.  Never in the software world are you going to have a situation where you can just have a hard cutover at a certain point in time, and everyone drops the old version and starts using the new version.


text:
Q: Ansible/Git code deployment, how do I get just code? (SOLVED) Everything I'm doing with my ansible deployment is functional up to the point where I fetch the Git bare repo to the remote server - this works but then I'm stuck.
I know you can use a post-receive hook to issue a command that copies the site code to the right place on the server, because I've done it before, but that wasn't automated with ansible.
git --work-tree={{ target_dir }} --git-dir={{ git_bare_dir }} checkout -f

The problem is that creating the bare repo using ansible means there's no hook so the raw code doesn't get copied.
Which means the site-specific composer stuff can't run because it's not in place.
I have tried adding an ansible task after the git clone:
    - name: Checkout the source code from the bare repo.
      command:
        cmd: "git --work-tree={{ target_path }} --git-dir={{ git_bare_dir }} checkout -f"
        chdir: "{{ git_bare_dir }}"

But it doesn't work - there's an error message that says it's not a git repo. I've tried different ways of doing this. Running it from the command line (in the right directory) on the server gives the same error.
If it's relevant (probably not) I'm deploying to a Digital Ocean droplet.
SOLUTION: (I'm adding the solution here because I can't "self-answer" yet.)
I'm not sure this is the best option but I used this:
    - name: Copy a bare repo from Git to the remote server.
      git:
        repo: "{{ git_repo_url }}" # Use ssh: url, so we're not asked for name/password
        version: "{{ git_repo_version }}"
        dest: "{{ target_path }}"
        separate_git_dir: "{{ git_bare_dir }}"
        force: yes
        single_branch: yes
        depth: 1
        accept_hostkey: yes
        key_file: "{{ github_deploy_key }}"

Although the ansible names are the same, it's not a bare repo. The code gets copied to dest while the report itself is at git_bare_repo (which is way outside the accessible part of the server).

A:
The problem is that creating the bare repo using ansible means there's no hook so the raw code doesn't get copied.

An alternative approach is to:

*

*automate the creation of the bare repository

*copy (builtin copy module) a hooks folder from your local Ansible server to the target bare repo folder, which would include the relevant hooks pre-populated.


text:
Q: Does creating one system restore points everyday damage my hard disk? I have a habit of creating a one system restore points every day. Will it cause any damage to my hard disk?
System restore points referring to C Drive only, not all drives.

A: There is no harm in creating system restore points.
System restore points are extremely beneficial.  They allow you to roll back to the time they were created, in case a system upgrade goes wrong, you are infected with a virus, or fix other negative affects that might make your system unresponsive.
There is one case where some people may say creating lots system restore points in a negative:  Solid state disks (SSD).  Solid state disks do have limited write cycles and will eventually wear out.  However, modern SSDs have extremely long lifespans and an "everyday user" will more than likely replace the drive long before the drive starts failing.

A: No, it won't damage your drive, unless you reach the storage limit. If you decide to overwrite data, although you shouldn't, then you would lose data.


text:
Q: Can't install MyPaint on 18.10 from usual repository (not flatpak or snap) After I installed 18.10 (when it was beta) and started to install all software I got this problem with MyPaint. Today this problem still persists. Universe repository is enabled. I was able to install it from flatpak thought.
sudo apt -f install doesn't see any problems.
When I'm trying to install MyPaint:
$ sudo apt install mypaint
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 mypaint : Depends: mypaint-data (>= 1.2.0-4.1) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

$ apt-cache policy mypaint mypaint-data
mypaint:
  Installed: (none)
  Candidate: 1.2.0-4.1
  Version table:
     1.2.0-4.1 500
        500 http://archive.ubuntu.com/ubuntu cosmic/universe amd64 Packages
mypaint-data:
  Installed: (none)
  Candidate: 1.2.0-4.1
  Version table:
     1.2.0-4.1 500
        500 http://archive.ubuntu.com/ubuntu cosmic/universe amd64 Packages
        500 http://archive.ubuntu.com/ubuntu cosmic/universe i386 Packages

A: sudo apt install mypaint-data

This command line resolves the problem but it removes Gimp (and installing Gimp after MyPaint will remove MyPaint).

A: I have the same problem on Ubuntu 18.04 and before on Fedora 26 and I didn't find any solution except swipe to another simple painting program like "Kolourpaint" you can install it from Ubuntu software (Gnome software center) or by executing the following command:
sudo apt install kolourpaint


text:
Q: Nginx as reverse proxy for Spring WebFlux changes streaming behavior I have developed a Spring Boot application that have RequestController's which returns a list Flux of objects.
Using the web application directly it works perfect. I get each object as my application have them ready.
But when I am running the application behind a reverse proxy using nginx I see a different behavior. Now I am not getting the result until the whole flux stream is ready.
So before I would get the first object in a second and the last after 20 seconds have passed. Now I get all objects after 20 seconds.
Controller:
@GetMapping(path = "/flux", produces = MediaType.APPLICATION_NDJSON_VALUE)
public Flux<Message> flux() {
    return messageService.getFluxStream();
}

Nginx setup:
server {
listen 80;
listen [::]:80;
server_name domain.tk www.domain.tk;
return 302 https://$server_name$request_uri;
}

server {
# SSL configuration

listen 443 ssl http2;
listen [::]:443 ssl http2;
ssl_certificate         /etc/ssl/cert.pem;
ssl_certificate_key     /etc/ssl/key.pem;

server_name domain.tk www.domain.tk;

location / {
    proxy_pass                    http://localhost:8082;
    proxy_pass_request_headers    on;
    #proxy_set_header    Host                $http_host;
    #proxy_set_header    X-Real-IP           $remote_addr;
    #proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
    #proxy_set_header    X-Forwarded-Proto   $scheme;
}
}

My DNS is cloudflare and I have a certificate from them and is proxying traffic cloudflare.
In the nginx log I won't get see the request being logged before all the objects is ready after the 20 seconds as well. Which makes me think it's not a cloudflare proxy issue, but likely more a nginx setup issue.
Any help is appreciated.

A: It ended up being a buffering issue. Adding proxy_buffering off; to the location block in nginx configuration solved it.


text:
Q: Matplotlib + Seaborn savefig text turns into boxes I have used seaborn to produce a violin plot. When I try to save the figure using matplotlib, I get something like this:

Why is it that I get a bunch of boxes rather than the actual text for the x- and y-axes?
My code is below:
for i, column in enumerate(data.columns[6:]):
    groups = list(np.unique(data['Group'].values))
    days = list(np.unique(data['Day sacrificed'].values))

    groups_days = list(product(groups, days))
    colors = ['r', 'g', 'b', 'y']
    shapes = ['>', '<', 'o', '^']
    fig = plt.figure(i)

    pos = []
    d = []
    for (group, day), df in data.groupby(['Group', 'Day sacrificed']):
        pos.append(groups_days.index((group, day)))
        if len(set(df[column].values)) == 1:

            d.append([df[column].values[0]])
        else:
            d.append(df[column].values)
    seaborn.violinplot(d, pos)
    colnames = [u'{0} {1}'.format(i,j) for i, j in groups_days]
    plt.xlim(-1, len(colnames))
    plt.xticks(range(len(colnames)), colnames, rotation='vertical')
    plt.xlabel('Grouping')
    plt.title(u'{0}'.format(column))
    plt.ylabel(u'{0}'.format(column))
    fig = plt.gcf()
    plt.savefig('{0}.pdf'.format(column.replace('/', '_')), bbox_inches='tight')


text:
Q: how to get nested value from json array using golang from mongodb I am having the below json
I want to extract the value of particular Data from Requirement array based on Id.
If "Data" = "String123" it should display the "Data" as ["WED"].
I tried this code
but I am getting all values irrespective of Id.

A: The result of a query is a collection of documents. If you store the collection of components in one document, even though you use fields of components in the query, the result will still return the whole document if it matches the filters.
MongoDB supports selecting properties which you want or don't want, but you can't exclude array elements based on their properties.
Note that MongoDB supports returning only a part of an array ($slice (projection)) but that is index based and is not really what you want.
You have to manually go through the components of your returned documents (Eligibility) and search for the component you want. Or looking at the content of your document, you should split it to store each component as a separate document and then you can filter them and retrieve them individually.

A: If I get you right you have one record in "clOfferMaster" collection and you're trying to fetch data from nested collection "Eligibility". That's probably not a typical way to work with data.
What if you restructure your data as follows:
[
    {
        "ComponentId" : "SessionDayCheck",
        "ConfigData" : [
            "WED"
        ]
    },
    {
        "ComponentId" : "TransDayCheck",
        "ConfigData" : [
            "WED",
            "THU"
        ]
    },
    {
        "ComponentId" : "SessionTransCheck",
        "ConfigData" : ""
    }
]

It that case you can do the following query
c := session.DB("offerengine2").C("clOfferMaster")

var result struct {
    ConfigData []string "ConfigData"
}
err = c.Find(bson.M{"ComponentId": "SessionDayCheck"}).One(&result)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Result:", result)
// Result: {[WED]}


text:
Q: Conflict jquery and contentFlow I'm trying to place ContentFlow (http://www.jacksasylum.eu/ContentFlow/) plug-in in a template on google blogger, but I think I have a problem of conflict with jquery.
Basically if I disable jquery it works perfectly but if active jquery, images do not load.
it appreciate some help, thanks.

A: Welcome to StackOverflow! Please go through posting rules and guidelines. Also instead of answering your question with additional information you can edit the original question.
First off, look into using developer tools for debugging issues like this. You can see what JavaScript error caused your issue, jump to it's code and read the comments in the vicinity and/or google out the root cause.
In my opinion you should search for something fresher than ContentFlow. The issue you're having is due to ContentFlow expecting Prototype.js to be bound to $.
Prototype.js is a jQuery-like library that was popular when jQuery was in it's infancy. Using a plugin that expects it (without stating it in any docs) seems unreasonable. Also there's a lot of bloat from IE6-specific fixes.
If you're determined to use it, then jQuery in .noConflict mode should probably work but I would expect complications down the road.
Alternatively look at these coverflow jQuery plugins or any of the numerous sliders avilable.


text:
Q: Zpanel on Ubuntu Server 14.04 I am installing zPanel with 'wget https://raw.githubusercontent.com/zpanel/installers/master/install/beta/Ubuntu-14_04-LTS/ubuntu-14.04-LTS-apache2.4.9-php5.5.14.sh " I'm stuck at "enter your MySQL root password" I installed the same zpanel on the same server like six months ago and everything was fine I installed it successfully, but I do not know what's going on now ... I do not get this message before
IMAGE
What should I do?
THANKS!


text:
Q: Does production date affect compability or lifetime of a drive? Yesterday we received some new drives for our in-house fileserver. We ordered 6 12TB HC520 from a supplier and they sent us four which are labeled 4 MAR 2020 and two labeled 18 AUG 2018.
They are meant to be used in a single volume, operating underneath ZFS in a 4:2 configuration (two drives failure protection).
Will the different dates have an affect on the performance or aging of the disks, are the older disks more prone to failure?

A: Actually it's a good thing that you have mixed batches.
HDD manufacturers sometimes have faulty batches. Disks from a bad batch tend to fail around the same time. That's no good because your RAID redundancy works on the assumption that disks die randomly.
Some people intentionally buy different disk models or try to mix disks from different batches to avoid this issue. And you've received mixed batches without asking for them.
I wouldn't worry too much about these two. You can run a little stress test to make sure they're good, for example fill them up with zeros.

A: If the drives were stored at a cold, dry place not exposed to sunlight or other radiation, their age should not make you worry.
However, some manufacturers update hard- and firmware between different batches and without notice. This can lead to unexpected behavior. E.g. Western Digital recently implemented SMR, which makes the new batches less suitable for certain use cases.
That is the reason why I prefer disks from the same batch, but as the other answer suggests, there are also reasons to mix different batches.
However, at least you want to make sure all disks run the newest firmware.


text:
Q: How to complement missing dates after groupby for each group in pandas? My goal is to complement the missing date entries per project_id with 0 in the data row.
For example
df = pd.DataFrame({
    'project_id': ['A', 'A', 'A', 'B', 'B'],
    'timestamp': ['2018-01-01', '2018-03-01', '2018-04-01', '2018-03-01', '2018-06-01'],
    'data': [100, 28, 45, 64, 55]})

which is
  project_id   timestamp  data
0          A  2018-01-01   100
1          A  2018-03-01    28
2          A  2018-04-01    45
3          B  2018-03-01    64
4          B  2018-06-01    55

shall become
  project_id   timestamp  data
0          A  2018-01-01   100
1          A  2018-02-01     0
2          A  2018-03-01    28
3          A  2018-04-01    45
4          B  2018-03-01    64
5          B  2018-04-01     0
6          B  2018-05-01     0
7          B  2018-06-01    55

where indices 1, 5, and 6 are added.
My current approach :
df.groupby('project_id').apply(lambda x: x[['timestamp', 'data']].set_index('timestamp').asfreq('M', how='start', fill_value=0))

is obviously wrong, because it sets everything to 0 and resampled not the first date of a month but the last one - although I thought this should be handled by how.
How do I expand/complement missing datetime entries after groupby to get a continuous time series for each group?

A: You are close:
df.timestamp = pd.to_datetime(df.timestamp)

# notice 'MS'
new_df = df.groupby('project_id').apply(lambda x: x[['timestamp', 'data']]
                                                    .set_index('timestamp').asfreq('MS'))

new_df.data = df.set_index(['project_id', 'timestamp']).data
df = new_df.fillna(0).reset_index()

A: You can use groupby in combination with pandas.Grouper:
df_new = pd.concat([
    d for n, d in df.set_index('timestamp').groupby(pd.Grouper(freq='MS'))
])

df_new = df_new.sort_values('project_id').reset_index()

Output
print(df_new)
   timestamp project_id   data
0 2018-01-01          A  100.0
1 2018-02-01          A    0.0
2 2018-03-01          A   28.0
3 2018-04-01          A   45.0
4 2018-03-01          B   64.0
5 2018-04-01          B    0.0
6 2018-05-01          B    0.0
7 2018-06-01          B   55.0


text:
Q: How can I combine these columns in SQL Server Management Studio (SSMS) I am using SMSS v17.3
added- select @@version shows "Microsoft SQL Server 2014 - 12.0.2269.0 (X64)   Jun 10 2015 03:35:45   Copyright (c) Microsoft Corporation  Enterprise Edition (64-bit) on Windows NT 6.1  (Build 7601: Service Pack 1) "
I have
-- Book = book name.
-- Ch=chapter V=verse

CREATE TABLE dbo.flow1(Id int, A varchar(10), B varchar(10), Book varchar(10), Ch INT, V INT)

INSERT INTO dbo.flow1 VALUES(1, 'qwe', 'asd', 'gggg', 3, 44)
INSERT INTO dbo.flow1 VALUES(2, 'qwe', 'asd', 'asdf', 43, 11)
INSERT INTO dbo.flow1 VALUES(3, 'erw', 'asd', 'fsef', 12, 53)
INSERT INTO dbo.flow1 VALUES(4, 'erw', 'zre', 'vxde', 53, 12)
INSERT INTO dbo.flow1 VALUES(5, 'vwe', 'hwa', 'vwhe', 11, 51)
INSERT INTO dbo.flow1 VALUES(6, 'rwq', 'yha', 'bgda', 63, 12)
INSERT INTO dbo.flow1 VALUES(7, 'qwe', 'asd', 'faaa', 32, 61)
INSERT INTO dbo.flow1 VALUES(8, 'rwq', 'yha', 'fsag', 35, 3)

SELECT A,B,COUNT(Id) as cnt  FROM dbo.flow1 GROUP BY A,B;

What I would like is

A while back I tried fiddling around with CONCAT to do it, I would include what I tried here but I can't find it, anyhow I never quite managed it at the time.

A: select
    A,
    B,
    Cnt = count(Id),
    Concatted =
    stuff
        (
            (
                select concat(',', Book, ' ', Ch, ':', V)
                from Flow1 i
                where o.A = i.A
                    and o.B= i.B
                for xml path(''), type
            ).value('.', 'nvarchar(max)'),
            1, 1, ''
        )

from flow1 o
group by A,B


text:
Q: upgrading ejabberd from 16.09-4 to latest Back in september '17 I installed an ejabberd-instance on a  (debian 9-)server my dad still pays for, but is no longer using. The small circle of friends that initially used it, quickly grew and now there's a few hundred of us chatting away.
Time has come to update the ejabberd (I installed 16.09-4) because we want to stay secure and be able to enjoy all the latest whistles and bells. I thought some simple 'apt-get upgrade'-magic would do the trick, but boy, was I wrong.
I looked at the docs (Specific version upgrade notes) and tried to update to 17.03, by following the steps described there.
These updates fail miserably (missing links to /usr/sbin/ causing failure to to restart server after update. Adding symlinks does not help. I believe I chose to install to /opt/ last year, which would explain why).
Since I have some experience with MySQL and none whatsoever with Mnesia, I also decided in the beginning to add "default_db : SQL" in my ejabberd.yml file. I (wrongly) assumed all data would be stored in a MySQL-DB, and no longer in the Mnesia. This does not seem to be the case: I see all of the registered users in Mnesia (using ejabberdctl) but only part of the complete list in MySQL.
I guess my question is twofold:

*

*What would be the most efficient way to update from 16.09-4 to the latest version ? (I am aiming for a solution without having to install a new ejabberd-instance on a different server and simply backing up and migrating the MySQL)

*How can I avoid using Mnesia completely and only use MySQL ? And, related: How can I push all existing Mnesia-data into MySQL ?

A:
What would be the most efficient way to update from 16.09-4 to the latest version ?

As you have some kind of confusion about what and where is installed, problems in links, paths, etc, I propose as "the most efficient" a solution that has many many steps, but at least will work whatever you have:
First handle the old one:

*

*Find your config dir and mnesia spool (try 'ejabberdctl help')

*Stop ejabberd

*Move to a safe location your config dir and mnesia spool

*Uninstall ejabberd and all ejabberd related files and dirs

Now comes the new one:

*Install ejabberd in the way you prefer: Debian package, source, whatever

*Let it start, so it creates default config files and minimal mnesia spool

*You can even register an account, login, check it runs correctly

*Find the new config dir and mnesia spool (maybe they are different paths due to different install process)

*Stop ejabberd

And now recover your old information

*Replace the new config dir with old one, and the new mnesia spool with your old one

*Start ejabberd again, with old config and old mnesia. It may complain about useless or unknown options, it may also report it's updating the database schema.

*If it at least starts, check you have all the users, and also update the config file in case there were renamed options...

Of course, there are easier and faster ways to update, but your special case requires special steps.

How can I avoid using Mnesia completely and only use MySQL ?

Why exactly do you want to avoid it at all costs? It's required for some stuff in ejabberd, like client sessions, internal routes, commands... Other stuff can be moved to MySQL, like roster, passwd, MUC, vcards...

And, related: How can I push all existing Mnesia-data into MySQL ?

You can configure many modules to use sql instead of mnesia, and then run the export2sql command that produces a *.sql file that you will import into your new MySQL database. After that, you can delete content of mnesia tables using the WebAdmin.


text:
Q: iPhone css hover I have a website which shows some information on hovering over an image it works fine in every device except iphone i need to keep on pressing the screen till the hover completes the transition. i need it to work under single tap it should show the information.Here is the code
i used for the website hover transition.
               { -webkit-transition: all .5s ease-in-out 0.5s;
            -moz-transition: all .5s  ease-in-out 0.5s;
         -o-transition: all .5s  ease-in-out 0.5s;
         -ms-transition: all .5s  ease-in-out 0.5s;
         transition: all .5s  ease-in-out 0.5s; }

A: It is impossible to hover on iPhone because there is only pressed, and not pressed. There is no mouse to hover over the object, therefore it does not see it.


text:
Q: How to read and save BIOS from GeForce GT630M to change throttle temperature in Acer V3 ORIGINAL POST Please skip to EDIT
Hello I am using the Acer V3-571G which has set GPU throttling temperature to really low value(lower than other manufacturers) it makes GPU useless it throttles immedeatly(computer is clean almost new), I know the risk...etc. **but straight to the point.**a
I have tried to read GPU BIOS by GPU-Z and then change throttle temperature by NiBiToR but GPU-Z cannot read the BIOS it says that file ...Local\Temp\\nvflash.rom cannot be find. This file really exists on my computer but on the location :...Local\Temp\nvflash.rom This double slashes in GPU-Z makes this path corrupted in my opinion.
How to fix that and read that .rom file correctly.

EDIT:
I have been thinking about other possible solutions beside changing throttle temperature. And I decided to not change throttle temperature but change throttle GPU Clock Frequency.
I have used nVidia Inspector which allows to read the graphics card performance profiles.
I wanted change minimum allowed GPU Clock frequency but it is not possible, it is blocked and this programm do not allow to change it, but maybe you know other way to overwrite graphics card profile.
PS: Unlock min just changes the displayed GPU Clock range not from 270 but from 0mHZ.


text:
Q: Unbind a jquery behavior on removeClass I wrote a simple jquery function that run a particular action clicking on a div.
After the click, this function loads another div like the first one, if you click on this second div the function load a third one and so on...
All works right but even if I remove the "active" class from every clicked div, if you click on a div already clicked it fire the function again.
How can I remove the behavior on the div already clicked so that they stop loading other divs?
Thanks in advance :)

A: The event are attached to elements not with selector, so once the event is attached it doesn't matter if you remove the CSS class.
You need to use Event Delegation using .on() delegated-events approach, when manipulation selector (like removing and adding classes).
General Syntax
$(staticParentElement).on('event','selector',callback_function)

A: mark clicked or only bind event to active elements
$(document).on('click', '.selector:not(.clicked)', function(){
    //add element
    $(this).addClass('clicked'); // do not trigger event again
});

$(document).on('click', '.selector.active', function(){
    //add element with active class
    $(this).removeClass('active'); // do not trigger event again
});

A: I use the unbind function on $(this) to remove the function behavior to the clicked element :)
Thanks to everyone!


text:
Q: Stored XSS in database.query We have submitted our code to security review. i'm facing stored xss vulnarabities as described in below  lines, please some one help me on this.
 public map<string,RecordType> RecordTypeMap(String ObjectName){
     map<string,RecordType> recdmap = new map<string,RecordType>();
     if(ObjectName!=''){
       for(RecordType RT :[select id,Name,SobjectType,NamespacePrefix,IsActive,DeveloperName,Description,BusinessProcessId from RecordType where SobjectType=:ObjectName ]){
         recdmap.put(String.ValueOf(RT.id),RT);
       }
     }
     return recdmap;
}

public Map<string,Calendar_Settings__c> CustomSettForSobject(string objectname){
      map<string,Calendar_Settings__c> MapCustomSett = Calendar_Settings__c.getall();
      map<string,Calendar_Settings__c> MapRecTypeAndCSett = new map<string,Calendar_Settings__c>();
      for(Calendar_Settings__c sett :MapCustomSett.values() ){
            if(sett.objectName__c==objectname){
               MapRecTypeAndCSett.put(sett.RecordTypeName__c,sett);
            }
      }
      return MapRecTypeAndCSett;
}

 map<string,RecordType> rtyp = RecordTypeMap(SelectedObj);

Map<string,Calendar_Settings__c> MapRecTypeAndCSett = CustomSettForSobject(SelectedObj);
 //checking already FLS in a util class before going to going to execute this query

   if(MapRecTypeAndCSett!=null && rtyp!=null){
      for(Calendar_Settings__c clndr : MapRecTypeAndCSett.values() ){
        for(RecordType rt :rtyp.values()){
          if(RT.SobjectType == clndr.objectName__c){
            if(clndr.RecordTypeName__c == RT.name ){
               recordtypeandmap.put(String.ValueOf(RT.Id),RT.name);
            }
            if(clndr.RecordTypeName__c == RT.developername){
                recordtypeandmap.put(String.ValueOf(RT.Id),RT.developername);
            }
          }
        }
      }

    }

    L 195: for(sObject e: Database.query(eventsQuery)){

L 307: if(e.get('RecordTypeId')!=''){ ... }
L 308: if(recordtypeandmap.ContainsKey((string)e.get('RecordTypeId'))){ .. }
L 317: if(e.get(MapRecTypeAndCSett.get(recordtypeandmap.get((string)e.get('RecordTypeId'))).EndDateField__c) !=null)&&(...){...
     ClndrEvent cE = new ClndrEvent();
     cE.allDay = false;
     cE.url = e.Id;
    cE.timezoneParam = tz;
    cE.sobj = string.ValueOF(e.getSObjectType());
  cE.rectype = recordtypeandmap.get((string)e.get('RecordTypeId'));
  cE.title =(string) e.get(
 MapRecTypeAndCSett.get(recordtypeandmap.get((string)e.get('RecordTypeId'))).subject__c);
    }
        L 504: JSONString = JSON.serialize(eventsList);
        L 506: JSONString = JSONString.replaceAll('pEnd', 'end');
                      ...
            }

Visualforce
  ....

these are the few regions that i suspect in page,

function reloadCal() {

    var selectedItems = [];
    var check = document.getElementsByName("fltr");
    var fltrstring = '';
    for (var i=0; i<check.length; i++)
     {

       if(check[i].checked==true){
        selectedItems.push(check[i].value);
        fltrstring = fltrstring+check[i].value+',';
    }
    }
    var myval='';
    $("input:radio").each(function () {

var $this = $(this);

if (this.checked) {
    myval = this.value;
    //alert(myval);

}

})
    console.log(selectedItems);
    console.log('--fltrstring--'+fltrstring );
    filterallevents(fltrstring,myval);

}

    function reloadevntsandtask(){
    console.log('Hello');
    console.log('-Is nOt Updated from Comp--'+'{!IsNotUpdated}');
    var localvar = '{!IsNotUpdated}';
    if(localvar=='false'){
    console.log('-Is Within the false --'+'{!IsNotUpdated}');
    reloadCal();
    }
    else {
    return false;
    }

    }

</script>
<apex:outputPanel id="rlde">

</apex:outputPanel>

    <apex:actionFunction status="ajaxldr" name="fetchevent" action="{!editevent}" reRender="frm">
    <apex:param value="" name="evntid" />
    <apex:param value="" name="sfobj" />
</apex:actionFunction>
<apex:actionFunction status="ajaxldr" name="filterallevents" action="{!filterevents}" reRender="clndrpnl,frm,rlde,">
    <apex:param value="" name="filterby" />
    <apex:param value="" name="changedview" assignto="{!viewtype}" />
</apex:actionFunction>
<apex:actionStatus id="ajaxldr" onstart="blockoverlay();" onstop="$.unblockUI();" />

            <legend style="color:white;font-weight:150;margin-bottom:0px;font-size:16px;border-radius:4px;background:{!headerColorvalue}  ;">Event Information
            </legend>

                <apex:commandButton status="ajaxldr" action="{!ToggleEditViewOfEvent}" title="Edit" reRender="frm,rlde" value="Edit" styleclass="btnedit" />

            <apex:pageblocksection columns="1" >
                    <apex:outputField value="{!evt.Subject}" styleclass="formcontrol1" />
                   <apex:outputField value="{!evt.activityDateTime}" styleclass="formcontrol1" />
                    <apex:outputField value="{!evt.StartDateTime}" styleclass="formcontrol1" />
                    <apex:outputField value="{!evt.EndDateTime}" styleclass="formcontrol1" />
                    <apex:outputField value="{!evt.Type}" styleclass="formcontrol1" />
                    <apex:outputField value="{!evt.DurationInMinutes}" styleclass="formcontrol1" />
                    <apex:outputField value="{!evt.Description}" styleclass="formcontrol1" />
            </apex:pageblocksection>

                                <apex:repeat value="{!CalendarSettings}" var="filter">

            <input type="Checkbox" id="slideThree" onchange="reloadCal();" class="rectypefilter" name="fltr" value="{!filter.RecordTypeName__c}" style="margin-right:3px;">{!filter.name}</input>

                </apex:repeat>

                    <apex:commandLink id="clEvent" onclick="changeColor('{!$Component.clEvent}', '{!headerColorvalue}  '); changeColor('{!$Component.clTask}', 'white');" status="ajaxldr" action="{!ToggleCalendar}" reRender="clndrpnl,frm,rlde,fltrepeat"  onmouseout="this.style.textDecoration='initial';this.style.color='#337ab7';" onmouseover="this.style.textDecoration='underline';" style="text-decoration: blink;font-weight: bold;" value="Events">
                        <apex:param name="evnt" value="{!EvntSel}" assignTo="{!SelectedObj}" />
                    </apex:commandLink>

                    <apex:commandLink id="clTask"  onclick="changeColor('{!$Component.clEvent}', 'white'); changeColor('{!$Component.clTask}', '{!headerColorvalue}  ');" status="ajaxldr" action="{!ToggleCalendar}" reRender="clndrpnl,frm,rlde,fltrepeat" onmouseout="this.style.textDecoration='initial';this.style.color='#337ab7';" onmouseover="this.style.textDecoration='underline';" style="text-decoration: blink;font-weight: bold;" value="Tasks">
                        <apex:param name="evnt" value="{!TaskSel}" assignTo="{!SelectedObj}" />
                    </apex:commandLink>

            .panel-primary>.panel-heading {
color: #fff;
background-color: {!headerColorvalue};
border-color: grey;
}

//keep the shape of the boxes we're hiding
.fc-other-month {
    visibility: hidden
}
.fc-toolbar .fc-state-active, .fc-toolbar .ui-state-active{
background:{!subheaderColorvalue} ;
}
.fc-toolbar button {
position: relative;
background: {!headerColorvalue}  ;
color: white;
border-radius:5px;
}

body button:hover, body .btn:hover, body .btnCancel:hover, body .menuButton .menuButtonButton:hover{
background:{!subheaderColorvalue} ;
}

.fc th {
 padding:0px;
 background:{!headerColorvalue}  ;
 color:white;
}
</style>

A: OK, I see a couple of incorrect encoding issues that might lead to XSS. Whether or not they are exploitable or false positives is going to depend on the data type -- you only need to encode strings, not booleans or integers, but I can't determine the datatype in all cases from looking at the code. If this is an automated scan, then the scanner probably also is not able to reason accurately about the data type.
Here are the issues:
Any time you have a mergefield in a


text:
Q: Laravel nova 1.1.8 and higher Cannot read property 'name' of undefined on filter icon click Laravel version: 5.7
When updating Laravel nova to a version higher then 1.1.7 when on a ResourceIndex page. Clicking on the filter icon results in the following error.
TypeError: Cannot read property 'name' of undefined
    at Proxy.render (nova-custom-filters:3752)
    at VueComponent.Vue._render (vendor.js?id=f1774ad54c9d6dde0d50:98488)
    at VueComponent.updateComponent (vendor.js?id=f1774ad54c9d6dde0d50:96735)
    at Watcher.get (vendor.js?id=f1774ad54c9d6dde0d50:97105)
    at new Watcher (vendor.js?id=f1774ad54c9d6dde0d50:97094)
    at mountComponent (vendor.js?id=f1774ad54c9d6dde0d50:96742)
    at VueComponent.webpackJsonp../node_modules/vue/dist/vue.common.js.Vue.$mount (vendor.js?id=f1774ad54c9d6dde0d50:102494)
    at VueComponent.webpackJsonp../node_modules/vue/dist/vue.common.js.Vue.$mount (vendor.js?id=f1774ad54c9d6dde0d50:104907)
    at init (vendor.js?id=f1774ad54c9d6dde0d50:98074)
    at createComponent (vendor.js?id=f1774ad54c9d6dde0d50:99545)

Even when I create a brand new filter and only load this filter on the resource.

A: 1) Install a brand new Laravel 5.7 installation.
2) Install Nova. (php artisan nova:install and php artisan nova:publish)
3) Create a user.
4) Log into Nova.
5) See the error.
This error is NOT reproducible when upgrading for some reason. Once I replaced the nova-assets directory with a working copy, the test site worked. Once I deleted the nova-assets directory and re-published the Nova assets, it still works, even with a cleared browser cache.
POSSIBLE FIX (May be why it still works after republishing):
cd to the laravel/nova vendor directory.
Following this 5 steps I solved the problem but you need to rename webpack.mix.js.dist to webpack.mix.js before run npm run dev.
npm install

npm run dev

Delete the public/nova-assets directory.
Make sure to run php artisan nova:publish --force to get the latest assets after update.


text:
Q: Drupal 8 "log in" form won't appear Not sure what the heck I did, but after a day of logging in just fine to the Admin panel of my new D8 site, I am now (apparently) not permitted to access that page.  I was in the middle of making new content, saved it, and got "Access Denied."  When I went to log in, instead of reaching the /user/login window to input my credentials, I am just redirected to the main page.
I am sure this must be a simple setting that I goofed on, but not sure what it might have been.  I haven't changed anything with the .htaccess, settings.php, or any permissions.  Just doing content addition and things like minor css visual tweaks.
So interestingly, it seems this is only happening on Firefox, which (oddly) was the browser I was using the whole day.  If I switch to Chrome I can log in and edit content.  But Firefox (or other variants) simply zip me right to the home page, with nary a chance to enter my login credentials.
If you know what might be going on I'd love a tip.  Right now I'm totally locked out of the site, though I do have file manager access and can do PhpMyAdmin if necessary.
Thanks in advance for any help, tips, or suggestions.

A: Could you please clear(truncate) cache* tables via Phpmyadmin and try to login


text:
Q: Adjusting for spatial autocorrelation I have a data set on sand martin population sizes along a stretch of river over 40 years. The river is split into sections and the number of birds per section was counted.
I have been trying to model changes in population sizes at these different sites in relation to sahel weather, north african temperature and english temperature among other factors but have run into a problem. There are obviously two main problems associated with my data, the  first is autocorrelation of population sizes between years and the second is correlation between sites.  I am not sure which is best to use and am unsure if I am able to combine the two into a single model. I'll talk you through my model and have posted the questions at the end.
Before I tried the autocorrelation structure I tried a normal model and there was a big cone-shaped pattern in the residuals. So I tried to create the model with autocorrelation, using gls in R. This is the model I came up with:
m1<-gls(pop~sahel.Index + Arrival.Date + NAO + Year + locaion + North.african.weather,
    data=ndd,
    method="REML",
correlation = corAR1(form=~Year|locaction))

From what I understand this means that population is correlated by year within location. The residuals outputs from this model look fine, I have used the normalised residuals to take into account the correlation structure. The residuals are completely normally distributed and have no pattern whatsoever in the residuals vs fitted. I would post them but can't because of my low "reputation."
So I then wanted to try and add spatial correlation to the model. I tried the different correlation structures: corLin, corGaus, corExp and corSpher. corExp had the lowest AIC so went with that.
My model for the spatial correlation thus looked like this:
mbestcor<-gls(pop~sahel.Index + Arrival.Date + NAO + Year + locaion + North.african.weather,
            data=ndd,
            method="ML",
            correlation = corExp(form=~scYear|loc.ID))

And the residuals vs fitted and histogram look like this:

These plots look slightly odd, the residuals vs fitted is slightly cone-shaped and the histogram although normally distributed has quite a long right hand tail.
When I compare the AIC of these two models the spatial model is lower than the first:
 AIC(m2, bestm)
  df      AIC
m2    23 2171.202
bestm 23 2157.828

But obviously the residual plots for the second one are also worse than the first.
I have a few questions: Which model should I go with?
Am I best basing this decision on the AIC or on the normality of residuals?
Ideally, I guess I would like to have a model that combines the two, but after lookign at Zuur et al. 2009 and online I can't seem to find a package that will let me do this unless I use a model builder.
Any help would be very much appreciated.
Thanks,
Thomas


text:
Q: Position a set of points such that they are all optimally a certain distance from the origin This is a very specific question and since I am no mathematician by trade I did not really figure out how to ask it in mathematical jargon, I apologize in advance for the inconvenience.
This is a problem I stumbled upon while doing regular linear algebra for an application for computational chemistry. It showed up in a subroutine to assemble the geometry of a large, complicated molecule which I had to do one piece at a time. I jotted down a few trials on how to solve this, but it got me stumped real fast and I can't find a way out.
Stripped from its chemical details, the problem is as such.
Suppose there is a set of points $\mathcal{S}$ in 3D Euclidian space $\mathbb{R}^3$ which is a subset of a larger set $\mathcal{A}$. Each of these points have a color. They can all be the same color or each be a different color or any combination of colors. Each color $c$ is associated with a certain distance $d_c$. This value $d_c$ is the optimal distance from the origin for the points of color $c$.
The solution to the problem would be to find the rotations and translations that transform the entire set of points $\mathcal{A}$ such that the norm of the position vector $|\vec{p}_i|$ of each point in $\mathcal{S}$ is as close as possible to each of their optimal distances.
So the question is: Is it possible to find the rotation matrices and translation vectors that accomplish that? Is there a procedure to do it?
P.S: It is important that the transformations be applied to all the points in $\mathcal{A}$ simultaneously.

A: From your description it looks like all the points are fixed relative to each other.  In that case, the only freedom is locating the origin.   Let $d_k$ be the optimum distance for point $k$ while $s_k(x)$ is the distance when the origin is at a point $x$.  Your problem is minimizing $\sum\limits_k (d_k-s_k(x))^2$ as a function of $x$.
Alternatively you might want to minimize $\sum\limits_k |d_k-s_k(x)|$.
Specifically, let $(y_{1k},y_{2k},y_{3k})$ be the location of point $k$ and $(x_1,x_2,x_3)$ the origin.  So $s_k(x)=\sqrt{\sum\limits_{j=1}^3(y_{jk}-x_j)^2}$


text:
Q: select only rows that have the same id in r ID Julian Month Year Location Distance
 2  40749  July 2011     8300    39625
 2  41425   May 2013 Hatchery    31325
 3  40749  July 2011     6950    38625
 3  41057   May 2012 Hatchery    31325
 6  40735  July 2011     8300    39650
12  40743  July 2011    11025    42350

Above is the head() for the data frame I'm working with. It contains over 7,000 rows and 3,000 unique ID values. I want to delete all the rows that have only one ID value. Is this possible? Maybe the solution is in keeping only rows where the ID is repeated?

A: If d is your data frame, I'd use duplicated to find the rows that have recurring IDs. Using both arguments in fromLast gets you the first and last duplicate ID row.
d[(duplicated(d$ID, fromLast = FALSE) | duplicated(d$ID, fromLast = TRUE)),]

This double-duplicated method has a variety of uses:
Finding ALL duplicate rows, including "elements with smaller subscripts"
How to get a subset of a dataframe which only has elements which appear in the set more than once in R
How to identify "similar" rows in R?

A: Here is how I would do it:
new.dataframe <- c()
ids <- unique(dataframe$ID)
for(id in ids){
temp <- dataframe[dataframe$ID == id, ]
if(nrow(temp) > 1){
new.dataframe <- rbind(new.dataframe, temp)
}}

This will remove all the IDs that only have one row


text:
Q: Task stack being reset to root when launching from app icon with a singleTask Activity; why? Scenario:
I have MainActivity, which has <intent-filter>s MAIN and LAUNCHER. This activity is set to have launchMode="singleTask" by required design.
I navigate in some path: MainActivity -> Activity A -> Activity B, which are all added to the task stack.
Scenario A: I background the app, resume it from the Recent Apps section. Task stack is resumed correctly e.g. B > A > Main
wm_task_moved: [269,0,2147483647]
am_focused_stack: [0,0,234,0,moveTaskToFront findTaskToMoveToFront]
wm_task_moved: [269,0,2147483647]
am_on_top_resumed_lost_called: [0,com.google.android.apps.nexuslauncher.NexusLauncherActivity,topStateChangedWhenResumed]
correct behavior --> am_set_resumed_activity: [0,test.ActivityB,moveTaskToFront findTaskToMoveToFront]
am_pause_activity: [0,60517111,com.google.android.apps.nexuslauncher/.NexusLauncherActivity,userLeaving=true]
am_task_to_front: [0,269]
am_on_paused_called: [0,com.google.android.apps.nexuslauncher.NexusLauncherActivity,performPause]
am_set_resumed_activity: [0,test.ActivityB,resumeTopActivityInnerLocked]
am_add_to_stopping: [0,60517111,com.google.android.apps.nexuslauncher/.NexusLauncherActivity,makeInvisible]
am_resume_activity: [0,29773184,269,test.ActivityA]
sysui_multi_action: [757,803,799,window_time_0,802,6]
am_on_restart_called: [0,test.ActivityB,performRestartActivity]
am_on_start_called: [0,test.ActivityB,handleStartActivity]
am_on_resume_called: [0,test.ActivityB,RESUME_ACTIVITY]
am_on_top_resumed_gained_called: [0,test.ActivityB,topWhenResuming]
sysui_multi_action: [319,30,321,25,322,123,325,110814,757,761,758,9,759,4,806,test.package,871,test.ActivityB,904,test.package,905,0,1320,12,1321,1]
am_stop_activity: [0,60517111,com.google.android.apps.nexuslauncher/.NexusLauncherActivity]
am_on_stop_called: [0,com.google.android.apps.nexuslauncher.NexusLauncherActivity,STOP_ACTIVITY_ITEM]

Scenario B: I background the app again, and this time resume it from the launcher icon; the Activity is flagged somehow, and clears the task stack, leaving only the root MainActivity.
incorrect behavior --> am_finish_activity: [0,262811058,269,test.ActivityA,clear-task-stack]
incorrect behavior --> am_destroy_activity: [0,262811058,269,test.ActivityA,finish-imm:finishActivityLocked]
incorrect behavior --> am_finish_activity: [0,214943796,269,test.ActivityB,clear-task-stack]
incorrect behavior --> am_destroy_activity: [0,214943796,269,test.ActivityB,finish-imm:finishActivityLocked]
am_new_intent: [0,24608519,269,test.Main,android.intent.action.MAIN,NULL,NULL,268435456]
wm_task_moved: [269,0,2147483647]
am_focused_stack: [0,0,234,0,bringingFoundTaskToFront]
wm_task_moved: [269,0,2147483647]
am_set_resumed_activity: [0,test.Main,bringingFoundTaskToFront]
am_pause_activity: [0,60517111,com.google.android.apps.nexuslauncher/.NexusLauncherActivity,userLeaving=true]
am_task_to_front: [0,269]
sysui_multi_action: [757,803,799,window_time_0,802,9]
sysui_multi_action: [757,803,799,window_time_0,802,0]
am_on_top_resumed_lost_called: [0,com.google.android.apps.nexuslauncher.NexusLauncherActivity,topStateChangedWhenResumed]
am_on_paused_called: [0,com.google.android.apps.nexuslauncher.NexusLauncherActivity,performPause]
am_set_resumed_activity: [0,test.Main,resumeTopActivityInnerLocked]
am_add_to_stopping: [0,60517111,com.google.android.apps.nexuslauncher/.NexusLauncherActivity,makeInvisible]
am_resume_activity: [0,24608519,269,test.Main]
incorrect behavior --> am_on_destroy_called: [0,test.ActivityA,performDestroy]
sysui_multi_action: [757,803,799,window_time_0,802,0]
incorrect behavior --> am_on_destroy_called: [0,test.ActivityB,performDestroy]
am_on_restart_called: [0,test.Main,performRestartActivity]
am_on_start_called: [0,test.Main,handleStartActivity]
I am_on_resume_called: [0,test.Main,RESUME_ACTIVITY]
am_on_top_resumed_gained_called: [0,test.Main,topWhenResuming]

The event log for scenario 2; it seems to be forcibly setting clear-task-stack on ActivityB & ActivityA when launching from the app icon vs Recent Apps.
To my knowledge, if I declare my activity as singleTask, when I re-launch the app from the app icon, it should find the existing task stack and recreate it, same as in Scenario A. The only conclusion I can come to is that launching the application from the app icon is flagging it somehow, which is overriding some inherent behavior to a singleTask Activity and manually resetting the task stack.
I believe this is a bug, but please correct me if I am wrong. I'm seeking clarity as to why the two scenarios act differently, and how I might workaround this if it is a bug, or change my implementation if it's intended behavior. I have read on SO about similiarly bugged behavior, but it differs in that I do not have a separate Launch activity of any kind; just a single MainActivity with defined intent-filter attributes for MAIN and LAUNCHER, while also being a singleTask activity. My MainActivity is still seeing itself as the root task; it's just clearing the other tasks when, I believe, it should not be.
The only solution I see right now is to change my MainActivity to launchMode="singleTop" and manually flag each time I'm starting it to avoid instance duplication, which seems to defeat the purpose of singleTask entirely.
Any help is appreciated; thanks!


text:
Q: WCF, Silverlight: Is Request/Reply possible over PollingDuplexHttpBinding? We have been using PollingDuplexHttpBinding for some time to do Pub/Sub messaging. We have methods that do not return results that allow clients to subscribe to some data feed then then the service pushes data back via CallBack contracts.
Just now we have been adding some Request/Reply methods to our OperationContract. As the clients are Silverlight 3 these methods are called using the async Begin() End() pattern. The problem is we cannot get this to work using PollingDuplexHttpBinding. We always get the following error (when client stack HTTP is used):

The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.

With browser stack we get HTTP 500: Not Found.
When switching to BasicHttpBinding the Request/Reply methods are called completely fine, but obviously Pub/Sub methods cannot be used with this binding.
We could use two seperate endpoints for each type of messaging, but would rather not and it seems odd to me that a binding would only support the Pub/Sub pattern (even though this is the motivation for PollingDuplexHttpBinding).
Could someone clear this up for me? Is it possible?

A: We never did get this to work. We use BasicHttpBinding for all of our Request/Reply operations between our Silverlight 4 apps and our WCF 4 services. These are all async method calls (have to be with Silverlight) to Per-Call services. For the couple of situations where we must do server push we have a Sessionful WCF service maintaining a PollingDuplexHttpBinding connection to the Silverlight client and we use Callback Contracts with One-Way methods to make calls.
Could never get Request/Reply operations to work with PollingDuplexHttpBinding, but never found an authority on the matter either...


text:
Q: Use Jenkins to swap a password parameter out when building git repo I would like to have the following scenario:

*

*Jenkins to grab my github repo (check!)

*find a particular file in my project (persistence.xml let's say)

*locate the parameter (for example PASSWORD_PLACEHOLDER)

*swap it in with a password I've previously provided it before running my tests

*Run my tests (via Maven) that depend on the DB connection the password is for

Question: Can this be done easily and if so, how? Should this be a MAVEN responsibility or a Jenkins one?

A: You could achieve it using Maven filtering on test resources (or on resources, if you prefer).
You can configure your POM as following:
<properties>
    <secretPassword>xxxx</secretPassword>
</properties>

<build>
    <testResources>
        <testResource>
            <filtering>true</filtering>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>
</build>

And have your persistence.xml file under src/test/resources with the following sample content:
<test>
    <password>${secretPassword}</password>
</test>

Then, from command line you can pass a value for this token as below:
mvn clean test -DsecretPasword="p4ssw0rd"

And Maven will automatically replace the token in the persistence.xml file with the provided value. As per Maven lifecycle, this replacement will occur before any test execution.
Once this mechanism is in place, you can then proceed with the Jenkins setup:

*

*Jenkins check the code out from version control

*Jenkins runs a Maven execution on the workspace passing to Maven the desired password value as on the example above

*Maven will replace the token and execute the tests

A common and good practice is also to place this behavior in a dedicated maven profile, having id ci for example, and then activate it as part of the Jenkins build (via the -Pci option, in this case, passed to maven).
Hence, back to your questions:

Can this be done easily and if so, how?

Yes, as described above

Should this be a MAVEN responsibility or a Jenkins one?

Maven and Jenkins working together

Additionally, beware that the password you passed would be part of the Jenkins build output on the Jenkins server (it will print the Maven command executed and as part of it the value you passed for the password, in clear).
You can check the Mask Password Jenkins Plugin to mask the password from the build output.


text:
Q: STG_E_WRITEFAULT while reading Excel file with Epplus In an ASP.NET MVC Core (.netcore2) application, I'm using the following method to read an Excel file.
[HttpPost]
public IActionResult Import (IFormFile importFile)
{
    using (var excel = new ExcelPackage(importFile.OpenReadStream())
    {
        var sheet = excel.Workbook.Worksheets.FirstOrDefault();
        if (sheet == null) return BadRequest("No worksheet.");

        var events = /* import logic */
        return Json(events);
    }
}

However, epplus is throwing this exception:

COMException: A disk error occurred during a write operation. (Exception from HRESULT: 0x8003001D (STG_E_WRITEFAULT))

I've used methods like this in the past to import Excel files, and I don't know what's going wrong.
I've checked:

*

*Versions of references on the project

*Excel file validity (I'm positive it's a valid xlsx file, not an old xls or other format)

A: Epplus currently has an issue when targeting .NetStandard with text encoding. To resolve this, add this reference to your project.
<ItemGroup>
    <PackageReference Include="System.Text.Encoding.CodePages" Version="4.4.0" />
</ItemGroup>

Then, call this once in your application's startup -
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

More detail here on why this is happening.