text:
Q: Magento 2 Rest Api as JSON i need to return the response of custom web api as JSON.
i need it to be like this:
{
  "data": [
    {
      "id": "1",
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$320,800",
      "start_date": "2011/04/25",
      "office": "Edinburgh",
      "extn": "5421"
    },
    {
      "id": "2",
      "name": "Garrett Winters",
      "position": "Accountant",
      "salary": "$170,750",
      "start_date": "2011/07/25",
      "office": "Tokyo",
      "extn": "8422"
    }
  ]
}

however, my module is coming out as
[
    {
      "id": "1",
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$320,800",
      "start_date": "2011/04/25",
      "office": "Edinburgh",
      "extn": "5421"
    },
    {
      "id": "2",
      "name": "Garrett Winters",
      "position": "Accountant",
      "salary": "$170,750",
      "start_date": "2011/07/25",
      "office": "Tokyo",
      "extn": "8422"
    }
]

My Interface is as follows:
<?php
namespace Mag\Rest\Api;

interface OrdersManagementInterface
{
  /**
   * GET for Stock api
   * @param mixed $items
   * @return string
   */
  public function getOrders();

}

My model is as follows:
<?php
namespace Mag\Rest\Model;

class OrdersManagement
{
    public function __construct(
    ) {
    }
    /**
     * {@inheritdoc}
     */
    public function getOrders()
    {
        //... sql code to get data goes here
        $results = $this->connection->fetchAll($sql);
        return  $response ;
    }
}

any idea on how to be able to format the output of the rest api ?


text:
Q: How to get all characters of an arbitrary encoding? If I want to know which letters are part of the ascii charset, I can simply ask python, which is nice:
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

I searched for a while, but couldn't find a generic function that returns charsets of arbitrary encodings. Something like this:
>>> import string
>>> string.get_charset('latin1')  # doesn't exist =(
'abc ... äöü ...'

Or did I just miss it? A function that checks whether a string only contains characters of some encoding would work too, but I'd like the intuitiveness of just having all valid characters as a list.

A: As far as I'm aware, no such function exists in the standard library.
In lack of a better idea, here's an ugly hack that tries to encode every single character in the utf8 range with the specified encoding and removes those characters that couldn't be encoded:
def get_charset(encoding):
    all_chars = ''.join(chr(x) for x in range(0x110000))
    return all_chars.encode(encoding, errors='ignore').decode(encoding)

Output:
>>> get_charset('latin-1')
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0¡¢£¤¥¦§¨©ª«¬\xad®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ'

Speed test:
In [2]: %timeit get_charset('latin1')
306 ms ± 8.34 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

redpajama_set_name: RedPajamaStackExchange


text:
Q: MVC: By SelectListItem I get "System.NullReferenceException: Object reference not set to an instance of an object." error By SelectListItem I get "System.NullReferenceException: Object reference not set to an instance of an object." error. What do I wrong?
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<Artiesten>
  <Item ID_Artiest="509998" Artiest="-" Product="-" Land="" Plaats="" Website="" Genre="Onbekend" />
  <Item ID_Artiest="970119" Artiest="(hed)p.e." Product="-" Land="" Plaats="" Website="" Genre="Onbekend" />
  <Item ID_Artiest="970080" Artiest="(urusei) yatsura" Product="-" Land="" Plaats="" Website="" Genre="Noise" />
  <Item ID_Artiest="1010302" Artiest="...and you will know us by the trail of dead" Product="-" Land="Verenigde Staten" Plaats="Austin (TX)" Website="" Genre="Noise" />
...
</Artiesten>

This is my Model
public class ArtiestInfoModel
    {
        [DisplayName("Selecteer artiest: ")]
        public int ID_Artiest { get; set; }
        public string SelectedArtiest { get; set; }
        public IEnumerable<SelectListItem> ArtiestenLijst { get; set; }
    }

The Controller:
 public ActionResult Index(int? AID_Artiest=810000)
        {
            var document = XDocument.Load(Server.MapPath("~/App_Data/Artiesten.xml"));
            var query = new ArtiestInfoModel
            {
                ArtiestenLijst =
                    (from artiest in document.Descendants("Artiesten").Elements("Item")
                    select new SelectListItem
                    {
                        Value = artiest.Attribute("ID_artiest").Value,
                        Text = artiest.Attribute("Artiest").Value,
                        Selected = false //  artiest.Attribute("ID_artiest").Value == AID_Artiest.ToString()
                    }).ToList()
            };

            ViewBag.ID_Artiest = AID_Artiest.Value;
            ViewBag.ArtiestenLijst = query.ArtiestenLijst;

            return View();
        }

The Controller is called by the next DropDownList:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% using (Html.BeginForm("Index", "Hitdossier", FormMethod.Post, new { id = "frmArtiest" })) %>
    <% { %>

Selecteer artiest:

                <%= Html.DropDownList("ID_Artiest",
                    new SelectList(ViewBag.ArtiestenLijst, "Value", "Text"),
                    "-- Selecteer artiest --",
                    new
                    {
                        @onchange = "document.getElementById('frmArtiest').submit();"
                    })%>

            <%= Html.Action("Detail_Hitdossier", new { AID_Artiest = ViewBag.ID_Artiest })%>

    <%} %>
</asp:Content>

thanks

A: In your controller you are reading the node ID_artiest as a lowercase while the xml shows camelcase.
Change
Value = artiest.Attribute("ID_artiest").Value,

To
Value = artiest.Attribute("ID_Artiest").Value,

If artiest.Attribute("ID_artiest") result in a NULL value, then reading a property Value will throw the null-reference-exception.

A: Please initialise as new object like this
ArtiestenLijst = new ArtiestenLijst(); then after use


text:
Q: Why does $f:[a,b] \rightarrow \mathbb{R}$ need $f$ to be continuous on $[a,b]$ but only differentiable on $(a,b)$, in some theorems. Why in some theorems relating to a real function $f:[a,b] \rightarrow \mathbb{R}$ do we need $f$ to be continuous on $[a,b]$ but only require differentiability on $(a,b)$?
One such example would be Rolle's theorem.

A: Do you know what mean to be differentiable in closed interval? Think for example that the limits aren't well defined on both sides.


text:
Q: Python pandas dataframe.value returns a ndarray with strange properties, that can be plotted but break lmfit I am working on an assignment that requires me to fit different kinetic models to some concentration versus time data. In order to acomplish this I performed the following steps:
1.Imported a spreadsheet into a python Jupyter notebook with pandas.read_excel and then removed all the columns after row 20
data = pd.read_excel("assignment1.xlsx")[:21]

2.plotted some of the data
X = data["X"].values
t = np.linspace(0,20,len(X))
plt.figure(1)
plt.plot(t,X)
plt.xlabel("time")
plt.ylabel("Conversion(x)")

3.attempted to fit a model to the data
from lmfit import minimize, Parameters, Model, Parameter

X2 = data["X"].values
t2 = np.linspace(0,20.1,len(X))
y2 = (data["A"].values+data["B"].values)*X
y3 = []
t3 = []

for y in y2: #these are used a little later
    y3.append(y)
for t in t2:
    t3.append(t)

def test2(t,k):
    return t*k

aModel = Model(test2)

p = aModel.make_params()
p["k"] = Parameter(name="k",value=3,min=0)

result = aModel.fit(np.array(y2),params=p,t=np.array(t2)) #source of error

but I got the following error...
error: Result from function call is not a proper array of floats.

yet the following code along with the previous block minus the result line does not give me an error
result = aModel.fit(np.array(y3),params=p,t=np.array(t3)) #y3, t3 replaces t2, y2

Obviously there is something wrong with df.values in that it returns some odd numpy array that is ok for plotting but not ok for fitting. Does anyone have an idea about what the difference is between these two arrays or how I could go about fixing the error in a more graceful way?
EDIT:
Here is some additional information that some of the commenters have asked for:
Here are the t2, y2 shape and type
code:
print("t2 shape: ", t2.shape, "t2 type: ", type(t2))
print("y2 shape: ", y2.shape, "y2 type: ", type(y2))

output:
t2 shape:  (21,) t2 type:  <class 'numpy.ndarray'>
y2 shape:  (21,) y2 type:  <class 'numpy.ndarray'>

full traceback:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-312-0681483eeeeb> in <module>()
     28
     29
---> 30 result = aModel.fit(np.array(y2),params=p,t=np.array(t2))
     31
     32 print(test2([0,3,0,3,0],1))

~\Anaconda3\lib\site-packages\lmfit\model.py in fit(self, data, params, weights, method, iter_cb, scale_covar, verbose, fit_kws, nan_policy, **kwargs)
    871                              scale_covar=scale_covar, fcn_kws=kwargs,
    872                              nan_policy=self.nan_policy, **fit_kws)
--> 873         output.fit(data=data, weights=weights)
    874         output.components = self.components
    875         return output

~\Anaconda3\lib\site-packages\lmfit\model.py in fit(self, data, params, weights, method, nan_policy, **kwargs)
   1215         self.userkws.update(kwargs)
   1216         self.init_fit = self.model.eval(params=self.params, **self.userkws)
-> 1217         _ret = self.minimize(method=self.method)
   1218
   1219         for attr in dir(_ret):

~\Anaconda3\lib\site-packages\lmfit\minimizer.py in minimize(self, method, params, **kws)
   1809                         val.lower().startswith(user_method)):
   1810                     kwargs['method'] = val
-> 1811         return function(**kwargs)
   1812
   1813

~\Anaconda3\lib\site-packages\lmfit\minimizer.py in leastsq(self, params, **kws)
   1362
   1363         try:
-> 1364             lsout = scipy_leastsq(self.__residual, variables, **lskws)
   1365             _best, _cov, infodict, errmsg, ier = lsout
   1366             result.residual = infodict['fvec']

~\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
    392         with _MINPACK_LOCK:
    393             retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,
--> 394                                      gtol, maxfev, epsfcn, factor, diag)
    395     else:
    396         if col_deriv:

error: Result from function call is not a proper array of floats.

A: This may not fully answer the question, but might point you in the right direction and is too long for a comment anyway.
Without knowing the details of your xlsx file, it looks like your code should work.  I think the most likely clue from the traceback is the message "... is not a proper array of floats".  You are coercing the data and x array to be numpy arrays, but they may not be Float64 (double precision) arrays.
So check the datatype as well as the shape and type of the ndarrays:
print("t2 shape: ", t2.shape, "t2 type: ", type(t2), "t2 dtype: ", t2.dtype)

For the fit to work, this must be dtype('float64').
The arrays might be integer array if the values in the spreadsheet are all integers.  In that case, just do
t2 = np.array(t2, dtype='float64')

or
t2 = np.asfarray(t2)

and so on to force the arrays to be Float64.
Or, it might also be that the arrays are "object arrays" if the Series from the spreadsheet mixes numerical and non-numerical data.  In that case, you'll have to remove the non-numerical rows, and/or force the dtype to Float64.


text:
Q: Array performance and how to get performance of independent variables I am writing a Java project which uses a custom object - smallObject, which is mainly composed of double variables.
Now as the project evolved, I required that every variable in smallObject becomes an array of 4 elements - so what was a double variable, became an array of type double, with 4 elements - bigObject.
The processes that use bigObject are exactly the same as smallObject, with the only difference being that they contain an element number, so smallObject.a = 4, becomes bigObject.a[2] = 4;
I was expecting that since every time I am accessing the array, I define exactly which element I require (don't have to search for it), the performance should be approximately the same, however, performance slowed down by a factor of 2-3. These objects are used in arraylists and queues which can grow up to 3 million elements.
Is it to be expected that performance slows down? How can I go around this issue? Was thinking of using individual variables (a[4], becomes a1, a2, a3, a4) - but this would require me to have different classes so that each one accesses the right variable and will make the code unreadable.
Thanks for your time.

A: As far as I know, if u use list-based objects to find an element in position 4 you have to go from 1 to 4 since lists are based on pointers (O(n) where n is the number of elements of the array if u are used to big O notation). If u use simpler elements like a true double array accessing element 4 should be done in 1 operation O(1)... so try to use double[].
Hope that this helps you.
Alex


text:
Q: Collision detection for nodes of varying sizes not working as expected I have a fully functional d3.js force directed graph. Trying to add collision detection so that the nodes do not overlap. But the caveat is my nodes having a varying radius calculated on the basis of its d.inDegree and d.outDegree
    node.attr("r", function(d) {
    var weight = d.inDegree ? d.inDegree : 0 + d.outDegree ? d.outDegree : 0;
    weight = weight > 20 ? 20 : (weight < 5 ? 5 : weight);
    return weight;
  });

Now I am trying to use this varying radius in the function for collision detection
    var padding = 1;
    var radius = function(d) { var weight = d.inDegree ? d.inDegree : 0 + d.outDegree ? d.outDegree : 0;
    weight = weight > 20 ? 20 : (weight < 5 ? 5 : weight);
    return weight;}
function collide(alpha) {
  var quadtree = d3.quadtree(d3GraphData.nodes);
  return function(e) {

    var rb = 2*radius + padding,
        nx1 = e.x - rb,
        nx2 = e.x + rb,
        ny1 = e.y - rb,
        ny2 = e.y + rb;
    quadtree.visit(function(quad, x1, y1, x2, y2) {
      if (quad.point && (quad.point !== e)) {
        var x = e.x - quad.point.x,
            y = e.y - quad.point.y,
            l = Math.sqrt(x * x + y * y);
          if (l < rb) {
          l = (l - rb) / l * alpha;
          e.x -= x *= l;
          e.y -= y *= l;
          quad.point.x += x;
          quad.point.y += y;
        }
      }
      return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
    });
  };
}

There is no error on the console , but the nodes are still overlapping when pushed into each other. So , I am not able to figure out what to attribute this to or how to debug it.
Below is the fiddle

A: This is an interesting question, which every so often is brought up in various flavors. The last time I remember having answered one of these was Gerardo Furtado's "Conflict between d3.forceCollide() and d3.forceX/Y() with high strength() value". It may be hard to grasp at first, but once it has fully sunken in, it is almost obvious. So bear with me as I will try to put this down in plain words first.
When using d3.forceSimulation() it is important to always keep in mind, that it is just that: a simulation, no more, no less. And its inner workings are far from being a realisitic replica of nature's forces. One major drawback is the fact, that forces are applied sequentially instead of simultaneously. And even the calculations for a single force will be applied to one node after another instead of all nodes at once. This is by no means a problem special to D3, but an issue any computer-driven simulation faces and has to find a solution for. Even worse, there will never be a real solution to the problem, but rather a trade-off between the performance of the calculations and the degree it lives up to the viewers expectations.
Contrary to nature, in our simulation a constraint can easily violate another constraint or the same constraint for another node without causing the annihilation of the essence of being. Often, these results might come unexpected when compared to forces you are accustomed to and are thus expecting.
How is this related to your special problem?
When doing collision detection you are pushing around some nodes to avoid violating the constraint of mutual exclusion. Mainly depending on how clever your algorithm is, there is a risk of pushing one node into the realm of another while trying to avoid a third node. Again, depending on the way you do the calculations, this induced violation might not be resolved until the next tick of the simulation. The same may happen if a force, which is calculated after the collision detection, pushes a node to a position where it violates the collision avoidance (or any other constraint). This may even give rise to a bunch of problems further down the road dealing with the other forces or the same force on other nodes.
The most common way around this is to apply the collision avoidance algorithm multiple times within one tick, whereby iteratively getting closer to a real solution, hopefully. When I first came across this approach, it seemed so helpless and pathetic, that I was astounded, that it should be our best shot… But it works not that bad.
Since you provided your own implementation for a collision detection, namely the function collide(), let us first try to improve that. By wrapping your entire calculations into a loop repeating it, say, ten times, the output will significantly improve (JSFiddle):
for (let i=10; i>0; i--) {   // approximation by iteration
  quadtree.visit(function(quad, x1, y1, x2, y2) {
      // heavy lifting omitted for brevity
  });
}

Although this works out pretty well, one notices nodes still overlapping, if not that many as before. To further improve on this, I suggest you ditch your own implementation in favor of D3's own collision detection algorithm which is available as d3.forceCollide(). This force's implementation has the above mentioned iterations already built in. You can control the number of iterations by setting it via collide.iterations(). Apart from that, the implementation is equipped with some more clever optimizations:

Overlapping nodes are resolved through iterative relaxation. For each node, the other nodes that are anticipated to overlap at the next tick (using the anticipated positions ⟨x + vx,y + vy⟩) are determined; the node's velocity is then modified to push the node out of each overlapping node. The change in velocity is dampened by the force's strength such that the resolution of simultaneous overlaps can be blended together to find a stable solution.

Tweaking your simulation could look like this (JSFiddle):
var simulation = d3.forceSimulation()
  .force("link",
    d3.forceLink()
      .id(function(d) { return d.id; })
      .distance(50)
      .strength(.5)            // weaken link strength
  )
  .force("charge", d3.forceManyBody())
  .force("center", d3.forceCenter(width / 2, height / 2))
  .force("gravity", gravity(0.25))
  .force("collide",
    d3.forceCollide()
      .strength(.9)            // strong collision avoidance
      .radius(radius)          // set your radius function
      .iterations(10)          // number of iterations per tick
  );

As you can see, there are still overlapping nodes, and it might be worth playing around with the parameters of the forces some more to yield an outcome which is pleasing to the eye. Given the large number of nodes, their rather large circles and the number of forces you apply, however, I would not expect it to be free of any collisions.


text:
Q: How to get exported function names from a .dll(system)? I want the exported function namelist (by name and by ordinal) from a DLL. I got the function names(exported by name) using export directory table,but I can't retrieve the exported function list, which exported by ordinals.
Please help me to retrieve it. I also tried .lib of that dll, there is also, displays NONAME. thanks in advance to legends

A: If You know dll name ,You can view through many tools (pe explorer,CFF Explorer),Here all exported function names  are viewable with ordinal .Another one way from microsoft (dumpbin.exe) its a command line tool ..its also list out all exported fn names

A: If you have mingw32 installed, simply run
nm.exe your_dll
Where your_dll is the dll you want to to get the ordinals and exports of.
nm.exe should be in the bin directory of your mingw32 installation.


text:
Q: Regular expression to match any table tag I'm trying to write a regular expression to see if a string contains any of the typical table tags:

Along with tags that may contain other attributes e.g:

I've come up with this so far, however, it matches
 tag and I'm not sure why:
/<\/?[table|td|th|tr|tfoot|thead|tbody]{1,}>?/

http://www.rexfiddle.net/20Xtqka

A: Regular expressions use parentheses, not square brackets, to group things. A set of characters inside square brackets matches any of those characters.
/<\/?(table|td|th|tr|tfoot|thead|tbody)+>?/

When you want to match 1 or more of something, use + rather than {1,}.


text:
Q: Duplicate field names in different tables make the `SELECT` query complex in mybatis I have some tables which all have a field named created_at, that's a timestamp to represent when the row inserted.
Now I use mybatis 3 as the persistence layer, I found it a little boring when I query something with join.
Look at the simple sql I expected to get all the questions and their answers:
<select id="selectQuestionsWithAnswers">
      select q.*, a.* from questions as q left inner join answers as a
             on q.id=a.id
      order by a.created_at desc
</select>

But I found, since questions and answers both have field created_at, and if I write select q.*, a.*, there are 2 created_at in the result set, and, the second one is ignored. So the answers will have the created_at value as questions, it's not correct.
To avoid this, I found 2 ways, but both not good:

*

*Modify the field names of each table, make sure they are not same. For example: questions.created_at -> questions.q_created_at, answers.created_at->answers.a_created_at.
This is not good because there are a lot of such fields as id, name, title, updated_at, it makes the database hard to read and maintain to change these names

*Modify the SQL. Change the field names in sql, like:
select q.id as q_id, q.title as q_title, ..., q.created_at as q_created_at,
       a.id as a_id, a.content as a_content, ..., a.created_at as a_created_at
from questions as q left inner join answers as a
       on q.id=a.id
order by a.created_at desc

This is not good because I need to change every field names in the SQL, it becomes very long and hard to read, and painful to write such SQLs every time.
I'm new to mybatis, is there any better solution for this problem?

A: What about
<select id="selectQuestionsWithAnswers">
      select q.*, a.*, q.created_at as qtime, a.created_at as atime from questions as q left inner join answers as a
             on q.id=a.id
      order by atime desc
</select>

now you'll have your times in atime and qtime


text:
Q: How to bootstrap confidence of a weighted measure? I have a large data set of 20M observations with 20+ measures for each observation (people).  Additionally I have a set of weights that reflect the racial population where each person lives.  For example, from Census data this could be the percentage of population in the zipcode, or tract that is African American, White, Asian etc.  These percentages will add to 100%.
We lack direct measure of race on individuals.  This information is not available.
The profile data will then look like this:
ID,White,Asian,AfricanAmerican,...
1234    70% 20% 5%  5%  0%
2345    30% 50% 10% 5%  5%
3456    5%  90% 5%  0%  0%
4567    25% 25% 25% 15% 10%

The 20 measures are a combination of financial data and true/false flags.  These finance data are heavily skewed, and also have a lot of zeroes.
We will compute the weighted means of all the measures, e.g. average value of African Americans.
My questions center around computing variance measures for these means.
I think the most straightforward way to compute variance estimates is to bootstrap the IDs, preserving the profile of each ID and compute $N$ weighted means.
Alternatively, we could randomly pick one race per person $N$ times according to the profile and compute $N$ weighted means.  We could also do both, re-sample the IDs and pick 1 race in each iteration.
I cant figure out what the "one race" simulation results actually measure.  Because each person is assigned one race, it can't be used for a confidence interval of the original  weighted means.
Is there a name for this second method of simulating the random variable?  Any references for using it?


text:
Q: How to visually think about the difference $dw_1 - dw_2$ between two 2-forms? Let's say that I have two differential 2-forms $dw_1$ and $dw_2$ that each describe separate smooth 2-dimensional manifolds with/without boundary. Each has its own differential 1-form $w_1$ and $w_2$ that provide a connection over the underlying parameter space. Each also is characterized by their respective Euler characteristics $\chi_1$ and $\chi_2$ from the Gauss-Bonnet theorem.
For instance, I can think of $dw_1$ and $dw_2$ describing two different torii, or one sphere and one torus, etc. But, what does the difference of 2-forms $dw_1-dw_2$ mean? How can I think of it intuitively? I know the connected sum allows comparison of $\chi_1+\chi_2$, but the difference? I ask only because I saw in a paper that $dw_1-dw_2$ allows a way to compare geodesic sprays between the two surfaces (i.e., they will both have the same sprays if the difference is antisymmetric), but how do I think about $dw_1-dw_2$ in general in the simplest intuitive way possible, i.e. pictorially? I doubt the picture is that removing the parts of $dw_2$ from $dw_1$, and I recently asked the following question: Insight on difference between Euler characteristics of 2 manifolds: $\chi(U)-\chi(V)$?


text:
Q: Upgrade simulator to 7,1,2 I have the latest xcode , Included iOS SDK: iOS 7.1 I but the app rejected cause it doesn't work with IOS 7.1.2
any idea how to upgrade the simulator to test on it

A: You could try checking for updates on your simulator, although I am not sure if there was one for 7.1.2

Why not test on a device though? You should be doing that anyway.


text:
Q: jquery opacity не срабатывает В шапке подключены js:

После jquery подключаю свой файл и пишу там:
$(".portfoliolist").ready(function(){
    $(".portfolio, .card, .mix_all").css({"opacity":"0"});
});

Ожидаю что при загрузке страницы, этому блоку применится свойство и он скроется, но этого не происходит, и в консоле ошибок нет. Что я делаю не правильно.
Это код дива, который хочу скрыть при загрузке страницы:

Привет! я див который не получается скрыть.

A:

$(function(){
    $(".portfolio.card.mix_all").css({"opacity":"0"});
});

Привет! я див который не получается скрыть.


text:
Q: Python list or pandas dataframe arbitrary indexing and slicing I have used both R and Python extensively in my work, and at times I get the syntax between them confused.
In R, if I wanted to create a model from only some features of my data set, I can do something like this:
subset = df[1:1000, c(1,5,14:18,24)]

This would take the first 1000 rows (yes, R starts on index 1), and it would take the 1st, 5th, 14th through 18th, and 24th columns.
I have tried to do any combination of slice, range, and similar sorts of functions, and have not been able to duplicate this sort of flexibility.  In the end, I just enumerated all of the values.
How can this be done in Python?

Pick an arbitrary subset of elements from a list, some of which are selected individually (as in the commas shown above) and some selected sequentially (as in the colons shown above)?

A: In a file of index_tricks, numpy defines a class instance that converts a scalars and slices into an enumerated list, using the r_ method:
In [560]: np.r_[1,5,14:18,24]
Out[560]: array([ 1,  5, 14, 15, 16, 17, 24])

It's an instance with a __getitem__ method, so it uses the indexing syntax.  It expands 14:18 into np.arange(14,18).  It can also expand values with linspace.
So I think you'd rewrite
subset = df[1:1000, c(1,5,14:18,24)]

as
df.iloc[:1000, np.r_[0,4,13:17,23]]

A: You can use iloc for integer indexing in pandas:
df.iloc[0:10000, [0, 4] + range(13,18) + [23]]

As commented by @root, in Python 3, you need to explicitly convert range() to list by df.iloc[0:10000, [0, 4] + list(range(13,18)) + [23]]

A: Try this, The first square brackets filter. The second set of square brackets slice.
df[[0,4]+ range(13,18)+[23]][:1000]


text:
Q: Removing user inserted image tags with PHP I am trying to remove any user inserted image tags while allowing my own image icon. I have this
$post = 'Here is an image  to check
         and my icon ';

$imgcheck = true;
$stringstart = 0;

while($imgcheck == 'true'){
    if($stringstart = strpos($post,'',$stringstart)){
            $strlength = $stringend - $stringstart;
            $substring = substr($post,$stringstart,$strlength);
            if (!preg_match('/src="\/images\/ImageLink.jpg"/',$substring)){
                $post = str_replace($substring, "", $post);
            }
            else{
                $stringstart = $stringend;
            }

        }
        else{
            $imgcheck = 'false';
        }
    }
    else{
            $imgcheck = 'false';
    }

}

I would like this to return
Here is an image to check and my icon

I seem to be getting an error on one of the strpos functions but cannot figure out why.
Update:Thank you hakre. That answer is much more elegant. I did finally make the code work with
$imgcheck = true;
$stringstart = 0;

while($imgcheck == 'true'){
    if($stringstart = strpos($post,'<img',$stringstart)){
        if ($stringend = strpos($post,'>',$stringstart)){
            $strlength = $stringend - $stringstart +4;
            $substring = substr($post,$stringstart,$strlength);
            if (!preg_match('~src="\/images\/ImageLink.jpg"~',$substring)){
                $post = str_replace($substring, "", $post);
            }
            else{
                $stringstart = $stringend;
            }

        }
        else{
            $imgcheck = 'false';
        }
    }
    else{
            $imgcheck = 'false';
    }

}

with < and > used because I am using a div with contenteditable=true for user input. This could also be used for a text area by simply replacing < and > with  respectively as well as changing
$strlength = $stringend - $stringstart +4;

to
$strlength = $stringend - $stringstart +1;

Thank you for your time.

A: You should use a HTML parser for the job, for example DOMDocument.
The following example code will put your html fragment into a div with the id post so it can be identified:
$post = 'Here is an image  to check
         and my icon ';

$post = '
'.$post.'
';

Then the DOMDocument is created and the html loaded into it. Additionally the container div is made available as a variable by it's id:
$doc = new DOMDocument();
$doc->loadHTML($post);
$container = $doc->getElementById('post');

The next step is to select all images you want to remove. This is done with xpath. The xpatch expression will then be queried with the $container as reference:
$xpath = new DOMXPath($doc);
$expression = './/img[@src != "/images/ImageLink.jpg"]';
$nodes = $xpath->query($expression, $container);

The next step is to iterate over all found elements and to remove them:
foreach($nodes as $node)
{
    $parent = $node->parentNode;
    $parent->removeChild($node);
}

Finally the changed HTML needs to be aquired by taking everything out of the $container:
$innerHTML = '';
foreach($container->childNodes as $child) {
    $innerHTML .= $node->ownerDocument->saveXML($child);
}

Now everything is in
echo $innerHTML;

which will give you:
Here is an image  to check
         and my icon

Hope this is useful.


text:
Q: Alfresco cron syntax: difference between 0/2 and */2? Alfresco has a cron-like system that allows you to run a job at regular intervals. The documentation specifies as an example the expression 0 0/2 * * * ? which will make the job run every 2 minutes. However, in a lot of code I see people using the expression 0 */2 * * * ? instead, the difference being that the zero is replaced by an asterisk. This syntax is more similar to the syntax found in some Unix implementations of cron, but I don't think I can blindly assume they work the same (Alfresco's syntax has a seconds field that Unix syntax lacks, for instance).
So my question is, is there any difference in functionality between the expression 0/2 and */2? And as a followup, is there a place where Alfresco's syntax is properly documented?

A: Oliver Charlesworth's comment led me to the Quartz docs that contain the answer:

You can also specify '/' after the '*' character - in this case '*' is equivalent to having '0' before the '/'.

So 0/2 and */2 are equivalent cron expressions.


text:
Q: Flutter TextFormField. How to stick validation text inside TextFormField How to stick validation text inside TextFormField. By default it goes below
the text field
I want like this

But it shows like this

I have looked in various sources, but did not find a suitable answer
is there any way to show the validation text inside the textbox

A: You can update text from TextEditingController if validation fails for a certain text field and also can remove text from controller in "onTap" property.
TextEditingController _passwordController = TextEditingController();
if(condition)
{
 //success call
}
else
{
setState((){
  _passwordController.text="Password Does not match
 });
}

A: you should validate your form  in the Following way
class MyForm extends StatefulWidget {
  @override
  MyFormState createState() {
    return MyFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyFormState extends State<MyForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<MyFormState>.
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TextFormField(
            // The validator receives the text that the user has entered.
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter some text';
              }
              return null;
            },
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: ElevatedButton(
              onPressed: () {
                // Validate returns true if the form is valid, or false otherwise.
                if (_formKey.currentState!.validate()) {
                  // If the form is valid, display a snackbar. In the real world,
                  // you'd often call a server or save the information in a database.
                  // sendData();
                  ScaffoldMessenger.of(context)
                      .showSnackBar(SnackBar(content: Text('Processing Data')));
                }
              },
              child: Text('Submit'),
            ),
          ),
        ],
      ),
    );
  }
}


text:
Q: Estimate for L1 funcction Suppose  for every $r\in \mathbb{R}$, $\int_{\mathbb{R}}\lvert f(x)\rvert e^{rx}dx<\infty$. Then is it true that there exists $C>0$ and $\alpha>1$, such that $\lvert f(x)\rvert\leq Ce^{\lvert x\rvert^{-\alpha}}$ almost everywhere.

A: Counter-example
Let us consider a function $f: \mathbb R \to \mathbb R$, such that for every $n \in \mathbb Z$, $f(x)=e^n$ on $[n, n+c_n]$, with $c_n>0$.
Let $r \in \mathbb R_{-}$, then $$\int_{\mathbb R} |f(x)| e^{rx} \mathrm{d}x \leq \sum_{n \in \mathbb Z} c_n e^{(r+1)n}$$ The last sum converges if $c_n$ = $e^{-n^2}$ for example.
Let $r \in \mathbb R_{+}$, then $$\int_{\mathbb R} |f(x)| e^{rx} \mathrm{d}x \leq \sum_{n \in \mathbb Z} c_n e^{r(n+1) + rc_n}$$ And the sum still converges.


text:
Q: how do i delete a file from azure blob based on file path in Django MODELS.PY
class FilesHistory(models.Model):
    filename = models.CharField(max_length=100, blank=False,  null=False)
    file = models.FileField(upload_to='upload/%y/%m/%d/',null=False,blank=False)
    sentGroupId = models.CharField(max_length=100,blank=False)
    uploaded_at = models.DateTimeField(auto_now_add=True,blank=True)

   def delete(self, using=None, keep_parents=False):
       self.file.storage.delete(self.file.path)
       super().delete()

this delete function is working for removing files from the media folder based on the file path.


text:
Q: how to test respond_with_content_type when it's deprecated in shoulda_matches 2.0 respond_with_content_type matcher is now deprecated in shoulda-matchers gem (version > 2.0 and lot of ugly warnings in version 1.5.6)
Thoughtbot suggest that developers should use Integration tests, however this is not always on low resources projects
So question is how to fix broken specs ?  ... or how to replace them
Referring to:

*

*https://github.com/thoughtbot/shoulda-matchers/issues/186

*https://github.com/thoughtbot/shoulda-matchers/issues/252

*Thoughtbots article related to these deprecations

A: simplest way is to just replace any occurrence of respond_with_content_type with :
# spec/controllers/users_controller_spec.rb
describe UsersController do
  before{ get :index, :format => :xlsx }
  it 'response should be excel format' do
    response.content_type.to_s.should eq Mime::Type.lookup_by_extension(:xlsx).to_s
  end
end

if you want a proper matcher than:
# spec/support/matchers/respond_with_content_type_matchers.rb
RSpec::Matchers.define :respond_with_content_type do |ability|
  match do |controller|
    expected.each do |format|  # for some reason formats are in array
      controller.response.content_type.to_s.should eq Mime::Type.lookup_by_extension(format.to_sym).to_s
    end
  end

  failure_message_for_should do |actual|
    "expected response with content type #{actual.to_sym}"
  end

  failure_message_for_should_not do |actual|
    "expected response not to be with content type #{actual.to_sym}"
  end
end

# spec/spec_helper.rb
...
#ensure support dir is loaded
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
...

B.T.W.: if you miss matcher should assign_to than there is an existing solution https://github.com/tinfoil/shoulda-kept-assign-to . Gem is just a simple shoulda-matcher extension module


text:
Q: Laravel 7 - Update user I'm having problems with the 'edit' action of my users. I can create new users, but I cannot update them.
This is my edit method in the UserController:
/**
    * Show the form for editing the specified resource.
    *
    * @param  \App\User  $user
    * @return \Illuminate\Http\Response
*/
public function edit($userID)
{
    //
    $user = User::query()->findOrFail($userID);
    $roles = Role::pluck('nombre_rol','id');
    $departments = Department::all(['id','department_name']);
    return view('user.edit',compact('user','roles','departments'));
}

This is the update method in the UserController:
/**
    * Update the specified resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \App\User  $user
    * @return \Illuminate\Http\Response
*/
public function update(Request $request, $usuarioID)
{
    $user = User::query()->findOrFail($usuarioID);
    $user->update($request->only('name','email','password', 'roles', 'departament_id'));
    $user->roles()->sync($request->roles);
    return back()->with('Success','Usuario actualizado con éxito');
}

This is the view for the edit:

@lang('edit.Editar') @lang('edit.Usuario')

{{$user->name}}

                <form method="POST" action="{{route('Usuario.update', $user->id)}} class="user" enctype="multipart/form-data"">
                    {!! method_field('PUT') !!}

                    @include('user.form')

@lang('edit.Roles')

                            @foreach($roles as $id => $name)
                            <input type="checkbox" value="{{$id}}" {{$user->roles->pluck('id')->contains($id) ? 'checked' : ''}} name="roles[]">
                            {{ $name }}
                            @endforeach

                        <button class="btn btn-warning" type="submit" value="Acttualizar">@lang('edit.Actualizar')</button>
                        <button class="btn btn-danger" onclick="cancel()" value="Cancelar">@lang('edit.Cancelar')</button>

                </form>

And this is the form that I @include in the edit view.

        @lang('form.Nombre')
        <input value="{{isset($user->name)?$user->name:old('name')}}" required type="text" name="name" id="name" class="form-control text-muted">

        @lang('form.Correo')
        <input value="{{isset($user->email)?$user->email:old('email')}}" required type="text" name="email" id="email" class="form-control text-muted">

        @lang('form.Contraseña')
        <input value="{{--decrypt($usuario->password) ?? old('password')--}}" class="form-control" type="password" name="password" id="password">

        @lang('form.Seleccionar')
        <select name="department_id" id="department_id" class="form-control">
            <option selected disabled value="">@lang('form.Seleccionar')</option>
                @foreach ($departments as $department)
                <option value="{{$department->id}}">{{$department->department_name}}</option>
                @endforeach
        </select>

When I press the edit button I get the error:

419 Page Expired

Images of the users table structure

A: If you're getting this error after submitting edit form, then put @csrf after  {!! method_field('PUT') !!}
It should like,
                    <form method="POST" action="{{route('Usuario.update', $user->id)}} class="user" enctype="multipart/form-data"">
                        {!! method_field('PUT') !!}
                        @csrf // For lower version use - {{ csrf_field() }}
                        @include('user.form')

@lang('edit.Roles')

                                @foreach($roles as $id => $name)
                                <input type="checkbox" value="{{$id}}" {{$user->roles->pluck('id')->contains($id) ? 'checked' : ''}} name="roles[]">
                                {{ $name }}
                                @endforeach

                            <button class="btn btn-warning" type="submit" value="Acttualizar">@lang('edit.Actualizar')</button>
                            <button class="btn btn-danger" onclick="cancel()" value="Cancelar">@lang('edit.Cancelar')</button>

                    </form>

A: HTML forms only support POST and GET so if u want to perform an action of updating u need to add @method('PUT') between your opening and closing form tags and then add @csrf still inside your form tags
 <form method="POST" action="{{route('user.update', $user->id)}} class="user" enctype="multipart/form-data"">
@method('PUT')
@csrf
</form>


text:
Q: len(bytes(1000)) takes 1000 bytes in memory? I tested the integer with the following codes:
In [10]: bin(5)
Out[10]: '0b101'
In [11]: bytes(5)
Out[11]: b'\x00\x00\x00\x00\x00'

Then I checked the length of bytes(5)
In [13]: len(bytes(5))
Out[13]: 5

In [14]: len(bytes(1000))
Out[14]: 1000

Does it mean that integer 1000 take 1000 bytes in memory?
And integer 1000 is 250 times more expensive than "text"?

A: bytes(5) creates a bytes object with 5 bytes, each initialized to '\x00' (a null byte). It does not create an integer 5.
The len function returns the number of elements in a container object. To check the memory footprint of an object you should instead use the sys.getsizeof method:
>>> import sys
>>> sys.getsizeof(bytes(5)) # memory footprint of a bytes object with a length of 5
22
>>> sys.getsizeof(5) # memory footprint of the integer 5
14
>>>

A: >>> len(bytes(5))
1
>>> len(bytes(1000))
4

I got a different output than yours.

A: bytes's meaning is different for python2 & python3.
In python2, it just a alias of str:
bytes(1000) -> '1000' # the length is 4

In python3, it initialized with null bytes you specify with the first parameter:
bytes(1000) -> b'\x00\x00...' # so the length is 1000.

If you just want to know why above code give your above output, that's all.
But, if you just want to know the size of 1000, you could use sys.getsizeof(1000) to get the size of one int.


text:
Q: UISplitview not alligned at the top I have a problem I can't figure out, I have made an application which uses UIsplitview inside a tab bar. I have been implementing the different tabs however now when I am working on the first tab - the UIsplitview is not aligned in landscape mode. Do you guys have any suggestions - if I start it in portrait and go to landscape, then there's no problem at all.

Update:
I dont do any init with frames anywhere, and I have checked the sizes etc. in IB. The following shows how I add the uisplitview controller in the app delegate. It has been done this way because I wanted a splitview in a tabbar controller. When i have added the spilview I just set the master and detail view in IB. A bit of mystery.
if (index == 2) {

        detailViewController = [[DetailUserCreatorViewController alloc] initWithNibName:@"DetailUserCreatorView" bundle:nil];

        userContent=[[UserContentForPopViewController alloc]init];

        userContent.userDetails=detailViewController;

        detailViewController.delegate=userContent;

        //rootViewController.navigationItem.title = @"List";
        UINavigationController *nav = [[[UINavigationController alloc] initWithRootViewController:userContent] autorelease];

        splitViewController = [[UISplitViewController alloc] init];
        splitViewController.tabBarItem = controller.tabBarItem;
        splitViewController.viewControllers = [NSArray arrayWithObjects:nav, detailViewController, nil];

        splitViewController.delegate = detailViewController;

        [controllers replaceObjectAtIndex:index withObject:splitViewController];
    }

Update: I tried to set the selected tab in application didfinishlaunch in the app delegate - self.tabBarController.selectedIndex = 0; and this made the tab start at the correct placement. However it does not seem to be a proper solution.

A: Some pointers...splitViewController needs to be added as a subview of window:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

[window addSubview:splitViewController.view];
[window makeKeyAndVisible];

return YES;
}

The following code is incorrect. You should not assign a viewController to a delegate.
splitViewController.delegate = detailViewController;

You will also not require this line of code:
[controllers replaceObjectAtIndex:index withObject:splitViewController];

The following line handles that part of assigning delegates.
splitViewController.viewControllers = [NSArray arrayWithObjects:nav, detailViewController, nil];

Also, if you can upload your code, I'll try to correct it and post back the reason and corrected code...


text:
Q: How to make this function work more efficiently to count dominators? I have to make a function where it would count the amount of dominators in a given list (number to the right of any number has to be smaller for it to be counted as a dominator.) For example, given the list [53,7,14,11,4,7] the function would return 4 since 53,14,11,7 are dominators(last item on the list is a dominator). Issue is that it takes a very long time to run for larger integers. Was just wondering if there is a less brute and more efficient way to achieve the same result?
Here's what I have:
def count_dominators(items): # works but takes a very long time to execute.
    k = 0
    for idx,item in enumerate(items):

        dominator = True
        for ritem in items[idx+1:]:

            if item<=ritem:
                dominator = False
                break
        if dominator:

            k = k+1
    return k

A: Going backwards, you get a linear-time algorithm:
def count_dominators(items):
    rev = list(reversed(items))
    if rev:
        max = rev[0]
        count = 1
        for i in range(1,len(rev)):
            if rev[i] > max:
                max = rev[i]
                count += 1
    else:
        count = 0
    return count

A: This gives a linear time algorithm and avoids copying the input list (helpful if the list is large):
import math

def count_dominators(numbers):
    count = 0
    max = -math.inf
    for number in reversed(numbers):
        if number > max:
            max = number
            count += 1
    return count


text:
Q: Active Directory, wildcard security certificate, and remote access Is there any way to secure an entire Active Directory (AD) domain using a single trusted, third-party Certification Authority (CA)-signed wildcard security certificate so that remote access will be seamless for:

*

*RDP using Remote Web Access (RWA) via Remote Desktop Gateway (RDG) to PCs.

*RDP using Remote Desktop Connection via Remote Desktop Gateway (RDG) to Remote Desktop Services (RDS) server.

Ideally, I'd like it so that the users get no security certificate warnings (regardless of the where the computer is or whether the computer is domain-joined) when remoting in by:

*

*Browsing to https://internal.domain.com/remote, signing in, and selecting PC-01.

*Opening a RemoteApp and signing in.

Details:

*

*Internet Domain Name: domain.com

*AD Domain Name: internal.domain.com

*AD Domain Controller and RDG server Fully Qualified Domain Name: server-01.internal.domain.com

*RDS server Fully Qualified Domain Name: server-02.internal.domain.com

*PC Fully Qualified Domain Name: pc-01.internal.domain.com

*Wildcard security certificate: *.internal.domain.com
As far as I'm aware, it cannot be done as a single security certificate can only be installed on a single computer and this scenario would require the security certificate to be installed on 3 computers (RDG server, RDS server, and PC).
However, I know that AD has its own Public Key Infrastructure (PKI) and "internal" CA which is used to ensure trust between its domain and domain-joined computers. So, is there any way to replace AD's CA root security certificate with the trusted, third-party CA-signed wildcard security certificate?
Update 2016/06/30 16:33: I have made significant progress with this and will write up the answer once the problems have been fixed.

A: Disclaimer: This is to the best of my recollection

Our security certificate provider, SSL247, informed me that wildcard security certificates:

*

*Only cover subdomains one level down, not the root domain.

*Can be installed on unlimited servers (also PCs?), unless they're provided by Symantec (if I recall correctly).

In simple terms, the full resolution was to:

*

*On the RDS server, open RemoteApp Manager and change the RDG from internal.domain.com to remote.internal.domain.com.

*On the Internet domain domain.com's authoritative name servers, create the DNS Resource Record (RR):
remote.internal.domain.com 3600 IN A <public IP address>

*On the router, create firewall and NAT rules to allow and forward port TCP 443 to the RDG server.

*On the RDG server, open IIS Manager and create a Certificate Signing Request (CSR) for *.internal.domain.com

*Submit the CSR to the trusted, third-party CA and wait for issuance.

*On the RDG server, open IIS Manager, complete the CSR thereby installing the wildcard security certificate, and export the wildcard security certificate with its private key to a PFX file.

*On the RDG server, open RDG Manager and configure the security certificate, Connection Authorization Policies (CAPs), and Resource Authorization Policies (RAPs).

*On the RDS server, open MMC > Certificates and import the PXF file thereby installing the wildcard security certificate.

*On the RDS server, open RDS Host Configuration and reconfigure the connection "RDP-Tcp" changing the security certificate.

In actuality, our resolution was a lot more complicated.
Our original setup was as follows:

*

*Role RDG installed on server server-01.internal.domain.com running Windows Server 2012 R2 Essentials.

*Role RDS installed on server server-02.internal.domain.com running Windows Server 2008 R2 Standard.

Long story short (ask for clarification if required), this setup just did not work. Despite using the domain administrative user account and all settings (RDG, CAPs, RAPs, NPS, etc) being configured as low / open as possible, external RDP failed consistently with the following errors:

Remote Desktop can't connect to the remote computer "server-02.internal.domain.com" for one of these reasons:
  1) Your user account is not authorized to access the RD Gateway "remote.internal.domain.com"
  2) Your computer is not authorized to access the RD Gateway "remote.internal.domain.com"
  3) You are using an incompatible authentication method (for example, the RD Gateway might be expecting a smart card but you provided a password)

Log Name: Microsoft-Windows-TerminalServices-Gateway/Operational
  Source: Microsoft-Windows-TerminalServices-Gateway
  Date: 2016/06/30 15:47:33
  Event ID: 201
  Task Category: (2)
  Level: Error
  Keywords: Audit Failure,(16777216)
  User: NETWORK SERVICE
  Computer: server-01.internal.domain.com
  Description:
  The user "%domainAdministrativeUserAccount%", on client computer "%ourPublicIPAddress%", did not meet connection authorization policy requirements and was therefore not authorized to access the RD Gateway server. The authentication method used was: "NTLM" and connection protocol used: "HTTP". The following error occurred: "23003".

I heavily researched this scenario and these errors and found a fair amount of resources but none resolved the problems.
I had our Network Operations Center (NOC) investigate and they concluded that the problem was caused by the use of Essentials.
I moved the role RDG from server #1 to server #2 (I realise this is nearly pointless), updated the network, and it worked pretty much instantly.
Oh, well. At least it works.


text:
Q: Where do I find Twilio invoices / billing section? Sorry for the stupid question, but I've spent about 15 minutes trying to find the billing section on twilio without success. I need to view invoices for a few month ago. Can anyone point me in the right direction? Thanks

A: Twilio developer evangelist here.
You can find all your billing information here. You can also view your usage information here.


text:
Q: Gulp watch terminates or builds the whole task chain I am developing a typescript project with the following build steps:

*

*lint

*build

*test

I am using Gulp 4.0 as a build tool and want to have a watch task, which should trigger the test (which means that lint and build tasks are triggered prior). Currently, when an error occurs (for example a lint error), the watch task terminates.
This problem is well known and easy to solve. The typical solution is a) to prevent errors or b) to patch the pipe behaviour.
a) For the gulp-tslint I could use this config from their homepage:
gulp.task("invalid-noemit", () =>
    gulp.src("input.ts")
        .pipe(tslint())
        .pipe(tslint.report("prose", {
          emitError: false
        }))
);

But when I include the emitError flag, the lint errors are logged and all following gulp tasks are executed (build, test).
b) I could also use gulp-plumber or catch errors manually (see here), but the behavior is the same for all this known solutions, the following gulp tasks are executed (build, test).
What I want is that the task chain stops after an error (no build and test after an lint error), but the watch task should never stop. How could I solve this? The watcher tasks look like this:
// watcher
gulp.task('watch', gulp.series('test', function doWatch() {
    gulp.watch([
        config.paths.sourcePattern,
        config.paths.testPattern,
        'gulpfile.js'
    ], gulp.parallel('test'));
}));

You can find the complete gulpfile.js here.

A: The reason your watch stops is because an err object is propagated up the callback chain. You have to prevent that err from reaching the final gulp.watch() callback.
You can do that by wrapping the callback provided by gulp.watch() and never passing the err object on to the original callback:
gulp.task('watch', function() {
  gulp.watch([
      config.paths.sourcePattern,
      config.paths.testPattern,
      'gulpfile.js'
    ], {ignoreInitial:false}, function(cb) {
      gulp.series('lint', 'build', 'test')(function wrappedCb(err) {
        cb(); // not passing err here
    });
  });
});

Note that gulp.series('lint', 'build', 'test') doesn't actually execute the tasks. It merely returns a new function that accepts a callback. Only when this new function is invoked as gulp.series('lint', 'build', 'test')() are the tasks actually executed.
I also added the ignoreInitial option so that the watch is executed once after startup which seems to be what you're trying to achieve with gulp.series('test', ...) in your watch task.
(Aside: watching gulpfile.js is useless. Changes to your gulpfile will not take effect until you rerun gulp watch. There's no way around this.)

Finally you need to decouple your other tasks, so they don't have explicit dependencies on other tasks. It's tempting to translate a gulp 3.x task like this:
gulp.task('foo', ['bar'], function() { });

Into a gulp 4.x task like this:
gulp.task('foo', gulp.series('bar', function() { }));

They look similar on the surface, but they're entirely different under the hood. See this article for more on that subject.
One good strategy is to organize your tasks into two categories:

*

*Standalone tasks that do one thing and don't depend on other tasks.

*Composite tasks that run several other tasks in series or parallel.

Following this principle your other tasks can be refactored into this:
gulp.task('lint', function() {
  return gulp.src([
    config.paths.sourcePattern,
    config.paths.testPattern
  ])
  .pipe(tslint())
  .pipe(tslint.report('verbose', {
    emitError: true, // we WANT to emit this err so our other tasks don't run
    summarizeFailureOutput: true
  }));
});

gulp.task('build-app', function doBuildApp() {
  /* ... */
});

gulp.task('build-test', function doBuildTest() {
  /* ... */
});

gulp.task('build', gulp.series('lint', 'build-app', 'build-test'));

gulp.task('test', gulp.series(function doPreTest() {
    /* ... */
  }, function doTest() {
    /* ... */
  }, function doPostTest() {
    /* ... */
}));


text:
Q: JavaScript string.replace using "$$" outputs "$" Can anyone explain to me why JavaScript outputs a single $ when using $$ as the replace value?
"hi".replace("hi", "$$bye$$");
"hi".replace("hi", "\$\$bye\$\$");

//both output -> $bye$
//but I expected $$bye$$

A: The $ acts as a metacharacter in the replacement strings for that function. The string $$ is used to indicate that you just want a $. Otherwise, $ followed by a digit refers to the contents of a capturing group from the regular expression. As an example:
alert("aaabbb".replace(/(a+)(b+)/, "$2$1")); // bbbaaa

The string "\$\$bye\$\$" is exactly the same as the string "$$bye$$". Because $ is not a metacharacter in the string grammar, the backslash preceding it will be ignored.
You can double-up on the backslashes to have them survive the string constant parse, but the .replace() function will pay no particular attention do them, and you'll get \$\$ in the result.


text:
Q: Are there any experimental data about potential time dilation caused by cyclical movement of heavy objects? I am dealing with a completely fabricated scenarios (while trying to write a sci-fi book), so my thougts are completely hyphotetical.
But I would like to ask you to help me find out if following experiment was ever executed:
Atomic clock A is paced in the line of Earths orbit but instead of orbiting Sun the clock is static in the space and does not orbit Sun. But it keeps the same distance from Sun as Earth had when the clock A was released.
Clock B is placed on Earth.
Clock A and B start at the same time (when clock A is realeased from Earth).
After one year when Earth is pasing the clock A again the clock A is colected and the time compared.
I think that some difference can be caused by missig mass of planet Earth. If I made right assumption - it can somewhere like clock A has 5-10 seconds + compared to clock B...can someone please confirm that at least magnitude is right? That is in mater of few seconds...
Or will the clock show the same time?
And if there was experiment, and there was a difference, how much it was? Was it exactly how much the mathematic explains as missing mass of our planet?

A: Leaving a clock "motionless" in space is already science fiction. To do what you suggest, clock A would need substantial rockets running continuously to prevent it from falling directly into the sun on a radial line. I feel sure no one has ever done that as it would be practically impossible and, even if possible, not worth it.
Terrestrially, we have this experiment which is the closest match to what you suggested, although on aircraft not spacecraft: Hafele-Keating experiment.
In space, there are the GPS satellites.  They obviously orbit the Earth, so they are not like your scenario, but the clocks on those have to be calibrated such that they keep the right time on orbit. That means they are "off" while still on the ground before launch.  You could easily look up a lot on that.
I don't really understand the part of your question about "missing mass", but I don't see where that would matter.  It is true that clocks run differently at different potential energies, and there would be a different gravitational pull, at some level, when the Earth was close to A vs far from A, but I don't think that would be very significant.  You might be able to estimate that from the effect on the GPS satellites as mentioned above.


text:
Q: I want to hide "/blog " from my post's url my blog url is like www.mysite.com/blog. and post urls are like www.mysite.com/blog/category/post_name. my problem is , I want to hide" /blog " from my post urls. Butblog url should be the same. in blog url "/blog" should show. Can i fix this by using htaccess? or is there any other method I can use?

A: Try this:
Go to your Wordpress Admin Area
Navigate to Settings->Permalinks.
Set permalink settings to Postname .
Or try using custom structure :

/%postname%/

Or try changing site url if it does not work!


text:
Q: Mapreduce job give empty output on cluster I have developed a mapreduce code which runs fine on Intellij and gives the output. When I run the same code on the cluster, I get an empty result.I keep getting the error

15/07/21 08:28:04 INFO mapreduce.Job: Task Id : attempt_1436660204513_0254_m_000000_0, Status : FAILED
  Error: Plink/PlinkMapper : Unsupported major.minor version 51.0

Also, the shuffle in final merge has failed.
Map-Reduce Framework
                Map input records=18858
                Map output records=0
                Map output bytes=0

I am using the same version of jdk during compile and run and I have no clue why I keep getting this error.Please find my code below:
Driver:
package Plink;

/**
 * Created by Sai Bharath on 7/21/2015.
 */
import Utils.PlinkConstants;
import Utils.PlinkDataSetDto;
import Utils.PlinkDto;
import Utils.PropertyUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.filecache.DistributedCache;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
 * Created by bvarre on 10/29/2014.
 */
public class PlinkDriver extends Configured implements Tool {

    @Override
    public int run(String[] args) throws Exception {

        if (args.length < 6) {
            System.err.printf("Usage: %s [generic options] <input> <output>\n",
                    getClass().getSimpleName());
            ToolRunner.printGenericCommandUsage(System.err);
            return -1;
        }
        Job job = new Job();
        Configuration conf=job.getConfiguration();
        conf.set("mapred.child.java.opts","-Xmx8g");

        job.setJarByClass(PlinkDriver.class);

        PropertyUtils.setConfigFromSystemProperty(job.getConfiguration());

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileInputFormat.addInputPath(job, new Path(args[1]));

        FileOutputFormat.setOutputPath(job, new Path(args[2]));

        if(args[3] != null && !args[3].isEmpty() && PlinkConstants.LOCAL_FILE_INPUT.equalsIgnoreCase(args[3])){
            job.getConfiguration().set("snip.codes", args[4]);
            job.getConfiguration().set("gene.codes", args[5]);
        }
        else {

            DistributedCache.addCacheFile(new Path(args[4]).toUri(), job.getConfiguration());
            DistributedCache.addCacheFile(new Path(args[5]).toUri(), job.getConfiguration());

            DistributedCache.createSymlink(conf);
        }

        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        job.setMapperClass(PlinkMapper.class);
        // job.setCombinerClass(PlinkCombiner.class);
        job.setReducerClass(PlinkReducer.class);

        //Setup Partitioner
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(PlinkDto.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        int exitCode = ToolRunner.run(new PlinkDriver(),args);
        System.exit(exitCode);
    }
}

Mapper:
package Plink;

import Utils.PlinkDataSetDto;
import Utils.PlinkDto;
import Utils.PlinkResourceBundle;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.util.*;

public class PlinkMapper extends Mapper<Object, Text, Text, PlinkDto> {

    private List<String> snipCodes = new ArrayList<String>();
    private List<String> geneCodes = new ArrayList<String>();

    private String domain;

    @Override
    protected void setup(Context context) throws IOException,
            InterruptedException {
        super.setup(context);
        Configuration conf = context.getConfiguration();

        snipCodes = PlinkResourceBundle.getCodes(conf, "snip.codes");
        geneCodes = PlinkResourceBundle.getCodes(conf, "gene.codes");

        System.out.println(" snip code size in nMapper :: " + snipCodes.size());
        System.out.println(" gene code size in nMapper :: " + geneCodes.size());
    }

    @Override
    protected void map(Object key, Text value,
                       Context context) throws IOException, InterruptedException {

        try {

            String str = (value.toString());
            if (str != null && !str.equals("")) {
                List<String> items = Arrays.asList(str.split("\\s+"));
                if(items!=null && items.size()>=3) {
                    List<PlinkDto> snipList = new ArrayList<PlinkDto>();
                    List<PlinkDto> geneList = new ArrayList<PlinkDto>();
                    Text plinkKey = new Text();
                    plinkKey.set(items.get(0));
                    if(!items.get(2).equalsIgnoreCase("null") && !items.get(2).equalsIgnoreCase("na")) {
                        PlinkDto plinkDto = new PlinkDto();
                        plinkDto.setCodeDesc(items.get(1));
                        plinkDto.setCodeValue(new Float(items.get(2)));
                        if (snipCodes.contains(items.get(1))) {
                            plinkDto.setCode("SNIP");
                            snipList.add(plinkDto);
                        } else if (geneCodes.contains(items.get(1))) {
                            plinkDto.setCode("GENE");
                            geneList.add(plinkDto);
                        }
                        context.write(plinkKey,plinkDto);
                    }
                }
            }
        }catch(Exception ex){
            //Collecting Patient data
            ex.printStackTrace();
        }

    }
}

Reducer:
package Plink;

/**
 * Created by Sai Bharath on 7/15/2015.
 */
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import Utils.PlinkDataSetDto;
import Utils.PlinkDto;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

public class PlinkReducer extends Reducer<Text, PlinkDto, Text, Text> {

    @Override
    public void reduce(Text key, Iterable<PlinkDto> values, Context context)
            throws IOException, InterruptedException {
        List<PlinkDto> snipList = new ArrayList<PlinkDto>();
        List<PlinkDto> geneList = new ArrayList<PlinkDto>();
        Iterator<PlinkDto> it=values.iterator();
        while (it.hasNext()) {
            PlinkDto tempDto =  it.next();
            if (tempDto.getCode().equalsIgnoreCase("SNIP")) {
                PlinkDto snipDto = new PlinkDto();
                snipDto.setCode(tempDto.getCode());
                snipDto.setCodeDesc(tempDto.getCodeDesc());
                snipDto.setCodeValue(tempDto.getCodeValue());
                snipList.add(snipDto);
            } else if (tempDto.getCode().equalsIgnoreCase("GENE")) {
                PlinkDto geneDto = new PlinkDto();
                geneDto.setCode(tempDto.getCode());
                geneDto.setCodeDesc(tempDto.getCodeDesc());
                geneDto.setCodeValue(tempDto.getCodeValue());
                geneList.add(geneDto);
            }
        }

        for(PlinkDto snip:snipList){
            for(PlinkDto gene:geneList){
                PlinkDataSetDto dataSetDto = new PlinkDataSetDto();
                dataSetDto.setSnipCodeDesc(snip.getCodeDesc());
                dataSetDto.setGeneCodeDesc(gene.getCodeDesc());
                dataSetDto.setSnipCodeValue(snip.getCodeValue());
                dataSetDto.setGeneCodeValue(gene.getCodeValue());
                Text output = new Text();
                output.set(dataSetDto.toString());
                context.write(key,output);
            }
        }

    }
}

PlinkResourceBundle
package Utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.Path;

import org.apache.hadoop.mapreduce.Job;

import java.util.*;

public class PlinkResourceBundle {

    private PlinkResourceBundle() {
    }

    public static List<String> getCodes(Configuration conf, String codeType) throws IOException {
        List<String> codeList = new ArrayList<String>();
        try {
            String inFile = conf.get(codeType);

            if (inFile != null) {
                List<String> lines = HdfsUtils.readFile(inFile);
                for (String line : lines) {
                    if (line != null && line.length() > 0) {
                        codeList.add(line.trim());
                    }
                }
            } else {
                Path[] cachefiles = DistributedCache.getLocalCacheFiles(conf);
                if (cachefiles.length > 0) {
                    BufferedReader reader = new BufferedReader(new FileReader(cachefiles[0].toString()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        codeList.add((line.trim()));
                    }
                }
            }
        }
        catch (Exception ex) {
            System.out.println("Error in getting snip/gene codes " + ex.getMessage());
        }
        return codeList;
    }//end of method
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>Plink</groupId>
    <artifactId>Plink</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <jdkLevel>1.7</jdkLevel>
        <requiredMavenVersion>[3.3,)</requiredMavenVersion>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.build.outputEncoding>UTF-8</project.build.outputEncoding>

    </properties>

    <distributionManagement>
        <repository>
            <id>code-artifacts</id>
            <url>
                http://code/artifacts/content/repositories/releases
            </url>
        </repository>
        <snapshotRepository>
            <id>code-artifacts</id>
            <url>
                http://code/artifacts/content/repositories/snapshots
            </url>
        </snapshotRepository>
    </distributionManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>${jdkLevel}</source>
                    <target>${jdkLevel}</target>
                    <showDeprecation>true</showDeprecation>
                    <showWarnings>true</showWarnings>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.codehaus.groovy</groupId>
                        <artifactId>groovy-eclipse-compiler</artifactId>
                        <version>2.9.2-01</version>
                    </dependency>

                    <dependency>
                        <groupId>org.codehaus.groovy</groupId>
                        <artifactId>groovy-eclipse-batch</artifactId>
                        <version>2.4.3-01</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>

                            <includeScope>provided</includeScope>
                            <includeScope>compile</includeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

    <repositories>
        <repository>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
                <checksumPolicy>warn</checksumPolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
                <updatePolicy>never</updatePolicy>
                <checksumPolicy>fail</checksumPolicy>
            </snapshots>
            <id>HDPReleases</id>
            <name>HDP Releases</name>
            <url>http://repo.hortonworks.com/content/repositories/releases/</url>
            <layout>default</layout>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.6.0.2.2.4.2-2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.oozie</groupId>
            <artifactId>oozie-core</artifactId>
            <version>4.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-core</artifactId>
            <version>0.20.2</version>

        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.mrunit</groupId>
            <artifactId>mrunit</artifactId>
            <version>1.0.0</version>
            <classifier>hadoop2</classifier>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
    </dependencies>

</project>

15/07/22 08:41:57 INFO mapreduce.Job:  map 0% reduce 0%
15/07/22 08:42:06 INFO mapreduce.Job:  map 100% reduce 0%
15/07/22 08:42:13 INFO mapreduce.Job:  map 100% reduce 100%
15/07/22 08:42:13 INFO mapreduce.Job: Job job_1436660204513_0286 completed successfully
15/07/22 08:42:13 INFO mapreduce.Job: Counters: 50
        File System Counters
                FILE: Number of bytes read=6
                FILE: Number of bytes written=364577
                FILE: Number of read operations=0
                FILE: Number of large read operations=0
                FILE: Number of write operations=0
                HDFS: Number of bytes read=604494
                HDFS: Number of bytes written=0
                HDFS: Number of read operations=9
                HDFS: Number of large read operations=0
                HDFS: Number of write operations=2
        Job Counters
                Launched map tasks=2
                Launched reduce tasks=1
                Other local map tasks=1
                Rack-local map tasks=1
                Total time spent by all maps in occupied slots (ms)=13453
                Total time spent by all reduces in occupied slots (ms)=9188
                Total time spent by all map tasks (ms)=13453
                Total time spent by all reduce tasks (ms)=4594
                Total vcore-seconds taken by all map tasks=13453
                Total vcore-seconds taken by all reduce tasks=4594
                Total megabyte-seconds taken by all map tasks=27551744
                Total megabyte-seconds taken by all reduce tasks=18817024
        Map-Reduce Framework
                Map input records=18858
                Map output records=0
                Map output bytes=0
                Map output materialized bytes=12
                Input split bytes=266
                Combine input records=0
                Combine output records=0
                Reduce input groups=0
                Reduce shuffle bytes=12
                Reduce input records=0
                Reduce output records=0
                Spilled Records=0
                Shuffled Maps =2
                Failed Shuffles=0
                Merged Map outputs=2
                GC time elapsed (ms)=118
                CPU time spent (ms)=10260
                Physical memory (bytes) snapshot=1023930368
                Virtual memory (bytes) snapshot=9347194880
                Total committed heap usage (bytes)=5474615296
        Shuffle Errors
                BAD_ID=0
                CONNECTION=0
                IO_ERROR=0
                WRONG_LENGTH=0
                WRONG_MAP=0
                WRONG_REDUCE=0
        File Input Format Counters
                Bytes Read=604228
        File Output Format Counters
                Bytes Written=0

Can anyone please help me?

A: This appears to be an incompatibility with the runtime Java VM on the cluster. The "Unsupported major.minor version 51.0" indicates that the class file PlinkMapper requires at least a Java 7 VM. I would recommend confirming what version of the JRE is running on the cluster.
The major version numbers as defined in class files are listed below -

*

*J2SE 8 = 52

*J2SE 7 = 51

*J2SE 6.0 = 50

*J2SE 5.0 = 49

*JDK 1.4 = 48

*JDK 1.3 = 47

*JDK 1.2 = 46

*JDK 1.1 = 45


text:
Q: Composer class not found even if it exists I'm developing a Laravel package but I have a problem with composer autoloading.
My package has 2 folders under src folder. One of them is named Laravel and the other one is Telegram. Here is the package structure:
./packages
.../typhoon
...../src
......./Laravel
........./Providers
............LumenServiceProvider.php
............LaravelServiceProvider.php
......./Telegram
..........Api.php
.....composer.json

This package is developed under SaliBhdr/Typhoon namespace.
I have added the packages/typhoon/src directory in Laravel's composer file like so:
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "SaliBhdr\\Typhoon\\" : "packages/typhoon/src/"
        }
    },

And add the src/ address in package composer.json file like so:
    "autoload": {
        "psr-4": {
            "SaliBhdr\\Typhoon\\": "src/"
        }
    },

Here is the strange behavior begins. When I execute the php artisan serve command Laravel throws an error that says :
 Class 'Salibhdr\Typhoon\Laravel\Providers\LumenServiceProvider' not found

And if I check if the class exists with class_exists('Salibhdr\Typhoon\Laravel\Providers\LumenServiceProvider') function it returns false. But if I check if Salibhdr\Typhoon\Telegram\Api exists it returns true.
I checked the autoload_classmap file and notice that the composer includes all the classes under Telegram subfolder but not Laravel subfolder.
Why composer acts weird like this? why did it include one subfolder and not the other? It is something that I do every day and never seen anything like this.
I desperately need help. Any help would be appreciated

A: You are trying to initialize Salibhdr\Typhoon\Laravel\Providers\LumenServiceProvider but in your composer it's "SaliBhdr\\Typhoon\\": "src/".
Notice the capital B in your composer. PHP classes are case sensitive so you have to make sure it's either both lowercase or both uppercase.
Also make sure to run composer dumpautoload if you modify composer.json.


text:
Q: Reject and terminate promise on external event I want to be able to reject and stop the rest of the promise from running if an external event occurs. This is the example usecase:
new Promise((resolve,reject)=>{
    websocket.onerror=reject;
    //do processing here
    websocket.onerror=undefined;
    resolve(...);
});

This has the intended effect of rejecting the promise if an error occurs while the promise is running. However, the problem is that the rest of the promise will continue running even if a rejection occurs.
Using async/await the above is not possible at all.
I think one way would be to have every single line of code in a separate promise, and cancelling the chain on an event, but that would be a pain.

A:
However, the problem is that the rest of the promise will continue running even if a rejection occurs.

This is a basic misunderstanding (and you're not alone in it!). There is no "rest of the promise." A promise is just a means of observing the completion of an asynchronous process. It's the process, not the promise, that's continuing.
How you cancel that process (and whether you can) depends entirely on what that process is and whether it provides a means of cancelling it, which is unrelated to promises themselves. You seem to be using a web socket, so you'd need to use the web socket API to cancel whatever you have it doing (or to send a message to the other end to tell it to stop what it's doing).
For instance: Suppose the promise were waiting for a timer (setTimeout) to fire, and would resolve when it did. Then some other thing happens and you no longer want that. Rejecting the promise just rejects the promise, it doesn't have any effect on the timer. You'd need to cancel the timer, too (clearTimeout).

Re your edit:

I think one way would be to have every single line of code in a separate promise, and cancelling the chain on an event, but that would be a pain.

No, the code in the promise executor (the function you pass new Promise) is run synchronously. Again, there's no "rest of the code" to cancel. There may well be asynchronous callbacks in there, or a process the code starts you need to send a cancellation too, but that's not going to require putting every line in its own promise, not at all.

A: Understanding the answer to this question may help you:
When you create the promise, it is executed synchronously. So this line is executed:
websocket.onerror=reject;

At this point, your code begins to process. If there is an event of websocket error, it is put in the js event loop, but your promise is still executing synchronously. Then you unhook the websocket's error handler, and resolve. The promise will resolve even if there was an error. At this point the call for resolve is also added to js' event loop. Then the next js tick executes, and maybe reject is called, maybe not, but it doesn't matter at this point because you resolved synchronously, and promises never change their minds once they've resolved or rejected.
So the key takeaway here is that creating a promise executes it synchronously. It's not a thread that you can cancel while waiting for other events. The promise' resolution or rejection is executed asynchronously, but that doesn't help you at all.
To cancel a promise, you'll need some pretty basic stuff such as
if(someOtherVariableThatDeterminesCancelation){
  reject()
}


text:
Q: iOS scrollable iFrame Since iOS4 there was a bug that an iFrame could not be scrolled:
index.html

iframe.html

You will notice that the height:100px style is ignored by iOS.
Is there an official bug ticket for this behaviour?
Is it possible in iOS10 to scroll the content of an iframe?

A: try this one:


text:
Q: Adding comments in programming consume system resources? I recently found two posts in StackOverflow about adding comments in programming. Posts : 1,2
After going through these posts i was eager to know a thing a comments.i.e :
1.Do adding comments in programming utilize system resource while compiling the code ?

A: Yes they do, but you probably have to add a lot of them to notice any difference.

A: Handling white space and comments is part of the "lexing" (lexical analysis) phase of compilation, so yes, they do consume resources in the process. As a previous commenter has said, it's so computationally cheap that you'd have to insert a lot of comments and white space (and maybe compile on a really slow computer) before you'd notice.
You may be interested in this document: Notes on How Parsers and Compilers Work.

A: The first rule of programming: write code that other people can easily read and modify. To achieve this:

*

*Write short, clear, code blocks that are easy to read and thus easy to determine the "what".

*Write unit tests to both convey the "why" and to provide a safety net when maintaining the code.

Everything else, including how long the code takes to compile, should be moot. So the answer to your question is "it doesn't matter".


text:
Q: What audio formats does QAudioDecoder support? In the documentation QAudioDecoder is mentioned to throw a FormatError when 'The format of a media resource isn't supported.'
My question is what formats does QAudioDecoder support and could more formats be supported by users installing software such as LAME?

A: There is a function for that:
  QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
  qDebug() << info.supportedCodecs();

IIRC it should support MP3 if you have LAME installed, FLAC if you have FLAC installed and so on in that fashion. By default it is only guaranteed to support pcm wav.


text:
Q: Assigning Roles to Users I'm having trouble figuring out how to assign roles to users. I've got the log in mechanism working, but need to figure out how to use roles defined to give users certain access.
I have a database with these tables:

                     Tables
                     ------
   UserTbl          RolesTbl           UserInRoleTbl
   -------         ----------          -------------
 UserID  (PK)      RoleId  (PK)        ID       (PK)
 Name              RoleName            UserId
 UserName          Description         RoleId
 Password
 Email

With this small database I'm testing the ability to assign roles to the user.
I'm using LINQtoSQL to act as the Data Access Layer.  I've created the login mechanism to login to the software, and then I get stuck on what to do next.
For Example:

username = admin,password= admin, RoleId = 1 ;Rolename =Administrator;

And then I use the following code after the login to get the role:n
public partial class Window3 : Window
{

    public Window3()
    {
        InitializeComponent();

        GenericIdentity My2 = new GenericIdentity("admin");

        string[] roles1 = { "Administrator" };

        GenericPrincipal principal1 = new GenericPrincipal(My2, roles1);
        Thread.CurrentPrincipal = principal1;
     }

private void LoadWindow(object sender, RoutedEventArgs e)
    {   if (Thread.CurrentPrincipal.IsInRole("Administrator"))
        {
             exercise.Visibility = Visibility;
              tot.IsEnabled = false;
        }

}
I implement the code role but there is no connection with database; instead I want to store the role from the database,create a method in C# and write down a code that after user's login to get access to the application.
To explain further: I gave Rolename = Administrator so if the user is admin he'll get this role, but I'm unsure how to retreive this information from the database and tie it to the user.  Can anyone assist me?
Related (or possible duplicate) questions by Same User:

Username and role
Forms Authenticate
How create role to put in the database?

A: Sorry, I find your question a little confusing.
You seem to want to have two tables, User and Role, with a many-to-many join table, UserRole, in between.  User and Role must both have primary keys, both of which appear in the join table.
create table user
(
    user_id int not null,
    -- other fields here, like username, password, etc.
    primary key(user_id)
);

create table role
(
    role_id int not null,
    -- other fields here, like role name, etc.
    primary key(role_id)
);

create table user_role
(
    user_id int not null,
    role_id int not null,
    primary key(user_id, role_id),
    foreign key(user_id) references(user),
    foreign key(role_id) references(role)
);

When you query for a user to see if they're authorized, you're joining the many-to-many table to bring back all the potential roles at the same time.  If the credential you supply includes a role, your authorization code should check to make sure that it's a member of the set of potential roles at that time.
One minor bit of advice: Leave the "Tbl" out of your table names.  They're redundant, in my opinion.

A: If you have the "UserTbl" and "RolesTbl" in your database, you should also have two classes called "UserTbl" and "RolesTbl" in your LINQ-to-SQL model.
To store a role in the database, instantiate one of thouse "RolesTbl" objects, set it's properties, and then add it to the LINQ data context. Same with the "UserTbl" object.
EDIT: here's the code sample requested - assuming you have set up your database, your LINQ-to-SQL model and used all the default names:
// create the LINQ-to-SQL Data context
UsersAndRolesDataContext dc = new UsersAndRolesDataContext();

// create new instace of "UserTbl" object
UserTbl newUser = new UserTbl();
newUser.UserID = "newuser";
newUser.Name = "Some NewUser";
newUser.EMail = "newuser@somewhere.org";
newUser.Password = "TopSecret";

// add new user to the table of users in the data context
dc.UserTbls.InsertOnSubmit(newUser);

// create new instance of a role
RolesTbl newRole = new RolesTbl();
newRole.RoleId = "ADMIN";
newRole.RoleName = "Administrators";
newRole.Description = "User with administrative rights";

// add new role into LINQ-to-SQL Data context
dc.RolesTbls.InsertOnSubmit(newRole);

// write out all changes back to database
dc.SubmitChanges();

Does that help at all?
Marc


text:
Q: Variadic template deduction from multiple template class parameter I've searched this topic and the possible solutions for a while, but non of the answer is achieving what I wish to do.
That's I have some class template like this:
template <typename T>
class Entry {
public:
    Entry(const std::string &key, const T &value) {}
};

class Dictionary {
public:
    template <typename... ValueTs>
    explicit Dictionary(Entry<ValueTs> &&... key_value_pairs) {}
};

In my main function, I am able to declare a Dictionary class using this method (using clang-10 -std=c++17)
int main() {
    Dictionary main_dict {
        Entry {"TestKeyword", 123},
        Entry {"testKeyword2", 234.5f},
    };

  return 0;
}

But what I wish to do is to eliminate the Entry keyword within the main_dict variable and achieving something like this (Not able to compile):
int main() {
    Dictionary main_dict {
        {"TestKeyword", 123},
        {"testKeyword2", 234.5f},
    };

  return 0;
}

My assumption for doing this is that I specifically declare Entry in Dictionary's constructor to wrap all types, and therefore only Entry template can be the parameter type.
I am wondering if this work around is possible or not?
Thanks in advance!


text:
Q: react-router is not letting Link send a GET request to the server Normally I would send a GET request using axios, but in the 'React Practice Course' tutorial, the instructor successfully hits this route
app.get('/api/admin/download/:filename', auth, admin, (req, res) => {
    console.log('here I am ', req.params.filename);
    const file = path.resolve('.')+`/uploads/${req.params.filename}`;
    res.download(file);
})

with the Links in this code
import {Link} from 'react-router-dom';

showFiles = () => (
    this.state.files &&
    this.state.files.map((filename,i) => (

            <Link   to={`/api/admin/download/${filename}`}
                    target="_blank">
                {filename}
            </Link>

    ))
)

As seen here, the link matches the path in the server, but react router is sending me to the PageNotFound component instead, and never sends the GET request.
What am I missing to make a Link file reach the server? I suspect the problem is in my routes file.
const Routes = () => {
    // null = public route
    return (
        <Layout>
            <Switch>
                <Route path="/admin/add_product" exact component={Auth(AddProduct, true)} />
                <Route path="/admin/manage_categories" exact component={Auth(ManageCategories, true)} />
                <Route path="/admin/manage_site" exact component={Auth(ManageSite, true)} />
                <Route path="/admin/add_file" exact component={Auth(AddFile, true)} />

                <Route path="/user/cart" exact component={Auth(Cart, true)} />
                <Route path="/user/dashboard" exact component={Auth(Dashboard, true)} />
                <Route path="/user/user_profile" exact component={Auth(UpdateProfile, true)} />

                <Route path="/register_login" exact component={Auth(RegisterLogin, false)} />
                <Route path="/register" exact component={Auth(Register, false)} />
                <Route path="/product/:id" exact component={Auth(Product, null)} />
                <Route path="/shop" exact component={Auth(Shop, null)} />
                <Route path="/" exact component={Auth(Home, null)} />
                <Route component={Auth(PageNotFound)} />
            </Switch>
        </Layout>
    )
}

A: To expand my comments I answer here.
The following works for me:
import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

const About = () =>
About

const Home = () =>
Home

const Topics = () =>
Topics

const apiUrl = "http://localhost:9000/api";

const BasicExample = () => (
  <Router>

          <Link to="/">Home</Link>

          <Link to="/about">About</Link>

          <Link to="/topics">Topics</Link>

          <a href={`${apiUrl}/v1/test`}>Api GET request

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />

  </Router>
);

render(<BasicExample />, document.getElementById("root"));

So basically I just created an  passing the proper href url and it didn't fall into <Router>, as indicated here: https://github.com/ReactTraining/react-router/issues/1147#issuecomment-113180174
Are you sure you are passing the right url to the anchor's href?