text:
Q: Stack overflow error due to long lineage in loop for (on DataFrame) I have an iterative algorithm (pyspark) in which I make update on a part of my Spark DataFrame. I do it via a loop for and at each iteration, my job becomes more expensive and have more long lineage. At iteration i, I have lineage of iteration i-1 + some steps (lineage becomes more and more long).
I tried many options to break lineage but it doesn't work. Here is my source code. I work on jupyterLab VM.
def chronologically_compute(myDataFrame, number_of_compute, spark_session):
    # UDFs
    find_law_to_apply_udf = udf(find_law_to_apply, IntegerType())
    compute_loss_udf = udf(compute_loss, FloatType())

    TIMING = []

    #myDataFrame = myDataFrame.repartition(1000)
    spark_session.sparkContext.setCheckpointDir("myDirectory")
    #myDataFrame.explain(True)
    #myDataFrame.checkpoint()

    for i in range(1, number_of_compute + 1):

        debutRank = time.time()
        print("Itération", i)
        myDataFrame = myDataFrame.withColumn("column1",
                                             when(myDataFrame.rank == i, find_law_to_apply_udf("updatedComputed")
                                                 ).otherwise(myDataFrame.column1))
        myDataFrame = myDataFrame.withColumn("SelectedValue",
                                             when(myDataFrame.rank == i, myDataFrame["column2"].getItem(col("column1") - 1)
                                                 ).otherwise(myDataFrame.SelectedValue))
        myDataFrame = myDataFrame.withColumn("computed",
                                             when(myDataFrame.rank == i, compute_loss_udf("SelectedValue", "Time")
                                                 ).otherwise(myDataFrame.computed))
        window = Window.partitionBy('ID')
        myDataFrame = myDataFrame.withColumn('computedSum', sum("computed").over(window))
        myDataFrame = myDataFrame.withColumn('updatedComputed',
                                             when(myDataFrame.rank == i, myDataFrame.computedSum + myDataFrame.updatedComputed
                                                 ).otherwise(myDataFrame.updatedComputed))
        myDataFrame = myDataFrame.withColumn('updatedComputed',
                                             when(myDataFrame.rank == i + 1, myDataFrame.computedSum + myDataFrame.updatedComputed
                                                 ).otherwise(myDataFrame.updatedComputed))
        if i % 10 == 0:
            d = time.time()
            myDataFrame.checkpoint()
            print(myDataFrame.count())
            #myDataFrame.persist(StorageLevel.DISK_ONLY_2)
            duree_lineage = time.time() - d
            print("Lineage took {0}".format(duree_lineage))
            TIMING.append(duree_lineage)

        duree = time.time() - debutRank
        print("Modif took {0}".format(duree))

    print("Iteration time sum", np.sum(TIMING))
    print("Iteration time avg", np.mean(TIMING))

return myDataFrame

def main(spark_session):
    try:
        spark_jobs(spark_session)
    except Exception as ex:
        print(traceback.format_exc())
        raise

if __name__ == "__main__":

SPARK_SESSION = SparkSession \
    .builder \
    .appName("AppName") \
    .enableHiveSupport() \
    .config('spark.executor.memory','2g') \
    .config('spark.driver.memory','2g') \
    .config('spark.driver.maxResultsSize','2g') \
    .config("spark.logLineage", "true") \
    .config("spark.executor.extraJavaOptions","-Xss32M") \
    .getOrCreate()

main(SPARK_SESSION)

SPARK_SESSION.stop()


text:
Q: Fourier-like expansion of a closed curve in 2D Fourier expansion can be used to represent any periodic function in one variable.
Closed surfaces in 3D can be built out of spherical harmonics.
Is there a similar expansion to represent a curve of any shape, like the following one?

A: As lurscher suggests in a comment, in the case of a closed curve, one could consider a periodic parametrization of the curve
$${\bf f}(\theta)~=~{\bf f}(\theta+2\pi)~\in~\mathbb{R}^2, \qquad {\bf f}(\theta)~=~(x(\theta),y(\theta)). \tag{1}$$
Then define Fourier coefficients in the standard way
$$   {\bf c}_n({\bf f})~:=~ \int_0^{2\pi} \frac{{\rm d}\theta}{2\pi} e^{-in\theta}~{\bf f}(\theta). \tag{2}$$
[The Fourier coefficients ${\bf c}_n({\bf f})$ are well-defined if the coordinate functions $x,y$ are Lebesgue integrable $x,y\in{\cal L}^1(\mathbb{R}/2\pi\mathbb{Z}).$] The Fourier series for ${\bf f}$ is vector-valued
$$\sum_{n\in\mathbb{Z}}{\bf c}_n({\bf f}) ~e^{in\theta}.\tag{3}$$
A similar approached works also for a closed curve in higher dimensions. In the 2 dimensional case, one may identify the plane $\mathbb{R}^2\cong \mathbb{C}$ with the complex plane, as Greg P, Mark Eichenlaub, and J.M. point out.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get all elements within using d3 I am new to d3.js and am trying to get an array of all the elements in the selectAll and get the reaction-label label text, for each reaction element. Below is my html and my code to access the elements:
    HTML:
   <g id='reactions'>
     <g id='r0' class='reaction'>
       <g class='reaction-label-group' transform='translate(360,500)'>
         <text class='reaction-label label'>HELLO</text>
       <g id='r1' class='reaction'>
         <g class='reaction-label-group' transform='translate(365,500)'>
           <text class='reaction-label label'>HELLO2</text>

Javascript:
var reactionsVar =d3.selectAll('#reactions').selectAll('.reaction').attr("transform").text;

However, I am unable to get all the reaction data.
Thanks in advance for your help.


text:
Q: Sqlite,HTML 5 local storage or Android local data store APIs for storing long texts in mobile phones I'm developing an android app using Cordova in which i have over 3000 long texts (each fits in about 5 pages in Microsoft Word). I want to know which storing system is the best for storing such huge data.
Sqlite,HTML 5 local storage, or Android local data store APIs, or something else maybe?
EDIT
Considering W3Schools and this question HTML 5 local storage is out, due to its limitations. I'm looking for a storage system which at least be able to store 500 MB.

A: Factors to consider with respect to Local Storage.
Local Storage size limit:
Web storage provides far greater storage capacity (5 MB per origin in Google Chrome,Mozilla Firefox,and Opera; 10 MB per storage area in Internet Explorer;25MB per origin on BlackBerry 10 devices) compared to 4 kB (around 1000 times less space) available to cookies. ( source Wiki)
Local Storage Method.
Web Storage:
Web SQL Database:
Indexed Database:
source: html5rocks, sitepoint
All MOBILE broswers have varying degree of support for above local storage method.
The most widely supported method is Web Storage.
If you would like to store more than the limits mentioned above than you need to use the native (OS) features for storing data. Then PhoneGap is the obvious choice for accessing native features.
Storage Options that exceed the above Local Storage Limits:
1) Sqlite Plugin:
You can use the plugin maintained by brodysoft. link here
2) Native File access:
Need to use cordova file plugins. link here

A: i think that using SQLite Database will be a good choice, but if you have a realy huge data, the best choice is to use MySQL or Oracle Database on a web server, and then develop REST APIs to communicate with the app.
Here is a tutorial about Using Android SQLite Database With Multiple Tables


text:
Q: iCheck library: value of selected radio button jsFiddle here.
I'm a novice at Javascript and having trouble following the documentation at the iCheck page. I've followed the answer to what appears to be a very relevant StackOverflow question here but cannot get an alert to pop up displaying the value I've selected. Can anyone point me in the right direction, please?
HTML

Are you sure you want to have your details removed from our marketing list?

            <input type="radio" name="iCheck" value="yes">
            Yes

            <input type="radio" name="iCheck" value="no">
            No

Javascript
$(document).ready(function () {
  $('input').iCheck({
     radioClass: 'iradio_flat-orange'
  });
  $("input:radio[name=iCheck]").click(function () {
     var value = $(this).val();
     alert("You clicked " + value);
  });
 });

A: I found the other answers to be useful.  However, they are dependent on iCheck's 'ifClicked'.  You may not want the value to pop up every time a new radio button is selected, but instead only when a user hits a specific button calling for the alert and corresponding value.
For example:
$(document).on('click', '.buttonClass', function(event) {
  return alert($('.radioClass:checked').val());
});

A: Try this out:- http://jsfiddle.net/adiioo7/yhmu97qh/
JS:-
$(document).ready(function () {
    $('input').iCheck({
        radioClass: 'iradio_flat-orange'
    });

    $('input').on('ifClicked', function (event) {
        var value = $(this).val();
        alert("You clicked " + value);
    });
});

A: You must use iCheck like this
$(document).ready(function () {
    $('input[name="iCheck"]').on('ifClicked', function (event) {
        alert("You clicked " + this.value);
    });
    $('input').iCheck({
        radioClass: 'iradio_flat-orange'
    });
});

DEMO
Documentation

A: Just another hacky way to get checked value with jQuery selectors:
$(".checked input[name=name-of-original-input]").val();

But AFAIK default class for checked values could be changed in configuration.
BTW, I think that iCheck isn't a good choice if it creates such issues with very simple functionality.

A: this works for me... try it
HTML: <input type="checkbox" id=checkbox" name="checkbox" />
jQuery: $( "#checkbox" ).prop("checked");

A: For radio buttons and current version of iCheck:

                <input type="radio" name="my-radio" class="flat-green my-radio" value="true"> Yes

                <input type="radio" name="my-radio" class="flat-red my-radio" value="false"> No

JS:
var isChecked = $("input[name=my-radio]:checked").val();

It will return undefined if no option is selected, true or false if selected.

A: try this code:
$(".radio .checked input[type=radio]").val()


text:
Q: Hibernate: 2 subclass mapping the same key column I would like to map the same key column, parent_id this example, across the subclasses. Both ClientProfileDO and BusinessProfileDO are inherited from UserProfileDO. They are on the same table, USERPROFILE. So, they refer the same foreign key on the Contact table. Is it logically incorrect?
<hibernate-mapping    package="com.rentorama2.frontpage.client.serialize"default-lazy="false">
<class name="UserProfileDO" table="USERPROFILE">
<id name="oid" type="long" column="oid" >
    <generator class="increment">
        <param name="initial_value">1</param>
    </generator>
</id>
<discriminator column="dcolumn" type="string" length="5"/>
<property name="acctOid">
    <column name="acctOid" />
</property>
<property name="email">
    <column name="email"/>
</property>

<subclass name="ClientProfileDO" discriminator-value="CP">
    <list name="c_contacts" cascade="all">
        <key column="parent_id" not-null="true"/>
        <index column="idx"/>
        <one-to-many class="Contact"/>
    </list>
</subclass>
<subclass name="BusinessProfileDO" discriminator-value="BP">
    <property name="b_updateAnnouncement">
        <column name="updateAnnouncement"/>
    </property>
    <list name="b_contacts" cascade="all">
        <key column="parent_id" not-null="true"/>
        <index column="idx"/>
        <one-to-many class="Contact"/>
    </list>
</subclass>
</class>

A: I think you should move the Contact one-to-many association into UserProfileDO base class:
<hibernate-mapping    package="com.rentorama2.frontpage.client.serialize"default-lazy="false">
    <class name="UserProfileDO" table="USERPROFILE">
    <id name="oid" type="long" column="oid" >
        <generator class="increment">
            <param name="initial_value">1</param>
        </generator>
    </id>
    <discriminator column="dcolumn" type="string" length="5"/>
    <property name="acctOid">
        <column name="acctOid" />
    </property>
    <property name="email">
        <column name="email"/>
    </property>

    <list name="contacts" cascade="all">
        <key column="parent_id" not-null="true"/>
        <index column="idx"/>
        <one-to-many class="Contact"/>
    </list>

    <subclass name="ClientProfileDO" discriminator-value="CP">

    </subclass>
    <subclass name="BusinessProfileDO" discriminator-value="BP">
        <property name="b_updateAnnouncement">
            <column name="updateAnnouncement"/>
        </property>
    </subclass>
</class>

And the UserProfileDO class will have a Contact list:
private List<Contact> contacts = new ArrayList<>();

public List<Contact> getContacts() {
    return contacts;
}

public void getContacts(List<Contact> contacts) {
    this.contacts = contacts;
}


text:
Q: Change Magento's Upsell Slider to use Related Products I have a client who has accidentally added the products in the Related Products section rather than the Upsell Section. I have a file named upsell_slider.phtml that spits out the following:
<?php if(count($this->getItemCollection()->getItems())): ?>

<?php echo $this->__('Fashion Statement') ?>

    <?php  $this->setColumnCount(4); // uncomment this line if you want to have another number of columns. also can be changed in layout ?>
    <?php $this->resetItemsIterator(); ?>
    <?php
        $products_count = 0;
        while($this->getIterableItem()){
            $products_count++;
        }
    ?>
    <div <?php if ($products_count > 1): ?>id="block-upsell-slider"<?php else:?> class="no-slider" <?php endif; ?>>

    <?php $this->resetItemsIterator(); while ($_item=$this->getIterableItem()) : ?>

            <a class="product-image" href="<?php echo $_item->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_item->getName()) ?>"><img src="<?php echo $this->helper('catalog/image')->init($_item, 'thumbnail')->constrainOnly(TRUE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(420, null); ?>" <?php echo MAGE::helper('ThemeOptions/Retina')->getRetinaData('upsell', $_item); ?> alt="<?php echo $this->htmlEscape($_item->getName()) ?>" />

<a href="<?php echo $_item->getProductUrl() ?>"><?php echo $this->htmlEscape($_item->getName()) ?>

    <?php endwhile; ?>

    <?php if ($products_count > 1): ?>

    <?php endif; ?>

<?php endif ?>

And I can't for the life of me get it to look at the related products, rather than the upsell products.

A: I have a better solution. You can transform the related products in upsells with one query.
UPDATE `catalog_product_link` SET `link_type_id` = 4 WHERE `link_type_id` = 1;

Note. This will make move all the related products to upsells.
...and back up the table before trying it.


text:
Q: Strapi Admin infinite loop I'm kinda new to strapi. actually this the first time to try it. so i followed the documentation and was able to get the first page to work but admin page always go blank. sadly i don't know nodeJs or react so I'm not sure about what to do in here but seems there's something wrong with the permissions please check the attached image.

i've tried
npm install in the project root directory.
npm run setup in the project root directory.

as mentioned in this issue on github but it want's useful
I'm using
strapi 3 alpha
nodeJs 11
npm 6+
mariaDB 10.1
windows 10 64bit

A: I suggest you to clean the database your use. And when it's done, restart your Strapi server. It will re-create all table needed by Strapi.

A: So simply, I checked strapi website to find out that version 3 is out of the alpha status and then I installed the newer version and tried to use it and it did work so seems some bug was in the alpha edition which strapi team has fixed by themselves

A: I had a similar issue after setting up SSL on Digital Ocean one-click. I just ran npm run build. I did not do anything with the database.


text:
Q: Integral inequality 5 How can I prove that:
$$8\le \int _3^4\frac{x^2}{x-2}dx\le 9$$
My teacher advised me to find the asymptotes, why? what helps me if I find the asymptotes?

A: The important point is that
$$\frac{d}{dx}\left(\frac{x^2}{x-2}\right)<0$$
for $x\in[3,4]$, so that $\frac{x^2}{x-2}$ is decreasing there. Hence,
$$\int_3^4\frac{4^2}{4-2}dx\leq \int_3^4\frac{x^2}{x-2}dx\leq\int_3^4\frac{3^2}{3-2}dx,$$
and the left and right hand sides evaluate to $8$ and $9$ respectively.

A: Hint
$$(b-a) m \leq \int_a^b f(x) \, dx \leq (b-a) M$$
where $m, M$ are the minimum and maximum of $f$ on $[a,b]$.
The asymptotes of this function occur around $x=2$, so I don't see why your teacher asks you to use them.

A: Direct approach is not so painful:
$$\int_{3}^{4}\frac{x^2}{x-2}\,dx = \int_{1}^{2}\frac{(x+2)^2}{x}\,dx = \int_{1}^{2}\left(x+4+\frac{4}{x}\right)\,dx =\frac{11}{2}+4\log 2 $$
and by the Hermite-Hadamard inequality we have:
$$ \log 2 =\int_{1}^{2}\frac{dx}{x} \in \left(\frac{2}{3},\frac{3}{4}\right) $$
so:
$$\int_{3}^{4}\frac{x^2}{x-2}\,dx \in \left(8+\frac{1}{6},8+\frac{1}{2}\right).$$

A: Hint
Show that $f(x)=\frac{x^2}{x-2}$ satisfies: $f(3)=9,$ $f(4)=8$ and $f$ is decreasing in the interval $[3,4].$


text:
Q: ShopWare 6 PlugIn i got 2 cloud based sw6 and one real woodclass low budget planner sw6
but in the cloud based sw6 i havent a plugin installer only showing me migration of sw5
and in my wood low budget class i only have a complete destroyed but working sw6 system
here the link http://shopware.silvervine.eu/public/
my admin also loOoks like its broken http://shopware.silvervine.eu/public/#admin/
think my installation went wrong or maybe i have to change the root structure
please help
SORRY for my english

A: Your assumption about your wrong folder structure is correct.
Your webserver document root must not be set to the projects root, but to the folder public inside your project.
You can relate to the Shopware 6 Documentation for configuring your Apache web server.
For nginx you have to google because there is no offical documentation.


text:
Q: How do I restart a cancelled Cloud Dataflow streaming job? I've created a standard PubSub to BigQuery dataflow.  However, in order to ensure I wasn't going to run up a huge bill while offline, I cancelled the dataflow.  From the GCP console, there doesn't seem to be an option to restart it - is this possible, either through the console, or through the shell (and if so, how)?

A: You can restart the job immediately by cloning.
You should see an option clone at the top.

A: Cloud Dataflow currently does not provide a mechanism to restart a Dataflow job that has been stopped or cancelled.
However, for this Pub/Sub -> BigQuery flow, one way to approach this would be to use the Google-provided Pub/Sub to BigQuery template; these templates provide code-free solutions for common data movement patterns using Cloud Dataflow.
You can execute a streaming Dataflow job using this template, via the REST API, using a unique job name to ensure that there is only one instance of this Dataflow job running at any point in time. If the job were cancelled, you could (re)start this streaming Dataflow job by running the same command again.


text:
Q: Disadvantages of vertical user stories The agile approach is to structure the work into vertical user stories and deliver a focused but fully functioning piece of the application from end-to-end. Because this is the new approach to building software I read a lot of literature about why this is better than horizontal stories but I do not find much about the disadvantages to this approach.
I already drank the agile cool-aid and I too agree that vertically slicing the cake has much advantages over horizontal slicing. Here is a short list of disadvantages that I could come up with:

*

*A developer might initially be slower at implementing a feature because s/he must understand all the technologies required to develop the story (UI + service layer + data access + networking, etc...)

*Overall architecture design (crating the backbone of the application) does not really fit this mantra (however some might argue that it is part of a user story to develop/change the overall architecture)

What are some more drawbacks of vertically slicing user stories?
Note: The reason I am asking this question now is because I am going to attempt to convince a team to start writing stories the 'vertical way' and I want to be able to bring up the possible trade-offs ahead of time so they won't consider the approach a failure when they are faced with the drawbacks.

A: I've been thinking about this exact question a lot.
I think it's important to distinguish between slicing by individual responsibilities vs. slicing by team responsibilities. I'll focus this answer mainly on slicing teams.
For some background: I have worked in projects with full-stack developers, single-tier developers, vertical (full-stack) teams, horizontal (single-tier) teams, and diagonal teams. By diagonal team I mean containing all the tiers needed for a story but not necessarily all the tiers in the system, and also possibly containing multiple developers focusing on the same tier(s); in other words vertical in spirit but maybe somewhat horizontal in appearance or in implementation detail.
Recently I have worked in a group that transitioned from horizontal teams to diagonal (nearly vertical) teams. It has been particularly instructional to see the same group of people aligned two different ways. It makes some advantages and disadvantages quite clear.
I'll round up my opinion so far with the following summary comparison:
Horizontal Teams
Advantages:

*

*Fosters good separation of concerns and loosely coupled tiers

*Much easier workload distribution management

*Easy for specialist technical lead to manage

*Fosters intra-tier collaboration, best practices, pride, and a culture of excellence

*Aligns with natural/emergent communication patterns

Disadvantages:

*

*Can lead to isolation of tiers and thus hinder inter-tier communication

*Enables tier "bubble" culture if unmitigated

*Difficult to take advantage of generalist leadership

*Hinders generalists

Vertical/Diagonal Teams
Advantages:

*

*All the parts of a user story in one team ("one stop shop")

*Specifically assists delivering n-tier stories in a single sprint (although do you really need that?)

*Fosters inter-tier collaboration and growth of generalist skills

*Supports generalists

Disadvantages:

*

*Much more difficult workload distribution management

*Enables poor separation of concerns and tightly coupled tiers

*Hinders specialization by curtailing intra-tier communication; it is difficult to see how a culture of excellence could arise out of this structure without adding mitigating horizontal/specialist behaviors

I do not think team membership has a one-size-fits-all solution. It seems pretty straightforward, however, that the vertical team lines up better for organizations requiring generalization. If your engineers are generalists and like working full stack, that's a pretty good reason to consider vertical teams. The horizontal team lines up better for organizations requiring specialists. If your engineers are specialists, that's a pretty good reason to consider horizontal teams.
As others have mentioned, secondary structures/behaviors that slice the other direction can help mitigate the drawbacks of either system. One interesting mitigating factor is sprint duration. Short sprints render some of the disadvantages of horizontal teams more tolerable. If you can build the backend this week and the frontend next week, that might be fast enough?
To apply some of these proposed principles to a real-world problem... I will say that the horizontal slices have worked quite well for a very real SaaS development team I've worked on that was solving very challenging technical problems in every tier (where specialization was in my opinion incredibly important), where frequency of delivery (and reliability at a high granularity/frequency) was critical to business success. Please note that this conclusion is for a very particular real-world team, not a general statement of superiority of horizontal slicing.
One caveat: I am probably biased against believing claims of generalist abilities by any individual in the modern software development world without significant proof, although I have known a few rare exceptional generalists. I feel that generality is a tall (vertical?) order indeed, particularly as each tier grows in complexity and with the proliferation of alternative languages/platforms/frameworks/deployments, each meeting different needs. These days especially, a jack of all trades can quite easily be a master of none. Also, anecdotally, I find most individuals want to specialize quite a bit, again with some exceptions.

A: I don't know of any long term disadvantages. In the short term, and for a team new to this kind of development, the main disadvantage is that it takes some getting used to and some learning.
The most efficient way to work vertically is to have full-stack developers: in this way a story can be typically executed by one person (or more than one but without pipelining tasks). Clearly this requires that the developers work vertically across the stack (from html to database in the case of a web application).
If your team is not used to working on vertical stories, then they are very likely to be doing the opposite: each person will have knowledge of one layer/tier of the application only. When you introduce vertical stories, you can expect the team to split them into tasks corresponding to layers and then distributing the tasks to different people. This will be very inefficient.
The best approach I can give regarding this is to tolerate this pipelining initially while making it clear that the long term goal is completely different. Have team members across layers pair program so to build up trust and eventually enable people to be completely independent.
I don't agree with the other answer that this approach brings technical debt. It can, but so can any other approach.

A: The big drawback I have found is that it makes it hard for a team to build the application following a unified architectural approach.
In the early stages of the project everyone will write their layers in isolation.  The stories (and layers involved) will work, but when looking back at the delivered product at the sprint-end it'll be easy to see the slight differences between each developer's architectural ideas.
This kind of thing is inevitable, but not a blocker.  I've tried to battle this in two ways:

*

*Have lengthy design discussions with the team before implementing each story

*

*This gets tiring quickly.  It's often too early for anyone to make an informed decision and then you just end up arguing over stuff that will definitely have to change anyway.

*Go ahead and develop in relative isolation, keeping in mind that you're building up technical debt.

*

*The key here is to log the technical (architectural) debt as an issue.  This is something that will need to be paid back.

*After a few sprints it'll be easier to decide on a coherent and unified architecture.  This is when you should request a hardening sprint to pay back some of your technical debt (refactor the existing code).  Alternatively, you can pay it back piecemeal over the next iterations of the project.

The only other problem I can think of other than that is that there's usually a lot of boilerplate code to add at the beginning of a project.  Writing vertical slice stories means the team's velocity on the first few stories will be artificially low due to this prerequisite boilerplate... but as long as everyone is aware that this should only affect the first couple of sprints then everything is fine.

A: I don't know any disadvantages either, however vertical stories can be implemented badly.
When I first started my career I joined a team that was keen to do XP but they had no experience with it. We made a number of mistakes when using vertical user stories.
One of the problems we encountered when doing horizontal work was that features did not integrate well across the layers. APIs often did not match the specification, features where missing and numerous other problems. Often because the developer of the had moved on to something else, you would either have to wait for them or do it yourself yourself.
Switching to doing Vertical Stories solved these problems and reduced/eliminated the waste of re-working to integrate.
There are a number of XP practices that support this way of working. Anyone needs to be able to work on any area and everyone is expected to fix the bugs they find (Collective Code ownership).
When you are making the change to vertical stories, it can be tricky to work in areas that you're not familiar with. Pair Programming can help, if you aren't confident grab someone in the team who is pair with them. I've found pair programming to be the fastest way to get up to speed with a new code base.
Without strong owners over layers we found, that there was some duplication emerging. Although this was not a big problem, we needed to make sure that we practiced Refactor Mercilessly (with appropriate tests to support).
Although I mention a number of problems, I don't think Vertical User Stories was the cause. In fact, it made the problems more apparent. After we made the switch, problems were no longer obfuscated across teams or application layers.


text:
Q: How to upgrade from Centos 7.2 to 7.3 and not up to 7.4? I'm trying to upgrade CentOS 7.2 to 7.3 and I don't want to upgrade it to 7.4.
How can I achieve this?
Any hints are quite welcome.

A: You could use the mirror at vault.centos.org which provide snapshots of the releases. Also view the readme.txt on that site.
To make use of this mirror, you have to disable the default mirrors in /etc/yum.repos.d by adding enabled=0 to the specific repo configuration. Or move the configuration files to .disabled and recreate a new configuration file for the 7.3 repositories.
A sample repo configuration placed e.g. at /etc/yum.repos.d/CentOS-7.3.repo would like as follows.
[base-7.3]
name=CentOS-7.3 - Base
baseurl=http://vault.centos.org/centos/7.3.1611/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

[updates-7.3]
name=CentOS-7.3 - Updates
baseurl=http://vault.centos.org/centos/7.3.1611/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

Depending on your needs you might want to add different or additional repositories. To see which repositories are active you can enter
yum repolist

After changing your repository configuration you should clean up the yum cache.
yum clean all
rm -rf /var/cache/yum

Now when you update your system with yum update the RPMs at the 7.3 repository should be picked up.


text:
Q: Ionic 3 - Extract the side menu in it's own component I need to build a scalable menu for an ionic 2/3 app (preferably using ion-menu). Following the guides on the docs the menu should be a sibling of the main content and they suggest to keep it inside app.html, which is a very high place inside the app that doesn't have to be crowded too much.
If we have a big menu or if we need to use several different menus, triggered by actions inside app, this place is not appropriate for this purpose.
I want to hide the complexity of the menu in it's own container/component and handle the logic outside app.component.ts.
app.html should stay slim and a construction like the one below may be useful.
<app-menu></app-menu> // this should be the enclosing container of the menu logic
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

If I do this, the following error comes up:
Menu: must have a [content] element to listen for drag events on. Example:
<ion-menu [content]="content"></ion-menu>
<ion-nav #content></ion-nav>

Any thoughts on how to implement this, avoiding to add code directly to app.html and app.component.ts?
Tks

A: error code just tells you to write <ion-nav #content></ion-nav> if you use <ion-menu [content]="content"></ion-menu>...
example toggle menu code below ...
<ion-header>
  <ion-navbar color="danger">
      <ion-buttons start>
        <button ion-button icon-only menuToggle>
          <ion-icon name="menu">

          </ion-icon>
        </button>
      </ion-buttons>
  </ion-navbar>

<ion-menu [content]="content">
    <ion-content padding>
        this is awkmal
    </ion-content>
</ion-menu>

</ion-header>
<ion-nav #content></ion-nav>


text:
Q: How to arrange data in descending order in Firebase - Python I have a game in python which takes info about the user and even stores the points. I wanted to make a leaderboard for it and so I decided to use Firebase and write the data into the database. I would just like the arrangement of the data to be in descending order based on the points limited upto the Top 20 ranks because the data is just randomly arranged now. Help will be appreciated. Thanks!

My code:
#Example Set
ref = db.reference('/')
ref.set({
    'Data':
        {

        'user'+str(userCounter): {
            'Username':userid,
            "Points": highscore
            }
        }

    })

#Updating Data
if current_score > highscore:
    ref = db.reference('Data')
    emp_ref = ref.child('user'+str(id))

    emp_ref.update({
        "Points": current_score
        })

A: Use the following query to retrieve the top 20 people in point list.
data_ref = db.reference('data')
snapshot = data_ref.order_by_child('Points').limit_to_first(20).get()
for key in snapshot:
    print(key)

Made query with the help of docs

A: The Firebase Realtime Database does not support descending ordering. If you want to display the items from the database in descending order, you have two options:

*

*Reverse the results client-side before displaying them.

*Storing an inverted value int he database, and use that in the query. So in your case that'd mean you add a negativePoints value in the database and sort on that, but then still use the existing points property in the display of course.

Also see:

*

*Display posts in descending posted order

*How to get data from firebase in descending order of value?

*Firebase Data Desc Sorting in Android

*firebase -> date order reverse


text:
Q: How to create a unique product page for an eCommerce website? I have a database set up with a couple of products on it.
I'm just struggling with the product page, you know the page that you are directed to when you click on a particular product - for the details, description  and add to cart button etc. How would I create one of these? Surely not with an

on every single product, right?
I currently have a while loop that loops through the database to display all of the products. So if I use the

it will just take me to the same product page every time.
Here is the loop of the database:
 <?php include 'connect.php';
 $sql = "SELECT * FROM products WHERE featured = 1";
 $featured = mysqli_query($conn,$sql);
 ?>

<?php while ($product = mysqli_fetch_assoc($featured)): ?>

       <img src="<?= $product['image'];?>" height="300"
       width="275">

<?=$product['title'];?>

Usual Price: £<s><?= $product['list_price'];?></s>

Sale Price: £<?= $product['price'];?>

<?php endwhile ?>

How would I create a unique product page for each product?

A: I suggest you create a unique SKU for each item number (put this sku in the database) and then create another page.   Let's say the new page is called item.php
So in your category listing page you can list the link like this:
<a href="item.php?sku=<?php echo $product['sku']; ?>">

and your next step would be to figure out how to pull in the individual product's information into item.php based on the sku in the url.


text:
Q: don't show movie in document folder in xcode I create one application that show file in document folder.
I have one file .mov format that I want show it from document folder but when run app and click play button don't show this movie and I see this image
 :
this is my code : (please guide me and tell me my mistake)
- (IBAction)Play:(id)sender
{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSString *file = [documentPath stringByAppendingPathComponent:@"xcode4-outlet.mov"];
    NSURL *url = [NSURL fileURLWithPath:file];
    _moviePlayer = [[MPMoviePlayerController alloc]initWithContentURL:url];
    [self.view addSubview:_moviePlayer.view];
    _moviePlayer.fullscreen = YES;
    _moviePlayer.shouldAutoplay = YES;
    _moviePlayer.allowsAirPlay = YES;
    [_moviePlayer play];
}

also compiler get me this massage :
movie player[9489:c07] [MPAVController] Autoplay: Likely to keep up or full buffer: 0
movie player[9489:c07] [MPAVController] Autoplay: Skipping autoplay, not enough buffered to keep up.
movie player[9489:c07] [MPAVController] Autoplay: Enabling autoplay
movie player[9489:c07] [MPCloudAssetDownloadController] Prioritization requested for media item ID: 0
movie player[9489:c07] [MPAVController] Autoplay: Enabling autoplay

A: You need to check whether a file is there or not before adding movie player also you can add default
-(IBAction)Play:(id)sender
{

    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSString *file = [documentPath stringByAppendingPathComponent:@"xcode4-outlet.mov"];
    NSURL *url = [NSURL fileURLWithPath:file];

    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:file];
    if(fileExists)
    {
        _moviePlayer = [[MPMoviePlayerController alloc]initWithContentURL:url];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePreloadDidFinish:) name:MPMoviePlayerLoadStateDidChangeNotification
                                                   object:_moviePlayer];
        _moviePlayer.shouldAutoplay=NO;
        [_moviePlayer prepareToPlay];
    }

}

Add  your movie after movie is completely loaded
-(void)moviePreloadDidFinish:(NSNotification*)notification
{

   _moviePlayer.controlStyle=MPMovieControlStyleDefault;
   [self.view addSubview:_moviePlayer.view];
   [_moviePlayer play];
   [_moviePlayer setFullscreen:YES animated:YES];

}

A: You may not be supplying a valid path to the URL. It looks like your trying to append your resource to the documents path, but that resource may not actually be there. You have to write the file to that path first. You should always double check your path with:
if ([[NSFileManager defaultManager] fileExistsAtPath:yourPath])
{
//path exists
}

Otherwise, just init the movie player with the straight up resource if you have it inside of your app.

A: Your code looks good. Check the file name is correct.. Also give a try like
-(void)playMovie
{
   NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
   NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"xcode4-outlet.mov"];

    NSURL    *fileURL    =   [NSURL fileURLWithPath:filePath];
    MPMoviePlayerController *moviePlayerController = [[[MPMoviePlayerController alloc] initWithContentURL:fileURL]retain];
   [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(moviePlaybackComplete:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:moviePlayerController];

   [self.view addSubview:moviePlayerController.view];

    moviePlayerController.fullscreen = YES;
   [moviePlayerController play];
  }

  - (void)moviePlaybackComplete:(NSNotification *)notification
  {
   // playback completed
  }


text:
Q: Disable a single nock scope immediately to re-setup a mocked URL Using nock, is there a way to disable a single nock scope?
I've been struggling with some tests that set up nocks of the same URL as some other tests. They both run fine separately, but when run in the same mocha session one of them fails, because I'm unable to re-nock the active nock scopes, meaning the nocks that were set up catches all the requests.
What I've tried:

*

*If I set up some nocks in before() and then call scope.persist(false) in my after(), it only "unpersists" the scope, so that it's active for one more request. It does not immediately disable it.

*I've found that nock.cleanAll() immediately disables the nocks so that they can be set up again, but then it also disables any global nocks that may have been set up once, common to all test cases.

So far, the only solutions I've found are 1) use unique URL:s for all nocks, which isn't always possible or 2) use nock.cleanAll() and don't rely on any global nocks - instead make sure to only set up nocks in local before() functions, including setting up the global ones repeatedly for every test that needs them.
It seems it would be highly useful to be able to do
scope = nock('http://somewhere.com').persist().get('/'.reply(200, 'foo');
and then use that nock in a bunch of tests, and finally do
scope.remove();
However, I've not been able to do something like this. Is it possible?
Example:
before(async () => {
   nock('http://common').persist().get('/').reply(200, 'common');
});

after(async () => {
});

describe('Foo tests', () => {
    let scope;
    before(async () => {
        scope = nock('http://mocked').persist().get('/').reply(200, 'foo');
    });
    after(() => {
        // scope.persist(false); // This causes the Bar tests to use the Foo nocks one more time :(
        // nock.cleanAll(); // This also disables the common nocks
    });
    it('Should get FOO', async () => {
        expect(await fetch('http://mocked').then(res => res.text())).to.equal('foo');
        expect(await fetch('http://common').then(res => res.text())).to.equal('common');
    });
    it('Should get FOO again', async () => {
        expect(await fetch('http://mocked').then(res => res.text())).to.equal('foo');
        expect(await fetch('http://common').then(res => res.text())).to.equal('common');
    });
});

describe('Bar tests', () => {
    let scope;
    before(async () => {
        scope = nock('http://mocked').persist().get('/').reply(200, 'bar');
    });
    after(() => {
        // scope.persist(false);
        // nock.cleanAll();
    });
    it('Should get BAR', async () => {
        expect(await fetch('http://mocked').then(res => res.text())).to.equal('bar');
        expect(await fetch('http://common').then(res => res.text())).to.equal('common');
    });
    it('Should get BAR again', async () => {
        expect(await fetch('http://mocked').then(res => res.text())).to.equal('bar');
        expect(await fetch('http://common').then(res => res.text())).to.equal('common');
    });
});

These tests either fail the 3rd test if using scope.persist(false) (since that test still gets the foo version), or fails tests 3 and 4 if using nock.cleanAll(), since the common nocks are then removed.

A: I also had this issue and found a way to work around it by listening to the request event emitted by the scope and removing the interceptor when the event is fired. Ideally, I think you should be listening to the replied event but for some reason, that event wasn't firing when I tried it, not sure why. But the code below worked for me:
/**
 * @jest-environment node
 */

const nock = require('nock');

describe('Test suite', () => {

  test('Test case', async () => {

    let interceptor1 = nock('https://example-url.com', {
        reqHeaders: {
          'Content-Type': 'text/xml',
          soapaction: 'http://www.sample.com/servie/getOrders',
        },
      })
      .post('/');

    let interceptor2 = nock('https://example-url.com', {
        reqHeaders: {
          soapaction: 'http://www.sample.com/servie/getProducts',
        },
      })
      .post('/');

    let scope = interceptor1.replyWithFile(200, path.join(__dirname, './path1.xml'));
    interceptor2.replyWithFile(200, path.join(__dirname, './path.xml'));

    scope.on('request', (req, interceptor) => {
      nock.removeInterceptor(interceptor1);
    });

    const resp = await asynccall();
    expect(resp).toStrictEqual(exp);
  });

});

A: As described here: Unable to remove interceptors using nock I found a way of not storing the interceptors by just setting the mock again (which apparently returns the interceptor again) and then using the returned interceptor in the removeInterceptor() function. This returns true indeed and does work in my tests.

A: I found a pretty simple workaround for this one - the scope has a property called "interceptors", which is an array of the various interceptors the scope uses. You can replace the "body" property of the interceptor with whatever you want.
let scope = nock(base).get(path).reply(200, []).persist();
testable.call(path).then(console.log);      //returns []
scope.interceptors[0].body = [1,2,3];
testable.call(path).then(console.log);      //returns [1,2,3]


text:
Q: JQuery Ajax function now working I have wrote an ajax function and it partially works. Doesn't give any errors . but when i add alert to check my values it works completely . It renders the complete thing . Can any one tell me where did i do wrong in here
$.ajax({
        type : "POST",
        url : "/usermanageajax/",
        data : 'key=' + key_value,
        success : function (data) {
                var element = users.salary[users.salary.length -1];
                var hrs = users.hours[users.hours.length -1];
                var html = "Name \"" + users.desc(0,50) + "...\" "+ "has  " + element + "  of "+ hrs + "";
                // alert('*');
                $('#title').html(html);
                chart_s = draw_chart(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
});

A: The justification of this issue is that the alert call blocks the calling of the two next line. Seems that the browser needs some milliseconds to achieve something before performing the two next lines.
Try to call setTimeOut on the two other lines to be called after few milliseconds.
Again, what is the browser you are testing on?

A: The fact that it works with the alert indicates a race condition.
Try moving your code to a complete handler instead of a success handler.  You can also check for success there.


text:
Q: how to integrate akka actors with decline I have an application with akka, akka http, and akka streams, so it is not rest or microservice is a ephemeral app; it is a data extractor from a rest api and the app writes to a postgres db,  and it works just i have a doubt , if it is correct to integrate decline and akka in this way.
code :
object App extends CommandIOApp(name = "app" , header = "extractor", version = "0.1.0") {

  val config = Config( token, jdbcDriver = jdbcDriver, jdbcURL = jdbcURL, jdbcUser = jdbcUser, jdbcPassword = jdbcPassword, jdbcSchema = jdbcSchema)

  override def main: Opts[IO[ExitCode]] =
    Opts.subcommand(name="extract-teams", help="Extract Teams from API"){

      val tableName = Opts.option[String]("recursive", short="r", help="Recursive Extraction")
      val outputFile = Opts.option[Path]("output", short="o", help="Output file").withDefault(Paths.get("output.csv"))

      ( tableName, outputFile).mapN{( table, output) =>
        println(table)
        println(output)

        ClickUpExtractions.extractTeams()

        IO(ExitCode.Success)
      }
    }

  object ClickUpExtractions extends ActorGlobalImplicits {

    def extractTeams(): Unit ={

      import com.arkondata.extractors.ClickUpTeamsActions._
      val extractorFetcher = system.actorOf(ClickUpTeamsFetcher.props(config), name = "EngineActor")
      val extractorWriter = system.actorOf(ClickUpTeamsBulk.props(config) , name = "Writer")

      extractorFetcher ! Fetch(extractorWriter)

    }

  }

}

receive code:
override def receive: Receive = {
    case WritePG(teamsData) =>
      println("-------writer")
      println(teamsData)
      val teamsPG: List[Teams] = teamsData.map(data => Teams(data.id, data.name, data.color, data.avatar))
      println(teamsPG)

      println("insert-----------------------")
      //// manejar exception aqui  importante!!!
      val upsertStatement = "insert into Teams (id, name, color, avatar) values ( ? , ? , ? , ?) ON CONFLICT(id) DO UPDATE SET name = EXCLUDED.name"
      BulkWriter(config).insertMany[Teams](teamsPG,upsertStatement).unsafeRunSync()//.unsafeToFuture()//.unsafeRunSync()
      //// manejar exception aqui  importante!!!
      println("insert doobie")
      println("end------------------------")

      self ! "mensaje salida myself!!!!"
    case msg:String =>
      println(msg)
      context.system.terminate()
      System.exit(1) // this is the last step in the akka flow
  }

note:
System.exit(1) // this is the last step in the akka flow

also i use other libraries like doobie, decline, cats: https://ben.kirw.in/decline/effect.html .
The applications works just i need to know if it is correct or if exists a better integration between akka and this : IO(ExitCode.Success)
is there any way to get from akka a tell response and validate it, something like :
val res = extractorFetcher ! Fetch(extractorWriter)
if (validate(res))
   IO(ExitCode.Success)
else

   IO(ExitCode.Error)

A: Some suggestions:

*

*You can use Akka with other cats based frameworks, but you will have two different jargons in your application : Fibers, ActorSystems, Futures vs IO effects, ... So, if you want to work with Cats go for Monix or FS2, they connect directly with Cats effects. Instead, if Akka is mandatory for you, use Akka Streams, it has a wonderful suite and deal only with Akka distpatchers and Scala Futures.

*Use Akka Typed. Akka has improved a lot since Akka Typed became production ready. You are creating async computations in the receive function, something prone to errors.

A: Akka ecosystem relies on Future. Cats Effect relies on some F[_] - the build-in is IO but there are also Monix's Task and ZIO.
Translation Future <=> IO can be done like:
io.unsafeToFuture

IO.fromFuture(IO(start future here)) // Future start is side-effect on its own

Similarly for Monix:
task.runToFuture // requires Scheduler

Task.deferFuture(future thunk) // or
Task.deferFutureAction(implicit scheduler => future)

If you are using tagless then it's:
Async.fromFuture(Sync[F].delay(start future)) // requires implicit Async[F]

val runToFuture: F ~> Future // AFAIR there is no popular type class for it
runToFuture(io)

If you are are using streams then there is streamz library that handles Akka Streams <=> FS2 translations. Akka Streams, Monix's Observable implements, and FS2 provide an implementation for Reactive Streams so you could make these libraries talk to each other using RS interfaces, so libraries like streamz are just a convenience tools.
There are no other integrations AFAIK and there is no need for them.
However, I would recommend getting some basic knowledge how Akka and Future work (eagerness, memoization, Execution Contexts etc) vs how Cats Effect work (usually laziness, no memoization, no EC besides initialization of Clock or ContextShift in CE IO, slight differences between CE IO and Monix e.g. Scheduler). If you don't know the difference between them you can easily do some damage.


text:
Q: What is ".in" file in java that is for inputs? in a Programming Contest, I found at the start of each problem such of these

Program :    vote (cpp|java)
Input:   vote.in
Baloon Color:     Gold

what is the ".in" extension and the Baloon Color ?

A: .in is nothing more than something used by programming contests to designate input.  The contents are just a plain text file.

A: The ".in" file extension doesn't have any special meaning as far as Java or C++ is concerned. It's just an extension to indicate (to humans) that it is an input file.


text:
Q: Lines of Level Curves of an Analytic Function's Real and Imaninary Parts I want to solve the following question:
Let $g(z)$ be analytic at $z_{0}$ and let $g'(z_{0})=0$ and $g''(z_{0})\neq 0$ so that near $z_{0}$,$g(z)-g(z_{0})=[w(z)^{2}]$ for $w$ analytic, $w'(z_{0})\neq 0$.
Prove that there are exactly two perpendicular curves on which $Re(g)$ (alternatively, $Im(g)$) are constant through $z_{0}$. Show also that lines of constant $Re(g)$ and $Im(g)$ intersect at $45 ^{\circ}$.
I know that if a function $f$ analytic on a domain and $f(z_{0})\neq 0$ then $Re(f)$ and $Im(f)$ are harmonic conjugate and their level curves passing through $z_{0}$ intersect at right angles at $z_{0}$. But how we interprete the fact that $g'(z_{0})=0$ to get the conclusion? Thanks.

A: The function $w$ is such that $w(z_0)=0$ and $w'(z_0)\neq 0$. Therefore we suppose $z_0=g(z_0)=0$ and write
$$w(z)=az+z^2\beta(z)$$
with $\beta$ a holomorphic function, $a\in\mathbb{C}$. There exists a neighbourhood $U=\{|z|<\epsilon\}$ such that $w'(z)\neq 0$ for $z\in U$, so $w$ is a conformal mapping from $U$ onto $w(U)=W\subseteq\mathbb{C}_\zeta$ (complex plane with $\zeta$ coordinate).
The set $\{z\in U\ :\ \mathrm{Re}\;w^2(z)=0\}$ is mapped by $w$ onto the set
$$\{\zeta\in W\ :\ \mathrm{Re}\;\zeta^2=0\}$$
which is union of two perpendicular lines through the origin (the two bisectors).
In the same way, the set $\{z\in U\ :\ \mathrm{Im}\;w^2(z)=0\}$ is mapped by $w$ onto the set
$$\{\zeta\in W\ :\ \mathrm{Im}\;\zeta^2=0\}$$
which is union of two perpendicular lines through the origin (the two axes).
Moreover, these two pairs of lines are mutually inclined by $45^\circ$.
Now, as we said, $w$ (and hence also its inverse) is a conformal mapping from $U$ to $W$ (both neighbourhoods of the origin), so it preserves angles between curves.


text:
Q: Change a image depending on a generated nr in a input field using jQuery I have the following working code: http://jsfiddle.net/NtHwN/4/
It will deduct the number that is in the input field when pressing the hyperlink or button by -1 and will do this just one time for both. This works great.
Now I have 3 images: 1.jpg, 2.jpg and 3.jpg. I want to show this image depending on the number in the input field. So I've added:

Now, if the user clicks the button or hyperlink, the nr will change from 3 to 2. When this happens, the image should also change from "test/images/3.jpg" to "test/images/2.jpg", but how to do this with jQuery? (so the nr in the input field corresponds with the nr in the .jpg)
Played around with this:
$(function () {
    $('#image_select').attr('img_', {
        'child': 'img',
        'change': 'src',
        'formatValue': function (value) {
            return 'test/images/' + value + '.jpg'
        }
    });
});

But with no luck.
Kind regards,
Maurice

A: Try -
$(document).ready(function() {
    $(".minus").one("click", function(){
        var value = parseInt($("#sum").val());
        value = value - 1;
        $("#sum").val(value);
        $("#img_select > img").attr("src","test/images/" + value + ".jpg")
    });
});

That should just concatenate your field value into the image string and insert it into the src attribut` of your image.  You'll probably also need to add some code to prevent your value going below 1.

A: Just do this:
http://jsfiddle.net/NtHwN/6/
Script:
$(document).ready(function() {
    $(".minus").one("click", function(){
        var value = parseInt($("#sum").val()) - 1;
        $("#sum").val(value);
        $("img").attr("src", "test/images/" + value + ".jpg");
    });
});

HTML:
<input size=10 id="sum" value="3">
<input class="minus" type=button value="-">
minus

A: In your click handler:
jQuery("#img_select img").attr("src", "test/images/" + jQuery("#sum").val() + ".jpg");

A: try this
http://jsfiddle.net/NtHwN/7/


text:
Q: UWP Optional package in C++/WinRT Visual Studio 2017 includes a project template for creating optional packages in C#. However, there is no corresponding project template for C++/WinRT. Is there any way to create the same kind of optional package using C++/WinRT in Visual Studio?

A: There's no separate 'Optional Code Package' visual studio template for C++\WinRT. Please see the OptionalPackageSample repository on GitHub. It creates a OptionalPackageDLL
 to show how to create a project with code that can be executed from the main package. The MyMainApp project demonstrates how to load code from the OptionalPackageDLL.dll file.


text:
Q: Cycle.js: making a multiselect component. Combined stream of option component states doesn't output changed states Runnable example:
https://esnextb.in/?gist=978799bf48a7f914cbbd39df0213d672
I'm trying to create a multiselect component for cycle.js to see if I want to replace the current UI of an application with a cycle app.
I have one component for the options within the multiselect. Each of the options gets passed props in the form {selected: Bool, label: String, value: Int}
Here's the overview of the code:
The Option component listens for clicks on itself and toggles the 'selected' boolean by combining a stream of booleans generated by folding logical 'not' functions upon the initial boolean passed to the option in the props$ source.
The Option component then outputs a stream of it's state so that the Multiselect component can refer to it in order to return a stream of selected values and such.
The Multiselect component receives a props$ source which contains a stream with the options [{selected, label, value}...].
From these options it constructs a stream of arrays of Option components.
The stream of Option components is then flattened into a stream of arrays of virtual dom trees (one for each option).
The stream of Option components is also flattened into a stream of arrays of states (one for each option).
Here is where the problem begins:
Both of the above only log once if I call .observe(console.log) on them.
In order to display the multiselect I then map the stream of arrays of virtual dom trees of the options to generate the virtual dom tree of the multiselect.
I also combine this vtree stream with the state stream so that I can console.log both (since observe only logs them once).
When I log them, the vtree arrays do change, but the states of all options are always the same as their initial states.
This only happens if the options are isolated. If they aren't isolated, they all respond to clicks on any of them, but their states are logged as changed.
What is going on here? Why does isolate matter? Because all the combined streams don't fire every time? Is what I'm doing completely non-idiomatic?
http://pastebin.com/RNWvL4nf here's a pastebin as well. I wanted to put it on webpackbin, but it wouldn't download the packages I need.
import * as most from 'most';
import {run} from '@cycle/most-run';
import {div, input, p, makeDOMDriver, li, ul, span, h2} from '@cycle/dom';
import fp from 'lodash/fp'
import isolate from '@cycle/isolate'

// props : { selected : Bool, label : String, value: Int}
function Option({DOM, props$}) {
    const click$ = DOM.select('.option').events('click')
    // a stream of toggle functions. one for each click
    const toggle$ = click$
                       .map(() => bool => !bool)
    /// stream of toggle functions folded upon the inital value so that clicking the option checks if off and on
    const selected$ = props$.map(prop => toggle$.scan((b, f) => f(b), prop.selected)).join()
    // a stream of states which has the same structure as props, but toggled 'selected' field according to selected$ stream
    const state$ = most.combineArray((props, selected) => ({...props, selected}), [props$, selected$])
    // the state mapped to a representation of the option
    const vtree$ = state$.map(state => {
        return li('.option', {class: {selected: state.selected}}, [
            input({attrs: {type: 'checkbox', checked: state.selected}}),
            p(state.label),
        ])
    })
    // returns the stream of state$ so that multiselect can output a stream of selected values
    return {
        DOM: vtree$,
        state$,
    }
}

function Multiselect({DOM, props$}) {
    // a stream of arrays of isolated Option components
    const options$ = props$.map(
        options =>
            options.map(it =>
                isolate(Option)({DOM, props$: most.of(it)})))
                // Option({DOM, props$: most.of(it)}))) // comment above line and uncomment this one. Without isolation the component doesn't work correctly, but the states are updated

    // a stream of arrays of virtual tree representations of child Option components
    const optionsVtree$ = options$.map(options => fp.map(fp.get('DOM'), options))
                                  .map(arrayOfVtree$ => most.combineArray(Array, arrayOfVtree$))
                                  .join()
    // a stream of arrays of states of child Option components
    const optionStates$ = options$.map(options => fp.map(fp.get('state$'), options))
                                  .map(arrayOfState$ => most.combineArray(Array, arrayOfState$))
                                  .join()
                                //   .map(fp.filter(fp.get('selected')))

    // here the virtual trees of options are combined with the state stream so that I can log the state. I only use the virtual dom trees
    const vtree$ = optionsVtree$.combine(Array, optionStates$).map(([vtrees, states]) => {
        console.log(states.map(state => state.selected)); // this always prints the initial states
        // console.log(vtrees); // but the vtrees do change
        return div('.multiselect', [
            ul('.options', vtrees)
        ])
    })

    const sinks = {
        DOM: vtree$,
        optionStates$
    };
    return sinks;
}

run(Multiselect, {
  DOM: makeDOMDriver('#app'),
  props$: () => most.of([
      {value: 0, label: 'Option 1', selected: false},
      {value: 1, label: 'Option 2', selected: false},
      {value: 2, label: 'Option 3', selected: false},
      {value: 3, label: 'Option 4', selected: false},
    ])
});

EDIT:
franciscotln kindly made a working example which revealed something in mine.
https://gist.github.com/franciscotln/e1d9b270ca1051fece868738d854d4e9
If the props are a simple array not wrapped within an observable it works. Maybe because if it's an observable of arrays it requires an observable of arrays of components instead of a simple array of child components.
However the two aren't equivalent. With my original version (where the options are a stream of arrays) the props$ can be something other than just an .of observable. It's value can change during the course of the program, whereas with the second I'm stuck with the original array.
Is there there some problem with a stream of arrays of isolated components?
const props = [{value: 0, label: 'Option 1', selected: false},
                 {value: 1, label: 'Option 2', selected: false},
                 {value: 2, label: 'Option 3', selected: false},
                 {value: 3, label: 'Option 4', selected: false}]
// a stream of arrays of isolated Option components
const options = props.map(prop =>
    isolate(Option)({
        DOM,
        props$: most.of(prop)
    })
);

A: @tusharmath In the cycle gitter chat found out what I was doing wrong.
Apparently all I had to do was call .multicast() on the stream of arrays of option components:
const options$ = props$.map(
        options =>
            options.map(it =>
                isolate(Option)({DOM, props$: most.of(it)}))).multicast()

Something to do with hot and cold observables. Got burned by cold observables I suppose.
Here's his explanation.

Ive ill try to explain as much as I have understood from the experts
here. isolate attaches a scope param to the virtual dom node that is
created. now in your case you are creating the virtual dom twice
because of the two subscriptions here — DOM :
https://esnextb.in/?gist=978799bf48a7f914cbbd39df0213d672 state$:
https://esnextb.in/?gist=978799bf48a7f914cbbd39df0213d672 the two
VDoms have different scopes effectively the event listeners are using
a different scope and the dom element has a different scope.


text:
Q: Format string case on INSERT? I'm inserting string values from one table into another where the string values are in all caps.
How can I alter the case of the string on INSERT such that only the first letter of every word in the string is capitalized?
Example: 'TESTING ABC' would be inserted as 'Testing Abc'

A: The initcap function should do the trick:
INSERT INTO some_table (some_column)
SELECT INITCAP(some_other_column)
FROM   some_other_table


text:
Q: Issue sending CloudWatch Event to SNS (Amazon Connect I want to have CloudTrail send a Connect API call to CloudWatch (it works) then have an event push an SNS to my email.
I have this working with Alarms but I want a custom message which I can't do in Alarms.
I believe it to be the way I have configured the Event Pattern for the rule.
The Event details in the CloudTrail API call is
"eventSource": "connect.amazonaws.com",
"eventName": "DeleteUser"
and I have attached an image of the configured Event Pattern.
Cheers!
https://imgur.com/a/UHRfbnq


text:
Q: Using p4merge as git diff tool I use windows 7. I want to use p4merge as Git diff/merge tool. I follow this article and this one to setup and config p4merge:
git config --global merge.tool p4merge
git config --global mergetool.p4merge.path "C:/Program Files/Perforce/p4merge.exe"
git config --global diff.tool p4merge
git config --global difftool.p4merge.path "C:/Program Files/Perforce/p4merge.exe"

And these lines are from git config:
merge.tool=p4merge
mergetool.p4merge.path=C:/Program Files/Perforce/p4merge.exe
diff.tool=p4merge
difftool.p4merge.path=C:/Program Files/Perforce/p4merge.exe
mergetool.keeptemporaries=false
mergetool.prompt=false

Now git mergetool command works fine. But when I use git difftool command in git bash, I expect p4merge but I see  internal implementation of diff in git bash.
I tried Smooth Git + P4merge but it does not work for me also I tried to do as described in External Merge and Diff Tools but I did not understand that.
Note:
When type of conflict is removed file conflict, git difftool command opens p4merge.

A: Better late than never :)
mergetool.p4merge.path should be mergetool.p4merge.cmd
Change path to cmd for both the mergetool and difftool lines.

A: Not sure if helps, but recent versions of Git support P4Merge (I use git version 2.17.0. on Windows through MSYS2).
You can tell if this is the case or not by running git difftool --tool-help. It'll list the available tools Git can use (because they've found them in your %PATH%) and the tools it could use (if they were installed).
If p4merge is in this list then you just need to add the path where p4merge.exe resides to your %PATH% (on Windows I recommend Rapid Environment Editor for this).
After this is done you just need the following config to be in your .gitconfig
[diff]
    tool = p4merge
[merge]
    tool = p4merge

and nothing else. So remove other stuff like difftool.path and all that.
Then just use git difftool or git mergetool to your hearts content.
Note: I had a repository in which even if I did issue the git difftool or git mergetool commands P4Merge wouldn't start. I'm not sure what was the problem in that repo. However I tried creating an empty repo somewhere on my drive with git init, add a file, commit it, then modify it, then I tried difftool and it worked. So if the above description doesn't work for you chances the problem lies somewhere else. Hope this helps.

A: If you are on Mac don't forget to add / before Applications as in:
[mergetool "p4merge"]
    path = /Applications/p4merge.app/Contents/MacOS/p4merge

This was why P4Merge wouldn't open for me when I ran below:
git mergetool

A: DeviantDev has a pretty good answer for this.
Adding this to my .gitconfig worked for me...
[diff]
    tool = p4merge
[difftool]
    prompt = false
[difftool "p4merge"]
    path = C:\\Program Files\\Perforce\\p4merge.exe
[merge]
    tool = p4merge
[mergetool "p4merge"]
    path = C:\\Program Files\\Perforce\\p4merge.exe
[mergetool]
    keepBackup = false


text:
Q: Screen Capture Using c# I have tried capturing the screen using the following. But it is throwing 'Exception was thrown from the UITest module' exception.
System.Drawing.Image image;
BrowserWindow win = new BrowserWindow();
image = win.CaptureImage();
String ErrorFile = "D:\\TestLog\\" + errorMsg + DateTime.Now.ToString("MM.dd.yyyy HH.mm.ss") + ".jpeg";
image.Save(ErrorFile);

I am not able to understand why the exception was showing
. It was working perfectly before.

This is what I am doing with this code
I am using this code in the testcase failure condition. If that test case is failed Iam captureing the browser screenshot and save it in D:/testlog folder.


text:
Q: JavaScript help with forms? So, I have a form that consists of 4 inputs, username, password, email, and name.
I am sick and tired of having to make a javascript function for each of them, because each input is a text input, and when a user clicks the input box I have it change the background of the input to a different color.
So heres how I coded:
The form inputs:
<input type="text" name="username" id="usernameInput" onclick="changeUsername(); return false;" onblur="changeUsernameback(); return false;">

<input type="text" name="password" id="passwordInput" onclick="changePassword(); return false;" onblur="changePasswordback(); return false;">

and the other two forms are the same, only with different names and different id's and javascript functions.
MY Javascript:
function changeUsername() {
 document.getElementById('usernameInput').style.background='#FFFF00';
}

function changeUsernameBack() {
 document.getElementById('passwordInput').style.background='#FFFF00';
}

and the other three are just like that only setup for their own specific id.
AND when creating CSS, I have to make different ID's for all 4 inputs.
What I want to know is: Is there a way I can only make one CSS id, and one javascript function to change all inputs? Because I know when you just use one function for all, javascript tries to change all at once..
I was thinking something like
document.getElementById('inputText'+[i]).style.background='#FFFF00';

and then when I give each input an id I could just automatically increment them on the page such as input1, input2, input3 etc.
But that doesn't seem to work? Maybe I am coding it wrong? Please help..

A: You COULD do this:
<input type="text" name="username" id="usernameInput" onfocus="change(this);" onblur="changeBack(this);">
<input type="text" name="password" id="passwordInput" onfocus="change(this);" onblur="changeBack(this);">

With this javascript:
function change(el) {
    el.style.background='#FFFF00';
}

function changeBack(el) {
    el.style.background='#FFFF00';
}

A couple of notes:

*

*You are using onclick - while that may work, I think what you want is onfocus.

*As far as I know, it is not necessary to return false; on either of these events.

While the above will work with plain Javascript, I am obligued to suggest the jQuery way:
<input type="text" name="username" id="usernameInput">
<input type="text" name="password" id="passwordInput">

And then do this with jQuery:
$(function() {
    $('input').focus(function() {
        $(this).css('background-color', '#FFFF00');
    }).blur(function() {
        $(this).css('background-color', '#FFFF00');
    });
});

I personally feel this is cleaner, as inline javascript events are ugly, but the first one should work.

A: <input type="text" name="whatever" id="uniqueVal" onclick="return gotFocus(this);" onblur="return lostFocus(this);">

function gotFocus(el) {
    el.style.background = 'Red';
    return false;
}

function lostFocus(el) {
    el.style.background = 'Blue';
    return false;
}

I personally like returning false from these types of functions to reduce the amount of code I have to write in the HTML element attribute.

A: You should try using jQuery - that's what we use. It would be very simple using jQuery.
<script>
$(document).ready(function(){
  $(".PrettyInput")
    .focus(function() { $(this).css("background-color", "#FFFF00"); })
    .blur(function() { $(this).css("background-color", "#FFFF00"); });
});
</script>

<html>
<body>
  Username: <input type="text" class="PrettyInput" />
  Password: <input type="text" class="PrettyInput" />
</body>
</html>

A: Here's a complete example using jQuery.
<html>

  <head>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
    <script>
      $(document).ready(function(){
      $("input:text")
        .focus(function() { $(this).css("background-color", "#FFFF00"); })
        .blur(function() { $(this).css("background-color", "#FFFFFF"); });
      });
    </script>

  </head>

  <body>

    <form>
      Username: <input type="text" />
      Password: <input type="text" />
    </form>

  </body>

</html>

A:
Is there a way I can only make one CSS id, and one javascript function to change all inputs?

Yes, you can attach one event handler to many elements simply by assigning it as a function; the subject element comes in as 'this'. You don't even need an ID.
For completeness, since no-one else seems to have said it, it's quite possible to have the advantages of non-inline, unobtrusive event handlers without dragging in the whole of jQuery (which is probably a bit excessive if all you want is a few highlighting inputs):
<input type="text" name="username" />
<input type="text" name="password" />

<script type="text/javascript">
    function inputFocussed() {
        this.style.backgroundColor= 'yellow';
    };
    function inputBlurred() {
        this.style.backgroundColor= 'white';
    };

    // Bind to input[type=text]
    //
    var inputs= document.getElementsByTagName('input');
    for (var i= inputs.length; i-->0;) {
        if (inputs[i].type=='text') {
            inputs[i].onfocus= inputFocused;
            inputs[i].onblurred= inputBlurred;
    }   }
</script>


text:
Q: Battery Charger output based on input Voltage If a charger is rated at input 230 V 50 Hz and output 3V 100 mA, is given an input of 220 V, how will it affect the output charging current? Will it be lower than the rated output current or higher?

A: If you are talking about a cell phone charger or something like that, they are designed to maintain the output voltage for a given load and a wide range of input voltages. Most chargers don't care if they get 230V or 120V (If it is a SMPS).
Further more the mains power supply has about 5-10% tolerance of the voltage as standard.
So the charging current will stay the same (for a well build charger.)


text:
Q: Add new RuleTemplate in the Targeted Content Widget in EKTRON CMS I have an ektron8.7 application. I need to Customize the Targeted Content Widget (add a new RuleTemplate). But I dont know how to achieve this. Please anyone help me for this
Please find this link and answer me.

A: In root\App_Code folder just create a class file for example MyRuleTemplate.cs
namespace Ektron.Com.Helpers
{
    public class MyRuleTemplate : RuleTemplate
    {

        private StringOperatorField _fieldOperator = null;

        public MyRuleTemplate ()
            : base("My First RuleTemplate")
        {
        _fieldOperator = new StringOperatorField("operator", "operator", "");
        }
        /// <summary>
        /// Evaluating the rule template condition set in the widget
        /// </summary>
        /// <param name="rule"></param>
        /// <returns></returns>
        public override bool Evaluate(Rule rule)
        {
            //write the code for evaluate
        string op = rule.Values["operator"];
            string visitorCountry = string.Empty;
            string ruleCountry = rule.Values["name"];

            try
            {
                string IP = HttpContext.Current.Request["remote_addr"];
                if (!string.IsNullOrEmpty(HttpContext.Current.Request["ip"]))
                    IP = HttpContext.Current.Request["ip"];
                else if (!string.IsNullOrEmpty(HttpContext.Current.Session["ipaddress"].ToString()))
                    IP = HttpContext.Current.Session["ipaddress"].ToString();
                var userData = Ektron.Cms.UserContext.GetLocationInfo(IP);
                visitorCountry = userData.CountryCode;
            }
            catch (Exception ex)
            {
                Ektron.Cms.EkException.LogException(ex, System.Diagnostics.EventLogEntryType.Error);
            }

            return _fieldOperator.Evaluate(visitorCountry, op, ruleCountry);
        }

    private Dictionary<string, Field> _fields = null;
        public override Dictionary<string, Field> Fields
        {
             get
            {
                if (_fields == null)
                {
                    _fields = new Dictionary<string, Field>();
                    this.AddField(_fieldOperator);
                    List<LocalizableValue> countryFields = new List<LocalizableValue>();
                    countryFields.Add(new LocalizableValue("US", "United States"));
                    countryFields.Add(new LocalizableValue("DE", "Germany"));
                    countryFields.Add(new LocalizableValue("CA", "Canada"));
                    countryFields.Add(new LocalizableValue("FR", "France"));
                    _fields.Add("name", new EnumField(new LocalizableValue("name", "name", ""), countryFields));
                }
                return _fields;
            }
        }

        /// <summary>
        /// Text which will be displayed in the condition
        /// </summary>
        public override string Text
        {
            get
            {
                return "Custom Country {operator} {name}";
            }
        }
        /// <summary>
        /// Title of the rule template
        /// </summary>
        public override string Title
        {
            get
            {
                return "Custom Country";
            }
        }

    }
}

Then, in \widgets\TargetedContent.ascx.cs inside the method AddAllRuleTemplates() just add a reference to the newly added custom rule template MyRuleTemplate as AddRuleTemplate(new MyRuleTemplate());


text:
Q: RStudio's embedded browser is not saving cookies In the Shiny app I'm developing, one step requires logging to a remote server to browse files. The authentication procedure is designed so, that upon successful login, the sever responds with an authorization token and a cookie with session id. Both of them are required to be passed when performing subsequent requests to the server.
When testing the app in Chrome, everything works smoothly. When trying to use it in RStudio, where it's rendered with RStudio's embedded browser, the user is logged out immediately after a successful login with error message saying that user session has expired.
I have discovered that the root of the problem is that the RStudio's embedded browser is not saving the cookie with session ID. The storage tab in the inspector is empty.

Is there a way to change the RStudio's default browser or may there be a glitch in my thinking?

A: I have been informed that to overcome this issue one has to download the preview release (1.2) of RStudio, which uses Chromium under the hood. It solved the problem in my case.


text:
Q: Qt: QProcess to call terminal + script I am having real trouble with the use of QProcess, I've looked at several locations to use it, but everytime I use it my program freezes, or it just doesn't do what I want it to do.
What I want to do from my GUI application is the following:
Change directory to /Users/Tim/etc etc.
From there I need to call gnuplot and load a script into it.
What I'd normally would do in a terminal window is the following:
 > cd /Users/Tim/...
 > /opt/local/bin/gnuplot barchartscript.txt

At the moment I'm using system call to do this, and that works, but everybody recommends using QProcess, and so I would like to do that.
How my code looks now with QProcess:
    QObject *parent;
    QProcess *process = new QProcess(parent);
    QString commands;
    QString changed = "cd /Users/Tim/etcetc";
    commands = (changed + "&& /opt/local/bin/gnuplot scatterplotscriptwithout.txt").c_str();

    process->start(commands);

Can anybody tell me what's wrong? Or the correct way to do multiple commands in one process?

A: This snippet may be useful (untested). Refer to QProcess documentation for detail on each method.
process->setWorkingDirectory("/Users/Tim/etcetc");
process->setArguments(QStringList() << "scatterplotscriptwithout.txt");
process->start("/opt/local/bin/gnuplot");

EDIT
Another thing that seem wrong in your program is the undefined pointer that you give as parent to your QProcess instance. It is useful to set a parent to take benefit of an automatic children deletion. In this case, just take care to delete the QProcess instance yourself.
EDIT 2 (error handling)
QProcess *process = new QProcess;
connect(process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(handleError(QProcess::ProcessError)));

Then define a proper slot (here handleError)
void MyClass::handleError(QProcess::ProcessError error) {
   switch(error) {
   case QProcess::FailedToStart:
    qDebug() << "Failed to start, may be due to insufficient permissions";
    break;
    case QProcess::Crashed:
    qDebug() << "Program crashed.";
    break;
    //debug each case..
   }
}

See here for a detail of all the enum values.
If your QProcess ends correctly but not with the expected output, you can look at the exit code of your process and refer to the gnuplot man page for information.


text:
Q: Spotfire: Inputting columns from Cross Table into data function I have a Spotfire Data function called ARIMA that works beautifully. It mainly needs two equally sized inputs: A column of evenly spaced dates, and a column of order values. My data function can handle input that is out of order or needs to be aggregated but for performance sakes I want to take advantage of the speed at which Spotfire can get that same data into a Cross Table.
Therefore, I need a way to get the values from a Cross table into my data function. Here is what I have so far in IronPython that extracts the actual numbers I need from the Cross Table:
from Spotfire.Dxp.Application.Visuals import CrossTablePlot
from Spotfire.Dxp.Data import IndexSet
from Spotfire.Dxp.Data import RowSelection
from Spotfire.Dxp.Data import DataValueCursor
from Spotfire.Dxp.Data import DataSelection
from datetime import date
from Spotfire.Dxp.Data.Expressions import ColumnExpression

crossTable = visual.As[CrossTablePlot]()
crossSource = crossTable.Data.DataTableReference

##Get a Row Count
rowCount = crossSource.RowCount

##Index Set of all our rows
allRows = IndexSet(rowCount,True)

##Empty Index Set to fill with our desired markings
rowsToMark = IndexSet(rowCount,False)

##Pick the column we're interested in examining for values.
##You can create multiple cursors to look at multiple columns.
##Specify the name of your column (or document property SelectBU).
colCurs = DataValueCursor.CreateFormatted(crossSource.Columns[SelectBU])
dateCurs = DataValueCursor.CreateFormatted(crossSource.Columns["Order Date"])
# Initialize OrderValue and OrderDate lists from cross table data
OrderValue = []
OrderDate = []

#ColumnExpression xColumnExpression = ColumnExpression.Create(context.XAxis.Expression);
OrderValueColumnExpression = ColumnExpression.Create(crossSource.Columns[SelectBU].NameEscapedForExpression)
OrderDateColumnExpression = ColumnExpression.Create(crossSource.Columns["Order Date"].NameEscapedForExpression)

for row in crossSource.GetRows(allRows, colCurs):
    OrderValue.append(colCurs.CurrentValue)
for row in crossSource.GetRows(allRows, dateCurs):
    dateStr = dateCurs.CurrentValue.split("/")
    d =(date(int(dateStr[2]),int(dateStr[0]),int(dateStr[1])))
    OrderDate.append(d)

So I have all the info I need in 2 python lists. But I dont know how to feed these in as inputs to a data function. Any ideas? Here is what I've tried:
from Spotfire.Dxp.Data.DataFunctions import DataFunctionExecutorService, DataFunctionInvocation, DataFunctionInvocationBuilder

    dataManager = Document.Data
    app = Application
    dataFunction = None
    for function in dataManager.DataFunctions:
        if function.Name == 'ARIMA':
            dataFunction = function
    inputParams = []

    inputCollection = dataFunction.Inputs.GetEnumerator()

    for inputs in dataFunction.DataFunctionDefinition.InputParameters:
                if inputs.DisplayName=="OrderDate":
                    dataFunction.Inputs.SetInput(inputs, OrderDate)
                if inputs.DisplayName=="OrderValue":
                    dataFunction.Inputs.SetInput(inputs, OrderValue)

    dfes = app.GetService(DataFunctionExecutorService)
    context = app.ImportContext
    invocationBuilder = DataFunctionInvocationBuilder(dataFunction.DataFunctionDefinition, app.ImportContext)
    dataFunctionInvocation = invocationBuilder.Build()
    print 'Executing...'
    dfes.Execute(dataFunctionInvocation)
    print 'Done'

I understand why it doesnt work: It's because of the line dataFunction.Inputs.SetInput(inputs, OrderDate)
OrderDate is a python variable for my dates list, but I believe the second argument of SetInput() expects something called an "expression" which I infer to be a Spotfire-like expression. No idea how to work around this so I need help.'
Edit I should add that the above code only has two input parameters: "visual" which is my cross table visual and "SelectBU" which is a document property which points to different numerical columns (BU = Business Units) I can  use as my time series.

A: Here is how I solved the problem:
I wrote a CSV string with all the information I needed and rewrote my data function to only have one parameter (the csv string) which it parses to extract all the info it needs. The way I did this was setting up a document property of type String called csv and used ironpython to set the document property equal to the calculated csv string.


text:
Q: Is there any way we can elect leader in my application in Kubernetes using node.js? I am trying to implement leader election algorithm in my distributed node.js application.I am using Kubernetes as the container manager and deploying docker containers.I do not have details of host and port of other instances of application running in different pods.
Kubernetes already uses leader election algorithm to choose one leader at a time but my application is inside the container and pod , it is not aware whether i am leader or not. There is one sample code also available to know who is the current leader.
https://github.com/kubernetes-retired/contrib/tree/master/election
This code helps to know which container is the leader but it requires some special privileges to call kubernetes API.
Bully/Ring algorithm can be a solution, but since there is a restriction to not to use any queue/Centralized services like redis or zookeeper as we need another process to run these, but i can use shared filesystem as it will not require monitoring of an extra process.
Not Sure if it is possible to use redis/zookeeper without running a new process and can be done within the application itself.
How can i implement this solution using the application either by pinging them to check if it is down and then make itself to master. In this process lot of race conditions also occur.
I have tried Kubenetes leader algorithm to elect the leader, but due to restricted access to API, it is not possible to use.
Tried Bully algorithm, but since containers are in different pods they are not aware of each other.
Tried Ring algorithm , but the same issue as Bully algorithm.
I expect to implement leader election using any algorithm but without introducing any new processes.

A: Check out this blog post on how you can achieve that by using a sidecar pattern and a nodejs application


text:
Q: How to unload a PHP array in a tree format? I've got that array that is based on the user 1014. So like a pyramid I would like to echo a tree with the users that come that come after 1014 respectively.
Like:
$arr = array(

        1005 => 1014,
        1008 => 1014,

        1019 => 1008,
        1020 => 1008,
        1022 => 1005,
        1023 => 1005,
        );

1014
    - 1005
    - 1022 (this should indent more than the 1005)
    - 1023 (this should indent more than the 1005)
    - 1008
    - 1019 (this should indent more than the 1008)
    - 1020 (this should indent more than the 1008)
1005 and 1008 came from 1014
1019 and 1020 came from 1008
1022 and 1023 came from 1005
And so on...
I've created a function to go from the user id to the top but no idea the oposite...
function get_rede($id_winner) {

global $link;

$precednt = array();
$precednt_id = array();

$result = mysqli_query($link, "SELECT rede FROM users WHERE id = '$id_winner' ");

$row = mysqli_fetch_row($result);
$rede = $row[0];

array_push($precednt, $rede);
array_push($precednt_id, $id_winner);

do {

$q_precednt = end($precednt);

$result = mysqli_query($link, "SELECT rede FROM users WHERE id = '$q_precednt' ");

$row = mysqli_fetch_row($result);
$rede = $row[0];

array_push($precednt, $rede);
array_push($precednt_id, $q_precednt);

}
while($rede != 1000);

return array($precednt,$precednt_id);
}

Thank you!
Well, that's the result I am after. Can't think of an array function to help me out.

A: <?php

$arr = array(
        1014 => 1003,
        1003 => 1002,
        1002 => 1000,

        1005 => 1014,
        1008 => 1014,

        1019 => 1008,
        1020 => 1008,
        1022 => 1005,
        1023 => 1005,
        );

foreach ($arr as $key => $value) {
    $new_arr[$value][$key] = 1;
}

ksort($new_arr);

// here is your output
$output = reorder($new_arr);

function reorder($new_arr)
{
    if (count($new_arr) == 1) return $new_arr;
    $tree_array = $new_arr;
    foreach ($new_arr as $key => $values) {
        foreach (array_keys($values) as $ak) {
            if (array_key_exists($ak, $new_arr)) {

                $values[$ak] = $new_arr[$ak];

                $tree_array[$key] = $values;
                unset($tree_array[$ak]);
            }
        }
    }

    return reorder($tree_array);
}

This would output:
Array
(
    [1000] => Array
        (
            [1002] => Array
                (
                    [1003] => Array
                        (
                            [1014] => Array
                                (
                                    [1005] => Array
                                        (
                                            [1022] => 1
                                            [1023] => 1
                                        )

                                    [1008] => Array
                                        (
                                            [1019] => 1
                                            [1020] => 1
                                        )

                                )

                        )

                )

        )

)

This assumes that you have one root.


text:
Q: Using resultants to check if multivariate polynomials have a common factor - is my proof correct? Proposition: Let $f, g \in \mathbb R[x,y,z]$. Then the condition that $f, g$ have a common polynomial factor is an algebraic condition on their coefficients.
By algebraic condition, I mean there is a finite set of algebraic (polynomial) expressions in the coefficients, such that all expressions are zero if and only if $f, g$ have a common factor.
My proof: Let $\operatorname{Res}_x(f,g)$ be the resultant of $f, g$ when viewed as univariate polynomials in $(\mathbb R[y,z])[x]$.
Then $\operatorname{Res}_x(f,g) \in \mathbb R[y,z]$ is zero if and only if $f, g$ have a common factor that depends on $x$. As a polynomial in $y,z$, it is zero if and only if all of its coefficients are zero. But the coefficients of the resultant are simply polynomial expressions in the coefficients of $f, g$.
Therefore there is an algebraic condition on the coefficients of $f,g$ that determines when $f,g$ have a common factor that depends on $x$.
Repeating the argument, there are two more algebraic conditions on the coefficients of $f,g$, which determine when they have a common factor that depends on $y$ and when they have one that depends on $z$. The union of all 3 conditions is what we're after.
Questions:

*

*Is my proof correct? I'm especially concerned about the claim that the resultant is the zero polynomial if and only if there is a common factor that depends on $x$. (Does the resultant behave ok for polynomials over rings instead of over fields?)

*Do you have comments or suggestions for improvement? Any recommended books on this subject?

A: Your proof seems to work, but it looks incomplete because you need to use more explicitly the fact that the ring of polynomials is an UFD.
The condition that the resultant $\mathrm{Res}(f,g)=0$ means that there are some polynomials $p,q$ such that $\deg p<\deg f$, $\deg q<\deg g$ and
$fq=gp$ (so $p/q=f/g$). In a UFD this is equivalent to having a common factor of $f$ and $g$.
To complete your approach you must replace the coefficient ring by its quotient field. You need the unique factorization at the end when you simplify the coefficients to be ring elements again.
*
For zero divisor free rings, without unique factorization, it will not work. For example, consider the polynomials $x^2-4y^2$ and $x^2+4xy+4y^2$. In some rings, like $(\mathbb{R}[y])[x]$, they have the common factor $x+2y$. In other rings, for example in $(\mathbb{Z}[4y,4y^2])[x]$, they don't.
However, the resultants will be the same zero polynomial in all rings.
So this method does not work if the coefficients are from the ring
$\mathbb{Z}[4y,4y^2]$.
*
Another possible approach is building a single (but huge) resultant. If $f,g\in\mathbb{R}[x_1,\dots,x_n]$ are nonzero polynomials then take all polynomials of the form $x_1^{a_1}\cdots x_n^{a_n}f$ with $a_1+\cdots+a_n<\deg g$ and $x_1^{b_1}\cdots x_n^{b_n}g$  with $b_1+\cdots+b_n<\deg f$. These polynomials are linearly dependent if and only if there are some polynomials $p,q$ with $\deg p<\deg f$, $\deg q<\deg g$ and $p/q=f/g$.
*
Sorry, I cannot recommend you books other than I can find by internet search...
:-(