text:
Q: Spinner, changing on selected item public class GraphFrame extends Fragment implements AdapterView.OnItemSelectedListener {
    Integer hoodSelector = 27;
    ArrayList<HoodData> hoodDataList = new ArrayList<>();
    ArrayList<String> hoodList = new ArrayList<>();
    Context mContext;

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String item = parent.getItemAtPosition(position).toString();
        // Showing selected spinner item
        if(item == "Tarwewijk"){
            setHoodId(27);
        }
        else if(item == "Carnisse"){
            setHoodId(28);
            //refreshFragment();
            //getDataFromApi((GraphView) view.findViewById(R.id.graph));
        }

        Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
    public void refreshFragment(){
        hoodDataList.clear();
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.detach(this).attach(this).commit();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_graph,
                container, false);
        //API Request for all the hoods

        getDataFromApi((GraphView) view.findViewById(R.id.graph));
        getDataForSpinner((Spinner) view.findViewById(R.id.spinner));
        return view;
    }

    public void setHoodId(Integer hood){
        hoodSelector = hood;
    }

    public void getDataFromApi(final GraphView graph) {
        RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
        String url= "http://test.dontstealmywag.ga/api/damage_or_theft_car_wijk.php?hood_id=" + hoodSelector;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Do something with the response
                        try{
                            JSONObject o = new JSONObject(response);
                            JSONArray values=o.getJSONArray("");
                            for (int i = 0; i < values.length(); i++) {
                                JSONObject jsonObject = values.getJSONObject(i);
                                hoodDataList.add(new HoodData(jsonObject.getDouble("percentage"), jsonObject.getInt("hood_id"), jsonObject.getInt("year"), jsonObject.getString("hood_name")));
                            }

                        }  catch (JSONException ex){}
                        LineGraphSeries<DataPoint> series = new LineGraphSeries<>(new DataPoint[] {
                                new DataPoint(1, hoodDataList.get(0).getPercentage()),
                                new DataPoint(2, hoodDataList.get(1).getPercentage()),
                                new DataPoint(3, hoodDataList.get(2).getPercentage()),
                                new DataPoint(4, hoodDataList.get(3).getPercentage()),
                                new DataPoint(5, hoodDataList.get(4).getPercentage())
                                //new DataPoint(12, 0)
                        });
                        graph.setTitle("Wijk " + hoodSelector + " - " + hoodDataList.get(0).getHood_name());
                        StaticLabelsFormatter staticLabelsFormatter = new StaticLabelsFormatter(graph);

                        // set manual x bounds
                        staticLabelsFormatter.setHorizontalLabels(new String[] {"2006", "2007","2008","2009","2011"});
                        //creates custom x-axis
                        graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);
                        //set nice background color :)
                        series.setDrawBackground(true);
                        //shows points at datapoints
                        series.setDrawDataPoints(true);
                        //size of the points
                        series.setDataPointsRadius(10.0f);
                        graph.addSeries(series);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // Handle error
                    }
                });

        rq.add(stringRequest);
    }
    public void getDataForSpinner(final Spinner spinner){
        setHoodId(28);
        RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
        String url= "http://test.dontstealmywag.ga/api/damage_or_theft_car_wijk.php";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Do something with the response

                        try{
                            JSONObject o = new JSONObject(response);
                            JSONArray values=o.getJSONArray("");
                            for (int i = 0; i < values.length(); i++) {
                                JSONObject jsonObject = values.getJSONObject(i);
                                if (!hoodList.contains(jsonObject.getString("hood_name"))) {
                                    hoodList.add(jsonObject.getString("hood_name"));
                                }
                            }
                        }  catch (JSONException ex){}
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(spinner.getContext(), android.R.layout.simple_spinner_item, hoodList);
                        // Specify the layout to use when the list of choices appears
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        // Apply the adapter to the spinner
                        spinner.setAdapter(adapter);
                        spinner.setOnItemSelectedListener(GraphFrame.this);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // Handle error
                    }
                });

        rq.add(stringRequest);
    }
}

Some explanation to my code: I creating graph views from data generated from an API online. Now I'm having multiple hoods to create graphs of. I made a spinner which contains all the hoods which are in my API. Now when I press a spinner item I want it to change the values which are pulled from the API. This can be done by changing the hoodId. So if HoodID = 27 it gives another graph then if HoodID = 28.
So what I thought is getting the value from the spinner in onItemSelectedListener, and make a condition like
if(item == "Tarwewijk"){
setHoodId(28);
}

This doesn't work somehow. Could anyone help me fixing the issue I'm facing.


text: Q: Syncronize data between master and client applications I have a Playframework 1.4 application that stores all the data from all branches and multiple branches that store only data of this branch. These branches can work offline, as there may be no Internet. I need to synchronize the data of the branch to the main server and from the main server to the branch server(for example directories, new users)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Processing API data as it comes in .NET Is it possible to read API data as it comes , I wrote the below Csharp code in my controller but sometimes the data takes more than 2 minutes and I was wondering if it was possible to load the data in my website as they come instead of waiting for it. Below is my current code:
private static async Task<List<Model>> GetFlightData()
    {
        using (var client = new HttpClient())
        {
            client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
            var content = await client.GetStringAsync(URL);
            var result = JsonConvert.DeserializeObject<List<Model>>(content);
            return result;
        }
    }

A: The fastest way is to save the data statically and initialize it on start up,
the problem with this solution is that IIS may restart you website when there's no traffic and the data will be lost (and will cause the next visitor to wait a whole 2 minutes).
The best suggestion I have is to save it to redis/other cache of your chosing and then just pull it from there.


text:
Q: Why do i get compile error while using template function I have a base class.
#include <string.h>
class Channel
{
private:
    std::string stdstrName;

public:
    Channel() : stdstrName("CHANNEL"){   }
    Channel(std::string name) : stdstrName(name){ }
    void PrintName() { std::cout << stdstrName << std::endl; }
};

which is inherited by Position class.
class PositionChannel : public Channel
{
public:
    std::vector<int> keyframes;
    PositionChannel() : Channel("POSITION") , keyframes( { 1 , 2, 3 }) {    }
};

There is a director class which has the channel clas as its data members.
#include "Channel.h"
#include <memory>

class Director
{
private:
    std::vector<std::shared_ptr<Channel>> channels;

public:
    void AddChannel(std::shared_ptr<Channel> chn) { channels.push_back(chn); }
    void GetChannel(Channel **chn) { *chn = channels[0].get(); }
};

now when in the main function.
 // Free function
 template<typename T>
    void GetChannel(Director *dir)
    {
        T *chn;
        dir->GetChannel(&chn);
    }

    Director dir;
    PositionChannel channel;
    std::shared_ptr<Channel> channelPointer = std::make_shared<Channel>(channel);
    dir.AddChannel(channelPointer);
    GetChannel< PositionChannel>(&dir); // here i get error

this is the error message  error C2664: ' cannot convert argument 1 from 'T **' to 'Channel **
if i change the templated function  to a non templted function than i do not get any error.

A: In you GetChannel call, &chn argument is of type PositionChannel**, but the type of Director::GetChannel parameter is Channel**. These two types are not convertible; see, for example this question: Conversion of pointer-to-pointer between derived and base classes?.
I am not sure what are your intentions since the code does not make much sense as is, but you can redefine GetChannel as follows:
template<typename T>
void GetChannel(Director *dir)
{
  Channel* ptr;
  dir->GetChannel(&ptr);
  T *chn = ptr;
}

A: T can be any type, you can't convert it to a Channel for any type.
There are probably ways to make it work with templates, but I feel like your problem could be more easily solved by using polymorphism with something like this :
void GetChannel(Channel* chn, Director *dir)
{
    dir->GetChannel(&chn);
}

And then chn can be any type dervived from Channel.

A: Yes, Daniel Langr already gave the correct answer. I added a check in the template if the class is derived.
#include <type_traits>
class Channel
{
    public:
    virtual ~Channel() = default;
};

class PositionChannel : public Channel
{
};

struct Director{
    void GetChannel(Channel **c) {}
};

template <typename T,
typename = typename std::enable_if<std::is_base_of<Channel, T>::value, T>::type>
void GetChannel(Director *dir)
{
    Channel *chn;
    dir->GetChannel(&chn);
    T* ptr = static_cast<T*>(chn);
}

int main(void) {
    Director dir;
    GetChannel<PositionChannel>(&dir);
    return 0;
}


text:
Q: Overriding MaxZoom on Google Earth Engine (GEE) I cannot zoom past maxZoom: 24 - and entering a number greater than 24 is not allowed.
Map.setLocked(0, 1, 24);

Any workarounds? I have assets with ~2cm Ground-sampling Distance / Pixel size and can't see all the detail as is in Earth Engine.


text:
Q: How to remove datetimes in list based on minutes? We are working with Python 3, where we have a list of datetimes, which looks like this:
first_datetime = {2019-08-08 14:00:00, 2019-08-08 14:10:00, 2019-08-08 14:20:00, 2019-08-08 14:30:00, 2019-08-08 14:40:00, 2019-08-08 14:50:00, 2019-08-08 15:00:00}

What we want is to only append datetimes, where minutes in datetime is either 00, 20 or 40, into a new list.
Therefore above list should look like:
new_datetime_list = {2019-08-08 14:00:00, 2019-08-08 14:20:00, 2019-08-08 14:40:00, 2019-08-08 15:00:00}

Our program looks like following:
for i in range(len(first_datetime)):
    time = datetime.datetime.strptime(first_datetime[i], '%Y-%m-%d %H:%M:%S')
    if time != x:
        new_datetime_list.append(first_datetime[i])

We imagine that we could do something like:
for i in range(len(first_datetime)):
    time = datetime.datetime.strptime(first_datetime[i], '%Y-%m-%d %H:%M:%S')
    if time != x and time != CAN'T CONTAIN 10, 30, 50 IN MINUTES:
        new_datetime_list.append(first_datetime[i])

Although we dont know how to to the above, hence we are posting this post.

A: You can check the minutes using time.minute in [0, 20, 40], so your snippet of code could look like
for i in range(len(first_datetime)):
    time = datetime.datetime.strptime(first_datetime[i], '%Y-%m-%d %H:%M:%S')
    if time != x and time.minute in [0, 20, 40]:
        new_datetime_list.append(first_datetime[i])

(I have kept the time != x condition, not sure if you need it for something else you didn't mention)
btw you can simplify the way you iterate through the array without using indexes like this:
for str_datetime in first_datetime:
    time = datetime.datetime.strptime(str_datetime, '%Y-%m-%d %H:%M:%S')
    if time != x and time.minute in [0, 20, 40]:
        new_datetime_list.append(str_datetime)

A: You can use the minute operator from datetime:
import datetime
first_datetime = ['2019-08-08 14:00:00', '2019-08-08 14:10:00', '2019-08-08 14:20:00', '2019-08-08 14:30:00', '2019-08-08 14:40:00', '2019-08-08 14:50:00', '2019-08-08 15:00:00']
new_datetime_list = []

for i in first_datetime:
    time = datetime.datetime.strptime(i, '%Y-%m-%d %H:%M:%S').minute
    if (time == 20) | (time == 40) | (time == 0):
        new_datetime_list.append(i)

Output (print(new_datetime_list)):
['2019-08-08 14:00:00', '2019-08-08 14:20:00', '2019-08-08 14:40:00', '2019-08-08 15:00:00']


text:
Q: How to indicate success with Web API 2? I'm issuing a PATCH request to my server in order to update a title:
$.ajax({
    url: Settings.get('serverURL') + 'Playlist/UpdateTitle',
    type: 'PATCH',
    dataType: 'json',
    data: {
        id: model.get('id'),
        title: title
    },
    success: function () {
        console.log("Success!");
    },
    error: function (error) {
        console.error("Failure!");
    }
});

[Route("UpdateTitle")]
[HttpPatch]
public IHttpActionResult UpdateTitle(PlaylistDto playlistDto)
{
    using (ITransaction transaction = Session.BeginTransaction())
    {
        PlaylistManager.UpdateTitle(playlistDto.Id, playlistDto.Title);

        transaction.Commit();
    }

    return Ok();
}

Everything works great except for the fact that the ajax request's error callback is executed and not the success callback.
Before Web API 2, I was using the following method which did not have the problem. Clearly the issue is that I am returning an Ok result instead of a JSON success object:
[HttpPost]
public JsonResult UpdateTitle(Guid playlistId, string title)
{
    using (ITransaction transaction = Session.BeginTransaction())
    {
        PlaylistManager.UpdateTitle(playlistId, title);

        transaction.Commit();
    }

    return Json(new
        {
            success = true
        });
}

What's the proper way to indicate success with web API 2?

A: Return an HttpResponseMessage and set the StatusCode to OK:
public HttpResponseMessage UpdateTitle() {
    ...
    return Request.CreateResponse(HttpStatusCode.OK);
}

A: The problem is actually pretty simple:
dataType: 'json',

tells jQuery to not use intelligent guessing for the server's response type. It will throw an error if the server does not respond with json. If I just delete that property then everything works as expected.


text:
Q: plotting issue on R (using heatmaps) I have a matrix to plot and I am using the following lines:
library(lattice)
levelplot(cont.freq)

I want to get rid of the black things in the plot? I would like to use rownames and colnames of the matrix for x&y labeling. However I don't know how to represent them in a nice way.
By the way, matrix is 1284x1284..

A: Following works:
x_at <- pretty(seq_len(nrow(cont.freq)))
y_at <- pretty(seq_len(ncol(cont.freq)))
levelplot(cont.freq, rm.na = TRUE, scales=list(y=list(at=y_at),x=list(at=x_at)), xlab="Residue ID", ylab="Residue ID", main="Contact Frequency")


text:
Q: CSS to override Google Sheets gridlines? I'm looking for help on why my CSS isn't working.
I want to use the Stylebot chrome extension with this CSS to make gridlines darker on a Google Sheet.
.waffle td, .grid-fixed-table td {
  border: 1px solid;
  border-color:  black;
  border-collapse: collapse;
}

The gridlines show for a second when loading a new sheet but then disappear. Can anyone help me to understand why/show me a solution?


text:
Q: Add logout buttom in customer navigation tab before making upgrade magento 2.1.10  it was incliging logout button ,

after upgrade to 2.3.5 this custom buttom was hidden
so i want to disable this button it's locate at app/design/frontend/../../../Magento_Customer/templates/account/navigation.phtml ,
so any idea please to how to solve it
Thank you


text:
Q: What EPC ID prefix to use? This is a bit of a 'I give up' question but....
The situation
My company is using RFID tags to track the movement of stuff (hire-able stuff like jack-hammers etc) around large industrial sites.
We are managing this by using RFID tags and a smattering of readers.
We are not the manufacturers or resellers of this equipment; nor are we the 'owners' of them. As a result,we have no interest in barcoding these items. Additionally, these items will never leave these sites, so will never be 'back in the world'.
The questions

*

*What 'prefix' should we use to program into the "EPC ID"? (afaik, our very own gold-plated GS1-approved good-for-a-year prefix)

*Are there any 'open access' EPC ID prefixes? (afaik, no)

*Does it matter if we just program any prefix in? (afaik, no, but yes, but no, so should we just keep the gold ourselves?)

Other info
I have read stuff from GS1 about registering a company prefix etc. The issue for us is that we would happily buy a prefix, but they seem to be very expensive; especially because we are not tracking these tags in the big-wide-world, just a controlled site. I have found the lack of simple information about what I am meant to do for EPC IDs and whether I am meant to register a prefix quite frustrating (hence my 'give up' question).
Any advice would be appreciated!

A: There is a list of 'restricted distribution' prefixes that can be used - see Wikipedia (https://en.wikipedia.org/wiki/List_of_GS1_country_codes). While officially those should not be used in EPC encoded tags; nobody is going to sue or fine you for actually doing so.
Probably you can use those best in combination with GRAI (Global Returnable Asset Identifier) or GIAI (Global Individual Asset Identifier) EPC encoding. See http://www.kentraub.net/tools/tagxlate/EPCEncoderDecoder.html for an easy online encoder/decoder.
You could use your own way of encoding, ignoring the GS1 EPC standards. However, this might limit future compatibility with 3rd party software solutions, and limit usability for other partners on the industrial sites.


text:
Q: Size in bytes for a vector of vector I tried to find the size in bytes for a vector of vector. I need this size in order to allocate a pointer with malloc. It seems to me that I allocated too much memory, because when I try to copy the content with memcpy it says "access violation reading location ...". The strange thing is that it crashes only some times, even If i don't change the code. Is there something that I'm missing?
In order to fully understand my question here is a piece of code:
struct Node
{
    int total;
    float threshold;
    float value[2];
    int child [2];
};

vector<vector<Node>> NodeArray;
NodeArray.resize(100);

for (int  i = 0; i < NodeArray.size(); i++)
{
    NodeArray[i].resize(20);
}

int ArraySize = sizeof(NodeArray);
for (vector<vector<Node>>::iterator it = NodeArray.begin(); it != NodeArray.end(); ++it)
{
    ArraySize += it->size() * sizeof(Node) + sizeof(it);
}

vector<vector<Node>> *NodeArray_d;
NodeArray_d= (vector<vector<Node>>*)malloc(ArraySize);
memcpy (NodeArray_d, &NodeArray, ArraySize);


text:
Q: String Replace in Python - Using Re.sub - having additional unnecessary characters I am using Python 2.7 here where have a String "portalColumn":"col-0","portlet": , and I am trying to replace the "col-0" with say "col-1" or "col-2".. So, I am trying to use the Python's s = re.sub("col-(.*?)", column, portletJsonString)
It replaces the "col-0" to "col-10" when I pass "col-1" in the column variable.. and portletJsonString is my string in which I want to replace.
So I see this after the re.sub call :
"portalColumn":"col-10","portlet"
What is the correct way to replace my string guys? It keeps the 0 intact.
Thanks for any help.

A: I figured it out :-)
Just used .? instead of .*? .. Unnecessary * in there.
Also, as Kenneth mentioned, can use \d+


text:
Q: How do I go to the latest commit from remote/master in git? I accidentally saved a file on the wrong branch. Then I did git reset --soft HEAD^ and now git status says I'm behind by 14 commits and lists a bunch of modified files in red. Including some untracked files.
I have no idea what to do. I tried to go to the latest commit from the remote repo but it says my local changes would be overwritten after I do git pull.
Help. I don't wanna mess up my local repo even more. I just want to get back to the state I was in, save the edited file in the correct branch, and commit.

A: If you have changed your local branch, and do not want to lose any change, you can use git-stash. Before any attempt, I recommend you to backup your local repository. Try the following steps:

*

*git stash save 'local changes'.
This will save your local changes in a temporary place, and let you work on the current branch without any of these previous changes.

*git pull <remote-name> <branch-name>. As you already know, it will retrieve newer commits from the remote branch, and apply to your local branch.

*git stash pop. This will revert what you did in step 1. It will apply your previous changes (those you saved) against the local branch. You are responsible for resolving any conflicts, if any occur. Once done, you may want to commit, and push - it's up to you.

A: Don't panic

*

*Backup your repository.

*Stash your changes with git stash save. This will put your changes in the stash.

*Then, pull from the remote branch: git pull <remote> <wrong-branch>. This will return your working copy to the pristine branch HEAD. This is what your branch looked like before you started working on the changeset.

*Now, apply the stashed changes to your working copy: git stash apply. Git will be smart enough to ignore stashed changes that match existing commits, so you will be left with your working copy in the same state as before you made the commit to the wrong branch.

*Now checkout the right branch, and commit as usual:
git checkout <right-branch>
git add [...]
git commit -m "blah blah blah"

You may have to wrangle your changes when checking out the correct branch if your change set is incompatible with the correct branch, but once done, Your changes will now be committed on the right branch.


text:
Q: Data Structure for Multilevel Key What is the best data-structure for efficient level search, when the key is function of multiple values.
Say my Key is [Row Key] [Column Name] [ TimeStamp ]

A: Maybe you are looking for a multi-dimensional index or aggregate index?
Aggregate indexes combine several keys (timestamp, row key, ...) into a single key which is then stored in a normal search index (Hashmap, B-tree or similar). Aggregation can be done by concatenating the keys or interleaving their bits.
Multidimensional indexes allow indexing and searching for several attributes at the same time. For example if you have [ID] [attr1] [attr2] [timestamp] then you could use a 4-dimensional index. You would have to turn all values into integers or floats (for Strings you could use turn the first few characters into an integer). For look-up, you can simply those dimension empty where you don't know the value.
Multi-dimensional indexes are for example R*-Tree, X-tree, PH-Tree. There are also the kd-tree and quadtrees, they are quite simple to implement but not really that good for large datasets or many dimensions.


text:
Q: Transaction Log a part of the server or database? In practice (and in general) is a transaction log a part of the database server or is it a part of the database itself? I've not been able to locate information in this domain anywhere. I need the information for a model that I'm putting together...
If this is extremely dependent upon implementation, I'm looking at SQL Server 2005/2008, MySQL and SQLite. But I'd prefer to stay as general as possible.
I imagine that if the transaction log is a part of the server, then there would be one (maybe two) transaction log in the entire server. This is opposed to each database having one transaction log which would give us many transaction logs in the single server.

A: To add to Joe's comment, when a change to a database is transmitted to a database server, it is "aimed" at one specific database. However, the change does not take place to the database directly. It is stored in memory (RAM) and then written to a transaction log. The transaction logs are then written (committed) to the actual databases. When that committal takes place varies based on the database software (MySQL, SQL Server, etc.), the database engine settings and other variables.
All that to say: transaction logs are, generally speaking, a component of the individual databases. You could theoretically have hundreds (thousands?!) of transaction logs on a single server. Some exceptions exist, such as Exchange servers where the transaction logs are a component of the Storage Group which may have multiple databases... but I won't mention that since it would muddy the waters. =)

A: In Microsoft SQL Server the transaction log is a component of the database.


text:
Q: XSLT: Consolidating Stylesheets I currently am using two stylesheets to get my intended output.  The first stylesheet (pass1.xsl) does the real work, and the second stylesheet (pass2.xsl) removes duplicates while providing minor formatting updates.
My question is whether I can perform both actions within a single stylesheet.
When I'm looking at the content, I don't get the impression I can via xsl:functions because both stylesheets contain template matches that would conflict if I copy/pasted from the second into the first.  IE:
pass1.xsl:
<xsl:template match="xs:complexType">
  <xsl:param name="prefix" />
  <xs:complexType name="{my:updateName($prefix, @name)}">

    <!-- insert xs:sequence ONLY if the child is NOT xs:complexContent -->
    <xsl:choose>
      <xsl:when test="*[name()='xs:complexContent']">
        <xsl:apply-templates select="node()" />
      </xsl:when>
      <xsl:otherwise>
        <xs:sequence>
          <xsl:apply-templates select="node()" />
        </xs:sequence>
      </xsl:otherwise>
    </xsl:choose>
  </xs:complexType>
  <xsl:apply-templates select=".//xs:element" />
</xsl:template>

pass2.xsl:
<xsl:template match="xs:complexType">
  <xsl:copy>
    <xsl:apply-templates select="*|@*"/>
  </xsl:copy>
</xsl:template>

To reiterate - the goal is to run only one stylesheet to produce the final result.
It's not a hardship to run two, but it'd be nice not to have to.  Am I looking at copy/pasting into the original & making it work, or are imports/includes what I should be looking at?  I'd prefer to only have one stylesheet file - to minimize the chance of someone mistakenly deleting a supporting file.

A: You should use different modes for templates (this will require adding mode attribute to all xsl:template and xsl:apply-templates statements). Then your template for the root node in default mode would first fire off the root template in first mode, and then pass the result of that to the root template in the second mode. For this, you will need the ability to treat a result tree fragment (which is what element constructors produce) as a node-set (which is what you can apply templates to and otherwise query via XPath) - there's no standard way to do this, but exsl:node-set is a de facto standard for that (note that the full list of processors supporting it is larger than what's on that page - for example, .NET XslCompiledTransform supports it). So:
<xsl:template match="/">
   <xsl:variable name="round1-output">
     <xsl:apply-templates select="/" mode="round1" />
   </xsl:variable>
   <xsl:apply-templates select="exsl:node-set($round1-output)" mode="round2" />
</xsl:template>

<xsl:template match="/" mode="round1">
   ...
   <xsl:apply-templates mode="round1" />
   ...
</xsl:template>

<xsl:template match="/" mode="round2">
   ...
   <xsl:apply-templates mode="round2" />
   ...
</xsl:template>

...

<xsl:template match="xs:complexType" mode="round1">
  <xsl:param name="prefix" />
  <xs:complexType name="{my:updateName($prefix, @name)}">
    <!-- insert xs:sequence ONLY if the child is NOT xs:complexContent -->
    <xsl:choose>
      <xsl:when test="*[name()='xs:complexContent']">
        <xsl:apply-templates select="node()" mode="round1"/>
      </xsl:when>
      <xsl:otherwise>
        <xs:sequence>
          <xsl:apply-templates select="node()" mode="round1"/>
        </xs:sequence>
      </xsl:otherwise>
    </xsl:choose>
  </xs:complexType>
  <xsl:apply-templates select=".//xs:element" mode="round1"/>
</xsl:template>

<xsl:template match="xs:complexType" mode="round2">
  <xsl:copy>
    <xsl:apply-templates select="*|@*" mode="round2"/>
  </xsl:copy>
</xsl:template>


text:
Q: A Dedekind (pseudo) finite set Quoting the wiki:- a set A is Dedekind-infinite if some proper subset B of A is equinumerous to A. Explicitly, this means that there is a bijective function from A onto some proper subset B of A. -.
There is a also a  categorical definition of Dedekind infinite object, which runs as follows:
-An object $A$ in a category $C$ is Dedekind infinite if there a monomorphism $j:A\rightarrow A$ which is not an iso.-
Now, my question is:
is there some suitable category $C$ over some ground  "category of sets"  $E$ (for instance a topos with a NNO) and a Dedekind infinite object $A$ in $C$, whose image is finite  (in Dedekind's sense, or even in the standard sense of being in a bijiection with a finite number) in $E$?
Basically,  I am after some gadget that "looks" (Dedekind) infinite inside of $C$  but not "in reality", ie in the ground category $E$.
Why I am interested: assuming that such animals exists somewhere in the vast world of mathematics, they would possibly be good candidates for mirroring  Cantor's paradise inside the finite world.

A: It seems reasonable to think that a topos $C$ defined over (i.e., equipped with a geometric morphism to) the category $E$ of sets counts as a "suitable category $C$ over some ground "category of sets" $E$."  Then presumably the word "image" in the question would refer to the forward-part of the geometric morphism, i.e., the "global sections" functor Hom$(1,-)$ from $C$ to $E$. With this interpretation, you get the following example (and lots more like it).  Take $C$ to be the topos of $G$-sets where $G$ is your favorite non-trivial group.  Take $A$ to be the disjoint union of infinitely many copies, say indexed by the natural numbers, of the regular action of $G$ on itself.  This is Dedekind-infinite because you can shift the $n$-th copy to the $(n+1)$-st.  But its set of global sections (i.e., $G$-fixed points) is not only finite but empty.
This sort of example is unlikely to be what you wanted.  So could you please clarify how I should interpret "suitable category," "over," and "image"?


text:
Q: how to add short sounds while swiping images in uiscrollview
Possible Duplicate:
how to add short sounds while swiping images in uiscrollview

this is my code
here i want to add sounds while swipe images.
int x,y,count;
    but=[[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:@"top2.png"],[UIImage imageNamed:@"top1.png"],[UIImage imageNamed:@"top3.png"],[UIImage imageNamed:@"top4.png"],[UIImage imageNamed:@"top5.png"],[UIImage imageNamed:@"top6.png"],[UIImage imageNamed:@"top7.png"],[UIImage imageNamed:@"top8.png"],nil];

    x=0;
    y=0;
    count=0;
    for (int i=0; i<=7; i++) {
        count++;
        for (int i=7; i>=0; i--) {
            count--;

            UIButton *but2=[[UIButton alloc]initWithFrame:CGRectMake(x, y, 320, 141)];

            //[but setImage:[UIImage imageNamed:@"mzl.jpg" ]forState:UIControlStateNormal];
            [but2 setImage:[but objectAtIndex:i] forState:UIControlStateNormal];
            NSLog(@"%@",but);

            x=x+320;
            // x=0;
            //y=0;

            if(count==8)
            {
                //count++;
            }
            //[scr addSubview:images];
            //[images release];
            [scrollview1 addSubview:but2];
        }
    }
    scrollview1.pagingEnabled=TRUE;
    [scrollview1 setContentSize:CGSizeMake(x, y)];


text:
Q: Social Events (White Whales, Royal Convoys, Social Chests) Locating This is somewhat related to this post.
I have yet to find a single white whale, royal convoy, or social chest in Assassin's Creed 4: Black Flag. I've played for about 70 hours (all of it while online) on the PS4. I've done everything I can in the game except these 3 things and it's killing me. All I've been doing lately is sailing around and wishing something would appear.
Could someone describe how you located the events? As in, the visuals, etc. I've read they appear as blue icons, but some questions I have are the following.

*

*Did you find them by looking at the minimap on the screen (circle in lower left), or by opening up the big map and scanning around?

*Do you remember finding one while you were moving at travel speed?

Also, does anyone know why these things might not be showing up for me? It seems like a few people online are having the same issue and some have even signed a petition to Ubisoft.
This is all so frustrating.

A: When the game was first released, people had little trouble finding these events and completed the associated challenges fairly swiftly. Ubisoft decided that the spawn rate was too high and decided to reduce it. With that and/or the release of the next gen consoles, people started to report that they were no longer locating these social events.
The following was posted by an Ubisoft employee known as Ubi-Valentin:

A maintenance is scheduled on 1/14 at 9:00 AM (GMT). The operation
  will last for approximately 1 hour.
Tasks for this maintenance: We need to update the game server on all
  platforms in order to fix an issue related to social events and also
  prepare for the next Title Update.

Since this update, people have responded positively that the issue is now fixed. This forum topic highlights this fact. I have linked from the point that the UK Forum Manager quotes Ubi-Valentin regarding the scheduled update.
In answer to your questions:

*

*With regards to Royal Convoys and White Whales, these are found by sailing close to them (approximately within 500-750 metres of the event). Chests are found inland and will be discovered when approaching them.

*They can be found whilst moving at travel speed.

The events appear on your map as a light blue icon (chest, whale and convoy). See the map linked further down for examples.
So far, it seems visual clues can be misleading. I have spotted numerous White Whales leaping from the water, but no White Whale event spawned around this location. I came to the following possible conclusions regarding this:

*

*The events were broken at the time, but the visual of the whale still worked.

*The visual of the whale informs the player that White Whales do spawn in this location, but this event is not currently up.

*Just eye candy. Huge whales leaping from the water is pretty cool looking!

Social Royal Convoys will be sailing with escorts, just like the normal Convoys. Look out for groups of ships sailing in unison. Chests can be heard via the normal "secret" sound, but will probably appear on your map before hearing this anyway.
A map has been created by the community over at ac initiates, which lists many known possible spawn points. Lots of people have reported success of using this since Ubisoft's server update. It can be found here.
Regarding my own experiences. I almost completed the achievement on the PC version when it was first released (about 1 month after console release). Then nothing for a month or two and now I am starting to see them pop up again. I believe I just need to locate a chest and I am done. Hope this helps.

A: It took me two days going back again and gain to the these sites, but I got the Simulation Challenges 100% completed today (01/20/2014).
These are the locations I found my Social Chest, White Whales, and Royal Convoys:
Social Chest
575,720: (Andreas Island) At the Tavern by the crated 4 Rum Crate directly behind the Morris Player.
633,784: (Nassau) Fast travel to the fort's tower (located Northeast), take out the guard, then to the left of the Leap of Faith (between the two small rock pillars), drop down and go inside the tower, (three window tower), and it appears right of the lamp on the floor next to the rope crate.
White Whale
674,315: (Between Anotto Bay and Cumberland Bay) One can approach it from either location.
NEW LOCATION:877,654. 198,346 for another 7hrs, 50min (January 30, 2014, 7:00pm [CET]).
Royal Convoy
62,162 (Ambergris Key) Sail a figure 8 around those two islands and you will find a royal convoy (the one I found was from Spain).

A: Social chests can be found on certain secondary locations(unnamed islands) you can pay 200R at taverns for a naval convoy location (not social royal convoy location)  and white whales are sometimes located near legendary ships.


text:
Q: SQL Multiple Count In One Query I am trying to run the following query to return a list of all months with the count of English and Scottish users. I am not sure how to run multiple Count queries along side each other.
SELECT month(Date) as month
     , COUNT(*) as scottishCount
  FROM users userTable
 WHERE year(Date) = 2015
   AND userTable.UserID in
 (select nationsTable.UserID
    from users nationsTable
   where nationsTable.Nation = 'Scotland'), COUNT(*) as englishCount FROM users userTable WHERE year(Date)=201 AND userTable.UserID in (select nationsTable.UserID from nations nationsTable where nationsTable.Nation= 'England') GROUP BY month(DateClicked);

Thanks in advance,
Fred

A: You must move your conditions to the SELECT clause in order to count conditionally. MySQL treats true as 1 and false as 0, so you can use SUM to count matches. It doesn't seem necessary to select from the users table multiple times:
SELECT
  MONTH(date) AS month,
  SUM(nation = 'Scotland') AS scottish_count,
  SUM(nation = 'England') AS english_count
FROM users
WHERE YEAR(date) = 2015
GROUP BY MONTH(date)
ORDER BY MONTH(date);


text:
Q: Implementing SOAP with OSGi in Eclipse I have been developing an application using OSGi-Equinox iwith Eclipse. Now I would liek to implement some web-services. I manage to implement some simple webservices using org.eclipse.equinox.http. Using this package I send HttpServletRequest and return HttpServletResponse, where i write the "answer" in a PrintWriter.
Now I would like that the messages exchanged are SOAP messages and also use WSDL. Can any one point me to a tutorial to do this using eclipse and OSGi? Is jetty a good option?Is there any tutorial with Jetty and OSGi to implement SOAP?
Thanks!
Ana

A: I found a very interesitng tutorial using apache:
http://cxf.apache.org/distributed-osgi.html


text:
Q: Release build for Visual Studio Cordova Project failes I am using visual studio 2015 with update 3 and TACO Update 10. Everything was working fine, but since yesterday I'm unable to make a release build for android. I reinstalled almost everything on my machine and the problem continues. The error has something to do with the gradle daemon. The relevant part of the build output is:
Starting a new Gradle Daemon for this build (subsequent builds will be faster).
1>MSBUILD : cordova-build error : FAILURE: Build failed with an exception.
1>MSBUILD : cordova-build error : * What went wrong:
**1>MSBUILD : cordova-build error : Unable to start the daemon process.**
1>MSBUILD : cordova-build error : This problem might be caused by incorrect configuration of the daemon.
1>MSBUILD : cordova-build error : For example, an unrecognized jvm option is used.
1>MSBUILD : cordova-build error : Please refer to the user guide chapter on the daemon at https://docs.gradle.org/2.13/userguide/gradle_daemon.html
1>MSBUILD : cordova-build error : Please read the following process output to find out more:
1>MSBUILD : cordova-build error : -----------------------
**1>MSBUILD : cordova-build error : java.lang.IllegalArgumentException: URI has an authority component**
1>MSBUILD : cordova-build error :  at java.io.File.<init>(File.java:423)
1>MSBUILD : cordova-build error :  at org.gradle.internal.classloader.ClasspathUtil.getClasspathForClass(ClasspathUtil.java:68)
1>MSBUILD : cordova-build error :  at org.gradle.internal.installation.CurrentGradleInstallationLocator.findDistDir(CurrentGradleInstallationLocator.java:54)
1>MSBUILD : cordova-build error :  at org.gradle.internal.installation.CurrentGradleInstallationLocator.locateViaClass(CurrentGradleInstallationLocator.java:45)
1>MSBUILD : cordova-build error :  at org.gradle.internal.installation.CurrentGradleInstallationLocator.locateViaClassLoader(CurrentGradleInstallationLocator.java:41)
1>MSBUILD : cordova-build error :  at org.gradle.internal.installation.CurrentGradleInstallationLocator.locate(CurrentGradleInstallationLocator.java:31)
1>MSBUILD : cordova-build error :  at org.gradle.internal.installation.CurrentGradleInstallation.locate(CurrentGradleInstallation.java:46)
1>MSBUILD : cordova-build error :  at org.gradle.internal.installation.CurrentGradleInstallation.get(CurrentGradleInstallation.java:41)
1>MSBUILD : cordova-build error :  at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:45)
1>MSBUILD : cordova-build error :  at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:36)
1>MSBUILD : cordova-build error :  at org.gradle.launcher.daemon.bootstrap.GradleDaemon.main(GradleDaemon.java:22)
1>MSBUILD : cordova-build error : Picked up _JAVA_OPTIONS: -Xmx512M

A: Forcing VS TACO to use the latest version of JAVA JDK fixed the problem.


text:
Q: Connecting to external database through telnet I have a java program that connects to a MS SQL database. The program works perfectly when running through eclipse however I get an error when I run it through AIX:

java.sql.SQLException: Network error IOException: A remote host refused an attempted connect operation.

I can successfully ping the server but am not able to telnet into the server.  I am also not able to telnet from my windows desktop.
I am using jtds to connect:
String connectionString = "jdbc:jtds:sqlserver://"+dropez_ip_address+"/"+dropez_db_name;
ResultSet rs = null;
Statement stmt = null;

try{

    Class.forName("net.sourceforge.jtds.jdbc.Driver");
    Connection conn = DriverManager.getConnection(connectionString, dropez_db_username, dropez_db_password);

    stmt = conn.createStatement();
}catch(Exception e){}

Here is some documentation from jTDS regarding the issue, but I am still not able to resolve the issue.
Why do I get java.sql.SQLException: "Network error IOException: Connection refused: connect" when trying to get a connection?

The "Connection refused" exception is thrown by jTDS when it is unable to connect to the server. There may be a number of reasons why this could happen:

    - The server name is misspelled or the port number is incorrect.
    - SQL Server is not configured to use TCP/IP. Either enable TCP/IP from SQL Server's Network Utility app or have jTDS connect via named pipes (see the URL format for information on how to do this).
    - There is a firewall blocking port 1433 on the server.

To check whether TCP/IP is enabled and the port is not blocked you can use "telnet 1433". Until telnet doesn't connect, jTDS won't either. If you can't figure out why, ask your network administrator for help.

A: If you can't telnet on port 1433, you are blocked by a firewall somewhere in the middle between your machine and the server. That's not a java related problem.
May it be that when you say "it runs perfectly under eclipse but not AIX" you are taking about 2 different computers ? If so, the one with eclipse is not firewalled, the one where you deploy your app is blocked.
But again, nothing to do with java. It's a level 3 error (TCP layer) of TCP-IP model.
Regards,
 Stéphane

A: Your SQL Server database probably doesn't have the TCP/IP protocol enabled, to enable it:

*

*From the Microsoft SQL Server 2005 -> Configuration Tools, open the 'Microsoft SQL Server Configuration Manager'.

*Expand 'SQL Server 2005 Network Configuration', and then click 'Protocols for '.

*Right-click 'TCP/IP' and then click 'Enable'. The icon for the protocol will change to show that the protocol is enabled.
For SQL Server 2008:


text:
Q: ReactJS handling a lot of data in state I have a React application that needs to handle a lot of data. Overall it's a simple application :

*

*Header with a few links

*Search bar

*Table

The catch is, depending on what is being searched for...the table needs to display up to 1,000 rows by about 100 columns. When the http request returns this data and set in state, the application pretty much becomes unusable. Any other attempt to update state after it contains that data either takes forever or crashes the browser. Even when I limit the table to display 20 rows x 100 columns, the state update is significantly faster, but still noticeable to update.
I tried scouring the web to find a good solution and have come up short so any ideas/help/suggestions are welcome. If redux will help, I have no issue implementing that, I just don't want to waste my time if there is no payoff.

A: You're probably re-rendering the entire table along with the search bar whenever you type in it.  Maybe try putting the table into a subcomponent which implements shouldComponentUpdate().  Is the table data supposed to dynamically update whenever you type a character into the input?  That might be expensive, you could also consider only re-rendering the table when a user clicks the "search" button by the input.
Rather than beat around the bush trying to figure out if it's a rendering issue, though, I recommend using the React performance tools*.  Benchling has a solid blog post which walks through the process of performance debugging in React, but the magic is Perf.printWasted().  It will show you how much time was spent re-rendering components which were the same after the rendering (e.g. your table when you're only changing the text input).  Test steps:

*

*From the console, run: Perf.start()

*type in your input, ideally just one keystroke

*console : Perf.stop()

*console : Perf.printWasted()
This method is super painless, but you can also use the Chrome profiling tools to find out the same info.
*I just found out that they've been deprecated in hot-off-the-press React 16, but you're likely still using a 15.x variant which works fine.
Also, +1 for react-virtualized!  It's excellent, supports many columns and layouts.

A: If I understood you correctly your problem is not the amount of data - problem in DOM rendering.
I think the best solution for you will be to render only visible part of table. For example try to use this library or similar.


text:
Q: This Objective-C method is supposed to return an IBAction. Why is there no return statement? I am learning Objective-C and iOS development. I think I have a handle on method syntax. Method Syntax in Objective C
If I am understanding correctly, this instance method called reset should return an IBAction object. But it just seems to be setting instance variables (which are UI text fields with those names). Why doesn't it have a return statement returning an IBAction object?
- (IBAction)reset {               //why does it not have a return statement?
    fahrenheit.text = @"32";
    celsius.text = @"0";
    kelvin.text = @"-273.15";
}

I am used to .NET code that would look like this (putting it in pseudocode for non-NET folks):
public function reset () returns IBAction
        me.fahrenheit.text = "32";
        me.celsius.text = "0"
        me.kelvin.text = "-273.15"
        return new IBAction    //I would expect something like this in obj C, based on my experience with .NET languages
end function

A: IBAction is typedef'd void. It is used by Xcode as a hint that the method is to be available for "hookup" in interface builder.


text:
Q: Compose array of Functions using stream I want to compose an array of functions to one function. Given multiple functions the method should return a function which is the composition of the input functions.
One way to do this is
public static <T> Function<T,T> composeAll(Function<T,T>... functions){
    Function<T,T> res = Function.identity();
    for(Function<T,T> f : functions){
       res = res.compose(f);
    }
    return res;
}

I'm looking to achieve the same result by first making a stream of the array of functions. But I can't figure out how to do this
public static <T> Function<T,T> composeAll2 (Function<T,T>... functions){
    Function<T,T> res = Function.identity();
    Arrays.stream(functions). ???
    return res;
}

What code should I enter in the last method where I put question marks now?

A: You can make use of the Stream#reduce() operation:
public static <T> Function<T,T> composeAll2 (Function<T,T>... functions){
    return Arrays.stream(functions).reduce(Function.identity(), Function::compose);
}

Which is identical to your iterative way of composing functions.

A: While @Lino's answer is concise, it is unsafe and prone to stack overflow:
List<Function<Integer, Integer>> list = Collections.nCopies(10000, i -> i + 1);
System.out.println(composeAll2(list.toArray(new Function[0])).apply(0));

If you run this code, it will fail with StackOverflowError:
Exception in thread "main" java.lang.StackOverflowError
    at java.util.function.Function.lambda$compose$0(Function.java:68)
    at java.util.function.Function.lambda$compose$0(Function.java:68)
    at java.util.function.Function.lambda$compose$0(Function.java:68)
    at java.util.function.Function.lambda$compose$0(Function.java:68)
    at java.util.function.Function.lambda$compose$0(Function.java:68)
    at java.util.function.Function.lambda$compose$0(Function.java:68)
    ...

To avoid this, I suggest not using streams at all and using the old for-each loop:
public static <T> Function<T,T> composeAll2(Function<T,T>... functions){
    return input -> {
        T res = input;
        for (Function<T, T> f : functions) {
            res = f.apply(res);
        }
        return res;
    };
}

This version of composeAll2 will use a constant stack space.


text:
Q: WooCommerce - Display how many people have a product in their cart with conditional message I'm using Show how many people have added a product in their current cart to display how many people have added a product in their current cart on the Shop and Single Product pages; similar to what you see on stores like Etsy.
The snippet works as is but it would be nice to conditionally change the message depending on if there is 1 user vs. multiple people (i.e "1 person has this in their cart right now." vs "10 people have this in their carts right now.").
If anyone has any suggestions on the best way to handle that it would be appreciated. :)
function show_no_of_people_added_in_cart(){
    global $wpdb, $product;
    $in_basket = 0;
    $wc_session_data = $wpdb->get_results( "SELECT session_key FROM {$wpdb->prefix}woocommerce_sessions" );
    $wc_session_keys = wp_list_pluck( $wc_session_data, 'session_key' );
    if( $wc_session_keys ) {
        foreach ( $wc_session_keys as $key => $_customer_id ) {
            // if you want to skip current viewer cart item in counts or else can remove belows checking
            if( WC()->session->get_customer_id() == $_customer_id ) continue;

            $session_contents = WC()->session->get_session( $_customer_id, array() );
            $cart_contents = maybe_unserialize( $session_contents['cart'] );
            if( $cart_contents ){
                foreach ( $cart_contents as $cart_key => $item ) {
                    if( $item['product_id'] == $product->get_id() ) {
                        $in_basket += 1;
                    }
                }
            }
        }
    }

    if( $in_basket )
        echo '
' . sprintf( __( '%d people have this in their cart', 'text-domain' ), $in_basket ) . '
';

}

add_action( 'woocommerce_after_shop_loop_item_title', 'show_no_of_people_added_in_cart', 11 );
add_action( 'woocommerce_single_product_summary', 'show_no_of_people_added_in_cart', 21 );

A: You can use for this situations function _n
The code after changing

function show_no_of_people_added_in_cart(){
    global $wpdb, $product;
    $in_basket = 0;
    $wc_session_data = $wpdb->get_results( "SELECT session_key FROM {$wpdb->prefix}woocommerce_sessions" );
    $wc_session_keys = wp_list_pluck( $wc_session_data, 'session_key' );
    if( $wc_session_keys ) {
        foreach ( $wc_session_keys as $key => $_customer_id ) {
            // if you want to skip current viewer cart item in counts or else can remove belows checking
            if( WC()->session->get_customer_id() == $_customer_id ) continue;

            $session_contents = WC()->session->get_session( $_customer_id, array() );
            $cart_contents = maybe_unserialize( $session_contents['cart'] );
            if( $cart_contents ){
                foreach ( $cart_contents as $cart_key => $item ) {
                    if( $item['product_id'] == $product->get_id() ) {
                        $in_basket += 1;
                    }
                }
            }
        }
    }

    if( $in_basket )
        echo '
' . sprintf(_n( '%s person have this in their cart', '%s people have this in their cart', $in_basket, 'text-domain' ), number_format_i18n($in_basket ) ) . '
';

}

add_action( 'woocommerce_after_shop_loop_item_title', 'show_no_of_people_added_in_cart', 11 );
add_action( 'woocommerce_single_product_summary', 'show_no_of_people_added_in_cart', 21 );


text:
Q: CakePHP 3 - CSV exporter according to user inputs Hi i'm working with a CSV exporter and it works pretty well for me. All credits to this guy (https://github.com/FriendsOfCake/cakephp-csvview) who did an amazing job at this.
So by default if i want to get some records displayed on a table to a csv view i just have to do the following.
Customers Controller
public function export() {
    $this->response->download('export.csv');
    $opts1['order'] = array('Customers.name' => 'asc');
    $data = $this->Customers->find('all',$opts1)->toArray();

    $_serialize = 'data';
    $_extract = ['id', 'name' ,'nic' , 'dob' , 'address'];

    $_header = ['ID', 'Name' ,'NIC' , 'DOB' , 'Address'];
    $this->set(compact('data', '_serialize', '_header', '_extract'));

    $this->viewBuilder()->className('CsvView.csv');
    return;
}

View
<?= $this->Html->link('Report', [
        'controller' => 'customers',
        'action' => 'export',
        '_ext' => 'csv'
        ],

        ['class' => 'btn btn-success'])
      ?>

I'm trying to get the CSV file to display the data according to the user selected dates from the frontend (from a html5 calendar view). How can I achive this? What is the approach to send data from the frontend to the controller in order to get a filtered output?
HTML5 date picker

I'm currently using the CakePHP v3.4.7.
PS - I'm really new to this :S trying to get familiar with the framework.

A: Follow these steps:

*

*Create one form with any unique id.

*Keep your datepicker inside that form.

*Add a Link or button.

*When you click on Link/button, call AJAX. Get the form data and pass it to your controller function which contains the code for generating CSV.

*Store the CSV in you assets folder.

*You function must return the name of CSV file.

*Now on your success AJAX call add below line
location.href="path/to/csv_file_in_asset".


text:
Q: move Ubuntu to RAID I have an Ubuntu Server up and running on LVM2 partition. My motherboard supports RAID 0 and 1.
I bought new, second HDD, the same as the system one. I want to set up RAID mirroring to ensure my data are safe.
How can I do this without reinstalling the whole system? Is software RAID better than hardware RAID from cheap motherboards?

A: It's a contentious issue but in general software RAID is much better than hardware RAID from cheap motherboards. I'd simply mirror them in software.

A: The general consensus is that motherboard RAID is crud, put in for people who think all buzzwords were created alike. Usually it's proprietary (need to replace your motherboard? You might lose your RAID array), it's lower in performance compared to software RAID, and overall is one of those things that when it works it's okay, when it fails you'll have headaches with no end (unless you make good backups.)
Go software or with a dedicated hardware controller for RAID.
By the way-mirroring isn't a backup. You get a corrupt drive, corrupt software, deletion of something important...instant mirror! Now you have twice the corruption and still lose the file you delete. Keeping your data safe involves making backups.


text:
Q: Android EditText duplicates every character I type I have several rows of EditText objects, which are maintained by my custom BaseAdapter class.
The EditText objects should only be able to accept numbers. In the image shown, I typed in "12345". As you can see, everything I type gets immediately duplicated.
I've found that the problem goes away if I remove the line of code that filters the EditText for numbers:
et.setInputType(InputType.TYPE_CLASS_PHONE);
Any idea what's going on?
I'm using a TextWatcher to listen for the input, which you can see in the getView() method:
public View getView(int position, View convertView, ViewGroup parent) {

            final ViewHolder holder;

            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.number, null);
                holder = new ViewHolder();
                holder.editText = (EditText) convertView.findViewById(R.id.number_edittext);
                holder.editText = setEditTextFilters(holder.editText);
                holder.editText.addTextChangedListener(new TextWatcher() {
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2){}
                    public void onTextChanged(CharSequence s, int start, int before, int count) {}
                    public void afterTextChanged(Editable s) {
                        textBoxStrings[holder.row] = s.toString();
                        System.out.println("row: " + holder.row + " " + s.toString());
                    }
                });

                convertView.setTag(holder);
            }
            else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.row = position;
            holder.editText.setText(textBoxStrings[holder.row]);

            TextView rowtext = (TextView) convertView.findViewById(R.id.number_rowtext);
            rowtext.setText("Row " + holder.row);
            return convertView;
}

Filters are added to the EditText using the following method:
public EditText setEditTextFilters(EditText et) {
        int maxLength = numColsMEM;
        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(maxLength);
        et.setFilters(FilterArray);
        et.setInputType(InputType.TYPE_CLASS_PHONE);
        et.setSingleLine();
        return et;
}

A: I have a hunch that the problem may be that your textChangedListener shouldn't be setting the textBoxStrings[holder.row] because the default textChangedListener is probably already doing this.

A: Was an issue with the emulator, doesn't occur on a true device. One of those things.


text:
Q: Assign datetime range to variable using python I'm trying to split a df by datetime. The df is indexed on the datetime variable. Essentially, I can do:
first = df['2020-04-09':'2020-04-21']
second  = df['2020-04-22':'2020-05-08']

and that yields my desired result of 2 dfs, each with their respective datetime range's worth of data.
However, I'd like a way to allow for easier editing at the top of the script by assigning the datetime ranges to local variables. Ideally something like this:
first_dates = '2020-04-09':'2020-04-21'
second_dates = '2020-04-22':'2020-05-08'

Such that later on I'm able to use something like:
first = df[first_dates]
second = df[second_dates]

and yield the same result of 2 dfs with their respective date ranges worth of data.

A: Is this what you want
# edit this
date_str = '2020-04-21'

# no need to edit this
date = pd.to_datetime(date_str, utc=True)

first = df[:date]
second = df[date+pd.to_timedelta('1D'):]

A: Using datetime, you could use mask comparison maybe?
like:
mask1 = df.index <= dt.date(2020,4,21)
mask2 = df.index > dt.date(2020,4,21)

df1 = df.loc[mask1]
df2 = df.loc[mask2]


text:
Q: Test rest api method with parameter in JMeter I'm building load tests for a web API, and I can't get one of them to work.
The url is something like http://myserver/myapp/mymethod and it calls a java method like public void mymethod(mytype param)
And I don't know how to pass that param...
I'm getting this error:
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method (Cannot consume content type).

EDIT:
I've tried setting Content-Type = "application/json" and passing a json parameter but now the server says:  An error occured while trying to do a POST request.: java.net.SocketException: Unexpected end of file from server
The parameter, which is correct and I can get the values when debugging the webservice is:
{
"email": "name@server.com",
"login": "name",
"password": "1234"
}

A: Well, the solution was just to pass a json parameter.
My class had the following properties:
private String email;
private String login;
private String password;

So I only needed to build a json object like:
{
"email": "name@server.com",
"login": "name",
"password": "1234"
}

and pass it as a parameter to the HTTP Request, with an empty name.


text:
Q: Klein–Gordon Inner Product in Reissner–Nördstrom Spacetime We consider a massless charged scalar field $\Phi$ on the Reissner–Nördstrom black hole space:
$$ds^2=-f(r)dt^2+f(r)^{-1}dr^2+r^2d\theta^2+r^2\sin^2\theta\,d\varphi^2, \tag{1}$$
with $f(r)=1-\frac{2M}{r}+\frac{Q^2}{r^2}$ and known horizons $r_\pm=M\pm\sqrt{M^2-Q^2}$. The dynamics of the scalar field is determined by
$$g^{\mu\nu}D_\mu D_\nu\Phi=0,\quad\text{with}\quad D_\mu=\nabla_\mu-iq A_\mu,\quad\text{and }\quad A_\mu=\left(-\frac{Q}{r},0,0,0\right). \tag{2}$$
The scalar field modes can be written as
$$\phi_{\omega\ell m}=\frac{e^{-i\omega t}}{r}\mathcal{N}_\omega X_{\omega\ell}(r)Y_{\ell m}(\theta,\varphi), \tag{3}$$
where $\ell=0,1,\dots$, $m=-\ell,\dots,\ell$; $X_{\omega\ell}(r)$ are radial functions, $Y_{\ell m}(\theta,\varphi)$ are the usual spherical harmonics and $\mathcal{N}_{\omega}$ is a normalization factor, which is the point of my question.
The tortoise coordinate $r_{\ast}$ is defined as $dr_{\ast}=f(r)^{-1}dr$, which lead to the following radial equation:
$$\left(-\frac{d^2}{dr_{\ast}^2}+V(r)\right)X_{\omega\ell}=0, \tag{4}$$
with a potential that has the following asymptotic values:
$$V(r)=\begin{cases}
-\tilde{\omega}=-\left(\omega-\frac{qQ}{r_+}\right), & \text{ if } r_\ast\rightarrow-\infty\;(r\rightarrow r_+)  \\
-\omega, & \text{ if } r_\ast\rightarrow+\infty\;(r\rightarrow\infty)
\end{cases}. \tag{5}$$
The asymptotic behavior of the radial part of the solution modes is the following:
$$X_{\omega\ell}^{(in)}(r)=\begin{cases}
T^{(in)}_{\omega\ell}e^{-i\tilde{\omega}r_\ast}, & \text{ if } r_\ast\rightarrow-\infty\;(r\rightarrow r_+)  \\
\boxed{I^{(in)}_{\omega\ell}e^{-i\omega r_\ast}}+R^{(in)}_{\omega\ell}e^{i\omega r_\ast}, & \text{ if } r_\ast\rightarrow+\infty\;(r\rightarrow\infty)
\end{cases}, \tag{6}$$
which are called in modes represents to waves incoming from the past null infinity, are partly reflected back to the future null infinity and also partly transmitted to the future horizon. In the same way, the so-called up modes:
$$X_{\omega\ell}^{(up)}(r)=\begin{cases}
\boxed{I^{(up)}_{\omega\ell}e^{i\tilde{\omega}r_\ast}}+R^{(up)}_{\omega\ell}e^{-i\tilde{\omega}r_\ast}, & \text{ if } r_\ast\rightarrow-\infty\;(r\rightarrow r_+)  \\
T^{(up)}_{\omega\ell}e^{i\omega r_\ast}, & \text{ if } r_\ast\rightarrow+\infty\;(r\rightarrow\infty)
\end{cases}, \tag{7}$$
which represent waves outgoing near the past event horizon, partly reflected back to the future horizon and party transmitted to the future null infinity.
Question:
To find the normalization constant $\mathcal{N}_{\omega}$, it is defined the Klein-Gordon inner product as
$$\langle\Phi_1\Phi_2\rangle=i\int_\Sigma\left(\left(D_\mu\Phi_1\right)^\ast\Phi_2-\Phi_1^\ast\left(D_\mu\Phi_2\right)\right)\sqrt{-g}\;d\Sigma^\mu, \tag{8}$$
where I know that $d\Sigma^\mu=d\Sigma\;n^\mu$. The statement says that by using a Cauchy surface close to the union of the past event horizon and past null infinity for the in and up modes, we find, as computed in this paper (eq. 16)
$$\mathcal{N}_{\omega\ell}=\frac{1}{\sqrt{4\pi|\omega|}}, \tag{9}\label{9}$$
which seems to be a quick exercise of computation as in the flat KG inner product computed here and here. I dont understand the configuration previous to the computation: a Cauchy surface close to the union of the past event horizon and past null infinity, and how this would lead to \eqref{9}.
EDIT: Use the Penrose diagram:
My reasoning is as follows. In the Penrose diagram for a RN black hole,

I must choose a Cauchy surface near the past null infinite and the past event horizon. So, it seems that I must consider only the $I_{\omega\ell}^{in/up}$ parts of the "waves", and then to compute the KG inner product. But it is weird to me to have a Cauchy surface near that regions. Also, I dont know if my arrowed waves (red/blue) depicting the process are correct.


text:
Q: Unexpected KeyError: in Python 2.7.10 I am new to coding in Python and I have encountered an unexpected error with my code. Any help with this would be much appreciated
import json
from urllib2 import urlopen

response = urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json")
source = response.read()

# print(source)

data = json.loads(source)

# print(json.dumps(data, indent=2))

usd_rates = dict()

for item in data['list']['resources']:
    name = item['resource']['fields']['name']
    price = item['resource']['fields']['price']
    usd_rates[name] = price
    print name, price

A: You are getting error because there is no tag 'name' under 'resource' > 'fields'.
You can add check if you will not get tag 'name' always:
name = item['resource']['fields'].get('name', '')

A: Use get to fetch value from json/dict and use a None check.
    import json
    from urllib2 import urlopen

    response = urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json")
    source = response.read()

    # print(source)

    data = json.loads(source)

    # print(json.dumps(data, indent=2))

    usd_rates = dict()

    for item in data['list']['resources']:
        name = item.get('resource').get('fields').get('name')
        price = item.get('resource').get('fields').get('price')
        if name is not None:
            usd_rates[name] = price
            print name, price


text:
Q: Varying Page Lengths How can I vary the vertical page length per page?
I want to have the page breaks at essentially arbitrary locations in the document, specified by a command, like \newpage but not necessarily this command. Moreover, I want these page breaks to determine the vertical length of the page.
(This must sound crazy!)
Thanks!

A: Do you mean physical dimensions of the page?  If yes, I had a talk about it at TUG'11.  Our paper is in the upcoming TUGboat, but the talk itself is here:  http://river-valley.zeeba.tv/ebooks-and-paper-size-output-routine-hacking-made-easy/
There are snippets of code on the screen;  if you are interested, let me know, and I put copies of them here.
Update:  here is LaTeX example that shows the idea:
\documentclass{article}
\usepackage{everyshi,lipsum}
\pagestyle{empty}
\textheight500cm
\EveryShipout{%
  \pdfpageheight=\pagetotal
  \advance\pdfpageheight by 2in
  \advance\pdfpageheight by 2\topmargin
  \advance\pdfpageheight by \textheight
  \advance\pdfpageheight by -\pagegoal}
\begin{document}

\lipsum[3-5]
\pagebreak

This line has a footnote\footnote{\lipsum[6-8]}.
\lipsum[1]

And this line too\footnote{\lipsum[12]}.
\pagebreak

\end{document}


text:
Q: Al pulsar botón se ejecute código PHP que devuelva 10 botones de descarga sin recargar la página en WP usando Ajax Sucede que tengo una web en WordPress en la que cada entrada tiene enlaces de descarga que son generados y obtenidos usando PHP desde un campo de Custom Field cada vez que se carga el post, entonces deseo que ese código PHP ya no se ejecute cada vez que se visualiza una entrada si no que se ejecute solo si el usuario hace click en un botón que lo llamaremos "Generar enlaces" el problema es que deseo que no se recargue la página al pulsar el botón (Usar Ajax), deseo que al pulsar el botón este desaparezca y se comience a ejecutar el código PHP que genera los enlaces y por supuesto aparezcan los botones de descarga generados segundos después de que PHP haya procesado todo el código. Es decir en un principio aparezca solo un único botón llamado "Generar enlaces" que al pulsarlo este desaparezca y se reemplace este fragmento de la página por los botones de descarga como en la siguiente imagen:

Necesariamente es necesario que solo se ejecute el fragmento de código PHP que genera los botones de descarga cuando se oprime el botón porque la razón es que PHP se toma en ejecutar ese código unos 50 segundos y cada vez que se carga una entrada esperar todo ese tiempo es un problema grave de experiencia para el usuario.
Tengo el siguiente código que es el que mejor se asemeja a la solución del problema, pero como mencioné ante, el problema es que necesito devolver y ejecutar código PHP no HTML como lo hace este.
Esto va en el single.php de las entrada (ó index.php de cada entrada) es el código que

<button type="button" name="name" class="clase" onClick="llamar();">Generar Enlaces</button>
Resultado:

En vez de leer el HTML que devuelve la variable 'data' de Ajax necesito ejecutar código PHP (El cual lee el Custom Field del post que contiene URL's de descarga  y genera botones de descarga para cada uno) dentro del mismo single.php (No desde una fuente externa como lo está haciendo acá leyendo el resultado HTML de generador.php).
Les agradezco de antemano toda su ayuda !!
NUEVO CÓDIGO IMPLEMENTADO
single.php

<button id="btnEnviar">Enviar</button>

script.js

$(function() {
    var $btnEnviar = $('#btnEnviar');
    var $divResult = $('#result');
    $btnEnviar.on('click', function() {
      $divResult.empty();
      var request =
        $.ajax({
          url: "/cont/themes/NOMBREDEMITEMA/generador.php",
          method: "GET",
          dataType: "html"
        });

      request.done(function(data) {
        var htmlButtons = '';
        $btnEnviar.hide()
        $("#result").html(data);

      });

      request.fail(function(jqXHR, textStatus) {
        alert("Error en la petición: " + textStatus);
      });

    })
  });

generador.php

<?php
echo 'Hola Mundo';
?>

CÓDIGO SOLUCIÓN @alo Malbarez (EN PROCESO)
functions.php

<?php
// imprimir el boton en el hook luego del content filter si hay customfield
function EMP_Boton_add_to_content( $content ) {
  $btnContent = "";
  if( is_single() ) {
    $postID = get_the_id();
    $ajax_url = admin_url('admin-ajax.php');
    $elCampoCustom = types_render_field("prueba-enlaces", array("output" => "raw"));
    if(!empty($elCampoCustom)) {

      // abro buffer asi el editor me colorea el html
      ob_start();?>
      <button class="button button-primary" id="mostrarEnlaces-<?php echo $postID;?>">Mostrar enlaces</button>
      <div id="resultados-<?php echo $postID;?>">

<?php
      // cierro buffer, lo guardo en una var
      $btnContent = ob_get_clean();
    }
  }
  // retorno el content + el html generado
  return $content . $btnContent;
}
add_filter( 'the_content', 'EMP_Boton_add_to_content' );

// action para usuarios anónimos: wp_ajax_nopriv_{action}
add_action(
  'wp_ajax_nopriv_nombreDeTuAction',
  'nombreDeTuFuncionParaElAction' );

// action para usuarios logueados: wp_ajax_{action}
add_action(
  'wp_ajax_nombreDeTuAction',
  'nombreDeTuFuncionParaElAction' );

  function post_get_enlacesCampoCustom(){
    $elCampoCustom = types_render_field("prueba-enlaces", array("output" => "raw"));
    // si tiene campo y si es ajax
    if(!empty($elCampoCustom) && defined( 'DOING_AJAX' ) && DOING_AJAX ) {
      // abro buffer asi el editor me colorea el html
      ob_start();

      //COMIENZO DE MI CODIGO GENERADOR Y CLASIFICADOR DE ENLACES
      echo 'Hola Mundo by oijm17';

      //FIN DE MI CODIGO GENERADOR Y CLASIFICADOR DE ENLACES

      // cierro buffer, lo guardo en una var
      $responseContent = ob_get_clean();
      echo $responseContent;
    }
    die(); // sin esto se muestra un 0
  }

  function nombreDeTuFuncionParaElAction(){
    // Aquí procesamos el action
    if (!empty($_POST['unparametro'])) {
      echo "El parametro es:". $_POST['unparametro'];
    }
    // el procesador ajax por default devuelve un 0 al final, aquí evitamos eso
    die();
  }

?>

A: Wordpress además de ser un CMS es también un framework, y como tal provee herramientas para tareas comunes. Todas las funciones las vamos a definir en el archivo functions.php
El Ajax
En el caso de Ajax expone un procesador de peticiones al cual le envias el tipo de acción a realizar y los datos para dicha acción.
Este "procesador de requests" es wp-admin/admin-ajax.php y además de procesar el request con la función correcta posee varios mecanismos para evitar XSS, CSFR y otras cosas que pasan en internet.
La forma de registrar una "action" para que pueda ser llamada por ajax es:
// action para usuarios anónimos: wp_ajax_nopriv_{action}
add_action(
  'wp_ajax_nopriv_nombreDeTuAction',
  'nombreDeTuFuncionParaElAction' );

// action para usuarios logueados: wp_ajax_{action}
add_action(
  'wp_ajax_nombreDeTuAction',
  'nombreDeTuFuncionParaElAction' );

function nombreDeTuFuncionParaElAction(){
  // Aquí procesamos el action
}

Aquí uso la misma function para ambos tipos de usuarios, adaptar a tus necesidades.
Una llamada ajax con jquery se vería así:
jQuery.post(
    "https://tudominio.com/wp-admin/admin-ajax.php",
    {
        'action': 'nombreDeTuAction',
        'unparametro':   123
    },
    function(response) {
        console.log('La respuesta es: ', response);
    }
);

El parámetro unparametro lo vas a ver en la funcion como $_POST['unparametro']
function nombreDeTuFuncionParaElAction(){
  // Aquí procesamos el action
  if (!empty($_POST['unparametro'])) {
    echo "El parametro es:". $_POST['unparametro'];
  }
  // el procesador ajax por default devuelve un 0 al final, aquí evitamos eso
  die();
}

El Botón
Para agregar cosas al contenido del post, dependiendo de si tiene o no un meta asociado, podemos usar el hook del filtro the_content, esto es un modificador(filter) del contenido del post que se aplica cuando uno llama a <?php the_content();?>, así que nos enganchamos ahí para no editar el single.php y agregamos un botón al final, junto con un div para los resultados:
// imprimir el boton en el hook luego del content filter si hay customfield
function EMP_Boton_add_to_content( $content ) {
  $btnContent = "";
  if( is_single() ) {
    $postID = get_the_id();
    $ajax_url = admin_url('admin-ajax.php');
    $elCampoCustom = get_post_meta($postID, 'elCampoCustom', TRUE);
    if(!empty($elCampoCustom)) {
      // abro buffer asi el editor me colorea el html
      ob_start();
      ?>
      <button
      class="button button-primary"
      id="mostrarEnlaces-<?php echo $postID;?>">Mostrar enlaces</button>
      <div id="resultados-<?php echo $postID;?>">

      // cierro buffer, lo guardo en una var
      $btnContent = ob_get_clean();
    }
  }
  // retorno el content + el html generado
  return $content . $btnContent;
}
add_filter( 'the_content', 'EMP_Boton_add_to_content' );

La llamada
Normalmente uno tendría un css y un js asociados y los encolaría con wp_enqueue_script() definiendo las dependencias (jQuery por ej) y el orden de carga.
En este caso, a fines de "brevidad" vamos a no depender de jQuery, usando vanilla javascript en un tag

Aquí uso fetch con método post y paso los datos "form-urlencodeados" con la ayuda de URLSearchParams(), los ID de botón y respuesta los defino con el id del post así no hay que hacer mucha movida con clases css (esto permite mostrar mas de un post con su propio boton), adapte a su necesidad y realidad.
Todo junto
En este ejemplo el custom_field se llama "elCampoCustom" (ya pensaré un nombre mas fácil de recordar), y la función ajax lo que hace es generar enlaces a buscadores con las palabras de este campo. Además hay por ahi un sleep(5) para simular un retraso en la respuesta.
Todo el código junto quedaría algo así:
functions.php
<?php
add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' );

function enqueue_parent_styles() {
  wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
}

// imprimir el boton en el hook luego del content filter si hay customfield
function EMP_Boton_add_to_content( $content ) {
  $btnContent = "";
  if( is_single() ) {
    $postID = get_the_id();
    $ajax_url = admin_url('admin-ajax.php');
    $elCampoCustom = get_post_meta($postID, 'elCampoCustom', TRUE);
    if(!empty($elCampoCustom)){
      // abro buffer asi el editor me colorea el html
      ob_start();
      ?>
      <button
      class="button button-primary"
      id="mostrarEnlaces-<?php echo $postID;?>">Mostrar enlaces</button>
      <div id="resultados-<?php echo $postID;?>">

      <?php
      // cierro buffer, lo guardo en una var
      $btnContent = ob_get_clean();
    }
  }
  // retorno el content + el html generado
  return $content . $btnContent;
}
add_filter( 'the_content', 'EMP_Boton_add_to_content' );

// para creacion de links
define(
'SEARCH_LINKS', [
'SOes' => [
'text'=> 'StackOverflow Español',
'url' => 'https://es.stackoverflow.com/search?q=',
],
'SOen' => [
'text'=>'StackOverflow',
'url' => 'https://stackoverflow.com/search?q=',
],
'google' => [
'text'=>'Google',
'url' => 'https://www.google.com/search?q=',
],
'googleIMG' => [
'text'=>'Google Imágenes',
'url' => 'https://www.google.com/search?tbm=isch&q=',
],
]
);

// actions ajax post
// el action _nopriv es para definir otro comportamiento si el usuario
// no tiene privilegios (x ej: no está logueado)
add_action(
  'wp_ajax_nopriv_post_get_enlacesCampoCustom',
  'post_get_enlacesCampoCustom'
);
add_action(
  'wp_ajax_post_get_enlacesCampoCustom',
  'post_get_enlacesCampoCustom'
);
function post_get_enlacesCampoCustom(){
  $elCampoCustom = get_post_meta( $_POST['post_id'], 'elCampoCustom', TRUE);
  // si tiene campo y si es ajax
  if(!empty($elCampoCustom) && defined( 'DOING_AJAX' ) && DOING_AJAX ) {
    // simulo 5 segundos de proceso
    sleep(5);
    // abro buffer asi el editor me colorea el html
    ob_start(); ?>

      <?php foreach(SEARCH_LINKS as $eID=>$enlace) : ?>

<a
           href="<?php echo $enlace['url'].urlencode($elCampoCustom)?>"
           target="tab-<?php echo $eID;?>"><?php echo $enlace['text']?>

      <?php  endforeach; ?>

    <?php
    // cierro buffer, lo guardo en una var
    $responseContent = ob_get_clean();
    echo $responseContent;
  }
  die(); // sin esto se muestra un 0
}

A: Este ejemplo hace algo parecido a lo que quieres, espero que te pueda servir como ayuda.
Hace lo siguiente:

*

*Lanza una petición Ajax a la API de Github (es una URL externa, pero si fuera interna funcionaría igual)

*La API responde con un JSON con información sobre usuarios de Github. Ese JSON es recuperado en la función done, es leído y se toman datos de él para crear un botón por usuario...

*Finalmente esos datos son presentados en el contenedor cuyo id es result.

*El botón Enviar es ocultado con hide.

Si por ejemplo, tu archivo PHP devolviese los botones ya creados, deberás cambiar el dataType de la petición Ajax por html. Aunque lo más recomendable es devolver un JSON y parsearlo en el cliente. El JSON es mucho más ligero de transportar. Descargas de trabajo suplementario al servidor, haciendo que la respuesta sea construida en el cliente.
Espero te sea de utilidad.

$(function() {
  var $btnEnviar = $('#btnEnviar');
  var $divResult = $('#result');
  $btnEnviar.on('click', function() {
    $divResult.empty();
    var request =
      $.ajax({
        url: "https://api.github.com/users",
        method: "GET",
        dataType: "json"
      });

    request.done(function(data) {
      var htmlButtons = '';

      $.each(data, function(k, v) {
        htmlButtons += `<button id="${v.id}">${v.login}`;
      });
      $btnEnviar.hide()
      $divResult.append(htmlButtons);

    });

    request.fail(function(jqXHR, textStatus) {
      alert("Error en la petición: " + textStatus);
    });

  })
});

Por favor, presiona el botón para probar el código:
<button id="btnEnviar">Enviar</button>


text:
Q: Prove that Killing vector fields form Lie algebra. I want to find the integral curves of $[X,Y]$, then maybe can use this to prove. Can anyone gives an answer ? Thanks.

A: From the Jacobi identity and definition of Lie derivative it follows that $L_{[X,Y]} = L_X \circ L_Y - L_Y \circ L_X$.  Thus $L_{[X,Y]} g = 0$ if $L_Y g = 0$ and $L_X g = 0$.


text:
Q: How to create group on drag drop I want to clone and create a group element on drag drop. A rectangle will be appended to group on dragend.
I am able to create group with rectangle appended on drop but its getting dislocated on drop. I guess its problem with its coordinates:
Preview: http://jsfiddle.net/hv2v4uLj/
Code:
var rectDrag = d3.behavior.drag()
                        .origin(function ()
                        {
                            var t = d3.select(this);
                            return {x: t.attr("x"), y: t.attr("y")};
                        })

                        .on('dragend', function (d)
                        {
                            var translate = d3.transform(this.getAttribute("transform")).translate;
                            var x = translate[0];
                            var y = translate[1];
                            //Append new element
                            var newRect = d3.select("g").append("rect")
                                    .classed("drg", true)
                                    .attr("width", 51)
                                    .attr("height", 41)
                                    .attr("x", x)
                                    .attr("y", y)
                                    .style("fill", "white")
                                    .style("stroke-width", 2)
                                    .style("stroke", "#CDB483");
                        });
                rectGroup.call(rectDrag);

A: I've added code to drag event,
.on("drag", dragged)

in rectDrag at line number 22,
and the code for dragged is below
function dragged() {
  d3.select(this).attr("x", d3.event.x).attr("y", d3.event.y);
}

The updated fiddle
Hope this is what you are looking for...If not ask for more.


text:
Q: Different metric of file size as output of ls command Why is ls command yielding different metric of file size? Example:
haniya@r079008:~/data$ ls -l
total 3948604
-rwxrwxrwx 1 haniya haniya   21254426 Mei 24 19:34 cliente_tabla.csv
-rw-rw-r-- 1 haniya haniya    6167128 Jul  2 02:03 cliente_tabla.csv.zip

If I assume the size is displayed in Byte, why total is given in KB.
While
haniya@r079008:~/data$ ls -s cliente_tabla.csv
20760 cliente_tabla.csv

Now the size is in KB. That makes the information unclear (inconsistent). Is there any way to 'regularize' the metric?

A: total and ls -s by default print the number of blocks of 1024 bytes or the size defined in BLOCKSIZE or BLOCK_SIZE environment variables.
To "regularize" the units for ls -l output add --block-size argument, for example:

*

*for KiB (2^10):
ls -l --block-size=K

*for MB (10^6):
ls -l --block-size=MB

*You can also specify 1M to display only numbers and skip the unit.
For all units and options refer to the Block Size chapter of GNU docs.

A: ls -lh

Will list file sizes in human readable format (e.g., 1K 234M 2G)
-rw-r----- 1 syslog            adm       68K Aug 19 19:30 syslog


text:
Q: Does Postfix need a TLS cert for every destination domain? When Postfix is the destination for multiple domains, does it need a TLS cert for every one of them, or just for the domain in $myhostname?
That is to say, are there smtp clients out there who will check certs against the MX they used to look us up, or are they all smart enough to wait for 220 response and/or do reverse DNS, and check against that?
Is it even possible to receive the 220 without checking the certificate first?
But otherwise, is it even possible for Postfix to know what cert the client wants?
EDIT: Even if they do reverse DNS, if clients are willing to accept MX addresses that resolve to arbitrary domains, isn't that trivial to MITM? Or is the solution to never use a vanity MX if I want TLS?

A: For my money, the way to do this is to avoid vanity MX.  It's close to meaningless, anyway - how many actual people ever get to see your MX record?  Vanity domains are fine, but TLS will be simpler if you have the MX record in all cases be the CN embedded in the certificate.


text:
Q: Run mysql query from a controller in ruby on rails I need run a mysql query from the controller but I do not know how to connect to db.
this is my method:
def set_dcs
  sql="select employees.nombre, employees.apellido_paterno, employees.apellido_materno from employees, activities, field_tests
  where activities.field_test_id=field_tests.id and employees.id=activities.dcs_id and field_tests.id=id"
end

How do I get the result of the query?
How could I do the same query but with the ActiveRecord?

A: You can execute raw SQL through ActiveRecord::Base.connection but I rarely recommend it and certainly not in this case, but for edification purposes
def set_dcs
  sql= <<SQL
      select employees.nombre, employees.apellido_paterno, employees.apellido_materno
      from employees, activities, field_tests
      where activities.field_test_id=field_tests.id and employees.id=activities.dcs_id and field_tests.id=id
SQL
  ActiveRecord::Base.connection.exec_query(sql)
end

I was not sure what the trailing id is in reference to and it will raise a SQL error due to it's ambiguity. I am going to assume it is a parameter and the primary search condition where as the rest are table joins.
That being said since you are using rails these can be true associations and joins resulting in far more readable controller code e.g. Model Definitions
class Employee < ActiveRecord::Base
   has_many :activities, foreign_key: :dcs_id
   has_many :field_tests, through: :activities
end
class FieldTest < ActiveRecord::Base
   has_many :activities
end
class Activity < ActiveRecord::Base
   belongs_to :employee, foreign_key: :dcs_id
   belongs_to :field_test
end

Then the controller is simply
 Employee.
  select("employees.nombre, employees.apellido_paterno, employees.apellido_materno").
  joins(:field_tests).where(field_tests: {id: SOME_ID})

the resulting SQL will be similar to
 SELECT
   employees.nombre,
   employees.apellido_paterno,
   employees.apellido_materno
 FROM
   employees
   INNER JOIN activities ON employees.id = activities.dcs_id
   INNER JOIN field_tests ON activities.field_test_id = field_tests.id
 WHERE
   field_tests.id = SOME_ID

And this will return a collection of  Employee Objects rather than an ActiveRecord::Result (returned from  ActiveRecord::Base.connection.exec_query) which is more similar to an Array than anything else.


text:
Q: Browser control not showing content from document stream I need to display binary content (eg. image, pdf file, etc) in a browser control. As I want to avoid first writing the content to a temporary file, I'm doing:
var browser = new WebBrowser() {
    Dock = DockStyle.Fill,
    DocumentStream = new MemoryStream(content)
};
this.Controls.Add(browser);

where content is a byte array whose content may vary.
However, when I do the above, the content is not being displayed (just an error icon).
Does DocumentStream work in such cases or do I need to go through the temp file path?


text:
Q: Pytest + FastApi + SQLAlchemy + asyncpg: Ошибка asyncio Пытаюсь протестировать приложение FastApi с использованием SQLAlchemy.
Первый тест проходит хорошо, а на втором выскакивает ошибка asyncio:
E               AttributeError: 'NoneType' object has no attribute 'send'

C:\Python310\lib\asyncio\proactor_events.py:397: AttributeError

database.py
import sys

from sqlalchemy.orm import declarative_base
from config import Config, TestConfig
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker

Base = declarative_base()
config_class = TestConfig if 'pytest' in sys.modules else Config

engine = create_async_engine(config_class.DB_CONFIG, echo=True, future=True)
LocalAsyncSession = async_sessionmaker(engine, expire_on_commit=False)

async def init_models():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

async def get_session() -> AsyncSession:
    if config_class is TestConfig and not config_class.DB_CREATED:
        await init_models()
        TestConfig.DB_CREATED = True
    async with LocalAsyncSession() as session:
        yield session

account_test.py
import pytest
from httpx import AsyncClient
from main import app
from pytest import fixture

@pytest.fixture
def anyio_backend():
    return 'asyncio'

@fixture(scope='session')
def client():
    client = AsyncClient(app=app, base_url='http://127.0.0.1:8000')
    return client

@pytest.mark.anyio
async def test_create_user(client):
    response = await client.post(
        '/users/create/',
        json={'email': 'test@test.mail', 'password': '123456'}
    )
    assert response.status_code == 201, response.text

    data = response.json()
    assert 'id' in data
    assert 'email' in data

@pytest.mark.anyio
async def test_get_user(client):
    auth = await client.post('/token/', data={'username': 'test@mail.com', 'password': '123456'})
    assert auth.json() == {'detail': 'Incorrect email or password'}
    assert auth.status_code == 401

Как я понимаю, на первом тесте все идет хорошо, а потом event loop FastApi приложения почему то ломается, и при обращении к методам engine происходит ошибка. Если на каждый тест создавать свой отдельный engine то тесты проходят успешно, но такой подход сликшом неоптимален.
При ручном тестировании через Postman все сценарии обрабатываются успешно.


text:
Q: How do you create resource route when the item has optional child items? How do you create routes for models that have option child properties?  Say I am creating a help desk app, and the ticket could be associated with an order that the customer had previously had with me, or it could be regarding an item in the catalog they have not yet ordered.
class CustomerServiceTicket
  belongs_to :order
  belongs_to :item
  belongs_to :buyer
  belongs_to :customer_service_category
end

class Order
  ...
  has_one :customer_service_ticket
  ...
end

class Item
  ...
  has_one :customer_service_ticket
  ...
end

in the schema for customer_service_ticket, order_id and item_id are nullable.
So I'll have a 'create a customer service ticket' link next to their say their order_id's on the their closed orders page...and a similar link next to the item_id on the product catalog page.
I'm thinking the url structure should look like this:
customer_service_ticket/new/order/123
for tickets created relating to an order
and
customer_service_ticket/new/item/789
for tickets created relating to an item
and just
customer_service_ticket/new
when there is neither (also valid for cases where the customer just has a general question)
How would I structure the routes to be the most efficient?  I'm not married to that URL structure above, if there is a better way I'm happy to try it.

A: Based on how you describe your routes, it sounds like the orders and items already exist at the time you need to create a new customer service ticket, is that correct?  If so, then it would be better to create your routes like this:
orders/123/customer_service_ticket/new
items/123/customer_service_ticket/new
customer_service_tickets/new

Any time you are adding a resource onto an existing resource, the new resource typically goes at the end, with the action you are performing being the last portion of the URL.  To create this structure it would be something like this:
resources :orders do
  resource :customer_service_ticket
end

resources :items do
  resource :customer_service_ticket
end

resources :customer_service_ticket

However, you may also want to rethink your relationships.  Once a customer service is closed for an order/item, are you certain there will never be another customer service ticket relating to that order/item?  That may indicate a has_many relationship.  You may also want to look into a polymorphic relationship for orders and items to customer service tickets.  That way if you want to add more entities that can relate to customer service tickets, you don't have to keep adding database fields.  Note that changing to a has_many would change the routes declarations above slightly.


text:
Q: Laravel Update or Create Relationships I have an Item model, that has ItemTranslations, I'm receive a Request with the Item I'm updating and the translations for that Item.
Now some of those translations will already be in the database (they have their own id), and some of them will be new. Is there a clean way to go about this?
In pseudo: Update the Item with this request, for each Translations you find in this request, update the translation relation if it exists, else create it for this Item.
This is the layout of my Item.
class Item extends Model
{
    protected $fillable = ['menu_id', 'parent_id', 'title', 'order', 'resource_link', 'html_class', 'is_blank'];

    public function translations()
    {
        return $this->hasMany(MenuItemTranslation::class, 'menu_item_id');
    }
}

This is the ItemTranslation
class ItemTranslation extends Model
{
    protected $table = 'item_translations';
    protected $fillable = ['menu_item_id', 'locale', 'name', 'order', 'description', 'link', 'is_online'];
}

A: You could use the updateOrCreate method on the translations() relationship. For example:
$item->translations()->updateOrCreate([
    'name' => $translation['name'],
    // Fields that should be used to find an existing record.
], [
    'description' => "New description",
    // Fields that should be updated.
]);

The first argument is the data that you want Eloquent to look up the translation by and second argument is the data that you want to be updated.
Both arguments will be used to create a new translation when an existing one couldn't be found.


text:
Q: How to read time stamp (DD/MM/YYYY) format from text file and correctly interpret it using Excel VBA? I need to write an Excel VBA program to read a text file and sort them by timestamp. Following is an example of the text file:

Time / Date ColumnB Column C
3/03/2017 3:07  Value B2 Value C2
3/02/2018 9:02  Value B4 Value C4
16/02/2018 9:03 Value B5 Value C5
17/02/2018 9:04 Value B6 Value C6

(File Name: import_File.csv)

where the time / Date is in DD/MM/YYYY HH:MM format.
However, when I try to open it in VBA, it have automatically interpreted the first column incorrectly by following American format (MM/DD/YYYY)

File            |Correct interpretation |VBA interpretation
----------------+-----------------------+---------------------------------
3/03/2017 3:07  |3 Mar 2017 3:07:00     |3 Mar 2017 3:07
3/02/2018 9:02  |3 Feb 2018 9:02:00     |2 Mar 2018 9:02
16/02/2018 9:03 |16 Feb 2018  9:03:00   |"16/02/2018  9:03:00" as a text
17/02/2018 9:04 |17 Feb 2018  9:04:00   |"17/02/2018  9:04" as a text

Following is how do I open the file:

Set Data_File = Application.Workbooks.Open("import_File.csv", 3, True, 1)

I do tried to use Selection.NumberFormat = "dd/mm/yyyy hh:mm:ss", but it doesn't help at all as it have already interpreted the column incorrectly when it first come in.
Should I need to open it as a text file first, then play around the timestamp myself? Or there is any quicker way to do the job.
Thanks for your help!

A: Use below sample code for your solution.
Sub csvx()

    Application.DisplayAlerts = False

    strPath = Path & "C:\root\abc.csv"
    Workbooks.OpenText Filename:=strPath & strFile, DataType:=xlDelimited, Comma:=True, Local:=True

    Selection.AutoFilter
    ActiveSheet.Range("A1").Select
    ActiveWorkbook.Worksheets(ActiveSheet.Name).AutoFilter.Sort.SortFields.Clear
    ActiveWorkbook.Worksheets(ActiveSheet.Name).AutoFilter.Sort.SortFields.Add Key:=Range _
        ("C1:C4"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.Worksheets(ActiveSheet.Name).AutoFilter.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

   ActiveWorkbook.Save
   ActiveWorkbook.Close

   Application.DisplayAlerts = True

End Sub

This is range of date column start to end e.g. C1:C4

Sample CSV File

CSV FILE DATA
Name,Age,Date
ewr,43,20-Mar
ewrwe,23,11-Oct
wee,34,11-Nov

A: If your local settings use the same date format as the one you describe you want, add the Local:=True qualifier to Workbook.Open to force the interpretation of dates to follow your computer's local settings (instead of the default EN-US interpretation that is built into VBA).
Example:
Set Data_File = Workbooks.Open Filename:="import_File.csv", ReadOnly:=True, Format:=1, Local:=True