text:
Q: AngularJS Rest call to authenticate user I am trying to write a service to authenticate users on login:
//Authentication Service
app.factory("AuthenticationService", function($location, $http) {
  return {
    login: function(credentials) {

    $http('api/auth/:username/:password',{'username': credentials.username, 'password' : credentials.password})
        .success(function(data,status,headers,config){
            if(data.success=="1"){
                //succefull login
                credentials.isLogged = true;
                credentials.username = data.username;
                return true;
            }
            else{
                credentials.isLogged = false;
                credentials.username = '';
                credentials.errormessage = "Login Failed! Try again...";
                return false;
            }
        })
        .error(function(data,status,headers,config){
            credentials.isLogged = false;
            credentials.username = '';
            credentials.errormessage = "Login Error. Missing Service";
            return false;
        });

    },

    logout: function() {
      $location.path('/logout');
    },

    checkAuth: function(){
        if (credentials.isLogged) {
            return true;
        } else {
            $location.path('/admin/login');
        }
    }

  };
});

In the backend I have a PHP api that responds with:
[{'success':'0'}]

However I cannot manage to make the call appropriately from Angular, since it always return the "Login Error" message.
Can someone have a look at this code and tell me what I am doing wrong? (I guess many things). Thanks a lot
EDIT
I changed the PHP to return:
{'success':'0'} (or 1, accordingly)
Also I tried
$http.post(...)

But I get 404. The URL is definitively correct, I must be doing something else wrongly...

A: Try with {'success':'0'},
I mean you can't return arrays as root object.

A: Try referencing the index of the array where your object is contained:
if (data[0].success=="1")


text:
Q: How to convert HEIC/HEIF image to what ever in ReactJs At the moment I am using the upload file component provided by antd

Also I am using a library to transform HEIC to JPG ... this library is called heic2any, and the truth works quite well, basically, it fulfills its objective, this is the code that im using
this is my code so far:
const handleChange = (info) => {
    setLoading(true);
    setimageUrl(null);
    if (info.file.originFileObj.type === "") {
      fetch(URL.createObjectURL(info.file.originFileObj))
        .then((res) => res.blob())
        .then((blob) => heic2any({ blob, toType: "image/jpeg" }))
        .then((conversionResult) => {
          console.log("HEIC");
          setimageUrl(URL.createObjectURL(conversionResult));
          setLoading(false);
        })
        .catch((e) => {
          console.log("error");
          setLoading(false);
        });
    } else {
      setLoading(false);
      setimageUrl(URL.createObjectURL(info.file.originFileObj));
    }
  };

My problem occurs the moment a HEIF file arrives ... because the library does not accept that format, it only allows HEIC ... but what happens I also have no way of knowing what type of file is being uploaded to avoid failure, due to Why, when I ask for a HEIF or HEiC type photo, these are the data that the input gives me:
TYPE HEIF

Type HEIC

for none of these cases, I can recognize the type of file that is being loaded so I have no way to validate it ... what can I do in this case? Do you know any library that allows me to upload HEIC and HEIF photos? maybe not load, at least convert to another format and with that allows me to show a preview

redpajama_set_name: RedPajamaStackExchange


text:
Q: google checkout returns item unavailable I'm integrating google checkout with my android application.
I have successfully tested the billing process with android.test.purchased.
but after uploading the apk (it is not published yet but is signed) and creating product list (products are published yet) I'm getting "The item you requested is not available for purchase" while trying to buy  an item.
in the logs I can see the response code RESPONSE_ITEM_UNAVAILABLE. google docs says that this eror code

"Indicates that Google Play cannot find the requested item in the
  application's product list. This can happen if the product ID is
  misspelled in your REQUEST_PURCHASE request or if an item is
  unpublished in the application's product list."

I have checked it twice - the item is published and is spelled correctly. and also I'm running the same version of apk on my device which is uploaded
thanks in advance!

A: after publishing the application as well the checkout started to work. just wondered why they have put in docs that there is no need to publish the application but the products.


text:
Q: How to get character level difference using "diff" command in Linux using shell script? I have two SQL files, one is old.sql and the other one is new.sql.
Suppose old.sql contains a table with three fields, Emp_Id, Name and Address and data stored in old.sql as follows:
Insert into table1 values (101 ,"a", "xyz");
Insert into table1 values (102 ,"b", "pqr");

Then I have changed "a" address "xyz" to "xyz123" and saved that data in the new.sql file.
Now the new.sql file contains data as follows:
Insert into table1 values (101 ,"a", "xyz123");
Insert into table1 values (102 ,"b", "pqr");

When I use the diff command like this:
diff old.sql new.sql

it gives differences line-wise but I want only updated data, like xyz123.

A: You might find wdiff useful for this type of comparison; it's a front-end to diff which produces word-by-word comparisons. With your example it produces by default
Insert into table1 values (101 ,"a", [-"xyz");-] {+"xyz123");+}
Insert into table1 values (102 ,"b", "pqr");

It can use terminal features to make the output more legible on a terminal (wdiff -t). It also has a -3 option which limits output to changed words only:
======================================================================
 [-"xyz");-] {+"xyz123");+}
======================================================================

If you don't have wdiff already installed, you need to install it. Run sudo apt-get install wdiff or sudo dnf install wdiff or sudo yum install wdiff or the command that is appropriate to your operating system.

A: You can use:
diff -u old.sql new.sql |colordiff |diff-highlight

colordiff is a Ubuntu package. You can install it using sudo apt-get install colordiff.
diff-hight is from git (since version 2.9). It is located in /usr/share/doc/git/contrib/diff-highlight/diff-highlight. You can put it somewhere in your $PATH. Or get it from diff-so-fancy project.

A: By definition, diff is showing differences lines by lines (see diff manual page), it will therefore not show only the differing characters.
You can reduce the amount of difference by pre-processing the files, for exemple by inserting an end-of-line character after each semi-column:
sed -e 's/;/;\'$'\n/g' old.sql > old.patched

Then use diff on the two resulting files.

A: Short answers from here:
git diff --word-diff=color --word-diff-regex=. file1 file2
And here:
diff -u file1 file2 |perl /usr/share/doc/git/contrib/diff-highlight/diff-highlight

A: I also wrote my own script to solve this problem using the Longest common subsequence algorithm.
It is executed as such
JLDiff.py a.txt b.txt out.html

The result is in html with red and green coloring. Larger files do exponentially take a longer amount of time to process but this does a true character-by-character comparison without checking line by line first.
This answer is cross-posted from here.
I have found that JLDiff runs a lot faster under pypy.


text:
Q: Create a fixed and dynamic header for a python dataframe I am reading a gzip file and converting it to a Dataframe by the below method
   df = pd.read_csv(file.gz, compression='gzip', header=0, sep=',', quotechar='"', error_bad_lines=False)

This actually populates the first row as column header. As the data in the gzip varies every time the column header also changes.Also there is no fixed column count it also differs as per file as below .
File 1
        01-10-2019  Samsung    Owned
        -----------------------------
        01-10-2019  Samsung    Owned
        03-10-2019  Motorolla  Sold

File 2
         SAMSUNG    Walmart    DHL    300$  Sold  Alaska
        --------------------------------------------------
        SAMSUNG    Walmart    DHL     300$  Sold  Alaska
        Sony       Motorolla  Fedex   250$  Sold  Chicago

For me to do some data manipulation it would be great if I have a fixed column as 1,2,3 based on the no of columns the dataframe has like
 File 1
            1            2         3
            -----------------------------
            01-10-2019  Samsung    Owned
            03-10-2019  Sony       Sold
File 2
          1         2         3        4    5      6
        --------------------------------------------------
        SAMSUNG    Walmart    DHL     300$  Sold  Alaska
        Sony       Motorolla  Fedex   250$  Sold  Chicago

A: If I understood you correctly, you don't want to read the header from the csv file.
That can be done using header=None.
If your csv file contain a header that you want to ignore, then you can also add skiprows=1.
df = pd.read_csv(file.gz, compression='gzip', header=None, sep=',', quotechar='"', error_bad_lines=False)


text:
Q: how to search for a checkbox inside innerHTML? I want to sum a selected column inside a table. 2nd and 3rd column in my case. I managed to get the sum but I really want to add the value of a row in case a checkbox in column #1 is checked.
I can get the innerHTML value of a cell abut I do not know how to search or find out if the checkbox inside is checked or not.
console.log(cell.innerHTML);
returns for example
"Extend      (2x)<input type=\"checkbox\" id=\"Extend2x\" name=\"Extend2x\" class=\"beru\" <=\"\" td=\"\">
so I can see that the checkbox is there but that is where I ended up
I tried
console.log(cell.innerHTML.getElementsByTagName("checkbox"));
console.log(cell.innerHTML.html());
console.log(cell.html());
console.log($(cell).find(':checkbox').checked) returns undefined

but nothing worked.
Could somoone help me to find out? The working fiddle is here You just click the checkbox and summing of the columns will be done.

A: The code you are looking for is this
$(':checked')

you can add stuff like input:checked, or something to make it more specific.
EDIT--
just saw the comments - and Taplar already answered this. Well this can be considered as alternative answer, and does not need to use cells / iterate through cells of the table.

A: I think this is what you wanted. This is using jQuery for every reference to elements in the the dom (html).

$(".beru").on('change', function() {
  updateTotals();
});

function updateTotals() {

  // loop cells with class 'celkem'
  $('.celkem').each(function(){

    // for each celkem, get the column
    const column = $(this).index();
    let total = 0;

    // loop trough all table rows, except the header and the row of totals
    $(this).closest('table').find('tr:not(:first, :last)').each(function(){
      if($(this).find('input').is(':checked')) {

        // if the input is checked, add the numeric part to the total
        const str = $(this).find(`td:eq(${column})`).text().replace(/\D/g, "");
        if(str) {
          total += Number(str);
        }
      }
    });

    if(!total) {
      // if the total is zero, clear the cell
      $(this).text("");
    } else {
      // otherwise, print the total for this column in the cell
      $(this).text(total + " EUR");
    }
  });
}
td {
  width: 25%;
}

Název
První balíček
Měsíčně

BalanceOil <input type="checkbox" id="BalanceOil" name="BalanceOil" class="beru">
149 EUR
30 EUR

Extend (2x)<input type="checkbox" id="Extend2x" name="Extend2x" class="beru"
44 EUR
22 EUR

Zinobiotic (3x)<input type="checkbox" id="Zinobiotic" name="Zinobiotic" class="beru"
64 EUR
23 EUR

Celkem

A: If you already have a reference to the DOM element then just select all the checkboxes using a selector.

var cbList = cell.querySelectorAll("[type='checkbox']");

for(var i = 0; i < cbList.length; i++){

    //do something with each checkbox
    //cbList[i];

}

Remember a node list is not an array, so you can't use forEach ;)


text:
Q: How to get the filename and extension out of a URL? I'm using prototype and trying to get the filename and extension out of a URL in the src attribute of an . For example, I want to get colorch091001-black-2.jpg out of this:

I can get the src value with:
var img = $('small_img_src').src;

But how do I get just the filename and extension?

A: Try this, For pure JavaScript Solution

var src = document.getElementById('small_img_src').src;
alert(src.substring(src.lastIndexOf('/') + 1));


text:
Q: How can I dodge Marie's attacks? Marie, the final boss in Skullgirls, has a lot moves that are either very tricky to dodge or do insane damage (often both). Since she barely moves I can hurt her even by button mashing, but dodging her attacks is the tricky part.
There's certain moves like the big circular shadow on the floor (dash left/right) and the snake of skulls along the floor (jump over) I can dodge, but certain moves like the "assists" coming from behind/in front of you that I can't seem to dodge or block. Her explosion (like when turning into her final form) is another tricky one to dodge, attacking in melee it seems I can't get out of the way once I've triggered it.
How can I dodge Marie's attacks, at least the trickiest ones?

A: Attacks are blocked based on your position relative the other character, not your position relative to the direction the attack is coming from. So even if the attack comes from behind if the opponent is in front you block holding back.
If your character is not blocking even while you're holding the correct direction, than the explanation is that you are not blocking with the correct stance. High attacks need to be blocked while standing, Crouch attacks need to be blocked while crouching. There is also the technique of Jumping backwards and blocking which tends to cover all your bases.
Since I can't say for sure with Marie's attacks I'll also mention that sometimes in fighting games you'll have a small "block buffer" to prevent unfair crossups, so even if the character crosses you up if you were holding the correct direction their fast first crossup hit will get blocked. Very unlikely to apply but there you have it.
I am fairly sure with most characters you have to block some of her attacks and just eat the chip damage.


text:
Q: Codeigniter $this->db->reconnect(); usage I'm not autoloading db because most pages of my application don't need db processing otherwise whole thing will slow down. What I want to do is not to establish a new connection to db when there is one already alive and use it instead not to bother server-db. So how do I implement $this->db->reconnect(); to my example below? I read user guide but no exact example there.
Note : If I necessary to use $this->db->close(); and $this->db->initialize(); then please help me implement them as well because I heard that calling $this->db->reconnect(); with autoloading disabled will throw an error.
I'm using CI 2.1
Thanks
class Test_model extends CI_Model
{
 public function __construct()
 {
  parent::__construct();

  $this->load->database();
 }

 public function function_a($id)
 {
  $this->db->protect_identifiers('year');

  $sql = "SELECT * FROM year WHERE id = ?";

  $data['dbquery'] = $this->db->query($sql, array($id));

  return $data['dbquery'];
 }

 public function function_b($id)
 {
  $this->db->protect_identifiers('month');

  $sql = "SELECT * FROM month WHERE id = ?";

  $data['dbquery'] = $this->db->query($sql, array($id));

  return $data['dbquery'];
 }

 public function function_c($id)...
 public function function_d($id)...
 public function function_e($id)...
}

A: Basically if you keep pconnect=false in database.php then the connection will be closed at the end of each script's execution automatically and by default it set to false.
Well if you want then you can use
$this->db->close();

after every query execution to close the connection manually and use
$this->db->initialize();

before any query execution to initialize the connection again after closing it.

A: The best way to do it is just close the connection and reconnect manually with:
$this->db->close();
$this->db->initialize();


text:
Q: finding the remainder of $f(x)$ when divided by $(x-1)(x-2)$ $f(x)\in \mathbb{R}[x]$ is a function that has a remainder of 2 when divided by $(x-1)$, and a remainder of 1 when divided by $(x-2)$.
I know that the remainder of $f(x)$ when divided by $(x-1)(x-2)=x^2-3x+2$ needs to be $-x+3$ but I just don't know how to prove it.
I tried to write down $$f(x)=q_1(x)\cdot (x-1)+2=q_2(x)\cdot (x-2)+1$$
for $q_1,q_2\in\mathbb{R}[x]$, but I couldn't find what need's to be $p(x)\in\mathbb{R}[x]$ so that $$f(x)=p(x)\cdot (x-1)(x-2)+(-x+3)$$

A: The remainder when $f$ is divided by $(x-1)(x-2)$ is at most a first degree polynomial. That means that $f(x) = p(x)\cdot (x-1)(x-2) + (ax+b)$ for some real numbers $a, b$. Now use your knowledge of $f(1)$ and $f(2)$ to find $a$ and $b$.

A: Well you already write $p(x) = q(x)(x-1)(x-2) + r(x)$, and you know that $deg(r) \leq 1$. And you know $r(1) = f(1) = 2$ and $r(2) = f(2) = 1$.

A: Note that here we have $P(1)+1 = P(2)+2 = 3$
i.e. the polynomial $P(x)+x-3$ has roots $x=1$ and $x=2$
$\Rightarrow P(x)+(x-3) = (x-1)(x-2)Q(x) \Rightarrow P(x) = (x-1)(x-2)Q(x) -(x-3)$
Its easy to see that $a=-1, b=3$


text:
Q: Does this lemma have a name? Does the following lemma have a name? I'm asking this because the following lemma is very useful and easy to prove. So it's very likely that it has a name in the literature.

Let $(X,\Sigma )$ be a measure space and $\mathcal{M(\Sigma) }$ be the
set that contains exactly all measurable functions $f:X\to
\mathbb{R}$. Suppose that $\mathcal{M}\subseteq \mathcal{M}(\Sigma)$
is such that

*

*$\chi _E\in\mathcal{M}$ (characteristic function of $E$) for all $E\in \Sigma $

*$af+bg\in\mathcal{M}$ for all $f,g\in\mathcal{M}$ and $a,b\in \mathbb{R}$

*If $(f_n)_{n\in\mathbb{N}}$ is a sequence of $\mathcal{M}$ that converges pointwise, then $\lim_{n\to\infty }f_n\in \mathcal{M}$.

Then $\mathcal{M}=\mathcal{M}(\Sigma )$.

To prove the above proposition you need to use that every measure function is a pointwise limit of simple functions.
Thank you for your attention!


text:
Q: If A is invertible, prove that $\lambda \neq 0$, and $\vec{v}$ is also an eigenvector for $A^{-1}$, what is the corresponding eigenvalue? If A is invertible, prove that $\lambda \neq 0$, and $\vec{v}$ is also an eigenvector for $A^{-1}$, what is the corresponding eigenvalue?
I don't really know where to start with this one. I know that $p(0)=det(0*I_{n}-A)=det(-A)=(-1)^{n}*det(A)$, thus if both $p(0)$ and $det(0) = 0$ then $0$ is an eigenvalue of A and A is not invertible. If neither are $0$, then $0$ is not an eigenvalue of A and thus A is invertible. I'm unsure of how to use this information to prove $\vec{v}$ is also an eigenvector for $A^{-1}$ and how to find a corresponding eigenvalue.

A: If you have $v\neq 0$ such that $A v = \lambda v$, and $A$ is invertible, then $v = \lambda A^{-1} v$.
What does that tell you about $\lambda$?

 $\lambda$ must be non-zero, otherwise this would mean $v=0$, a contradiction.

How do you use the above to find an eigenvalue corresponding to $v$?

 Since $\lambda \neq 0$, we have $A^{-1} v = \frac{1}{\lambda} v$, hence the eigenvalue is $\frac{1}{\lambda}$.

A: Hint: Look at $I_nv=A^{-1}(Av)$.

A: Remember that
If $v$ is an eigenvector of $A$ corresponding to eigenvalue $\lambda$, then
$$
Av = \lambda v.
$$
You want to show that, for some other number $\mu$,
$$
A^{-1}v = \mu v.
$$
So, starting with $Av = \lambda v$ again,
$$
A^{-1}A v = A^{-1} \lambda v = \lambda A^{-1} v
$$
and I'll leave the rest to you.


text:
Q: DanialFarid Ng File Upload issue I am using your Angular File upload (https://github.com/danialfarid/ng-file-upload#contrib)
I just have Angular in my project I don't have Bower or any other stuff.
The issue that I have is all of a sudden it starts throwing the error mentioned below and for some reason even after doing everything I can't get this to work.
Error: [$injector:unpr] Unknown provider: UploadProvider <- Upload
http://errors.angularjs.org/1.2.28/$injector/unpr?p0=UploadProvider%20%3C-
%20Upload at http://localhost:8080/Rsdf/Rsdf_Common/lib/angular.js:78:12 at
http://localhost:8080/Rsdf/Rsdf_Common/lib/angular.js:3801:19 at
Object.getService [as get]
(http://localhost:8080/Rsdf/Rsdf_Common/lib/angular.js:3929:39) at
http://localhost:8080/Rsdf/Rsdf_Common/lib/angular.js:3806:45 at getService
(http://localhost:8080/Rsdf/Rsdf_Common/lib/angular.js:3929:39) at invoke
(http://localhost:8080/Rsdf/Rsdf_Common/lib/angular.js:3956:13) at
Object.instantiate
(http://localhost:8080/Rsdf/Rsdf_Common/lib/angular.js:3976:23) at
http://localhost:8080/Rsdf/Rsdf_Common/lib/angular.js:7315:28 at
http://localhost:8080/Rsdf/Rsdf_Common/lib/ui-bootstrap-tpls-
0.12.0.min.js:8:29473 at wrappedCallback
(http://localhost:8080/Rsdf/Rsdf_Common/lib/angular.js:11682:81)

I have included all these files
<script src="Rsdf_Common/lib/ng-file-upload-bower-4.2.4/ng-file-upload-shim.min.js"></script>
<script src="Rsdf_Common/lib/ng-file-upload-bower-4.2.4/ng-file-upload.min.js"></script>
<script src="Rsdf_Common/lib/ng-file-upload-bower-4.2.4/ng-file-upload-all.js"></script>
<script src="Rsdf_Common/lib/ng-file-upload-bower-4.2.4/FileAPI.js"></script>

This is my controller definition as you can see I have injected the upload module but it still seems to not work
rsdf.controller('fileUploadCtrl',function($scope,$modalInstance,notificationService,$http,userInfo,$timeout,$log,Upload){

Need help ...!!!

A: I got this resolved thanks guys i had missed to add that in the app.js as my dependency i added ngFileUpload dependency and it started to work


text:
Q: Linux distro to run a MIDI-server on a PII 333 MHz I am looking for a Linux distro that can be used to redirect MIDI message from the network to the soundboard a TurtleBeach Montego from 1997. Currently the computer is running Windows 98 se and I get a total latency of 10 ms when feeding audio back through an analog cable. Since the computer has no display, I cannot do any remote control (other than shutdown, which I have added as ad-hoc messages).
Full hardware list:

*

*Sound: TurtleBeach Montego

*Graphics: NVIDIA GeForce 6200 AGP

*CPU: Pentium II Deschutes 333 MHz

*RAM: 256 MB

*IDE controller

The following is a list of requirements for the setup

*

*A total latency shorter or equal to 10 ms

*SSH

*ALSA

*Utility programs (ls, cp, ... )

Also, it would be nice to achive digital audio return through "what you hear" port without increased latency (on Windows 98 I cannot come below 40 ms if I do so).
All distros seems to be too demanding for that machine. Do I need to configure my own? I do not need any GUI since it is just a server.

A: Latency is mostly a kernel issue, I'd say that newer kernels (and thus newer distributions) will give better results. Distributions are built on the same base software, so what should make a difference is probably more the familiarity with it (you will have to keep it up to date, and having a half-forgotten system around which is managed in an unfamiliar way is a sure recipe for bit rot). Check a minimal install for what you use day to day.

A: Planet CCRMA. This is a Fedora-derived distribution optimized for audio. It includes optional realtime/low-latency patches for the kernel (see this part of the docs for details) but notes that recent kernels have a lot of this work integrated already and so you may actually find it good enough for your needs.
Within whichever distro you chose, you probably want to look at JACK for low-latency audio and MIDI.

A: Gentoo and some patience.
I've run Gentoo on more minimal hardware than that and was able to run a full X11 desktop with minimal WM and Opera Browser on it too. (it was more of an "I wonder if it would work" than a daily use box).
I'd recommend Gentoo and the following performance optimizations to limit CPU usage.

*

*Compile your kernel options manually selecting only the hardware you need.

*Compile specifically for the CPU with appropriate SSE extensions.

*Use BusyBox instead of the normal userland to further reduce memory & CPU loads

*compile the absolute minimum of the modular GPU drivers for X11 3 is usually the most you need. The one specifically for your card (ATI open source), the last resort VGA default, and whichever other fallback driver you prefer.

*Compile your audio kernel drivers to only provide the ones you need.

*Manually compile your userland software by carefully selecting the use flags, avoid any extraneous software that will touch the audio bus.

That may sound like a complex set of things, but to do all that on Gentoo will take just patience, a little medium level technical documentation reading, and determination to not throw in the towel.

A: I use Debian (probably buster) on s plll 600 MHz with 256 MB ram as a streaming client. Works like a charm.


text:
Q: ValueProvider not called for property not in form I'm not having any luck getting a custom value provider to be called for a property on my view model. I'm trying to encapsulate some of the standard request data, such as UserHostAddress into my view model, using a custom value provider.
For example, my view model looks like:
public class MyViewModel
{
    public string Name { get; set; }

    public string IPAddress { get; set; }
}

I want my custom value provider to populate the IPAddress property automatically. Unfortunately, GetValue is never called for that property. This seems strange, as I thought the DefaultModelBinder would iterate over the model's properties and check the value providers for a value.

A: You could have a custom value provider:
public class MyValueProvider : IValueProvider
{
    public bool ContainsPrefix(string prefix)
    {
        return true;
    }

    public ValueProviderResult GetValue(string key)
    {
        if (key.EndsWith("Name"))
        {
            var value = "john";
            return new ValueProviderResult(value, value, CultureInfo.InvariantCulture);
        }
        else if (key.EndsWith("IPAddress"))
        {
            var value = "127.0.0.1";
            return new ValueProviderResult(value, value, CultureInfo.InvariantCulture);
        }

        return null;
    }
}

and a corresponding factory:
public class MyValueProviderFactory : ValueProviderFactory
{
    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        return new MyValueProvider();
    }
}

that will be registered in Application_Start:
ValueProviderFactories.Factories.Add(new MyValueProviderFactory());

and now you could have a controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

and a view:
@model MyViewModel

@Html.DisplayFor(x => x.Name)
@Html.DisplayFor(x => x.IPAddress)

@using (Html.BeginForm())
{
    <button type="submit">OK</button>
}

Your custom value provider will be used by the default model binder.


text:
Q: How to configure and use a bundle in Xcode for iPhone apps? I need to use some audio content in the app I'm coding in Swift with Xcode. That's the first time I try to use a bundle with Xcode.
First I created a local folder on my Mac called "mybundle.bundle" containing my file "mysound.mp3"
I dragged and dropped it in Xcode, the bundle goes to the assets correctly.
But then things get tough. I tried different syntaxes of code to access my file in the bundle.
guard let path = Bundle.main.resourcePath!+"/bundle mybundle.bundle/mysound.mp3" else {
    return print("Error")
}

That code always goes to print "Error".
Also tried this :
guard let url = Bundle.main.url(forResource: "mysound", withExtension: "mp3") else {
   print("Error")
   return
}

Same thing.
Is there any additional setup to do before that main bundle is available for access ?
Thanks a lot !


text:
Q: Limit the width of a JScrollpane containing a JList I created a JList inside a JScrollPane that uses a custom ListCellRenderer. The ListCellRenderer contains a Jlabel that wraps its contents with HTML so the text automatically wraps. Without using the the JScrollPane the wrapping works, but when I use the JScrollPane the text is not wrapped and a horizontal scrollbar appears.
Excerpt of my ListCellRenderer:
public class WorkableCellRenderer implements ListCellRenderer<Workable> {

    @Override
    public final Component getListCellRendererComponent(final JList<? extends Workable> list, final Workable value,
            final int index, final boolean isSelected, final boolean isFocused) {
        JPanel cell = new JPanel();
        cell.setLayout(new BoxLayout(cell, BoxLayout.Y_AXIS));

        // ...

        JPanel pnlDescription = new JPanel();
        cell.add(pnlDescription);
        pnlDescription.setLayout(new BorderLayout());

        JLabel lblDescription =
                new JLabel("
" + value.getDescription() + "
");
        lblDescription.setFont(lblDescription.getFont().deriveFont(Font.PLAIN));
        pnlDescription.add(lblDescription, BorderLayout.CENTER);

        // ...

        return cell;
    }

}

The method that adds my list to the JFrame:
private void addLoadedModulesPanel() {
    pnlLoadedModulesWrapper = new JPanel();
    pnlBottom.add(pnlLoadedModulesWrapper, BorderLayout.CENTER);
    pnlLoadedModulesWrapper.setLayout(new MigLayout("insets 0 5 5 5", "[grow]", "[grow]"));

    pnlLoadedModulesBox = new JPanel();
    pnlLoadedModulesWrapper.add(pnlLoadedModulesBox, "cell 0 0,grow");
    pnlLoadedModulesBox.setLayout(new MigLayout("insets 3", "[grow]", "[grow]"));
    pnlLoadedModulesBox.setBorder(BorderFactory.createTitledBorder("Geladene Module"));

    lstLoadedModules = new JList<Workable>(DefaultWorkableManager.getInstance());
    lstLoadedModules.setCellRenderer(new WorkableCellRenderer());

    final JScrollPane listScroller = new JScrollPane(lstLoadedModules);

    pnlLoadedModulesBox.add(listScroller, "cell 0 0,grow");
}

I think that the problem is the viewport of the JScrollPane because it is bigger than the JScrollPane itself. How can I adjust the viewports width so that it has always the same width as the JScrollPane?
Here is a MCVE which shows my problem:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.border.EmptyBorder;

public class TestFrame extends JFrame {

    private static final long serialVersionUID = -5281126214046039839L;

    public static void main(final String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    final TestFrame frame = new TestFrame();
                    frame.setVisible(true);
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public TestFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200, 500);
        getContentPane().setLayout(new BorderLayout());

        final JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(mainPanel);

        final DefaultListModel<String> lm = new DefaultListModel<>();
        final JList<String> list = new JList<>(lm);
        list.setCellRenderer(new MyListCellRenderer());

        final JScrollPane scrollPane = new JScrollPane(list);
        mainPanel.add(scrollPane);

        for (int i = 1; i < 21; i++) {
            lm.addElement(String.valueOf(i));
        }
    }

    private class MyListCellRenderer implements ListCellRenderer<String> {

        private final JPanel panel = new JPanel();
        private final JLabel label = new JLabel();

        public MyListCellRenderer() {
            panel.setLayout(new BorderLayout());
            panel.setBackground(new Color(16777215));
            panel.add(label);
        }

        @Override
        public Component getListCellRendererComponent(final JList<? extends String> list, final String val,
                final int index, final boolean isSelected, final boolean hasFocus) {
            label.setText("
Item number " + val
                    + " contains some very long text, that ideally should wrap.
");

            if (isSelected) {
                panel.setBackground(new Color(5323));
            } else {
                panel.setBackground(new Color(16777215));
            }

            return panel;
        }
    }

}

A: everything depends ..., then JList in JScrollPane can returns proper getPreferredSize (or directly by using JList.setPrototypeCellValue) for used LayoutManager

*

*whats is value for getPreferredSize returns ListCellRenderer, is this PreferredSize the same for all Items or not

*how is set for JList.setLayoutOrientation()

*is there used limits for visible row or not JList.setVisibleRowCount()

A:
think that the problem is the viewport of the JScrollPane because it is bigger than the JScrollPane itself. How can I adjust the viewports width so that it has always the same width as the JScrollPane?

You need to implement the Scrollable interface on your panel to limit the width of the panel to the width of the scroll pane.
Or you can use the Scrollable Panel which provides a couple of methods that allow you to control this behaviour.


text:
Q: Open File in Modal Dialogue I have this code for open any file from a path. But in this case, the file is opened in a new tab.
I need that response open this file in a modal bootstrap or a dialogue.
File file = new File(path);
String name = file.getName();
int fileSize = (int) file.length();
response.setContentType(contentType);
response.setContentLength(sizeFile);
response.setHeader("Content-Disposition", "inline; filename=\"" + name + "\"");
output = response.getOutputStream();
Files.copy(file.toPath(), output);

Someone has a tip or other method to do?

A: I found a solution.
Using bootstrap 3.3.5
In the HTML a button calls a javascript function 'view' passing as parameters the path to servlet (MSD) and the extension of file:
<button class="btn-doc-sm btn-default" type="button"
    onclick="view('<% out.print(MSD?p=c:/upload/documents/document.docx&action=view)); %>', '<% out.print(ext); %>')" id="view">
   View
</button>

The .js function set the path's value on modal identifyed by pathDoc and open the 'view' modal.
function view(path, ext) {
        var booleanValue;
        if (path !== null) {
            $("#pathDoc").attr("src", path);
            $("#view").modal('show');
            booleanValue = true;
        }
        if (booleanValue !== true) {
            $("#error").modal('show');
        }
    }

Modal:

                        X

The 'variable path' is a link to call the servlet passing the 'real path' and the action as a parameter. The servlet will open a output with the file.
switch(action){
            case "view":
                try {
                    File file = new File(filePath);
                    String name = file.getName();
                    int fileSize = (int) file.length();
                    response.setContentType(action);
                    response.setContentLength(fileSize);
                    response.setHeader("Content-Disposition", "inline; filename=\"" + name + "\"");
                    output = response.getOutputStream();
                    Files.copy(file.toPath(), output);
                    break;
                } catch (Exception ex ) {
                    System.out.println(ex.getMessage());
                } finally {
                    output.close();
                }
                break;

So, when the Modal is called, a link to servlet to open a file is set on src. The servlet search and open the file on output.


text:
Q: Check if post is being published for the first time, or is an already published post being updated I am building an add-on to an events module that checks for availability, since there wasn't a function for that in that module. Now that I have built the logic, there are three emails I will need to send:

*

*One if the post is being submitted for the first time (ie 'New appointment')

*One if the post has been published by the site admin, as normal users won't be able to publish by themselves (ie 'Your appointment has been approved')

*One for if the post has been edited, AFTER it has been published already (ie 'Your appointment has been edited')

I have hooked into save_post and publish_post for those first two, but I want an entirely different email sent upon editing a PUBLISHED post. How can I test for whether the post is already published and this is just an edit, versus it being published for the first time?

A: Hook into edit_post to catch changes. And take a look at wp_transition_post_status() which is called on inserts and updates:
function wp_transition_post_status($new_status, $old_status, $post) {
    do_action('transition_post_status', $new_status, $old_status, $post);
    do_action("{$old_status}_to_{$new_status}", $post);
    do_action("{$new_status}_{$post->post_type}", $post->ID, $post);
}

On publish you hook into

*

*draft_to_publish,

*pending_to_publish and

*auto-draft_to_publish.

For edits hook into publish_to_publish.
Example
A mini plugin that notifies all authors during post publish or edit.
<?php
/**
 * Plugin Name: (#56779) Notify authors
 */
add_action( 'transition_post_status', 'wpse_56779_notify_authors', 10, 3 );
function wpse_56779_notify_authors( $new_status, $old_status, $post )
{
    if ( 'publish' !== $new_status )
        return;

    $subject = 'publish' === $old_status
        ? __( 'Edited: %s', 'your_textdomain' )
        : __( 'New post: %s', 'your_textdomain' );

    $authors = new WP_User_Query( array( 'role' => 'Author' ) );
    foreach ( $authors as $author )
    {
        wp_mail(
            $author->user_email,
            sprintf( $subject, $post->post_title ),
            $post->post_content
            // Headers
            // Attachments
        );
        // Slow down
        sleep( 5 );
    }
}

A: Use this....
function save_func($ID, $post,$update) {

   if($update == false) {
     // do something if its first time publish
   } else {
     // Do something if its update
   }
}

add_action( 'save_post', 'save_func', 10, 3 );


text:
Q: OpenGL only most recent vertex draw displayed New to OpenGL, tried to draw 2 rectangles separately using a rectangle draw function.  Using openGL 3, GLFW and GLEW.  I made a function called drawBox to draw a rectangle.
My problem here is that if I call it more than once in the main loop, only the last rectangle drawn is displayed.
void drawBox(float x, float y, float w, float h, float r, float g, float b) {
GLfloat colours[15], vertices[10] = {
    x, y,
    x, y + h,
    x + w, y + h,
    x + w, y,
    x, y
};
for(int i = 0; i < 5; ++i) {
    colours[3*i] = (GLfloat)r;
    colours[3*i + 1] = (GLfloat)g;
    colours[3*i + 2] = (GLfloat)b;
}
GLuint buff[2];
glGenBuffers(2, buff);

glBindBuffer(GL_ARRAY_BUFFER, buff[1]);
glBufferData(GL_ARRAY_BUFFER, 15*sizeof(GLfloat), colours, GL_STREAM_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(1);

glBindBuffer(GL_ARRAY_BUFFER, buff[0]);
glBufferData(GL_ARRAY_BUFFER, 10*sizeof(GLfloat), vertices, GL_STREAM_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(0);

glClear( GL_COLOR_BUFFER_BIT );
glUseProgram(defaultShader);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 5);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDeleteBuffers(2, buff);
}

What would I need to change to make this function display a rectangle regardless of past draws.  Assume all z-indices are 0 and overlap never happens.  Assume that I may have to make drawCircle calls or drawTriangle or something in between 2 calls to drawBox.

A: You should call glClear( GL_COLOR_BUFFER_BIT ); only once, before all draw*() calls.


text:
Q: composer.json requires illuminate/support ^5.2 I try to install:

composer require laravel-notification-channels/pusher-push-notifications

package to my laravel project. But i Keep receive this error

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Root composer.json requires illuminate/support ^5.2, found illuminate/support[v5.2.0, ..., 5.8.x-dev] but these were not loaded, likely because it conflicts with another require.
and here is my composer.json:
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.2.5",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^1.0",
        "guzzlehttp/guzzle": "^6.3",
        "hekmatinasser/verta": "^1.10",
        "intervention/image": "^2.5",
        "laravel/framework": "^7.0",
        "laravel/tinker": "^2.0",
        "laravel/ui": "^2.0",
        "morilog/jalali": "3.*",
        "shetabit/payment": "^4.0",
        "tzsk/sms": "^4.0",
        "illuminate/support" : "^5.2",
        "econea/nusoap": "v0.9.5.*",
        "rackspace/php-opencloud": "dev-master"

    },
    "require-dev": {
        "facade/ignition": "^2.0",
        "fzaninotto/faker": "^1.9.1",
        "mockery/mockery": "^1.3.1",
        "nunomaduro/collision": "^4.1",
        "phpunit/phpunit": "^8.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

I am a beginner in laravel. Hope anyone provide the solution. Thanks in advance.

A: Remove illuminate/support from your composer.json file. You are trying to use laravel/framework ^7.0 which would provide you with illuminate/support for ^7.0 as its part of the framework.


text:
Q: Browser detection versus capability detection for IE 6 select / z-index bug I have a written a jquery plug-in which pops-up a div section on hover over an element, and I need to deal with the "select z-index" bug in IE6 (http://blogs.msdn.com/ie/archive/2006/01/17/514076.aspx). So, if running in IE6, my code needs to hide some select boxes on the page, when the pop-up div is visible.
My question is: In trying to follow best practices, I would like to avoid detecting the actual browser version and instead do a 'feature-test", to determine whether I am in an affected browser. (http://ejohn.org/blog/future-proofing-javascript-libraries). Is there any way to do this? Or should I just treat this as a special case, detect the browser and handle IE6?

A: I use this snippet all the time. It's cool because it checks only for IE6. But be aware that if you using any code compression tools that removes HTML comments this won't work.
<!-- THESE LINES ARE NOT NORMAL HTML COMMENTS! They are instructions that only IE6 can understand. -->
<!--[if IE 6]>
    <script type="text/javascript">
        // redirect to the Default error page passing a custom error code.
        window.location = '/your/redirect/page';
    </script>

Cheers.

A: Use the bgiframe plugin to fix the bug without having to hide the select boxes on the page.


text:
Q: How to Group by 28 day Period and District in R I have the following data in a CSV:
OBJECTID,District,Zone,year_value,FROM_DATE,SUM_Crime
1,Northwestern,Not in Zone,2019,2/6/2019,4
2,Northwestern,Zone 30,2019,2/7/2019,6
3,Northwestern,Zone 40,2019,2/8/2019,5
4,Northwestern,Zone 30,2019,2/9/2019,2
5,Northwestern,Not in Zone,2019,2/10/2019,4
6,Northwestern,Zone 40,2019,2/11/2019,4
7,Northwestern,Zone 30,2019,2/12/2019,0

How would I group this every 3 days, starting on the 6th in R? The end result would look like the following (the values are the Sum_Crime over the 3 day period):
Zone,2/6/2019 - 2/8/2019,2/9/2019 - 2/11/2019,2/12/2019 - 2/13/2019

Not in Zone,4,4,
Zone 30,6,2,0
Zone 40,5,4,

However this is for only one District (northwestern), ideally it would do this by each district I have.
Thank you.

A: Several ways to attack this.
First, we need to identify a 3-day period for each. To do so, I'll create a datevec which is a sequence of days.
dat$RealDate <- as.Date(dat$FROM_DATE, format = "%m/%d/%Y")
datevec <- seq(min(dat$RealDate), max(dat$RealDate) + 3, by = 3)
dat$Period1 <- cut(dat$RealDate, datevec,
                   labels = paste(datevec[-length(datevec)], datevec[-1], sep = " - "))
dat
#   OBJECTID     District        Zone year_value FROM_DATE SUM_Crime   RealDate                 Period1
# 1        1 Northwestern Not in Zone       2019  2/6/2019         4 2019-02-06 2019-02-06 - 2019-02-09
# 2        2 Northwestern     Zone 30       2019  2/7/2019         6 2019-02-07 2019-02-06 - 2019-02-09
# 3        3 Northwestern     Zone 40       2019  2/8/2019         5 2019-02-08 2019-02-06 - 2019-02-09
# 4        4 Northwestern     Zone 30       2019  2/9/2019         2 2019-02-09 2019-02-09 - 2019-02-12
# 5        5 Northwestern Not in Zone       2019 2/10/2019         4 2019-02-10 2019-02-09 - 2019-02-12
# 6        6 Northwestern     Zone 40       2019 2/11/2019         4 2019-02-11 2019-02-09 - 2019-02-12
# 7        7 Northwestern     Zone 30       2019 2/12/2019         0 2019-02-12 2019-02-12 - 2019-02-15

If you want to keep the dates formatted as you have them (which are not real Dates in R), then we can add a second column for that format:
datevec2 <- format(datevec, format = "%m/%d/%Y")
dat$Period2 <- cut(dat$RealDate, datevec,
                   labels = paste(datevec2[-length(datevec2)], datevec2[-1], sep = " - "))
dat
#   OBJECTID     District        Zone year_value FROM_DATE SUM_Crime   RealDate                 Period1                 Period2
# 1        1 Northwestern Not in Zone       2019  2/6/2019         4 2019-02-06 2019-02-06 - 2019-02-09 02/06/2019 - 02/09/2019
# 2        2 Northwestern     Zone 30       2019  2/7/2019         6 2019-02-07 2019-02-06 - 2019-02-09 02/06/2019 - 02/09/2019
# 3        3 Northwestern     Zone 40       2019  2/8/2019         5 2019-02-08 2019-02-06 - 2019-02-09 02/06/2019 - 02/09/2019
# 4        4 Northwestern     Zone 30       2019  2/9/2019         2 2019-02-09 2019-02-09 - 2019-02-12 02/09/2019 - 02/12/2019
# 5        5 Northwestern Not in Zone       2019 2/10/2019         4 2019-02-10 2019-02-09 - 2019-02-12 02/09/2019 - 02/12/2019
# 6        6 Northwestern     Zone 40       2019 2/11/2019         4 2019-02-11 2019-02-09 - 2019-02-12 02/09/2019 - 02/12/2019
# 7        7 Northwestern     Zone 30       2019 2/12/2019         0 2019-02-12 2019-02-12 - 2019-02-15 02/12/2019 - 02/15/2019

From here, base R aggregation:
ag <- aggregate(SUM_Crime ~ Zone + Period2, data = dat, FUN = sum)
ag
#          Zone                 Period2 SUM_Crime
# 1 Not in Zone 02/06/2019 - 02/09/2019         4
# 2     Zone 30 02/06/2019 - 02/09/2019         6
# 3     Zone 40 02/06/2019 - 02/09/2019         5
# 4 Not in Zone 02/09/2019 - 02/12/2019         4
# 5     Zone 30 02/09/2019 - 02/12/2019         2
# 6     Zone 40 02/09/2019 - 02/12/2019         4
# 7     Zone 30 02/12/2019 - 02/15/2019         0
xtabs( SUM_Crime ~ Zone + Period2, data = ag)
#              Period2
# Zone          02/06/2019 - 02/09/2019 02/09/2019 - 02/12/2019 02/12/2019 - 02/15/2019
#   Not in Zone                       4                       4                       0
#   Zone 30                           6                       2                       0
#   Zone 40                           5                       4                       0

You can also put this into a dplyr pipe if you'd like:
library(dplyr)
library(tidyr) # pivot_wider
dat2 <- dat %>%
  mutate(RealDate = as.Date(FROM_DATE, format = "%m/%d/%Y"))
datevec <- seq(min(dat2$RealDate), max(dat2$RealDate) + 3, by = 3)
dat2 %>%
  mutate(
    Period1 = cut(RealDate, datevec,
                  labels = paste(datevec[-length(datevec)], datevec[-1], sep = " - "))
  ) %>%
  group_by(Zone, Period1) %>%
  summarize(SUM_Crime = sum(SUM_Crime)) %>%
  ungroup() %>%
  filter(SUM_Crime > 0) %>%
  pivot_wider(., "Zone", names_from = "Period1", values_from = "SUM_Crime")
# # A tibble: 3 x 3
#   Zone        `2019-02-06 - 2019-02-09` `2019-02-09 - 2019-02-12`
#   <chr>                           <int>                     <int>
# 1 Not in Zone                         4                         4
# 2 Zone 30                             6                         2
# 3 Zone 40                             5                         4

Data
dat <- read.csv(header = TRUE, stringsAsFactors = FALSE, text = "
OBJECTID,District,Zone,year_value,FROM_DATE,SUM_Crime
1,Northwestern,Not in Zone,2019,2/6/2019,4
2,Northwestern,Zone 30,2019,2/7/2019,6
3,Northwestern,Zone 40,2019,2/8/2019,5
4,Northwestern,Zone 30,2019,2/9/2019,2
5,Northwestern,Not in Zone,2019,2/10/2019,4
6,Northwestern,Zone 40,2019,2/11/2019,4
7,Northwestern,Zone 30,2019,2/12/2019,0")

A: One approach might be to calculate Period of 3 days starting with the first date. A Date_Range can be calculated between the first and last of these 3 days. Then pivot_wider would put data into long form.
library(tidyverse)

df2 <- df %>%
  group_by(Period = rep(row_number(), length.out = n(), each = 3)) %>%
  mutate(Date_Range = paste(first(FROM_DATE), "-", last(FROM_DATE))) %>%
  pivot_wider(id_cols = c(District, Zone), names_from = Date_Range, values_from = SUM_Crime)

Then to put into comma separated format, you can add:
cat(format_csv(df2))

Output
District,Zone,2/6/2019 - 2/8/2019,2/9/2019 - 2/11/2019,2/12/2019 - 2/12/2019
Northwestern,Not in Zone,4,4,NA
Northwestern,Zone 30,6,2,0
Northwestern,Zone 40,5,4,NA

A: Code:
library('data.table')
setDT(df)[, FROM_DATE := as.Date(FROM_DATE, "%m/%d/%y")]
date_seq <- seq(from = as.Date("2020-02-06"), to =max(df$FROM_DATE), by = 3)

df1 <- df[FROM_DATE >= as.Date("2020-02-06"), .(Zone, SUM_Crime,
                                                DATE_INTERVAL = paste0(date_seq[findInterval(x = FROM_DATE, vec = date_seq)], " - ",
                                                                       date_seq[findInterval(x = FROM_DATE, vec = date_seq)]+2)),
          by = .(District)]
dcast(df1, Zone + District ~ DATE_INTERVAL, value.var = 'SUM_Crime', fill = NA)
#           Zone     District 2020-02-06 - 2020-02-08 2020-02-09 - 2020-02-11 2020-02-12 - 2020-02-14
# 1: Not in Zone Northwestern                       4                       4                      NA
# 2:     Zone 30 Northwestern                       6                       2                       0
# 3:     Zone 40 Northwestern                       5                       4                      NA

Data:
df <- read.table(text='OBJECTID,District,Zone,year_value,FROM_DATE,SUM_Crime
1,Northwestern,Not in Zone,2019,2/6/2019,4
                 2,Northwestern,Zone 30,2019,2/7/2019,6
                 3,Northwestern,Zone 40,2019,2/8/2019,5
                 4,Northwestern,Zone 30,2019,2/9/2019,2
                 5,Northwestern,Not in Zone,2019,2/10/2019,4
                 6,Northwestern,Zone 40,2019,2/11/2019,4
                 7,Northwestern,Zone 30,2019,2/12/2019,0', header = TRUE, stringsAsFactors = FALSE, sep = ",")


text:
Q: devtools::test() in parallel?
I have a test suite using testthat containing several files in R/tests and I would like to test them in parallel to speed up testing. Are there any implemented methods in devtools, testthat, or elsewhere towards this end?
I tried doing it "manually" using the future packages, but the text rendering of stdout is unreadable:
# Get a vector of test files without "test-" and ".R"
test_files = list.files("tests/testthat", "test-")
test_filters = stringr::str_replace_all(test_files, c("test-|\\.R"), "")

# Run test for each file in parallel
future::plan(future::multiprocess)
future.apply::future_mapply(devtools::test, filter = test_filters)

A: With the caveat of a long-time user of RUnit who more recently switched to tinytest, the feature you are looking for exists in tinytest already. I would think that someone has or may build a parallel test runner for testthat at some point, but in the 'here and now' we do have tinytest with very fine behavior, good documentation and leads for converting from RUnit or testthat.
My favourite features of tinytest are the default installation of tests in the package, the lack of other dependencies and the parallel runner.
And another caveat coming: I like the command-line for this way more than an R prompt because there may always be some side-effects of some form.  So I added a little test runner wrappre tt.r to littler:
edd@rob:~$ tt.r -h
Usage: tt.r [-h] [-x] [-a] [-b] [-d] [-f] [-n NCPUS] [-p] [-s] [-z] [ARG...]

-a --all            use test_all mode [default: FALSE]
-b --build          use build-install-test mode [default: FALSE]
-d --directory      use directory mode [default: FALSE]
-f --file           use file mode [default: FALSE]
-n --ncpus NCPUS    use 'ncpus' in parallel [default: getOption]
-p --package        use package mode [default: FALSE]
-s --silent         use silent and do not print result [default: FALSE]
-z --effects        suppress side effects [default: FALSE]
-h --help           show this help text
-x --usage          show help and short example usage
edd@rob:~$

(I should add here that writing such wrapper is easy thanks to docopt.)
And then we simply do
edd@rob:~$ tt.r -n 4 -p anytime
starting worker pid=642068 on localhost:11092 at 17:11:25.636
starting worker pid=642067 on localhost:11092 at 17:11:25.654
starting worker pid=642065 on localhost:11092 at 17:11:25.687
starting worker pid=642066 on localhost:11092 at 17:11:25.689
Running test_gh_issue_12.R............    2 tests OK
Running test_gh_issue_56.R............    7 tests OK
Running test_gh_issue_33.R............    2 tests OK

Running test_all_formats.R............    0 tests    ris or Windows or Release
Running test_assertions.R.............    2 tests OK
Running test_calc_unique.R............    4 tests OK
Running test_gh_issue_100.R...........    2 tests OK
Running test_simple.R.................   34 tests OK
Running test_utilities.R..............    2 tests OK
Running test_bulk.R................... 2328 tests OK
[1] "All ok, 2383 results"
edd@rob:~$

You see a little bit of output got swallowed there.
You can of course also run this by hand from R:
R> tinytest::test_package("anytime", ncpu=4)
starting worker pid=651865 on localhost:11762 at 17:14:45.970
starting worker pid=651864 on localhost:11762 at 17:14:45.980
starting worker pid=651863 on localhost:11762 at 17:14:45.980
starting worker pid=651862 on localhost:11762 at 17:14:45.984
Running test_gh_issue_12.R............    2 tests
 Exited 'test_all_formats.R' at line 24. Skipping Solaris or Windows or ReleaseOK
Running test_all_formats.R............    0 tests
Running test_gh_issue_56.R............    7 tests OK
Running test_assertions.R.............    2 tests OK
Running test_gh_issue_33.R............    2 tests OK
Running test_calc_unique.R............    4 tests OK
Running test_gh_issue_100.R...........    2 tests OK
Running test_simple.R.................   34 tests OK
Running test_utilities.R..............    2 tests OK
Running test_bulk.R................... 2328 tests OK
[1] "All ok, 2383 results"
R>

There are other runners for file, directory, a build+install+test cycle and more.  And hey if after all of this you still don't like it Mark will give you your money back :)
PS Here and eg in Rcpp I have some tests "dimmed" because they produce an ungodly amount of cmdline noise so that only happens in package tests when the opt-in var is set.  Hence the few 'zero tests run' above. That is my setup and not a tinytest issue.

A: The new testthat >= 3.0 introduces parallel tests. You just need to add to your description
Config/testthat/parallel: true
Config/testthat/edition: 3

and devtools::test() should work in parallel.
See the parallel vignette. for more information


text:
Q: I don't understand the example of closure for loop error from mdn 1.MDN example
The code snippet below assign a function that display the help text to each text field when focus, here is the link to JsFiddle: https://jsfiddle.net/v7gjv/8164/
function showHelp(help) {
          document.getElementById('help').textContent = help;
        }

        function setupHelp() {
          var helpText = [
              {'id': 'email', 'help': 'Your e-mail address'},
              {'id': 'name', 'help': 'Your full name'},
              {'id': 'age', 'help': 'Your age (you must be over 16)'}
            ];

          for (var i = 0; i < helpText.length; i++) {
            var item = helpText[i];
            document.getElementById(item.id).onfocus = function() {
              showHelp(item.help);
            }
          }
        }

        setupHelp();

But it will only display the last help text no matter which of the three input is focused. MDN says the function assigned to all three inputs is a closure, so they share the same reference to variable helpText, when the loop's over, i=2, so all three input have reference to the last item in helpText.
2.My test
The part where i dont understand is why all three inputs have the same reference to the same variable item
I make a test like this

(function() {
  function closure() {
    var i = 0;
    return {
      display: function() {
        console.log(i);
      },
      add: function() {
        i += 1;
      }
    }
  }

  var a = closure();
  var b = closure();

  a.add();
  a.display(); //return 1
  b.display(); //return 0
})()

3.My thoughts and questions
From the test, a and b have different i variables, i from a changed but b remain the same.
But in the for loop, all inputs point to the same variable, thus the for loop change the value i causing all inputs point to the last item in helpText
So my question is why do they points to the same variable but in my test a,b don't.

A: In your example, you're declaring the variable i inside the closure method. When you are calling closure a second time, a new i variable is created in the scope of that specific function execution, and the returned object is bound to that variable.
Try moving the variable declaration outside of the closure function and you will see that the result is the same as the MDN example.


text:
Q: javascript: how to continuously load a page I know it sounds a bit counterintuitive,
but I'm looking for a way to have a webpage continuously loading. With this I mean I want the favicon on chrome for instance, keeping the blue animated gif.
Any suggestion?

A: I would do something like this:

Make a .php file called loader.php, and just enter something like this:
<? sleep(6); ?>

Then in your main page, use this:
// DONT FORGET TO INCLUDE JQUERY SOMEWHERE IN YOUR HEADER

This file is loaded in the first iFrame. It will be done after 6 seconds, but you will change the content of the second iFrame before that time: calling the same file after 4 seconds. Just repeat this process. The reason to use two iframes and a sleep of 6 seconds is to make sure the iframe WILL manage to load (since each div will be reloaded every 8 (4 + 4) seconds) otherwise the browser will/might crash. By using two iframes, one will always be loading while the other is allowed to finish. The loader.php?timer=<number> is used to stop the browser from caching the page (though I think it shouldn't be able to do this anyway since the PHP sleep() function is always slowing down the loading, but just to be safe)

A: You can inject an iframe, and use document.open():
var f = document.createElement('iframe');
f.style.display = 'none';
document.body.appendChild(f);
f.contentWindow.document.open();
console.log(f.contentWindow.document.readyState); // "loading"

To stop the loading, call f.contentWindow.document.close();.
The previous worked very well in Firefox 10. In Chrome, this does not work. To trick Chrome, the following can be used:
var f = document.createElement('iframe');
f.onload = function(){
    if (f.parentNode) setTimeout(function() {
        f.contentWindow.location.reload();
    },40);
};
f.src = 'about:blank';
f.style.display = 'none';
document.body.appendChild(f);

To stop the spinning in this case, remove the  from the document:
f.parentNode.removeChild(f);


text:
Q: Wildfly 10 ClassNotFoundException: org.jboss.logging.appender.DailyRollingFileAppender I'm using Wildfly 10 in standalone mode,  when I start Wildfly, I saw the the error message saying
java.lang.ClassNotFoundException: org.jboss.logging.appender.DailyRollingFileAppender from [Module "org.jboss.log4j.logmanager:main" from local module loader @33e5ccce (finder: local module finder @5a42bbf4 (roots: /opt/jboss/modules,/opt/jboss/modules/system/layers/base))]

I Unzipped the jar files under modules directory, it seems that the DailyRollingFileAppender class is under org.apache.log4j, not org.jboss.logging.  I'm not sure if I need to do any configurations.
And another thing is: this error message only shows up on console, not in my log file, not sure why. Other error messages showed up in my log file.
The following is the stack trace:
10:26:21,167 ERROR [stderr] log4j:ERROR Could not create an Appender. Reported error follows.
10:26:21,174 ERROR [stderr] java.lang.ClassNotFoundException: org.jboss.logging.appender.DailyRollingFileAppender from [Module "org.jboss.log4j.logmanager:main" from local module loader @33e5ccce (finder: local module finder @5a42bbf4 (roots: /opt/jboss/modules,/opt/jboss/modules/system/layers/base))]
10:26:21,174 ERROR [stderr]     at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
10:26:21,174 ERROR [stderr]     at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
10:26:21,174 ERROR [stderr]     at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
10:26:21,174 ERROR [stderr]     at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
10:26:21,174 ERROR [stderr]     at java.lang.Class.forName0(Native Method)
10:26:21,175 ERROR [stderr]     at java.lang.Class.forName(Class.java:264)
10:26:21,175 ERROR [stderr]     at org.apache.log4j.helpers.Loader.loadClass(Loader.java:198)
10:26:21,175 ERROR [stderr]     at org.apache.log4j.xml.DOMConfigurator.parseAppender(DOMConfigurator.java:247)
10:26:21,175 ERROR [stderr]     at org.apache.log4j.xml.DOMConfigurator.findAppenderByName(DOMConfigurator.java:176)
10:26:21,175 ERROR [stderr]     at org.apache.log4j.xml.DOMConfigurator.findAppenderByReference(DOMConfigurator.java:191)
10:26:21,175 ERROR [stderr]     at org.apache.log4j.xml.DOMConfigurator.parseChildrenOfLoggerElement(DOMConfigurator.java:523)
10:26:21,175 ERROR [stderr]     at org.apache.log4j.xml.DOMConfigurator.parseRoot(DOMConfigurator.java:492)
10:26:21,175 ERROR [stderr]     at org.apache.log4j.xml.DOMConfigurator.parse(DOMConfigurator.java:1001)
10:26:21,175 ERROR [stderr]     at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:867)
10:26:21,176 ERROR [stderr]     at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:794)
10:26:21,176 ERROR [stderr]     at org.jboss.as.logging.deployments.LoggingConfigDeploymentProcessor.configure(LoggingConfigDeploymentProcessor.java:238)
10:26:21,176 ERROR [stderr]     at org.jboss.as.logging.deployments.LoggingConfigDeploymentProcessor.processDeployment(LoggingConfigDeploymentProcessor.java:114)
10:26:21,176 ERROR [stderr]     at org.jboss.as.logging.deployments.LoggingConfigDeploymentProcessor.processDeployment(LoggingConfigDeploymentProcessor.java:144)
10:26:21,176 ERROR [stderr]     at org.jboss.as.logging.deployments.AbstractLoggingDeploymentProcessor.deploy(AbstractLoggingDeploymentProcessor.java:67)
10:26:21,176 ERROR [stderr]     at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:147)
10:26:21,176 ERROR [stderr]     at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
10:26:21,176 ERROR [stderr]     at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
10:26:21,176 ERROR [stderr]     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
10:26:21,177 ERROR [stderr]     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
10:26:21,177 ERROR [stderr]     at java.lang.Thread.run(Thread.java:745)

Thanks, Helen

A: I got help from Jboss community, I had an app which has log4j.xml packaged inside the war file and used org.jboss.logging.appender.DailyRollingFileAppender. This log4j.xml caused this error message.  Setting use-deployment-logging-config to be false in standalone.xml logging subsystem solved this problem.
Helen


text:
Q: Is there a way to take multiple means and store them in a vector in R I would like an easier way to do what this does
MEAN1 = mean(CIS2017$USHRWK[CIS2017$AGE == 1 | CIS2017$ALFST == 1], na.rm = TRUE)
MEAN2 = mean(CIS2017$USHRWK[CIS2017$AGE == 2 | CIS2017$ALFST == 1], na.rm = TRUE)
MEAN3 = mean(CIS2017$USHRWK[CIS2017$AGE == 3 | CIS2017$ALFST == 1], na.rm = TRUE)
MEAN4 = mean(CIS2017$USHRWK[CIS2017$AGE == 4 | CIS2017$ALFST == 1], na.rm = TRUE)
MEAN5 = mean(CIS2017$USHRWK[CIS2017$AGE == 5 | CIS2017$ALFST == 1], na.rm = TRUE)
MEAN6 = mean(CIS2017$USHRWK[CIS2017$AGE == 6 | CIS2017$ALFST == 1], na.rm = TRUE)
MEAN7 = mean(CIS2017$USHRWK[CIS2017$AGE == 7 | CIS2017$ALFST == 1], na.rm = TRUE)
MEAN8 = mean(CIS2017$USHRWK[CIS2017$AGE == 8 | CIS2017$ALFST == 1], na.rm = TRUE)
MEAN9 = mean(CIS2017$USHRWK[CIS2017$AGE == 9 | CIS2017$ALFST == 1], na.rm = TRUE)

Doing the following doesn't seem to work
AGE_GROUPS = seq(1, 16, 1)
MEAN = mean(CIS2017$USHRWK[CIS2017$AGE == AGE_GROUPS | CIS2017$ALFSTN == 1], na.rm = TRUE)

A: Maybe this is what you are after
list2env(setNames(
  lapply(AGE_GROUPS,
       function(k) mean(CIS2017$USHRWK[CIS2017$AGE == k | CIS2017$ALFSTN == 1], na.rm = TRUE)),
  paste("MEAN",AGE_GROUPS)),envir = .GlobalEnv)

or
v <- setNames(
  sapply(AGE_GROUPS,
       function(k) mean(CIS2017$USHRWK[CIS2017$AGE == k | CIS2017$ALFSTN == 1], na.rm = TRUE)),
  paste("MEAN",AGE_GROUPS))


text:
Q: Excel Formula to count arguments in a sum I've been given a spreadsheet with a series of values in a column, made from summing individual numbers. e.g. =1+2+3
I'm looking for a way to count the number of numbers that have been summed (i.e. 3)?
But I can't seem to find any Excel formulas which will run on other formulas. Anything like LEN just runs on the result, not the formula.
Thanks.

A: If the formulas are like your example then you can use FORMULATEXT function like this
=LEN(FORMULATEXT(A2))-LEN(SUBSTITUTE(FORMULATEXT(A2),"+",""))+1
That counts the number of "+"s in your formula and adds 1 which should be the count of numbers added
FORMULATEXT function is available in Excel 2013 and later versions


text:
Q: Crash after updating Facebook Audience Network 6.5 I had recently updated SDK of Facebook Audience Network to 6.5 and am suddenly facing crash, java.lang.IllegalArgumentException: (Wrong state class, expecting View State but received class com.facebook.ads.internal.util.parcelable.WrappedParcelable instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/0x3.
I am not able to see this id in my code there is no mapping file, any help would be greatly appreciated.


text:
Q: is Increment/Decrement Optional in a for loop in JavaScript? Is Increment/Decrement Optional in a for loop in JavaScript?
for(var i=0;i<10;)
{
  i++;
}

is this code valid?.

A: I believe so, for loops are designed to work well without this, you would just have to put it at the end of the loop

A: Yes but this is classic for loop
for(var i=0;i<10;i++)
{
// do somthing
}

A: Tested on W3School's preexisting code, yes it is.
Clear it then paste the code below (or edit out the i++ yourself):
<!DOCTYPE html>

JavaScript For Loop

A: You can use a while loop.
var i = 0;
while(i<10){
 i++;
}

Basically, it is the same just in my opinion looks a bit cleaner.

A: Yes all 3 statements are optional. You can vary your for loop according to the output you want from it.
The following code would result in an infinite loop:
for(;;){
    // Code block
}

A: There is a for loop that could be used and there is foreach as well. Reference example below:
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
In your case, it could be
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.forEach(number => console.log(number));


text:
Q: How do you typedef a function pointer type with parameter pack arguments What's the syntax to typdef a parameter pack into a function pointer?
I want to be able to typedef a function pointer, but the compiler complains when I do something like this
template< class ...Args >
struct method { typedef typename void(*type)(void*, Args...); };

with a message along the lines of error: expected nested-name-specifier before 'void'

A: It works fine without typename. http://coliru.stacked-crooked.com/a/64b3fbec9276dd70
You shouldn't use typename here because there is no nested-name-specifier.

A: I suppose that you should remove typename from the typedef line
template <typename ... Args>
struct method
 { typedef void(*type)(void*, Args...); };

Another solution could be using using instead of typedef (IMHO is a little clearer)
template <typename ... Args>
struct method
 { using type = void(*)(void*, Args...); };


text:
Q: Can't run official Docker tutorial container: npm ERR! missing script: start I'm trying to go through this part 2 of Docker's tutorial.
Here is my issue:
After creating successfully an image for the app, I try the command line (sudo) docker run --publish 8000:8080 --detach --name bb bulletinboard:1.0 which should run a container and allow me to access the app at localhost:8000.
But when checking out docker ps, nothing, so I used docker ps -a to find back my container, and find it with STATUS Exited (1).
Then I try docker logs bb to find out more, and get this:

npm ERR! missing script: start.

This is more than surprising, knowing that it comes from the docs, I don't know what to do next. If anybody has any clue, it would be really nice. Thank you in advance

A: The error message means that npm can't find a package.json file which includes a script named start. So make sure that your package.json contains a script named start! Might already be the issue.
// Simple package.json example that contains a script with name test.
{
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
}

When you look at the tutorial's dockerfile:
This makes sure that the commands are executed in a specific folder, e.g. copying files:
# Set the working directory.
WORKDIR /usr/src/app

This makes sure that the package.json file is copied into the workdir:
# Copy the file from your host to your current location.
COPY package.json .

Here it defines that npm start will be executed when you run the container:
# Run the specified command within the container.
CMD [ "npm", "start" ]

To further investigate I would execute the following command to start the container:
docker run -it -d <container-id> /bin/sh

Then go to the workdir and check if the app can be started manually:
# Go to workdir
cd /usr/src/app
# Here check if the package.json is part of the directory.
ls
# Manually run npm script
npm start

A: It worked to add these lines to package.json
  "scripts": {
  "start": "node server.js"
}

and the remake a new image etc...

A: I ran to the same issue, but the missing script this time is "debug"
there is no note in the package.json about this script only this:
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },

however the docker-compose.dev.yml contains this
command: npm run debug
apparently the npm that I am using is a bit different, because this is the file generated by $npm init -y command.
$npm --version
6.14.4
$node --version
v10.19.0


text:
Q: Get id Corrdinate javascript leaflet How can I get the ID I gave to a polygon by clicking?
var geojson = {
                "type": "FeatureCollection",
                "features": [{
                    "postalAreaId": item.PostalAreaId,
                    "type": "Feature",
                    "properties": {
                        "name": "Coors Field",
                        "amenity": "Baseball Stadium",
                        "popupContent": "This is where the Rockies play!"
                    },
                    "geometry": {
                        "type": "Polygon",
                        "coordinates": []
                    }
                }]
            };

A: You can use the OnEachFeature option when you draw your features on the map... A possible solution would be:

var geojson = {
    "type": "FeatureCollection",
    "features": [
        {
            "postalAreaId": 1,
            "type": "Feature",
            "properties": {
                "name": "Coors Field",
                "amenity": "Baseball Stadium",
                "popupContent": "This is where the Rockies play!"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [-105.00341892242432, 39.75383843460583],
            }
        },
        {
            "postalAreaId": 2,
            "type": "Feature",
            "properties": {
                "name": "Coors Field",
                "amenity": "Baseball Stadium",
                "popupContent": "This is where the Rockies play!"
            },
            "geometry": {
                "type": "Point",
                "coordinates":     [-105.0008225440979, 39.751891803969535],
            }
        }]
};
var map = L.map('map').setView([39.74739, -105], 13);

L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
    maxZoom: 18,
    attribution: 'Map data © OpenStreetMap contributors, ' +
    'Imagery © Mapbox',
    id: 'mapbox/light-v9',
    tileSize: 512,
    zoomOffset: -1
}).addTo(map);

function onEachFeature(feature, layer) {
    layer.on('click', function (e) {
        alert(feature.postalAreaId)
    })
}

L.geoJSON(geojson, {
    onEachFeature: onEachFeature
}).addTo(map);
html, body {
    height: 100%;
    margin: 0;
}

#map {
    width: 600px;
    height: 400px;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin=""/>

In this case, I'm using click but you could also use mousein and mouseout. Basically, inside the onEachFeature function you're adding a listener that will check events that happen on each feature of the map.


text:
Q: PartCover console produces empty output xml I'm using partcover to produce codecoverage for a bunch of mstest powered unit tests.
I use the command line:
PartCover.exe --target "c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe" --target-args "/testcontainer:c:\CrusieControlProjects\AcademyPro\AcademyTests\bin\Release\AcademyTests.dll" --include [AcademyPro*]*

This runs, all tests pass, but I end up with the output:
Results file:      C:\Program Files\Gubka Bob\PartCover .NET 2.3\TestResults\Administrator_PSLV22 2009-03-31 17_54_18.trx
Run Configuration: Default Run Configuration
Target PageFaultCount: 10565
Target PagefileUsage: 27631616
Target PeakPagefileUsage: 31297536
Target PeakWorkingSetSize: 31498240
Target QuotaNonPagedPoolUsage: 8180
Target QuotaPagedPoolUsage: 217124
Target QuotaPeakNonPagedPoolUsage: 13012
Target QuotaPeakPagedPoolUsage: 255524
Target WorkingSetSize: 30310400
request target shutdown
<PartCoverReport date="2009-03-31T18:00:36.7676250+01:00" />

When I run with the --output command the xml file ends up with just
<PartCoverReport date="2009-03-31T18:00:36.7676250+01:00" />

Why might this be happening?

A: To fix this I ended up downgrading.
I was using version 2.3 (which is a dev build) and switched to version 2.2.
Now the tests run fine and I get sensible coverage data.
Maybe that will help someone.

A: I was having a similar problem with NUnit on x64. The problem was that I was using nunit-console.exe (AnyCPU). Switching to nunit-console-x86.exe (explicitly 32-bit) solved the problem.
I don't have access to an environment with MSTest, but if the executable you're referencing is AnyCPU, you might look for an explicitly 32-bit version of it on your system. Worst case, you could create one using CorFlags.


text:
Q: How can I get the value of a specific key in a map? So lets say I have a map
let queue = new Map()
queue.set("the key", "the value")

now if I have the key how do get the values which are assigned to the key?
this is a genuine doubt I have tried queue.get("the key") but it doesnt seem to work
Ok my bad I forgot to mention some important details, I have exported the queue and imported it to anoter file with module.exports and require()
module.exports.Words = (queue)

and then in the second file
let Something = require("../File1")
value = Something.Words.get("the key")

console.log(value)

This console.log gives the error:
value = Something.Words.get('the key')
^
TypeError: Cannot read property 'get' of undefined

A: Please see the working example below:

 let queue = new Map();
 queue.set('the key', 'the value');
 alert(queue.get('the key'));


text:
Q: Помогите с задачей на си Нужно Разработать функцию HowMore(const S1,S2:string):integer, определяющую, на сколько
больше пробелов в строке S1, чем в S2. С помощью данной функции вывести только
такие строки из введенного набора, в которых пробелов по крайней мере на 3 больше,
чем в предыдущей строке. Количество строк может быть любое. Уже 3 дня убил на решение, не могу придумать.
# include <stdio.h>
# include <conio.h>

int HowMore(char s1[], char s2[]) {
    int sum = 0, sum1 = 0;
    for (int i = 0; sizeof(s1)<sizeof(s2)?s2[i] != '\0':s1[i] != '\0';i++) {
        if (s1[i] == ' ') sum++;
        if (s2[i] == ' ') sum1++;
    }
    if (sum > sum1) return (sum - sum1);
    else {
        return 0;
    }
}

int main() {
    char s1[100], s2[100];
    int n;
    printf("Hi, please, enter the number of lines: ");
    scanf("%i", &n);
    for (int i=0; i <= n ; i++){
        gets(s1);
        printf("Enter next string: ");
        gets(s2);
        if (HowMore(s2, s1) >= 3) puts(s2);

    }
    getchar();
}

A: Я бы делал не совсем так...
int Spaces(const char *s)
{
    int count = 0;
    for(; *s; s++)
        if (*s == ' ') count++;
    return count;
}

int main()
{
    char s[2][100] = {0};
    int n, sp = 0;
    printf("Hi, please, enter the number of lines: ");
    scanf("%i", &n);
    for (int f = 0, i = 0; i <= n ; i++, f = 1 - f)
    {
        gets_s(s[f],100);
        int cur = Spaces(s[f]);
        if (cur - sp >= 3)
        {
            printf("Prev string \"%s\" has %d spaces\n",s[1-f],sp);
            printf("This string \"%s\" has %d spaces\n",s[f],cur);
        }
        sp = cur;
    }
}

Если позарез нужна HowMore, то
int HowMore(const char * s1, const char * s2) { return Spaces(s1) - Spaces(s2); }

P.S. sizeof(s1) вернет не то 4, не то 8 — размер указателя в вашей системе...
P.P.S. i = 0; i <= n ; — специально, для сброса лишнего \n из буфера после чтения n.


text:
Q: Warning: include failed to open stream: No such file or directory in magento helper I have created the following config.xml file:
<config>
    <global>
        <helpers>
            <awesome>
                <class>CommissionJunction</class>
            </awesome>
        </helpers>
    </global>
</config>

I have added the following php file: as Data.php
<?php
    class CommissionJunction extends Mage_Core_Helper_Data
    {

        /**
        * Get SKU, quantity, price and discount amount for each product in a given order
        * @param object $order
        * @return array
        */
        private function _getOrderProductsList($order)
        {
            $orderItems = $order->getAllItems();
            $purchasedSkus = array();
            $count_orderItems = count($orderItems);
            for($i = 0; $i < $count_orderItems; $i++) {
                $purchasedSkus[$i] = array(
                    'ITEM' => $orderItems[$i]['sku'],
                    'QTY' => number_format($orderItems[$i]['qty_ordered'],0), // no decimals
                    'AMT' => number_format($orderItems[$i]['price'],2), // 2 decimal places
                    'DCNT' => number_format(abs($orderItems[$i]['discount_amount']),2)
                 );
            }

            return $purchasedSkus;
        }

        /**
        * Get the Universal Data (JSON) Object for Commission Junction.
        * This object contains the order details passed on to Commission Junction for reporting purposes
        * on the Checkout Success / Order Confirmation page.
        * Notes:
        *  - CID, TYPE AND CURRENCY are hard coded
        * @param string $orderId
        * @return JSON object Universal Data Object for Commission Junction $json_masterTmsUdp
        */
        public function getCommissionJunctionUdo($orderId)
        {
            $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
            $udo = array();
            $udo['CID'] = 'XXXX';
            $udo['TYPE'] = 'XXXX';
            $udo['CURRENCY'] = 'USD';
            $udo['OID'] = $orderId;
            $udo['DISCOUNT'] = number_format(abs($order->discount_amount),2);

            $order_coupon_code = $order->coupon_code;
            if(!is_null($order_coupon_code) && !empty($order_coupon_code))
            {
                $udo['COUPON'] = $order_coupon_code;
            }

            $udo['PRODUCTLIST'] = self::_getOrderProductsList($order);

            if(Mage::getModel('core/cookie')->get('aff_commissionjunction') == 'cjafflx')
            {
                $udo['FIRECJ'] = "TRUE";
            }
            else
            {
                $udo['FIRECJ'] = "FALSE";
            }

            $masterTmsUdo['CJ'] = $udo;
            $json_masterTmsUdo = json_encode($masterTmsUdo);

            return $json_masterTmsUdo;

        }

    }

Then in succes.phtml I added this:
<script>var MasterTmsUdo = <?php echo Mage::helper('commissionjunction')->getCommissionJunctionUdo($this->getOrderId()); ?></script>
<script>/*DO NOT ALTER *** tpd*/(function(e){var t="1340",n=document,r,i,s={http:"http://cdn.mplxtms.com/s/MasterTMS.min.js",https:"https://secure-cdn.mplxtms.com/s/MasterTMS.min.js"},o=s[/\w+/.exec(window.location.protocol)[0]];i=n.createElement("script"),i.type="text/javascript",i.async=!0,i.src=o+"#"+t,r=n.getElementsByTagName("script")[0],r.parentNode.insertBefore(i,r),i.readyState?i.onreadystatechange=function(){if(i.readyState==="loaded"||i.readyState==="complete")i.onreadystatechange=null}:i.onload=function(){try{e()}catch(t){}}})(function(){});</script>

Errors:
1. My success page is not rendering correctly, the template is lost.
2. I got the following in system.log
014-08-09T21:33:07+00:00 ERR (3): Warning: include(Mage/Commissionjunction/Helper/Data.php): failed to open stream: No such file or directory  in /home/theprint/public_html/preprod/lib/Varien/Autoload.php on line 93
2014-08-09T21:33:07+00:00 ERR (3): Warning: include(Mage/Commissionjunction/Helper/Data.php): failed to open stream: No such file or directory  in /home/theprint/public_html/preprod/lib/Varien/Autoload.php on line 93

A: I can see at least 3 mistakes:

*

*Your helper class can't be called just CommissionJunction. The name must contain all the path starting from namespace of your extension like Mage_Core_Helper_Data does. And if your file is called Data.php, then helpr class name must end with Data. So it should look like Namespace_Extension_Helper_Data.

*In config you declare that your helpers should be referenced by string awesome, but in template you're trying to get helper by string commissionjunction. So you should change it either in config.xml, or in the template.

*And in config.xml class tag you have to write the path to the helper folder. Something like Namespace_Extension_Helper.

A: magento needs class name like Packagename_Modulename_Helper
config.xml
<config>
    <global>
        <helpers>
            <CommissionJunction>
                <class>CompanyName_CommissionJunction_Helper</class>
            </CommissionJunction>
        </helpers>
   </global>
</config>

and in your class head:
class CompanyName_CommissionJunction_Helper_Data extends Mage_Core_Helper_Abstract

then you can call with: Mage::helper('CommissionJunction');


text:
Q: find file with wild card matching In node.js, can I list files with wild card matching like
fs.readdirSync('C:/tmp/*.csv')?

I did not find the information on wild card matching from the fs documention.

A: Just in case you want to search files by regex (for complex matches), then consider using file-regex, which supports recursive search and concurrency control (for faster results).
Sample usage
import FindFiles from 'file-regex'

// This will find all the files with extension .js
// in the given directory
const result = await FindFiles(__dirname, /\.js$/);
console.log(result)

A: Pretty straightforward with match out of the box
import fs from 'fs'

fs.readdirSync('C:/tmp/').filter((allFilesPaths:string) =>
    allFilesPaths.match(/\.csv$/) !== null)

A: If you don't want to add a new dependency to your project (like glob), you can use plain js/node functions, like:
var files = fs.readdirSync('C:/tmp').filter(fn => fn.endsWith('.csv'));

Regex may help in more complex comparisons

A: If glob is not quite what you want, or a little confusing, there is also glob-fs. The documentation covers many usage scenarios with examples.
// sync
var files = glob.readdirSync('*.js', {});

// async
glob.readdir('*.js', function(err, files) {
  console.log(files);
});

// stream
glob.readdirStream('*.js', {})
  .on('data', function(file) {
    console.log(file);
  });

// promise
glob.readdirPromise('*.js')
  .then(function(files) {
    console.log(file);
  });

A: This is not covered by Node core. You can check out this module for what you are after.
Setup
npm i glob

Usage
var glob = require("glob")

// options is optional
glob("**/*.js", options, function (er, files) {
  // files is an array of filenames.
  // If the `nonull` option is set, and nothing
  // was found, then files is ["**/*.js"]
  // er is an error object or null.
})

A: dont reinvent the wheel, if you are on *nix the ls tool can easily do this (node api docs)
var options = {
  cwd: process.cwd(),
}
require('child_process')
.exec('ls -1 *.csv', options, function(err, stdout, stderr){
  if(err){ console.log(stderr); throw err };
  // remove any trailing newline, otherwise last element will be "":
  stdout = stdout.replace(/\n$/, '');
  var files = stdout.split('\n');
});


text:
Q: How to write custom interceptor for spring cache(@cachable) I am caching data using spring cache. Now i want to encrypt few data before writing into cache and decrypt data while reading. So is there any way i can write custom interceptor/aop for @cachable annotation

A: Instead of using AOP you can simply use a decorator for your Cache and CacheResolver.
public class EncodingCacheResolver implements CacheResolver {

  private final CacheResolver delegate;

  public EncodingCacheResolver(CacheResolver delegate) {
    this.delegate=delegate;
  }

  @Override
  public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context) {
    Collection<Cache> result = delegate.resolveCaches(context);
    return result.stream().map(EncodingCache::new).collect(Collectors.toLlist());
  }
}

The cache implementation
public class EncodingCache implements Cache {

  private final Cache delegate;

  public EncodingCache(Cache delegate) {
    this.delegate=delegate;
  }

  public String getName() {
    return delegate.getName();
  }

  public Object getNativeCache() {
    return delegate.getNativeCache();
  }

  public void evict(Object key) {
    delegate.evict(key)
  }

  public void put(Object key, Object value) {
    Object encodedValue = encode(value);
    this.delegate.put(key, encodedValue);
  }

  public <T> T get(Object key, Class<T> type) {
    Object encodedValue = delegate.get(key, type);
    return decode(encodedValue);
  }

  // Other Cache methods omitted but the pattern is the same

  private Object encode(Object value) {
    // encoding logic here
  }

  private Object decode(Object value) {
    // decoding logic here
  }

}

Then some configuration
@Configuration
@EnableCache
public void CacheConfiguration {

  @Bean
  public CacheResolver cacheResolver(CacheManager cacheManager) {
    return new EncodingCacheResolver(SimpleCache.of(cacheManager));
  }

}

Haven't tested the implementation, typed it from the top of my head. But this should more or less be what you need. You don't really need AOP for this.


text:
Q: What do you do when a random effect is collinear with a fixed effect? Say I have a dataset which has rows of observations of Mood (HAPPY/SAD), with info on the user (unique usernames), their hometown (a city, always the same for a given user) and their activity (standing/sitting/cycling):

MOOD
User
Hometown
Activity

HAPPY
Tom
New York
Standing

SAD
Tom
New York
Sitting

HAPPY
Tom
New York
Cycling

HAPPY
Dina
San Francisco
Standing

HAPPY
Dina
San Francisco
Sitting

HAPPY
Ellis
San Francisco
Sitting

HAPPY
Xiaomei
Beijing
Cycling

I want to find out the relationship between a mood and hometown/activity. For some hometowns (e.g. Beijing) I have very few users. Therefore I want to include user as a random effect in my regression model, to make sure to account for any difference due to sampling the same individuals multiple times. Let's say I try to model MOOD ~ Activity + Hometown + (1|User).
The problem here is that, for each user, the hometown will always be the same. My model produces errors (e.g. in R), I guess because of a collinearity problem. Is that right? I couldn't find much on what to do in these cases. I can run the model without the random effect and get neat results; however, in my field it is considered 'best practice' to use mixed-effects models.
What does one do here? Do you think my thinking on this is clear? Are there any solutions I'm missing?


text:
Q: Interpretation - "my younger brothers seem never to do anything else." I couldn't accurately understand what is the meaning of the following sentence.
"Oh, brothers! I don't care for brothers. My elder brother won't die, and my younger brothers seem never to do anything else."
- Wilde, Oscar, The Picture of Dorian Gray, Gutenberg Edition
Especially, "my younger bothers seem never to do anything else". What is it that is implicit here "anything other than ???". I see that it conveys some contempt but I am not sure if that just means "They don't do anything useful". Also, due to (maybe) cultural difference(I am Korean), what is the meaning behind "My elder brother won't die"? does it implicitly mean that I want him to be dead? (It seems too harsh remark from the context)
To see the context of the above sentences, you may click the link on the sentence.

A: Harry is being deliberately dismissive towards his family. The line "my younger brothers seem never to do anything else" refers back to "my elder brother won't die". So that part means something along the lines of: "my younger brothers seem never to do anything other than die", which is kind of deliberately nonsensical since it's a joke.
He's speaking flippantly of his younger brothers' deaths, and on top of that he's implying that his elder brother should be dead. You are correct that this is harsh. Hallward reacts negatively to Harry's statement, and Harry replies by admitting he wasn't serious, but he also goes off on another sarcastic rant, which Hallward reacts negatively to again. My perception is that these sarcastic comments are a major part of Harry's character.


text:
Q: ggplot aesthetics don't accommodate for a variable name So I'm plotting a shape file (from the ONS) of Great Britain split into 11 regions with the hope of creating a choropleth map based on COVID-19 cases.
I join the covid data with the shape file so that I can work within 1 data frame, joining on the region name.
I've used the longitude and latitude fields of the shape file for the x and y values within the aesthetics.
covid <- data.frame(Name = c("Scotland","Eastern","West Midlands","Yorkshire and the Humber","East Midlands","London","South West","South East","North West","North East","Wales"),
                    Cases = c(20,50,45,30,25,75,100,5,60,35,80))

#'greatb' is the name of the shape file
join <- merge(greatb,covid,by=c("NAME","Name"),by.x=c("NAME"),by.y=c("Name"), all=TRUE)

ggplot()+
 geom_polygon(data=join, aes(x=long, y=lat, group=group, fill=Cases))

However, it seems that once I do this I can't use a variable name to fill the regions of the map. I get confronted with the error message: object 'Cases' not found
I'm unsure why I get this is message though as 'covid$data' is clearly an object and therefore so is 'join$data'. Can anyone help me with this?


text:
Q: Loading text asynchronously on a webforms page? How do you click a button on a webforms page and watch the results of async requests gradually display on the page? For example, at the moment all the results appear after the postback completes!
Protected Async Sub lbtnSubmitTest_Click(sender As Object, e As EventArgs) Handles lbtnSubmitTest.Click
    Dim counter As Integer = 0
    Dim loopMax As Integer = 50
    Dim requestList As New List(Of Task(Of String))

    While counter < loopMax
        requestList.Add(FetchTokenAsync())
        counter = counter + 1
    End While

    While (requestList.Count > 0)

        Threading.Thread.Sleep(55500)

        Dim finishedTask = Await Task.WhenAny(requestList)
        requestList.Remove(finishedTask)

        Dim message = Await finishedTask
        lblResults.Text = lblResults.Text + message

    End While

    Dim file As System.IO.StreamWriter
    file = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\APITestResults.txt", True)
    file.WriteLine(lblResults.Text)
    file.Close()

End Sub

A: You are mixing things up.
The client (web browsers) makes a request to the server. That request might be a local synchronous or asynchronous operation, but it has no relation with the server.
Likewise, the server might execute the request synchronously or asynchronously but has no relation with the client.
They live worlds apart.
In order to asynchronously notify the client, you must use some server-to-client communication like SignalR.


text:
Q: NSUserDefaults return nil for previously set values on debug builds I have a strange issue with NSUserDefaults. I set a value like this:
NSUserDefaults.standardUserDefaults.setObject("Test", forKey: "test")
NSUserDefaults.standardUserDefaults.synchronize()

And I retrieve it like that
let storedValue = NSUserDefaults.standardUserDefaults.objectForKey("test")

The problem now is, that sometimes, not always, when recompiling the app onto my device, storedValue == nil. Even if no part of my app ever removed that value!!!
How can it be that that value gets nil? Is there a way that UserDefaults get deleted somehow? I only noticed the problem when doing a recompile onto the device. Without a debugger attached it always behaves like it should (I use it to show an intro screen, so I can see if it works).


text:
Q: Create java class validation code When we creating java class there is set of validation for the class name example that the class name will not start with number or . etc. I believe that this set of validation are done with regex ,how can i find this code ,I need somehow to reuse it.
Thanks!

A: You can find complete grammar syntaxes for Java in popular LR or LARL compiler-compiler tools, e.g. ANTLR.
If you want to create a regex one of your own, the syntax is available here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8
And here is another post that will help: Regular expression matching fully qualified class names

A: Almost every IDE will check your code to match Java naming conventions (probably you will want to turn on checks in IDE options). Also you may want to use different tools to check your code such as:
FindBugs
- a very solid bug finder tool, use at least this tool.
PMD
- this tool can be extended by the user (requires some skills).
CheckStyle
- this tool specifically checks JavaDoc comments.
They will help you find not only errors in naming conventions but much more