text:
Q: Magento - How can I tell if I'm on a "My Account" page? I'd like to add something to the top of the page on my Magento site, but only if the customer is in the "My Account" section. I'll be adding it to /app/design/frontend/xxxx/xxxx/template/page/html/header.phtml. How can I detect if the customer is in the "My Account" section?
I've found a few ways that don't work, the closest being Mage::app()->getFrontController()->getRequest()->getRouteName(), which doesn't give a rock-solid way of checking if I'm in the "My Account" section.
These pages all have <update handle="customer_account" /> in the XML, is there a way I can get the handle of the current page?

A: The magento way of doing it would be to edit your local.xml file.
There you should use the customer_account_index handle like this:
<customer_account_index>
  <reference name="header">
    <block type="core/template" name="new_customer_data" template="page/html/customer.phtml"/>
  </reference>
</customer_account_index>

Create the page/html/customer.phtml with the data that you want.
And in template/page/html/header.phtml write <?php echo $this->getChildHtml('new_customer_data') ?>
Another way is:
<?php $action = Mage::app()->getFrontController()->getAction();
echo $action->getFullActionName('_');
if($action->getFullActionName('_')=="customer_account_index")
{

}?>

A: Try this :
In layout page
<customer_account_index translate="label">
    <label>Custom Page</label>
        <reference name="header">
        <block type="page/header" name="header">
            <action method="setTemplate"><template>your_custom_header_template_path/yourcustomheader.phtml</template></action>
        </block>
    </reference>
    <!-- Mage_Customer -->
    <update handle="customer_account"/>
</customer_account_index>

Reference links:
http://www.atwix.com/magento/how-to-change-the-header-of-magento-cms-page/
http://istockphp.com/magento/adding-custom-page-to-the-customer-account-dashboard/


text:
Q: What does it mean for a vector field to be perpendicular to a level surface? Assume I have a vector field expressed as:
$F=f(x,y,z)i + g(x,y,z)j +h(x,y,z)k$
Assume I have a level surface (spheres, ellipsoids, hyperboloid...) $S$.
What does it mean for $F$ to be perpendicular to $S$? In other words, what mathematical property must be satisfied?

A: When we say some vector is perpendicular to some curve/surface at $p$, what we really mean is that vector is perpendicular to the tangent space of that curve/surface. In the case of the curve, the tangent space is a line. In the case of a surface, the tangent space is a plane.
In this case it means $F$ is perpendicular to the tangent plane of $S$ (at some point $p$). Which means that $F$ is orthogonal to all tangent vectors to $S$ at $p$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: cvblob compile error in Visual C++ 6.0 I'm using Microsoft Visual C++ 6.0 and Microsoft Visual Studio 2008 to develop an academic computer vision project.
In this project i need to use OpenCV 1.1 (http://opencv.willowgarage.com/) and CvBlob (http://code.google.com/p/cvblob/).
I tried to compile this project with Microsoft Visual Studio 2008 and it compiles without errors.
With Visual C++ 6.0 i got a lot of errors.
OpenCV are not responsible of this behavior, because a trivial project with only OpenCV (without CvBlob) works well.
To understand the errors better I made an empty project with only the CvBlob inclusion.
I paste here a brief summary of the errors:
cvcontour.cpp(253) : error C2371: 'i' : redefinition; different basic types (and others similar to this. i solved with variable redefinition, every time)

cvcontour.cpp(318) : error C2664: 'thiscall std::vector<struct CvPoint,class std::allocator<struct CvPoint> >::std::vector<struct CvPoint,class std::allocator<struct CvPoint> >(unsigned int,const struct CvPoint &,const class std::allocator<struct CvPoint> &)' : cannot convert parameter 1 from 'class std::deque<struct CvPoint,class std::allocator<struct CvPoint> >::iterator' to 'unsigned int' No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

cvtrack.cpp(278) : error C2440: 'initializing' : cannot convert from 'struct cvb::CvTrack *const ' to 'struct cvb::CvBlob *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

Have you ideas on how can i solve these problems?
Thanks in advance for the help!
-------- UPDATE --------
I tried to edit and correct the code in order to elminate the three errors in my question.
The error C2664 seems to be the more difficult to cirmumvent...
I have replaced the indicted line
return new CvContourPolygon(dq.begin(), dq.end());

where CvContourPolygon is a typedef std::vector<CvPoint> CvContourPolygon;
with
deque<int>::iterator dq_it;dq_it = dq.begin();
CvContourPolygon v_tmp;
v_tmp.push_back(*dq_it);
while (dq_it != dq.end()){
  v_tmp.push_back(*dq_it++);
}

First, what that i wrote is correct? Than, how can i solve the errors that occured from this?
Thank you in advance!
Errors (suppose that the first line is 318:
cvcontour.cpp(319) : error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'class std::deque<struct CvPoint,class std::allocator<struct CvPoint> >::iterator' (or
there is no acceptable conversion)
cvcontour.cpp(321) : error C2664: 'push_back' : cannot convert parameter 1 from 'int' to 'const struct CvPoint &'
    Reason: cannot convert from 'int' to 'const struct CvPoint'
    No constructor could take the source type, or constructor overload resolution was ambiguous
cvcontour.cpp(322) : error C2679: binary '!=' : no operator defined which takes a right-hand operand of type 'class std::deque<struct CvPoint,class std::allocator<struct CvPoint> >::iterator' (or there is no acceptable conversion)
cvcontour.cpp(322) : fatal error C1903: unable to recover from previous error(s); stopping compilation

Error executing cl.exe.
-------- UPDATE2 --------
This code seems to work correctly!
deque<CvPoint>::iterator dq_it;
dq_it = dq.begin();
CvContourPolygon v_tmp;
for (dq_it = dq.begin(); dq_it != dq.end(); ++dq_it){
  v_tmp.push_back(*dq_it);
}
//return new CvContourPolygon(dq.begin(), dq.end());
return &v_tmp;

A: C2371 - VC6 was sloppy with scope of local variables. Should be able to fix this by making the code use variable names unambiguously.
C2664 - looks like failure to initialize a vector using deque iterators - wrong overload on vector::vector() being called?  Probably have to work around this by manually copying the deque elements to the new vector somehow.
C2440 - check the objects are compatible (VS2008 seems to think so) and add the appropriate cast.
EDIT:
Shouldn't your code look like this?
deque<CVPoint>::iterator dq_it;dq_it = dq.begin();
CvContourPolygon v_tmp;
for (dq_it = dq.begin(); dq_it != dq.end(); ++dq_it)
{
  v_tmp.push_back(*dq_it);
}


text:
Q: Future continuous vs. future simple I wonder if it's correct to say:

We'll be having a great time.

at the end of this letter.

Shouldn't it be:

We'll have a great time.

A: Both are accepted and mean the same thing, the difference is where they are used.  "We'll be having a great time would be used when trying to convince someone to come with me, for example:

"Come with us (or just me), it will be fun!"

On the contrary, "We'll have a great time" would be used once the recipient of the letter was involved, for example:

We are going to have a great time at the park tomorrow!


text:
Q: Can someone make sure that my understanding of D-caches is accurate? I'm working on a problem (I'm going to change the problem here a bit because I'm more interested in someone checking my knowledge) that goes something along the lines of:
You have three 10x20 two-dimensional arrays A, B, and C. They all hold double precision floating point numbers. There's a D-cache that's 2048 lines long, each of which is 256 bytes long. It's in row-major order.
You then have some code that runs like:
for(i = 0 to 9)
    for(j = 0 to 19)
      C[i][j] = A[i][j] + B[i][j]

A is at address 0x10014000, B is at address 0x10019000 and C is at address 0x1001E000
And the question asks for the read hits and write misses.
now, as far as I understand, double precision floating point numbers are 8 bytes long. Since the line lengths are 256 bytes each, each line of the cache can hold 32 values, correct? And since it's 2048 lines long, the cache can hold 65536 values. Right?
A, B, and C each have 200 elements in them. Does that mean that everything after the first read-ins of A and B all of the readings from the array would be read hits? And there would only be one write miss-- when C isn't first loaded into the D-cache?
Is that accurate, or am I mistaken? That doesn't sound right but I don't know what I'm missing.

A: It is not true. The first "filling" of A and b only fill one cache line, in your example, which is from 0x10014000 to 0x100140ff for matrix A. And when 0x10014100 is needed, cache miss will occur in matrix A again.
What's more

now, as far as I understand, double precision floating point numbers are 8 bytes long. Since the line lengths are 256 bytes each, each line of the cache can hold 32 values, correct? And since it's 2048 lines long, the cache can hold 65536 values. Right?

It is right. But It cannot be concluded that there will be no cache miss if cache capacity is larger that the content, unless the cache is fully associative. That is called "Collision". There are some links about cache associativity:

*

*https://en.wikipedia.org/wiki/CPU_cache#Associativity

*http://csillustrated.berkeley.edu/PDFs/handouts/cache-3-associativity-handout.pdf


text:
Q: Freemarker: null value displayed I have this code:
<input type="text" name="zipCode" maxlength="5" value="${zipCode!}">

When zipCode = null (I use Java), the input field displayes null. Why?
Thanks!

A: @ddekany: you were rignt. zipCode has a String value that equals "null".


text:
Q: How to change element.style to display responsive photos? I have a header image that I would like to change responsively. However is shows in CSS as element.style and overrides any CSS that I add. I read some answers on this forum, however I still do not understand what do I need to do to override this setting. I think that my theme manages this. I have code like this and I want to change background-image:
element.style {

      background-image: url('https://imagelink.com');
      background-size: cover;
      background-repeat: no-repeat;
      background-position: center;
      background-color: rgba(0, 0, 0, 0);
      min-height: 499px;

}

EDIT: My main goal is to background-image responsive for smaller/bigger screens, because my page builder (wpbakery) does not have this option

A: CSS observes some rules to render the style and you need to follow them in order to manage your styles.
In general, CSS will render first rules with !important, then selectors more specific, and then the last processed (if your specificity is the same and without !important the last rule will be rendered).
A good practice is to increase specificity when you want to override something, you can read more about it here.

A: The rules of priorities are the following:

*

*IDs are the most important (#unique-element).

*Classes come next (.multiple-elements).

*Names come then (div).

The more elements you have, the most priority. Example: div span.highlight has a higher priority than h1.main-title (2 elements + 1 class VS 1 element + 1 class).
In case of the same priority, it's the latest defined (the one on the lowest line in your file) that matters as CSS rewrited the rules previously defined.
Exceptions:

*

*Inline code (<div style="...">) overrides everything.

*Adding !important overrides everything even inline code but is considered bad practice because as it's higher than style="", it's also not affected by any changes you could make from JavaScript.

Examples with a bunch of fish


text:
Q: How to Open .001 .002 .003 and .r01 .r02 .r03 RAR Files Is WinRAR the same as Linux rar?  Additional features?  Missing features?  Special way of handling files?

Software is available for Microsoft Windows (named WinRAR), Linux...

-wikipedia
The context is files which are split:

Sometimes you'll download a large file and find that instead of the
  single file you wanted, your folder is full of .001 .002 .003 or .r01
  .r02 .r03 files. These files are part of a split RAR archive. Much
  like a zip file, a RAR file is a compressed version of what you
  downloaded. Rather than transmit in a single file, it's spread out
  over these several files -- usually to speed downloading or to
  accommodate the file size limit of a commercial file storage host.

I'm not asking how to unrar files.  I'm asking:  why are these files named so?  Is this a Windows convention, or also Linux?  Is this just a "split" file?
Not inclined to install WINE solely to install QuickPar.
These specific files are named with this pattern:
foo bar - baz.rar.001

complete with the spacees and hyphens between foo, bar, baz.
Not named .r01, just 001.  If that makes a difference.  (?)

A:
How to Open .001 .002 .003 and .r01 .r02 .r03 RAR Files

rar takes care of this by itself. You unrar the file without the extension and it will scan for all the files it needs to recreate the original file.

Is WinRAR the same as Linux rar?

Winrar is a clone of rar for Windows.

Additional features? Missing features? Special way of handling files?

man rar

to see all features of rar.

I'm asking: why are these files named so?

Because we have media that have a limited storage capacity. If you want to save a 10Gb large movie  on a ...

*

*3.5 inch you'd need 720Kb, 1.44Mb or 2.88Mb large files. You need a lot of disks. 7367...

*cd rom drive you would need files roughly 700Mb. So 14 files to go on 14 CDs.

*a dvd drive you would need files roughly 4.7Gb for a single-layer or 8.5Gb for a dual-layer disk. You'd need 3 or 2 dvds.

Nowadays there is no more need to split files though. And BD drives are pretty common and those started with 25Gb and can go up to roughly 3Tb.
But this all became obsolete due to larger disks and online storage.

Is this just a "split" file?

Yes.

Not named .r01, just 001. If that makes a difference. (?)

It is the same. You can make your own extensions. It is also possible to do .aaa through .zzz as an extension to the filename.

A: A shorter answer that works great.

*

*Go to the rar editor's website and download the single distrib "linux" (a tar.gz file).

2.unzip it with your native system (i had ubuntu),

*then go to that directory and type "./unrar myfile.part1.rar" and that's going to work like a breeze. Thanks to the Editor !!


text:
Q: Unable to get out from crontab command I am using a fresh installation of Ubuntu 16.04 LTS.
Whenever I type:
sudo crontab -e

OR
sudo -u www-data crontab -e

The command prints some number and nothing else.
And whatever you do to try to exit from it, by any means, you are not able to do.
Questions

*

*First of all, How to exit from above command? I am just stuck.

*Why the command is not showing the crontab entries?

*How to make the above command to show crontab entries?

EDITED
I have chosen the editor as vim.basic with:
sudo update-alternatives --config editor

But when I do echo $EDITOR prints empty.
Also,
crontab -e -> works fine
sudo -u www-data crontab -e -> stuck as mentioned above

A:
First of all, How to exit from above command? I am just stuck.

We don't know what editor you are using. Try Esc :q (vim) or Ctrl-x (nano) or Ctrl-x Ctrl-c (emacs) or q (ed).

*

*Run command select-editor and choose an editor you want to use

*Alternative: set environment variable EDITOR or VISUAL to an editor of your liking.
Example: export EDITOR=emacs to use emacs or export EDITOR=nano for nano.

*Then, run crontab -e to edit your crontab

*Use crontab -l to show the content of your crontab

A: I would guess that your default editor is not set and is defaulting to ed.
What do you get if you run:
env | egrep 'EDITOR|VISUAL'

sudo env | egrep 'EDITOR|VISUAL'

sudo -u www-data env | egrep 'EDITOR|VISUAL'

The way to quit from ed is to type: qCR
To set a different editor, you could do:
sudo -u www-data EDITOR=$EDITOR crontab -e

A: I have applied the following commands
# Interactive way
update-alternatives --config editor
# And choose 3 (vim.basic)

# Non Interactive way
sudo update-alternatives --set editor /usr/bin/vim.basic

# Verify as
sudo update-alternatives --query editor

Alternatively, you can add it in ~/.bashrc or ~/.bash_profile file and reload to reflect the changes.
export VISUAL=vim
export EDITOR="$VISUAL"

For crontab for www-data user, I am using as:
sudo crontab -u www-data -e

And this fixed the issue.


text:
Q: Can you rename columns in an R "formattable", without losing previously applied formatting? grateful for any thoughts on a very minor issue I have.
I have created a table using the excellent formattable package in R, in which the column headers use the associated variable name. This is fine for internal work, but isn't how I intend to present them for their final use. To make them more human readable for the final table, I renamed them, but the new names are a little unwieldy, so I save this to the last step. However, any variables I rename lose the previously applied formatting.
The obvious solution is to rename before I carry out any formatting, but as mentioned, the names can be a little verbose for code. Is there a way to rename the columns as a last step, but not lose the previously applied formatting? I've yet to find a solution in the package documentation, but as I'm relatively new to R, it's very possible I have overlooked something very obvious - or that this approach is considered bad practice, so isn't something that would be advised.
I've included a working example below. I'm using R v3.5.2 and formattable version 0.2.0.1 - due to workplace security, I am limited by what packages (and their versions) I can use. Many thanks in advance for any thoughts.
library(tidyverse)
library(formattable)
data("iris")

# A very simple summary of iris data
my_table <- iris %>% group_by(Species) %>%
  summarise(
    mean_sepal_length = mean(Sepal.Length),
    mean_sepal_width = mean(Sepal.Width)
  )

#Create my formattable with some arbitrary formatting
my_formattable <- formattable(
  my_table,
  align = c ("l", "r", "r"),
  list(
    Species = formatter("span", style = ~ style(
      color = "grey", font.weight = "bold"
    )),
    mean_sepal_length = color_bar('lightseagreen'),
    mean_sepal_width = color_bar('pink')
  )
)

my_formattable

# Change a column header to something more human-readable
my_formattable_renamed_cols <-
  my_formattable %>%  rename("Mean sepal length (cm)" = mean_sepal_length)

#Renamed columns lose their formatting
my_formattable_renamed_cols

A: my_table <- iris %>% group_by(Species) %>%
      summarise(
        `Mean sepal length (cm)` = mean(Sepal.Length),
        `Mean sepal width (cm)` = mean(Sepal.Width)
      )

    #Create my formattable with some arbitrary formatting
    my_formattable <- formattable(
      my_table,
      align = c ("l", "r", "r"),
      list(Species = formatter("span", style = ~ style(color = "grey", font.weight = "bold")),
        `Mean sepal length (cm)` = color_bar('lightseagreen'), `Mean sepal width (cm)` = color_bar('pink'))
    )


text:
Q: ASP.NET Core 6 MVC : read xml read outerxml remove tags I am writing an ASP.NET Core 6 MVC app, and I have to read an XML with this format:
<?xml version="1.0" encoding="utf-8" ?>
<taglines common-copyright="©2007 ">
    <tagline brandID="1" brandName="BCBS" >
        <registered registered="®Registered">
        </registered>
        <copyright copyright="©2007">
        </copyright>
        <tagline2 tagline2="Data.">
        </tagline2>
    </tagline>
</taglines>

I need to read the content in tag tagline2
The way I am doing it is
private  string ReadXMLAnthemFile()
{
    string footer = "";

    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Load(String.Concat(this.Environment.WebRootPath,"/img/TagLines.xml"));

    foreach (XmlNode node in xmlDocument.SelectNodes("taglines/tagline/tagline2"))
    {
        footer = node.OuterXml;
    }

    return footer;
}

But node.OuterXml returns the entire tag
<tagline2 tagline2="Data."></tagline2>

How can I get only the data inside the tag?
Thanks

A: You don't need to read the "outer" XML - you need to reach into the XML node you've fetched, and read it's tagline2 attribute - if present.
Try something like this:
foreach (XmlNode node in xmlDocument.SelectNodes("taglines/tagline/tagline2"))
{
    if (node.Attributes["@tagline2"] != null)
    {
        footer = node.Attributes["@tagline2"].Value;
    }
}

That should get you the .Value of the tagline2 attribute of the XML node that your XPath expression matches - the value would be Data. in your case here.


text:
Q: what is the right order to stop/start kafka with zookeeper and schema registry we have 3 kafka brokers in the cluster
kafka version - 1.0.0
each kafka machine include also : zookeper server , schema registry
what is the right order to stop/start the following services:
1. kafka
2  zookeeper
3  schema registry

A: To start the services:

*

*ZooKeeper is a prerequisite for Kafka and Schema Registry so it has
to go first.
(Ideally, you would also want to verify that Leader election took place too with the 4-letter stat command.)

*Kafka is a prerequisite for Schema Registry so it goes 2nd.

*Schema Registry goes last.
To stop them, go in the reverse order.

*

*Schema Registry

*Kafka

*ZooKeeper

References

*

*Using Schema Registry

A: As the accepted answer says, it goes like;

*

*Zookeeper

*Kafka

*Schema Registry

*+Kafka Connect

If you are using Kafka Connect, like me, you should start it after you've started both Zookeeper and Kafka. I don't think the order between Schema Registry and Kafka Connect matters but I do start Kafka Connect last and haven't faced any problem so far.


text:
Q: UI/UX Design in Real Time Applications Lately I've been developing applications with Meteorjs and I notice that most developers/designers don't pass the idea to the user that you don't need to refresh the browser.
In Meteor, it's completely useless to refresh the browser, the data changes are directly pushed to client.
What UI/UX Design practice match this kind of application behaviour?
I thought about adding a refresh button in the UI, in the hope that the user doesn't refresh the browser, but this is bad design, it's not an honest design. With this approach I'm lying to the user.

A: I've been dealing with this lately and there are a few different ways I've handled it, depending on the scenario.
Sometimes it doesn't really matter that much for UX that the user refreshes. Generally, for data that changes often, you can use methods like those described in this link about designing for realtime (provided by larsbuur's answer) to make your user understand that they don't need to refresh. The general idea is to use unobtrusive but visible and clear cues that the data has changed.
If there is not much UI state that can't be recovered from the route, refreshing the browser should work pretty much how the user expects. Generally, you don't want to try to make browser features work in unexpected ways. If you want to persist UI state across refreshes, you can try something like the Meteor package u2622:persistent-session.
You could also remind the user that they don't need to refresh after they do. For example, using the web storage API:
Meteor.startup(function() {
  var reload = !!sessionStorage.getItem('reload');
  var manualReload = reload && !Session.get('hotReload');

  if (manualReload) {
    // Tell the user they don't need to manually reload the browser
  }

  sessionStorage.setItem('reload', true);
  Session.set('hotReload', true);
});

In certain cases, it is more important that the user understands they shouldn't refresh. For example, in online games you often have a pre-match lobby system where game settings can be adjusted, and the lobby leader is the player who has been in the lobby the longest. If the lobby leader refreshes, they will lose their position.
It is possible to make this work by having a reconnect time window where the user can reclaim their position, or the user will lose their spot in the lobby after the timeout. The mizzao:user-status is helpful with this. This is, in my opinion, the most friendly UX option, and you can even display a spinner icon next to the username to indicate to other users that the user may be reconnecting. However, my attempts at implementing this have proven to be a bit buggy and unpredictable when it comes to data integrity/server reliability.
For now, I've chosen to simply use the beforeunload event like StackOverflow does when you are typing. It's not very customizable and not as friendly as transparent reload/reconnect, but sometimes it's the best compromise when you simply want to warn the user why they might not want to refresh right now.


text:
Q: Django: Reverse for 'verify-payment' with arguments '('',)' not found. 1 pattern(s) tried: ['course/u/(?P[^/]+)/$'] i wrote a view to verify payment bbut when i hit the payment button i get this error that say Reverse for 'verify-payment' with arguments '('',)' not found. 1 pattern(s) tried: ['course/u/(?P<ref>[^/]+)/$']
i know it's a url configuation error, i am not passing in the right arguments but i dont know what to pass in, i already tried payment.ref
views.py
@login_required
def course_checkout(request, slug):
    course = Course.objects.get(slug=slug)
    user = request.user
    action = request.GET.get('action')
    order = None
    payment = None
    error = None

    try:
        user_course = UserCourse.objects.get(user=user, course=course)
        error = "Congratulations! You are Already Enrolled In This Course"
    except:
        pass
        amount = None
        if error is None:
            amount = int((course.price - (course.price * course.discount * 0.01)) * 100)
        if amount == 0:
            userCourse = UserCourse(user=user, course=course)
            userCourse.save()
            return redirect('course:course-content', course.slug) # change this to redirect to my courses page with a button to start course because this course is free

        if action == 'create_payment':
            currency = "NGN"
            notes = {
            "email": user.email,
            "name": user.username
            }
            reciept = f"DexxaEd-{int(time())}"
            order = client.order.create(
                {
                'reciept' : reciept,
                'notes' : notes,
                'amount' : amount,
                'currency' : currency,
                'paystack_public_key' : settings.PAYSTACK_PUBLIC_KEY,
                }
            )

            payment = Payment()
            payment.user = user
            payment.course = course
            payment.order_id = order.get('id')
            payment.save()

    context = {
        "course":course,
        "order":order,
        "payment":payment,
        "user":user,
        "error":error,
    }

    return render(request, "course/course-checkout.html", context)

def verify_payment(request: HttpRequest, ref: str) -> HttpResponse:
    payment = get_object_or_404(Payment, ref=ref)
    verified = payment.verify_payment()
    return redirect("userauths:profile")

models.py

class Payment(models.Model):
    order_id = models.CharField(max_length = 50 , null = False)
    payment_id = models.CharField(max_length = 50)
    user_course = models.ForeignKey(UserCourse , null = True , blank = True ,  on_delete=models.CASCADE)
    user = models.ForeignKey(User ,  on_delete=models.CASCADE)
    course = models.ForeignKey(Course , on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now_add=True)
    status = models.BooleanField(default=False)

    email = models.EmailField()
    ref = models.CharField(max_length=200)
    verified = models.BooleanField(default=False)

    def __str__(self):
        return f"Payment: {self.course.price}"

    def save(self ,*args, **kwargs):
        while not self.ref:
            ref = secrets.token_urlsafe(50)
            objects_with_similar_ref = Payment.objects.filter(ref=ref)
            if not objects_with_similar_ref:
                self.ref = ref
            super().save(*args, **kwargs)

    def amount_value(self) -> int:
        return self.course.price * 100

    def verify_payment(self):
        paystack = PayStack()
        status, result = paystack,verify_payment(self.ref, self.course.price)
        if status:
            if result['course.price'] / 100 == self.course.price:
            # if result['amount'] / 100 == self.course.price:
                self.verified = True
            self.save()
        if self.verified:
            return True
        return False

urls.py
    path('u/<str:ref>/', views.verify_payment, name = 'verify-payment'),

course-checkout.html
{{ course.price }}
<button id="django-paystack-button" onclick="payWithPayStack()" class="chck-btn22">Make Payment</button>

<script>
    function payWithPaystack() {
        let currency = "USD";
        let plan = "";
        let ref = "{{payment.ref}}";
        let obj = {
            key: "{{ paystack_public_key }}",
            email: "{{ request.user.email }}",
            amount: "{{course.price_value}}",
            ref: ref,
            callback: function (response) {
                window.location.href = "{% url 'course:verify-payment' payment.ref %}";
            },
        };

        if (Boolean(currency)) {
            obj.currency = currency.toUpperCase();
        }
        if (Boolean(plan)) {
            obj.plan = plan;
        }
        var handler = PaystackPop.setup(obj);
        handler.openIframe();
    }
</script>

A: The issue is not with your url configuration, nor the payment.ref, but with the logic in your course_checkout page.  The issue is that a user can land on the course-checkout.html page even if the payment is None, which is what causes the error, because the url is expecting on non empty <str:ref>.  My expectation, and apologies if this is not what you are after, is that the only time the user should get to the course-checkout page is if (1) the user is not already registered for the course, or (2) the course is free.  Otherwise, the user should be taken to the course-checkout page (no need to check for if action == 'create_payment':, since if (1) or (2) are false, this is the only other option, as I see it).  I haven't tested the code below, but I think this might be the way to do it:
def course_checkout(request, slug):
    course = Course.objects.get(slug=slug)
    user = request.user
    action = request.GET.get('action')
    order = None
    payment = None
    error = None

    try:
        user_course = UserCourse.objects.get(user=user, course=course)
    except:
        pass

    # User is already registered for course, so go to the course page
    if user_course:
        return redirect('course:course-content', course.slug)

    amount = int((course.price - (course.price * course.discount * 0.01)) * 100)

    # Redirect to my courses page with a button to start course because this course is free
    if amount == 0:
        userCourse = UserCourse(user=user, course=course)
        userCourse.save()
        return redirect('course:course-content', course.slug)

    # User is not registered for the course, and the amount is NOT 0, so send
    # to the checkout page
    currency = "NGN"
    notes = {
        "email": user.email,
        "name": user.username
    }
    reciept = f"DexxaEd-{int(time())}"
    order = client.order.create(
        {
            'reciept' : reciept,
            'notes' : notes,
            'amount' : amount,
            'currency' : currency,
            'paystack_public_key' : settings.PAYSTACK_PUBLIC_KEY,
        }
    )

    payment = Payment()
    payment.user = user
    payment.course = course
    payment.order_id = order.get('id')
    payment.save()

    context = {
        "course":course,
        "order":order,
        "payment":payment,
        "user":user,
        "error":error,
    }

    return render(request, "course/course-checkout.html", context)


text:
Q: Alternative to the `c()` function that works with pipes in R? A workaround to use c() with the pipe operator is to add curly brackets
library(dplyr)

mtcars %>% {
  c(.$mpg, .$cyl)
}

But it's not pretty.
Is there alternative to the c function that works with pipes in R?
library(dplyr)

mtcars %>%
  alternative_c(.$mpg, .$cyl) # Does such a function exist?

A: Using the magrittr exposition pipe %$% you could do:
library(magrittr)

mtcars %$% c(mpg, cyl)
#>  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
#> [16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
#> [31] 15.0 21.4  6.0  6.0  4.0  6.0  8.0  6.0  8.0  4.0  4.0  6.0  6.0  8.0  8.0
#> [46]  8.0  8.0  8.0  8.0  4.0  4.0  4.0  4.0  8.0  8.0  8.0  8.0  4.0  4.0  4.0
#> [61]  8.0  6.0  8.0  4.0

A: An alternative is to pipe into with():
mtcars %>%
   with(c(mpg, cyl))

 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2
[24] 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4  6.0  6.0  4.0  6.0  8.0  6.0  8.0  4.0  4.0  6.0  6.0  8.0  8.0  8.0
[47]  8.0  8.0  8.0  4.0  4.0  4.0  4.0  8.0  8.0  8.0  8.0  4.0  4.0  4.0  8.0  6.0  8.0  4.0

A: A solution with an anonymous function
mtcars %>%
  (\(.) c(.$mpg, .$cyl))

 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3
[25] 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4  6.0  6.0  4.0  6.0  8.0  6.0  8.0  4.0  4.0  6.0  6.0  8.0  8.0  8.0  8.0  8.0
[49]  8.0  4.0  4.0  4.0  4.0  8.0  8.0  8.0  8.0  4.0  4.0  4.0  8.0  6.0  8.0  4.0


text:
Q: form_widget with dynamic form name In my Twig template I have a FOR LOOP that creates a multiple number of forms like so:
{% for thing in things %}

{% set form_id = 'myform_' ~ thing.Id %}

{% set form_name = attribute(form, 'myform_' ~ thing.Id) %}

 {{ form_widget(form_id) }}
 {{ form_widget(form_name) }}

{% endfor %}

I would like this to generate the following:
   {{ form_widget(myform_1) }}

   {{ form_widget(myform_2) }}

.... and so on.
I left my 2 failed attempts in there, (form_id and form_name), to save anyone from suggesting those as possible solutions.
To summarize; I need to insert the dynamically created value (myform_1, myform_2) inside of  {{ form_widget()  }}

A: You can render dynamic fields form with dynamic name in Twig with special function of Twig :
{{ attribute(object, method) }}
{{ attribute(object, method, arguments) }}
{{ attribute(array, item) }}

With this function you can easily generate dynamic string name for your field dynamic into your form like this
{{ form_widget(attribute(form, 'myfielddynamicname' ~ var ~ ' lastchar')) }}

With this variable "var" (array or others type) you can render lot of dynamic form name like :

*

*myfielddynamicnamefoolastchar

*myfielddynamicnamebarlastchar

*myfielddynamicnameneolastchar

For more understanding you can read this official twig documentation function
here : attribute twig function documentation

A: The things myform_1 and myform_2 simply are variables with FormView object as you define in your controller.
I don't know if Twig allows on dynamic variables call, although you can collect these form objects in array in controller before passing to view. After this step, you can just iterate thought this array It will manage the problem you are facing with.

A: Don't create a loop in your Twig: the layout should only render a single form. Then you can build the forms in your controller and render each one of them.
See this documentation on the Symfony book on how to get the result of a rendered template. You can concatenate the single render results and return a response with the full content.


text:
Q: Centering a div within a responsive div Basically I have 3 floating elements, they are next to each other and are scaled down when you resize the browser window.
Now under a certain width (@media (max-width: 800px)) the elements get a fixed width and a clear:both so that they are below eachother and no longer scale.
What I'm trying to do now is centering those 3 divs inside their parent.
margin:0 auto is not helping
Above 800pixel width:

Below 800pixel width:

--> Div should be centered inside the yellow one
Code I have for the media query:
@media (max-width: 800px){
.data .data_column{width:215px;background-color:red;clear:both; margin: 0 auto;}
.data{width:90%;background-color:yellow;}

}

A: Replacing your clear:both with a float: none should be enough to let margin: auto do the work.

A: Try following:

And CSS:
.data {
    position: relative;
    width:90%;
    height: 250px;
    background-color:yellow;
}

.data-column {
    clear:both;
    position: absolute;
    height: 150px;
    width: 215px;

    /* horizontal centering */
    right: 0;
    margin-right: auto;

    left: 0;
    margin-left: auto;

    /* vertically centering */
    top: 0;
    margin-top: auto;

    bottom: 0;
    margin-bottom: auto;

    background-color: red;
}

Here is a FIDDLE


text:
Q: Faster anova of regression models I have the following toy data -
data<-data.frame(y=rnorm(1000),x1=rnorm(1000), x2=rnorm(1000), x3=rnorm(1000), x4=rnorm(1000))

On this data, I am creating two models as below -
fit1 = lm(y ~ x1 + x3, data)
fit2 = lm(y ~ x2 + x3 + x4, data)

Finally, I am comparing these models using anova
anova(fit1, fit2)

Since I am running these tests on ~1 million separate datasets, I want to improve the performance and don't want to use lm and anova functions.
To speed up computation, I am using RcppArmadillo::fastLM, instead of lm but there is no available anova function to compare models. Is there a faster function (compared to lm), which also has a corresponding anova function?
Any suggestions to improve performance will be appreciated.
Here are the performance results of various lm versions used below. For linear regression fastLM is an obvious winner. Function anova2 by @Jay is much faster than anova function and works on fastLM. Function f by @Donald is also faster than anova function and works on fastLM.
microbenchmark::microbenchmark(
  base_lm_1 = fit1 <- lm(y ~ x1 + x3, data),
  base_lm_2 = fit2 <-lm(y ~ x2 + x3 + x4, data),
  lm.fit_1 = lm.fit1 <- with(data, .lm.fit(y = y, x = cbind(1, x1, x3))),
  lm.fit_2 = lm.fit2 <- with(data, .lm.fit(y = y, x = cbind(1, x2, x3, x4))),
  lm.fit_3 = lm.fit3 <- lm_fun(y ~ x1 + x3, data),
  lm.fit_4 = lm.fit4 <- lm_fun(y ~ x2 + x3 + x4, data),
  fastLm1 = fastLM1 <- with(data, RcppArmadillo::fastLm(y = y, X = cbind(1, x1, x3))),
  fastLm2 = fastLM2 <- with(data, RcppArmadillo::fastLm(y = y, X = cbind(1, x2, x3, x4))),
  anova_base = anova(fit1, fit2),
  Jay_fastLM = anova2(fastLM1, fastLM1),
  Jay_lm.fit = anova2(lm.fit3, lm.fit4),
  Donald = f(fastLM1, fastLM1),
  times = 100L,
  control=list(warmup=100L)
)
Unit: microseconds
       expr      min        lq      mean    median        uq       max neval    cld
  base_lm_1 1472.480 1499.2560 1817.2659 1532.3840 1582.2615 28370.870   100     e
  base_lm_2 1657.745 1706.5505 1796.3631 1744.3945 1825.7435  4761.020   100     e
   lm.fit_1   94.212  106.9020  112.3093  111.2235  116.7010   147.192   100 a
   lm.fit_2  124.220  129.8080  134.4455  132.9830  138.2510   156.166   100 a
   lm.fit_3  853.906  873.9035  902.5856  889.9715  917.9375  1028.415   100   cd
   lm.fit_4  991.238 1006.7015 1213.7061 1021.5325 1045.8980 19379.399   100    d
    fastLm1  368.289  390.7805  434.1467  422.0855  476.9085   584.761   100 a c
    fastLm2  416.645  441.8660  481.0027  462.8850  514.0755   617.619   100 a c
 anova_base 2021.982 2099.8755 2322.2707 2190.3340 2246.7800 15345.093   100      f
 Jay_fastLM  202.026  218.2580  229.6244  226.3405  238.9490   303.964   100 ab
 Jay_lm.fit  200.028  216.0805  234.0143  229.7580  246.1870   292.268   100 ab
     Donald  549.425  582.8105  612.6990  605.4400  625.5340  1079.989   100  bc

A: We could hack stats:::anova.lmlist so that it works for lists produced by .lm.fit (notice the dot) and RcppArmadillo::fastLm. Please check stats:::anova.lmlist, if I didn't delete stuff you need!
anova2 <- function(object, ...) {
  objects <- list(object, ...)
  ns <- vapply(objects, function(x) length(x$residuals), 0L)
  stopifnot(!any(ns != ns[1L]))
  resdf <- vapply(objects, df.residual, 0L)
  resdev <- vapply(objects, function(x) crossprod(residuals(x)), 0)
  bigmodel <- order(resdf)[1L]
  dfs <- c(NA, -diff(resdf))[bigmodel]
  ssq <- c(NA, -diff(resdev))[bigmodel]
  df.scale <- resdf[bigmodel]
  scale <- resdev[bigmodel]/resdf[bigmodel]
  fstat <- (ssq/dfs)/scale
  p <- pf(fstat, abs(dfs), df.scale, lower.tail=FALSE)
  return(c(F=fstat, p=p))
}

These wrappers make .lm.fit and RcppArmadillo::fastLm a little more convenient:
lm_fun <- function(fo, dat) {
  X <- model.matrix(fo, dat)
  fit <- .lm.fit(X, dat[[all.vars(fo)[1]]])
  fit$df.residual <- dim(X)[1] - dim(X)[2]
  return(fit)
}

fastLm_fun <- function(fo, dat) {
  fit <- RcppArmadillo::fastLm(model.matrix(fo, dat), dat[[all.vars(fo)[1]]])
  return(fit)
}

Use it
fit1 <- lm_fun(y ~ x1 + x3, data)
fit2 <- lm_fun(y ~ x2 + x3 + x4, data)
anova2(fit1, fit2)
#         F         p
# 0.3609728 0.5481032

## Or use `fastLm_fun` here, but it's slower.

Compare
anova(lm(y ~ x1 + x3, data), lm(y ~ x2 + x3 + x4, data))
# Analysis of Variance Table
#
# Model 1: y ~ x1 + x3
# Model 2: y ~ x2 + x3 + x4
#   Res.Df    RSS Df Sum of Sq     F Pr(>F)
# 1    997 1003.7
# 2    996 1003.4  1   0.36365 0.361 0.5481

lm_fun (which outperforms fastLm_fun) combined with anova2 appears to be around 60% faster than the conventional approach:
microbenchmark::microbenchmark(
  conventional={
    fit1 <- lm(y ~ x1 + x3, data)
    fit2 <- lm(y ~ x2 + x3 + x4, data)
    anova(fit1, fit2)
  },
  anova2={  ## using `.lm.fit`
    fit1 <- lm_fun(y ~ x1 + x3, data)
    fit2 <- lm_fun(y ~ x2 + x3 + x4, data)
    anova2(fit1, fit2)
  },
  anova2_Fast={  ## using `RcppArmadillo::fastLm`
    fit1 <- fastLm_fun(y ~ x1 + x3, data)
    fit2 <- fastLm_fun(y ~ x2 + x3 + x4, data)
    anova2(fit1, fit2)
  },
  anova_Donald={
    fit1 <- lm_fun(y ~ x1 + x3, data)
    fit2 <- lm_fun(y ~ x2 + x3 + x4, data)
    anova_Donald(fit1, fit2)
  },
  times=1000L,
  control=list(warmup=100L)
)
# Unit: milliseconds
#         expr      min       lq     mean   median       uq      max neval  cld
# conventional 2.885718 2.967053 3.205947 3.018668 3.090954 40.15720  1000    d
#       anova2 1.180683 1.218121 1.285131 1.233335 1.267833 23.81955  1000 a
#  anova2_Fast 1.961897 2.012756 2.179458 2.037854 2.087893 26.65279  1000   c
# anova_Donald 1.368699 1.409198 1.561751 1.430562 1.472148 33.12247  1000  b

Data:
set.seed(42)
data <- data.frame(y=rnorm(1000), x1=rnorm(1000), x2=rnorm(1000), x3=rnorm(1000),
                   x4=rnorm(1000))


text:
Q: find difference in months between two date having formats dd.MM.yyyy HH:mm:ss in JQuery Hi i have two dates in UI: To and From, in format dd.MM.YYYY HH:mm:ss
I need to find the difference between the two dates in months.
I tried the following to get month and year of the date but does not work:
var To = $("#startDate").val();
alert(To.getMonth() + To.getFullYear());

It gives NANANA as alert.
P.S it works pretty fine for format YYYY-MM-dd HH:mm:ss but not for the above format

A: Duplicate here: https://stackoverflow.com/a/34904248/4342197
But save your values like this.
var date = new Date();

var date1 = new Date("#startDate").val());
var date2 = d.getDate();

A:

var To = moment($("#startDate").val(), "dd.MM.YYYY HH:mm:ss");
var From = moment($('#endDate').val(), "dd.MM.YYYY HH:mm:ss");
$('#MonthDiff').text(moment.duration(From.diff(To)).asMonths());
$('#YearDiff').text(moment.duration(From.diff(To)).asYears());

<input type="text" value="01.07.2016 07:00:03" id="startDate" />
<input type="text" value="30.07.2017 13:43:46" id="endDate" />

Month Difference:

Year Difference:


text:
Q: Trying to obtain a voltage gain equal to 3 without an op-amp I'm a beginner in electronics and currently, I am trying to design a Wien bridge oscillator. I've read documents about oscillators. For now I am stuck at trying to design the amplifier, without using op-amps. I'm trying to obtain a voltage gain equal to 3, to respect the Barkhausen condition.
Can you give me some ideas or advice about what I'm doing wrong? The Wien Bridge is disconnected so that I can verify the gain of the amplifier.

A: A darlington bipolar, to have high input resistance so your Wein circuit remains on frequency, with 1Kohm in  the emitter and 3K ohm in the collector, will provide approximately 3X gain.
Then follow that with an emitter follower to handle some loads.
You will need to "adjust the gain", likely in real time with an Automatic Level Control.

A: You have your amplifier inputs the wrong way around.
This design below uses a conventional voltage amplifier stage (Q6 & Q11) with its current source load (Q9).
I've also added an output stage to drive a load.
R13 & R14 linearise the J-fet.


text:
Q: Read multiple strings input using fgets() I need to

*

*Take a command line argument giving number of strings (say N).

*Call a function to take N input lines from user (using fgets)

*Store them in an array of pointers.
i.e. char *input_lines[MAX_LINES];

*All newlines from the lines should be removed

How can I achieve this?


text:
Q: Custom Listview with multiple lines per row Basically, I need some rows to be 3 lines and others for the text to be centered on the middle line.  I already have the 3 lines working.  I just need to figure out how to check if the lines R.id.text2 and R.id.text3 are empty and set TAG_1 to be displayed on R.id.text2.  I'm posting what I think it relevent.  If more code is needed just let me know
ListAdapter simpleAdapter = new SimpleAdapter(this, makeList,
        R.layout.custom_list_view,
        new String[] { TAG_1, TAG_2, TAG_3 }, new int[] { R.id.text1, R.id.text2, R.id.text3 });
  listView.setAdapter(simpleAdapter);

custom_list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView android:id="@+id/text1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:textSize="19sp"/>
<TextView android:id="@+id/text2"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"/>
<TextView android:id="@+id/text3"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"/>
</LinearLayout>

A: SimpleAdapter is pretty useless for displaying anything but the most basic list. You will have much more success extending your own adapter. Start with an ArrayAdapter.
The basic concept is that you extend the adapter and implement its getView() function. In this you inflate (or reuse) a view for each row and populate it with your data.
There are many adapter tutorials on the internet, I found this one with a quick search.
Understanding how to utilize adapters is a fundamental part of android development.


text:
Q: Best DB practices for counts / sums etc I'm wondering what the best practices are in terms of storing counts / sums etc are? Is calculating on the fly on each page load a big no no?
I have a Rails App that contains products and sales reports from multiple sources. Some of these sales reports can stretch to 100k+ lines per day. At the moment, we're calculating on the fly for each page load. This is clearly extremely slow.
As the sales reports are almost certainly written once but read many times, would it be better to add a sum column to my product table and increment that each time new sales are written? I can see how this would be clearly a lot faster, but it does seriously limit my ability to offer date filtering; 'Top 10 in last 7 days' etc.
Would another solution that would enable filtering be to create a third table with daily sums for each product? The main sales table can contain multiple, sometimes thousands of lines for each product each day so again I can see how a condensed version of the main sales table could speed things up as well.
Should I be doing these calculations with before/after_save callbacks / during my import or should should I look at scheduled tasks to run in the background?
Can anyone offer some suggestions or recommended reading to help set me on the right path and help me towards improving my embarrassingly slow page load times?
Thanks in advance!

A: Great questions.
Generally I think it is good to start with generating the counts and sums on the fly.  This follows Codd's rules, etc.  The problem is that this may get slow over time.  How you deal with it will depend on quite a number of things.  I will give you my solutions for dealing with sales data and why I see this as ideal.
Sales data is significant because while it can be adjusted sometimes for brief periods of time after a while it will never be adjusted any more absent foul play (this is after books are closed).  Sales books are often closed either monthly or yearly.
what you can do is put the aggregates in a closing entry with the date, or max id or the like, and put in triggers so that you can ensure that no entries get added to a closed period.  this allows you to roll forward your aggregates from a known good value.  In this case you are likely to aggregate only over periods between closings or over open periods.


text:
Q: Why does pulling sometimes make me create a commit? I'm working with someone on the same branch.
I'm pulling each time after I've made changes to my working directory before I add or commit or push and only sometimes I get the below message. When does it do this and why?

Please enter a commit message to explain why this merge is necessary,
   especially if it merges an updated upstream into a topic branch.
Lines starting with '#' will be ignored, and an empty message aborts
   the commit.

A: Simple answer: git pull is, essentially, a combination of git fetch and then a git merge.
As any merge, if Git finds out fast-forwarding is not possible, a traditional merge is necessary (one more commit with two parents), therefore this process asks for a commit message.
Reference: Git docs for branching and merging

A: Please use git pull --rebase.

A: Well, as usually with git, that behaviour depends on a couple of things, in this case you are seeing that message because you got some conflicts between your colleague code and yours and it tries to make a merge commit, instead of doing a fast-forward merge.
Lets clear up the previous phrase, and for that we must start from the beginning:
When you are pulling, what you really are doing are two operations in one:

*

*get the remote data to your local machine (git fetch)

*"join" the data you just retrieved to your local branch (git merge origin/master)

To "join"  the code you have two possible operations: merge or rebase
When doing a merge, git creates a new special commit. It contains two parents, one for your last local commit and another for the last code of the merged branch. That's why you see a bifurcation in the history line when you create a merge, if you use a GUI client or git log --graph
No matter how special it is, it is still a commit, and this it requires a message for it. This is the case you are describing.
However there is another operation you can do to bring the remote data to your local machine: rebase. In that case you'll get the remote data, and then your local commits (the ones that are not yet in the remote location) will be applied in the same order on top of the last commit your fetched. In that case you are not really creating a merge commit, so no message is needed, because the history will be kept linear.
Well, here's the trick: git pull can actually do a rebase if the operation can be completed without any conflict. That's called a fast-forward pull.
You can configure git to use whatever default you want (rebase or merge) or supply the parameters when doing the merge:
git pull --ff, pulls the data and tries to rebase. This operation will abort if there are conflicts
git pull --no-ffalways create a merge, even if there are no conflicts
Here's an SO answer on how to configure git to use fast-forward by default
But take into consideration that even if you have ff by default, the pull operation will fallback to a normal merge if there are conflicts. If you want to force the pull to make a rebase you'll need to do
git pull --rebase
But note that doing this won't make the conflicts disappear, you'll need to fix them anyway ;)

A: Git most likely wants you to provide a message for the merge. When the origin has changed from your copy, Git will try and merge it. It wants to provide a commit message, because the act of merging is a commit in of itself.

A: One simple rule is: As soon as you commit a change to your local repo, if someone else has pushed his/her commit to the origin since you last pulled, you'll be forced to pull (fetch/merge) which will require a merge message before pushing your own changes.


text:
Q: how to use JSON data Coming from PHP file in Angular2? export class LoginComponent
{
     getdata : string;
      public data;
      username : any ;
       password : any ;

    constructor(private http: Http){}

    login() {
     var headers= new Headers({'Content-Type' : 'application/x-www-form-urlencoded '});
    var body = JSON.stringify({
       user : this.username,
       pwd : this.password,
 })
  this.http.post('.../pos_system/Widgets/Login.php',body, {
  headers:headers; })
   .map(res => res.json())
   .map(res => {
         if(res.success)
         {
            this.msg="Login Complete";
         }
         else{
             this.msg1="username and password is wrong";
         }
    })
      .subscribe(
        data =>this.getdata = JSON.stringify(data),
        err => console.error(err),
        () => console.log('done'));
    }
}

This is my Angular2 part here i m getting JSON data from php file in res.Now I want to use this response in my angualr2 part.I want to use display username of the user which is in json data.so how to do that in angular2?

A: it's simple just make this change,
for Example
this.msg=res.username;
this will display username in message.
note: you need to do this in php file.
$data=array();

    $df=json_decode(file_get_contents("php://input"));
    $nam=$df->user;
    $pws=$df->pwd;

    $select=mysql_query("SELECT * FROM userData WHERE username='$nam' AND password='$pws'")or mysql_error();

    $sql=mysql_num_rows($select);
    if($sql>0)
    {
        while($row=mysql_fetch_array($select))
        {
            $data['success']=true;
            $user=$row['username'];
            $data['username']=$user;

        }
    }
    echo json_encode($data);


text:
Q: get table column value of selected row in table asp.net in jQuery I am working on asp.net mvc project.
I want to get the cell value from the selected row (row in which "Manage "button is clicked).
in this case value of userID.

        User ID
        User Name
        View

    @foreach (var item in Model.TypeList)
    {

                @Html.DisplayFor(modelItem => item.UserId)

                @Html.DisplayFor(modelItem => item.UserName)

                <input id="Manage2" class="btn btn-primary" type="button" value="Manage" />

    }

I am calling jQuery click function and Ajax call and want to send the UserId value in data from selected row to the controller.
below is the jQuery ajax call,

Below is the view screen shot,

A: You can actually store the UserId value with html 5 data attribute on the button itself.
Your current code has Id attribute value hard coded inside a loop, which will create more than one element with same Id value. That is invalid HTML!
Remove the Id and use a more generic selector to wire up the click event. Here I added another CSS class "manage" to the button.
<input data-userid="@item.UserId" class="btn btn-primary manage"
                                  type="button" value="Manage" />

and now
$(document).ready(function () {
      $('.manage').click(function () {
         var id = $(this).data("userid");
         alert(id);
         // use id for your ajax call
      });
});

You do not necessarily need to add the extra css class only to use that as the selector later. Since you are adding a data attribute, you may simply use that as well for your jQuery selector.
$(function () {

    $('[data-userid]').click(function () {
        var id = $(this).data("userid");
        alert(id);
        // use id
    });

});

A: You have invalid html because of the duplicate id attributes in your button.
Remove the id="Manage2" and replace with a class name and data- attribute for the value
<input data-id="@item.UserId" class="btn btn-primary Manage2" type="button" value="Manage" />

Then in the script, get the value using
$('.Manage2').click(function () { // class selector
   var id = $(this).data('id);
   var url = '@Url.Action("ManageUserRole", "UserRoleCompany")';
   $.ajax({
      url: url,
      data: { Id: id },
      ....

Alternatively you could use relative selectors
$('.Manage2').click(function () {
    var id = $(this).closest('tr').children('td:first').text();
    ....


text:
Q: How to cancel submit in IE8? I've been struggling to make this work for quite some time. I have the following code:
$(document).ready(function (event) {
    $('form').submit(function (event) {
    ...
    });
});

I've found in most of the places, including on the jQuery site, that this will prevent the form from being submitted:
return false;

It doesn't.
Next I've read all related question and answers on this site and tried them all out.
In Chrome and Firefox this works:
event.preventDefault();

In IE8 it doesn't. I've read that IE doesn't support this and we should use this:
event.returnValue = false;

Although several people confirm that it worked for them (e.g. event.preventDefault() function not working in IE. Any help?), it doesn't for me. I'm not sure why though. I have a form with a submit button, nothing special, but, even if I put only this piece of code, the form is still submitted:
$(document).ready(function (event) {
    $('form').submit(function (event) {
        event.returnValue = false;
    });
});

Any ideas?
One last thing: I've read that we should test this first before calling preventDefault():
if (event.preventDefault) { event.preventDefault(); }

But in IE8, event.preventDefault exists and no error is thrown. How can that be if it's unsupported by IE?
Update 1: I've tried a simplified version with the following code:
CancelSubmitTest.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CancelSubmitTest.aspx.cs" Inherits="HtmlEditor.CancelSubmitTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="Scripts/CancelSubmit.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="SaveButton" runat="server"
            Text="Save" OnClick="SaveButtonClick" CausesValidation="true" ValidationGroup="SomeValidationGroup" />
    </div>
    </form>
</body>
</html>

CancelSubmitTest.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace HtmlEditor
{
    public partial class CancelSubmitTest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void SaveButtonClick(object sender, EventArgs e)
        {

        }
    }
}

CancelSubmit.js
$(document).ready(function (event) {
    $('form').submit(function (event) {
        event.returnValue = false;
    });
});

It's a pretty straight-forward example. The JavaScript code is executed but the form is still submitted, although I set event.returnValue to false. What am I doing wrong?
Update 2: I've changed the javascript code in the simplified project as follows:
$(document).ready(function (event) {
    $('form').submit(function (event) {
        return false;
    });
});

It works in IE but I still have to figure out why it doesn't work in my application. Thanks to everyone for your help.

A: *

*It does work: http://jsfiddle.net/AEC2U/

*The problem is somewhere else in your code.

*Post more code/stripped down example where it doesn't work.

A: return false is equal to event.returnValue
But sometimes this does not work because of DOM compatibility
For Example:
// Not Working
OnClientClick="return confirm('Are you sure want to Delete this file?');"

// Working
OnClientClick="event.returnValue=confirm('Are you sure want to Delete this file?');"

A: $(document).ready(function () {
    $('form').submit(function () {
        alert( 'test' )
        return false;
    });
});

This works for me no problem in IE8.  If anything all I did was get rid of the two passed event variables


text:
Q: grep command is not giving intended result I have set of words in text file and i want to search for these words in another set of files and write the results into an output file
Eg.
Input file contains data as below
KFIS000025-02555593
KFIS000025-02556443
KFIS000025-02555082

The files in which I need this to be searched is as below
PFZ_EDI850_JKC_MLC_ORDER_20170413155724.TXT
PFZ_EDI850_JKC_MLC_ORDER_20170414090413.TXT
PFZ_EDI850_JKC_MLC_ORDER_20170414162518.TXT

I am using the below grep command but it is giving me 0 results, However, when I check few manually the input data is present in this files.
grep –wFf val.txt -o *JKC* > results.txt

Can you tell me what's wrong here?


text:
Q: Managed package not able to dynamically instantiate orgs default namespace class I would have thought, given the other questions on the same subject that I would be able to solve this fairly easily, but it does not seem to be the case. I have tried solutions from both the following questions without success -
Managed package cannot see a class from another managed package
A class in one namespace dynamically instantiating an object outside its namespace
I have a managed package which has a helper class called ObjectHelper which is able to instantiate classes given their string name. This package has been installed in another Dev Org. I am trying to call ObjectHelper to instantiate a class created in the Dev Org. Here is the code which tries to instantiate the class (based on one of the answers in the above questions) -
String className = config.Class_Name__c;

Integer index = className.indexOf('.');
if (index != -1) {
    t = Type.forName(className.substring(index), className.substring(index + 1, className.length()));
} else {
    t = Type.forName(null, className);
}

I have also tried the following -
String className = config.Class_Name__c;

t = Type.forName(className);

if (t == null)
    t = Type.forName('', className);

Nothing is working. I have tried to instantiate the class in anonymous code on the Dev Org using the following and it works fine -
String className = config.Class_Name__c
System.debug('TYPE - ' + Type.forName(null, className));

A: I finally figured it out. The class being instantiated needed to have itself and its constructors be global. They were originally set to public. Once the scope was changed the installed package found the type and was able to construct it as necessary using the following code as mentioned above -
String className = config.Class_Name__c;

Integer index = className.indexOf('.');
if (index != -1) {
    t = Type.forName(className.substring(index), className.substring(index + 1, className.length()));
} else {
    t = Type.forName(null, className);
}


text:
Q: Comparing Multiple Tables There is a horrible legacy tool at my workplace that has been updated/patched to output information to an SQLite database. No one wants to touch the back end of the system, and I don't know enough to dig into it - not my problem. Here is my problem however:
I have an SQLite database, with a number of tables in it. Each table represents a day and contains all of the bus runs, listed such as such:
| Direction |   Time   | RunNumber | StopIndex |
 ----------------------------------------------
|    In     |   6:30   |     1     |     1     |
|    In     |   6:35   |     1     |     2     |
|    In     |   6:40   |     1     |     3     |
|    In     |   6:45   |     1     |     4     |
|    In     |   7:30   |     2     |     1     |
|    In     |   7:35   |     2     |     2     |
|    In     |   7:40   |     2     |     3     |
|    In     |   7:45   |     2     |     4     |
|    Out    |   6:40   |     1     |     1     |
|    Out    |   6:45   |     1     |     2     |
|    Out    |   6:50   |     1     |     3     |
|    Out    |   6:55   |     1     |     4     |

Some days can have more run's than others. The numbers of stops will be the same across all tables.
The definition of equal is that both direction and time are the same. Each run is treated as a set - if one of the times for a stop differs, then the entire run needs to be merged into a table.
My question is:
What would be the easiest way, given a list of tables, to generate another table that contains values that were not present on all the given tables? This can be done on the SQLite side, or by C# .NET 4.0.
In reality, I only need to know the run number that differs, so I can later extract it and put it into an Excel Spreadsheet, if that makes it any easier.

A: Try using EXCEPT. For example, the following query will list all rows that exist in Table1 but do not exist in Table2:
SELECT Direction, Time, RunNumber, StopIndex
FROM Table1
EXCEPT
SELECT Direction, Time, RunNumber, StopIndex
FROM Table2


text:
Q: AI(artificial intelligence) Consider the following problem:
The start state in a state space is being marked with the ID=1. Each other state x, will have two successors that are marked with IDs: 2x+1 and 2x. Show the part of this state space for states 1-20.

A: The problem can be solved with a C++ program which generates a graphviz script.
// g++ generator.cpp
// ./a.out
// dot -Tpng graph.dot > output.png
#include <iostream>
#include <fstream>
int main()
{
  std::ofstream myfile;
  myfile.open ("graph.dot");
  myfile << "digraph statespace \{ \n";
  for (int i=1;i<10;i++) {
    myfile << "  "<< i << " -> " << i*2 << "\n";
    myfile << "  "<< i << " -> " << i*2+1 << "\n";
  }
  myfile << "} \n\n";
  myfile.close();
  return 0;
}


text:
Q: error -->The pipe 'filter' could not be found while using angular4 I am doing unit-testing in angular4 -node.js deployed project.And while testing i found this error -
Template parse errors:
The pipe 'filter' could not be found ("
  </thead>
  <tbody>
    <tr *ngFor="let[ERROR ->] dat of result | filter:filterdata|
paginate: { itemsPerPage: 5, currentPage: p };let i = index ">

so i added these two modules to my module.ts and spec.ts files -->
import { PipesModule } from '../../pipes/pipes.module';
import { Pipe, PipeTransform } from '@angular/core';

@NgModule({
 imports: [PipesModule
 ],

And for this particular module import -->
import { PipesModule } from '../../pipes/pipes.module';

Error -->Cannot find module '../../pipes/pipes.module'.
Please help resolve the issue

A: You must include FilterPipe in the declarations and exports of your PipesModule.

A: Angular 7/8 - nested routes
If you're using some nested routes and you're using the filter in child components, remove the filter from app.modules.ts and :
For custom filter
Import the filter in the declaration section of your child childmodule.module.ts
For ng2-search-filter
Import Ng2SearchPipeModule in the import section of your child childmodule.module.ts

A: Hello Here is the sample example you can check it.

App.module.ts

import { NgModule, Component, Injectable  } from '@angular/core';
import { LimitToPipe } from './pipes/limit-to.pipe'; // your pipe path

@NgModule({
 declarations: [
   LimitToPipe
 ]
});

Create limit-to.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';

    @Pipe({
      name: 'limitTo'
    })
    export class LimitToPipe implements PipeTransform {

    transform(value: string, args: string): string {
        const limit = args ? parseInt(args, 10) : 10;
        const trail = '...';
        return value.length > limit ? value.substring(0, limit) + trail : value;
      }
    }

import in your component

 import { LimitToPipe } from '../pipes/limit-to.pipe';

in your html

{{ name | limitTo :60 : 0 }}

Unit Test (limit-to.pipe.spec.ts)

    import { LimitToPipe } from './limit-to.pipe'; // your custom pipe path

    describe('Pipe: LimitTo', () => {
      let pipe: LimitToPipe;

      beforeEach(() => {
        pipe = new LimitToPipe();
      });

      it('show 3 dot when string length is grater ther 15 chartacter', () => {
        expect(pipe.transform('my name is vikram sharma', '15')).toBe('my name is vikr...');
      });

      it('show full string when string length is less then 15 character', () => {
        expect(pipe.transform('my name is vikram sharma', '200')).toBe('my name is vikram sharma');
      });
    });

A: You can install the Search Filter Plugin.
Install the third-party search filter package with npm command:
npm install ng2-search-filter
Then import it in the app.module.ts,
import { Ng2SearchPipeModule } from 'ng2-search-filter';
and add it into the imports array,
imports:[Ng2SearchPipeModule]
https://www.remotestack.io/angular-search-filter-pipe-with-ng2-search-filter-tutorial/

A: add to imports Ng2SearchPipeModule, example:
import { Ng2SearchPipeModule } from 'ng2-search-filter';
...
  imports:[Ng2SearchPipeModule],

A: In Angular a good technique for sharing common directives, components, pipes, etc. is to use a so called shared module.
Those modules declare and export common parts, to make them usable for any of your other modules.
// other imports
import { filterPipe} from './{your-path}';

@NgModule({
  imports: [
    // dep modules
  ],
  declarations: [
    filterPipe
  ],
  exports: [
    filterPipe
  ]
})
export class PipesModule {}

and then,
mport the created ApplicationPipesModule module into the modules where your pipe is going to be used, by adding it to the imports array
// other imports
import { PipesModule } from './{your-path}';

    @NgModule({
     imports: [
       // other dep modules
       PipesModule
     ],
     declarations: [],
     exports: []
    })
    export class MyModule1 {}


text:
Q: Compare two colors in image? I'm trying to compare the given pixel to Color.BLACK. But the problem is it yields false for all the images. (I made a black image and it also returned false!)
public int isItBlackOrWhite(int x , int y)
{
     int c = bimg.getPixel(x, y);
     if(c == Color.BLACK)
         {System.out.println("Helooo");return 0;}
     else
      return 1;
}

Also I tried to compare it with Color.White but the application quit and force closed!
public int isItBlackOrWhite(int x , int y)
{
     int c = bimg.getPixel(x, y);
     if(c == Color.WHITE)
         {System.out.println("Helooo");return 0;}
     else
      return 1;
}

NOTE: bimg is an Bitmap image taken from the camera.

A: First, use LogCat for printing comments and variables. (Eclipse -> Window -> Show View -> Android -> LogCat.
Then you should see the error in the Log.
That will help us to locate the error.

A: I don't know the specifics of the pixel formats you're using, but you're trying to compare a 32-bit integer representation of a color (most probably in ARGB format) with an object of type Color. You need to first get the ARGB representation of the Color object (probably by calling Color.getRGB() ) before comparing it to the result of getPixel().

A: As for the "black" image: you need another test image. Taking a picture with the camera will never get you a truly black photo. So finding truly black pixels will be hard too.
(Just add a debug statement to print the value of c to validate that. For Color.BLACK you should get -16777216, or hexadecimal 0xff000000.)

A: Color.BLACK is Color but not int. You need to cast them to the same type before comparing.

A: Ugly solution, but the answers below doesn't give actual solution to your problem. Try this:
Color white = new Color(0,0,0); // for white
Color black = new Color(255,255,255); // for black
if(yourPixel.equals(white)) { // operate }

You can also create a Color Constants class and use it accordingly and I think you can find one from the internet. If you're willing to implement that class, RGB value of colors.

A: The problem might be your usage of ==, which doesnt quite have the meaning you intend. In java it checks that two objects are the same object, and the color you get from your picture will never be equal to the value recorded in Color.BLACK
What you want to do is check that the color's values are the same, the red, green, blue, and alpha channels.  This is a context dependent equality, which is usually implemented as the .equals() function of an object.
Try this one:
c.equals(Color.BLACK)

instead of
c == Color.BLACK


text:
Q: Attempted to call function "openssl_pkey_get_private" from namespace "WAYF" I'm getting this error message

Attempted to call function "openssl_pkey_get_private" from namespace "WAYF"

I'm upgrading the symfony version from symfony2 to symfony3, and "WAYF" is my bundle and
In that I have one class name as "CustomLogin.php"
in that class I have declared one function "function prepareparamsforjs(){}" and
in that function I'm calling "openssl_pkey_get_private()" function with arguments "$privatekey" and "$privatekeypass" to get a private Key
but I'm getting above error message.
Can anybody tell me how to solve this issue.
Thanks in Advance!...

A: IMHO you don't have the OpenSSL extension (http://php.net/manual/en/book.openssl.php) loaded in PHP, so the parser is trying to find it inside the current namespace, which is the WAYF.
A quick way to verify if the OpenSSL extension is loaded is to run:
var_dump(extension_loaded('openssl'));


text:
Q: filling an array in a loop I have a function that constantly gets called. I have 3 smaller arrays that I need to pack into a larger array each loop
float* a;
float* b;
float* c;
float* abc;

a = calloc(1, sizeof(float)*3);
b = calloc(1, sizeof(float)*3);
c = calloc(1, sizeof(float)*3);
abc = calloc(1, sizeof(float)*9);

void update() {

   for(int i = 0; i < 3; i++) {
     fill_a(a);
     fill_b(b)
     fill_c(c);

     abc[0] = a[0];
     abc[1] = b[0];
     abc[2] = c[0];

     abc[0] = a[1];
     abc[1] = b[1];
     abc[2] = c[1];

     abc[0] = a[2];
     abc[1] = b[2];
     abc[2] = c[2];
   }
}

free(a);
free(b);
free(c);
free(abc);

the implementation above has problems because the values get overwritten on subsequent loops.
I've tried adding an offset to the values like this:
   for(int i = 0; i < 3; i++) {
     fill_a(a);
     fill_b(b)
     fill_c(c);

     abc[(i*9)+0] = a[0];
     abc[(i*9)+1] = b[0];
     abc[(i*9)+2] = c[0];

and while that seem to work, if I try to add one by one that also doesn't work.
I've also tried adding offsets via an index value but it counts off to infinity.
int idx = 0;

void update() {

   for(int i = 0; i < 3; i++) {
     fill_a(a);
     fill_b(b)
     fill_c(c);

     abc[++idx] = a[0];
     abc[++idx] = b[0];
     abc[++idx] = c[0];

     abc[++idx] = a[1];
     abc[++idx] = b[1];
     abc[++idx] = c[1];

i've also tried filling the first arrays in one for loop. Then later in the update loop putting those values into the larger array.
int idx;

idx = 0;
void update() {

   for(int i = 0; i < 3; i++) {
     fill_a(a);
     fill_b(b)
     fill_c(c);
   }
  int tidx = idx;
  abc[++tidx] a[0];
  abc[++tidx] b[0];
  abc[++tidx] c[0];
  ....
  idx = tidx;
 }

but again the idx runs off to infinity. How can I arrange this algorithm so that I can fill the larger array inside that loop with the values from the smaller array while also keeping the offsets in order?
The values of the larger array is always going to be overwritten ever loop so after it's filled, it's consumed elsewhere then overwritten the next call to update.
edit
I have tried gdb debugging stepping through the code one variable at a time.
The expected output is something like this:
a = { 0, 1, 2 };
b = { -3, -2, -1 };

abc = { 0, -3, 11.
        1, -2, 22 };

Here's a fully working example from actual code.
    int count = 3;
    float* v_buff;
    float* c_buff;

    size_t vs = sizeof(float) * 6);
    v_buff = calloc(1, (vs));

void update() {
     for(int i = 0; i < count; i++) {
         float a[3] = { 0, 1, 2}; //these will be new every update
         float b[3] = { -3, -2, -1};
         int idx = 0;
         v_buff[++idx] = a[0];
         v_buff[++idx] = a[1];
         v_buff[++idx] = a[2];

         v_buff[++idx] = b[0];
         v_buff[++idx] = b[1];
         v_buff[++idx] = b[2];
     }
}

That sample code compiles but the same thing applies.
trying the offset:
v_buff[(i * 3) + (++idx)] = a[0];

causes my counter to run off to infinity or just overwrites the first set of values in v_buff.

A: For your abc array, the first approach doesn't work because you set the first 3 entries of the array to the contents of a, then overwrite them with the contents of b, then again with the contents of c.
Your second approach is close but not quite because you're multiplying i by 9 instead of 3, so the index goes out of bounds after the first iteration.
Your third approach is also close but is issue there is that you're using a preincrement (++idx) instead of a postincrement (idx++) so your indexes go from 1 to 9 instead of 0 to 8.
Also, your update function is calling fill_a, fill_b, and fill_c in a loop.  Without seeing those functions, I'm guessing that it's filling them with the same contents each time, so those probably don't need to be in a loop.
So assuming that the allocation and deallocation for each of the 4 arrays occurs outside of update, the function should look like this:
void update()
{
    int i;

    fill_a(a);
    fill_b(b)
    fill_c(c);

    for(int i = 0; i < 3; i++) {
        abc[(i*3)+0] = a[i];
        abc[(i*3)+1] = b[i];
        abc[(i*3)+2] = c[i];
    }
}

On the first iteration of the loop, i is 0, so the three lines evaluate to:
abc[0] = a[0];
abc[1] = b[0];
abc[2] = c[0];

On the second iteration, i is 1, and the body evaluates to:
abc[3] = a[1];
abc[4] = b[1];
abc[5] = c[1];

On the third iteration, i is 2, and the body evaluates to:
abc[6] = a[2];
abc[7] = b[2];
abc[8] = c[2];

You could also implement it like this:
void update()
{
    int i, idx;

    fill_a(a);
    fill_b(b)
    fill_c(c);

    for(int i = 0, idx = 0; i < 3; i++) {
        abc[idx++] = a[i];
        abc[idx++] = b[i];
        abc[idx++] = c[i];
    }
}


text:
Q: What kind of spell happened to the snake enclosure glass? In Harry Potter and the Philosopher's Stone Harry Potter makes the glass disappear into the snakes enclosure. What did actually happen to it?
Was it an apparition or transfiguration? Or just untyped spontaneous magic not related to the mentioned two types?

A: While this effect was clearly produced by instinctive magic, it seems most similar to the vanishing spell Evanesco, which by its inclusion in Professor McGonnagall's class would presumably be counted as a transfiguration. Indeed, in Order of the Phoenix, chapter 13 "Detention with Dolores" Professor McGonagall sets her fifth year students on a task to practicing vanishing spells  on snails, categorising them as "among the most difficult magic [the students] will be tested on in [their] O.W.L".
And to answer the question in the comments as to where vanished objects go:

"Into non-being, which is to say, everything"
  - Professor McGonagall to the Ravenclaw door knocker, Harry Potter and the Deathly Hallows


text:
Q: Multiple Languages for your app? I am using the ionic framework with Ionic Creator.
Is it possible to have all my text referenced to any String file. And this file can be different for each language so that i can change my displayed language dynamically?
Thanks

A: This is my working Example clone from github.
Github Repo


text:
Q: What is the mistake in layout code Whats the mistake in this code, please let me know this way of approach is correct or not.
When i load list items, the list is expanding till the search bar, not the entire screen. please advice  me.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:background="#000044">

        <TableRow>
             <EditText
                 android:id="@+id/txtUserName"
                 android:width="270dp" />

             <Button
                 android:id="@+id/Search_button"
                 android:width="50dp" />
                 />
        </TableRow>

        <TableRow>
            <ListView
                android:id="@+id/Service_name_list"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"/>
        </TableRow>

    </TableLayout>

Also tell me, this will work for all screens or not.

A: Change the second row as below:
    <TableRow android:layout_span="2">
        <ListView
        android:id="@+id/Service_name_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    </TableRow>

The only thing changed is android:layout_span="2" that is equal to HTML colspan.

A: Add a layout_span to force the one cell to span two cells.
<ListView
    android:id="@+id/Service_name_list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_span="2"/>


text:
Q: Is there a way to remove indents for question parts>
For the example above, how can I remove the indent from the parts so (a), (b), (c), (d) all line up with "Question 1"?
\documentclass[addpoints, 12pt]{exam}
\usepackage[a4paper, total={6in, 8in}]{geometry}
\linespread{1.6}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{fancyhdr}
\usepackage{mlmodern}
\usepackage{amsmath}
\usepackage{amssymb}
\setlength{\topmargin}{0cm}
\setlength{\textheight}{9.25in}
\setlength{\oddsidemargin}{0.0in}
\setlength{\evensidemargin}{0.0in}
\setlength{\textwidth}{16cm}
\pagestyle{fancy}
\lhead{}
\chead{}
\rhead{}
\lfoot{}
\cfoot{\footnotesize{Page \thepage \ of \pageref{finalpage} -- \titlehd \ (\examcode)}}
\rfoot{}

\newcommand{\institution}{Maths Extension 2}
\newcommand{\titlehd}{Complex Numbers}
\newcommand{\examtype}{Summer Holidays Examination}
\newcommand{\examdate}{2021-2022}
\newcommand{\readtime}{10 Minutes}
\newcommand{\writetime}{THREE Hours}
\newcommand{\materials}{Non-programmable Calculators}

\setlength{\rightpointsmargin}{1.5cm}
\newpage
\begin{questions}
\marksnotpoints
\pointsinrightmargin
\pointformat{\bfseries\themarginpoints}
\qformat{\textbf{Question \thequestion} \hspace{2mm}\textbf{(\totalpoints \hspace{1mm}\points)}\hfill}

\question
\vspace{2mm}
\begin{parts}

\part[1]\text{If $(x+iy)^{2n}=a+ib$ where} $x,y,a,b,n$ $\in{\Bbb{Z}}$ find the value of $(y-ix)^{4n}$ in terms of $a$ and $b$

\vspace{8mm}
\part[2] Let $w=\cos{\frac{2\pi}{7}}+i\sin{\frac{2\pi}{7}}$. Show that $w, w^4$ and $w^5$ form the sides of an equilateral triangle.

\vspace{8mm}
\part
\begin{subparts}
\subpart[2] Find the solutions to the equation $z^n-1=0$ where $n$ is odd.

\vspace{2mm}
\subpart[2]Hence show that $\cos{\frac{2\pi}{n}}+\cos{\frac{4\pi}{n}}+...+\cos{\frac{(n-1)\pi}{n}}$ is independent of $n$.
\end{subparts}
\vspace{0.8cm}

\part[3]Let $w=\frac{2}{1+z}$. If $|z|=1$ and $0<\arg{z}<\frac{2\pi}{3}$, sketch the complex number $w$
\vspace{1cm}
\end{parts}
\newpage

A: Using the newcommand \questionx instead of \question
\newcommand{\questionx}[1]{% added <<<<<<<<<<<<<<<<<<<<
    \marksnotpoints
    \qformat{\textbf{Question~\thequestion} \hspace{1ex}\textbf{(\totalpoints \enspace \points)}\hfill}
    \pointsinrightmargin%
    \pointformat{\textbf{\themarginpoints}}%
    \settowidth{\leftmargin}{(m)\hskip\labelsep}%
    \question\hspace*{-\leftmargin}\parbox{\textwidth}{#1}
}

\documentclass[addpoints, 12pt]{exam}
\usepackage[a4paper, total={6in, 8in}]{geometry}
\linespread{1.6}
%\usepackage[utf8]{inputenc}
\usepackage{graphicx}
%\usepackage{fancyhdr}
\usepackage{mlmodern}
\usepackage{amsmath}
\usepackage{amssymb}
\setlength{\topmargin}{0cm}
\setlength{\textheight}{9.25in}
\setlength{\oddsidemargin}{0.0in}
\setlength{\evensidemargin}{0.0in}
\setlength{\textwidth}{16cm}

\usepackage{showframe} % show margins

\newcommand{\questionx}[1]{% added <<<<<<<<<<<<<<<<<<<<
    \marksnotpoints
    \qformat{\textbf{Question~\thequestion} \hspace{1ex}\textbf{(\totalpoints \enspace \points)}\hfill}
    \pointsinrightmargin%
    \pointformat{\textbf{\themarginpoints}}%
    \settowidth{\leftmargin}{(m)\hskip\labelsep}%
    \question\hspace*{-\leftmargin}\parbox{\textwidth}{#1}
}

\begin{document}
\newcommand{\institution}{Maths Extension 2}
\newcommand{\titlehd}{Complex Numbers}
\newcommand{\examtype}{Summer Holidays Examination}
\newcommand{\examdate}{2021-2022}
\newcommand{\readtime}{10 Minutes}
\newcommand{\writetime}{THREE Hours}
\newcommand{\materials}{Non-programmable Calculators}

\setlength{\rightpointsmargin}{1.5cm}
\newpage
\begin{questions}
%   \marksnotpoints
%   \pointsinrightmargin
%   \pointformat{\bfseries\themarginpoints}
%   \qformat{\textbf{Question \thequestion} \hspace{2mm}\textbf{(\totalpoints \hspace{1mm}\points)}\hfill}

    \questionx{%
    \vspace*{3mm}
    \begin{parts}

        \part[1]\text{If $(x+iy)^{2n}=a+ib$ where} $x,y,a,b,n$ $\in{\Bbb{Z}}$ find the value of $(y-ix)^{4n}$ in terms of $a$ and $b$

        \vspace{8mm}
        \part[2] Let $w=\cos{\frac{2\pi}{7}}+i\sin{\frac{2\pi}{7}}$. Show that $w, w^4$ and $w^5$ form the sides of an equilateral triangle.

        \vspace{8mm}
        \part
        \begin{subparts}
            \subpart[2] Find the solutions to the equation $z^n-1=0$ where $n$ is odd.

            \vspace{2mm}
            \subpart[2]Hence show that $\cos{\frac{2\pi}{n}}+\cos{\frac{4\pi}{n}}+...+\cos{\frac{(n-1)\pi}{n}}$ is independent of $n$.
        \end{subparts}
        \vspace{0.8cm}

        \part[3]Let $w=\frac{2}{1+z}$. If $|z|=1$ and $0<\arg{z}<\frac{2\pi}{3}$, sketch the complex number $w$
        \vspace{1cm}
    \end{parts}
}% added <<<<<<<<<<<<<<<<<<<<
\end{questions}
\end{document}

UPDATE (after follow up)
To allow page break within parts use
\newcommand{\questionx}[1]{% added <<<<<<<<<<<<<<<<<<<<
    \marksnotpoints
    \qformat{\textbf{Question \thequestion} \hspace{2mm}\textbf{(\totalpoints \hspace{1mm}\points)}\hfill}
    \pointsinrightmargin%
    \pointformat{\textbf{\themarginpoints}}%
    \settowidth{\leftmargin}{(m)\hskip\labelsep}%
    \question\hspace*{-\leftmargin}#1% changed <<<<<<<<<<
}

\renewcommand{\partshook}{% added <<<<<<<<<<<<<<<<<<<<
    \setlength{\leftmargin}{0pt}%
    \setlength{\labelwidth}{0pt}%
}

A: You can use "partshook" to get at lengths associated with parts.  Note that I created something more like a minimum compile-able file, as your file gave me trouble.  I didn't bother making the equations correct.
\documentclass{exam}

\begin{document}
\begin{questions}
\vspace{2mm}

% ***********
\renewcommand{\partshook}{%
    \setlength{\leftmargin}{0pt}%
    \setlength{\labelwidth}{-\labelsep}%
}
% **********

\question
\begin{parts}

    \part[1] If $(x+iy)^{2n}=a+ib$ where $x,y,a,b,n$ $\in{{Z}}$ find the value of $(y-ix)^{4n}$ in terms of $a$ and $b$

    \vspace{8mm}
    \part[2] Let $w=\cos{\frac{2\pi}{7}}+i\sin{\frac{2\pi}{7}}$. Show that $w, w^4$ and $w^5$ form the sides of an equilateral triangle.

    \vspace{8mm}
    \part
    \begin{subparts}
        \subpart[2] Find the solutions to the equation $z^n-1=0$ where $n$ is odd.

        \vspace{2mm}
        \subpart[2]Hence show that $\cos{\frac{2\pi}{n}}+\cos{\frac{4\pi}{n}}+...+\cos{\frac{(n-1)\pi}{n}}$ is independent of $n$.
    \end{subparts}
    \vspace{0.8cm}

    \part[3]Let $w=\frac{2}{1+z}$. If $|z|=1$ and $0<\arg{z}<\frac{2\pi}{3}$, sketch the complex number $w$
    \vspace{1cm}
\end{parts}
\end{questions}
\end{document}

This yields
.  Of course, the parts letter now overlaps with the question number -- but that's an issue inherent with your request.


text:
Q: Why isn't this line chart drawing? (d3js) The data comes in a format like this:
[
    {y: 17.0, x: '2015-07-23 00:02:41'},
    {y: 17.0, x: '2015-07-23 00:03:41'},
    {y: 15.0, x: '2015-07-23 01:21:44'},
    {y: 23.0, x: '2015-07-23 02:50:48'},
    {y: 21.0, x: '2015-07-23 02:51:48'},
    {y: 28.0, x: '2015-07-23 02:52:48'},
    {y: 24.0, x: '2015-07-23 02:53:48'},
    {y: 27.0, x: '2015-07-23 02:54:48'},
    {y: 18.0, x: '2015-07-23 02:55:48'},
    {y: 28.0, x: '2015-07-23 02:56:48'}
]

I'm trying to draw a line chart based on that data; but every time I try it's blank; this is what I'm doing:
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;

var x = d3.time.scale()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height,0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(5);

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(5);

var vline = d3.svg.line()
    .x(function(d, i) { return x(parseDate(d.x)); })
    .y(function(d, i) { return y(d.y); });

// add canvas
var svg = d3.select(".swatch").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
.append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

x.domain(d3.extent(data, function(d) { return d.x; }));
y.domain([0, d3.max(data, function(d) { return d.y; })]);

// draw line
svg.append("path")
  .attr("class", "line")
  .attr("d", vline(data));

// x axis
svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

// y axis
svg.append("g")
  .attr("class", "y axis")
  .call(yAxis);

The fields output properly when printed with console.log (from var vline = d3.svg.line()... but the line is never drawn.
Any idea why it's not drawing the line?

A:

$(document).ready(function () {
 data =[
    {y: 17.0, x: '2015-07-23 00:02:41'},
    {y: 17.0, x: '2015-07-23 00:03:41'},
    {y: 15.0, x: '2015-07-23 01:21:44'},
    {y: 23.0, x: '2015-07-23 02:50:48'},
    {y: 21.0, x: '2015-07-23 02:51:48'},
    {y: 28.0, x: '2015-07-23 02:52:48'},
    {y: 24.0, x: '2015-07-23 02:53:48'},
    {y: 27.0, x: '2015-07-23 02:54:48'},
    {y: 18.0, x: '2015-07-23 02:55:48'},
    {y: 28.0, x: '2015-07-23 02:56:48'}
];
  var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;

var x = d3.time.scale()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height,0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(5);

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(5);

var vline = d3.svg.line()
    .x(function(d, i) { return x(parseDate(d.x)); })
    .y(function(d, i) { return y(d.y); });

// add canvas
var svg = d3.select(".swatch").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
.append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

x.domain(d3.extent(data, function(d) { return parseDate(d.x); }));
y.domain([0, d3.max(data, function(d) { return d.y; })]);

// draw line
svg.append("path")
  .attr("class", "line")
  .attr("d", vline(data));

// x axis
svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

// y axis
svg.append("g")
  .attr("class", "y axis")
  .call(yAxis);
    });
path {
 stroke: black;
 fill: none;
}

Here is working.....


text:
Q: How to return php array to ajax call? returns
I have a php script which is called by ajax and i do some operation on mysql in this file and now i want to return the result stored in php array to ajax call. So how it can be possible.

A: You should use it.
echo json_encode($array);

A: Anything you print in the php script will be 'returned' to the ajax call and caught in the success callback.
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: function(response){
    alert(response); // Will print whatever the php script 'echos' out.
    // or with the php code below as the script you call, you can use:
    if(response.result) {
       alert(response.data); // For the data in 'data' to be printed.
       // Where response.data is your array:
       for(var i=0;i<response.data.length;i++){
         console.log(response.data[i]);
       }
    } else {
      console.log(response.error);
    }
  },
});

Edit:
As other states in the other answers, json is perfect to return from a php script to an ajax callback, cause JavaScript and PHP both handles this very well.
<?php
  // I like to return an associative array,
  // which in the javascript part of the code can be used as a object.
  // I always include a 'result' boolean value which will let me know on the js
  // side if the request was successfully done or not, and if false,
  // i usually include a 'error' property with a error message.
  $myreturndata = array("result" => true, "data" => $yourArray, "error" => null);
  header('Content-Type: application/json');
  die(json_encode($myreturndata));

A: Try this:
Use json for that. Read this for more details.

http://php.net/json_encode
JSON is used especially for this purpose.

--
Thanks

A: If you want to pass PHP Array to an AJAX call convert it as JSON and pass it.
The below is an example
<?php
$arr = array('a' => 10, 'b' => 23, 'c' => 32, 'd' => 42, 'e' => 52);
echo json_encode($arr);
?>

A: In your ajax call you can specify the return datatype like this
$.ajax({
   url : url,
   data : data,
   dataType : 'json',
   success : function(data){
      console.log(data);
   }
})

In you php script you can print the json encoded string like this
print_r(json_enocde(array()));

A: A useful example on top of the other answers. Splitting each array value into javascript variables.
Improved with useful advice :)
PHP
echo json_encode($array);

jQuery.ajax in your success function
// pass each value to variables (this example array looks like this: [100,200,300])
var variableOne = response[0]; // This variable will = 100
var variableTwo = response[1]; // This variable will = 200
var variableThree = response[2]; // This variable will = 300

// Now you can easily use each individual value.
alert(variableOne);


text:
Q: Can I ensure all tests contain an assertion in test/unit? With test/unit, and minitest, is it possible to fail any test that doesn't contain an assertion, or would monkey-patching be required (for example, checking if the assertion count increased after each test was executed)?
Background: I shouldn't write unit tests without assertions - at a minimum, I should use assert_nothing_raised if I'm smoke testing to indicate that I'm smoke testing.
Usually I write tests that fail first, but I'm writing some regression tests. Alternatively, I could supply an incorrect expected value to see if the test is comparing the expected and actual value.

A: To ensure unit tests actually verify anything a technique called Mutation testing is used.
For Ruby, you can take a look at Mutant.

A: As PK's link points out too, the presence of assertions in itself doesn't mean the unit test is meaningful and correct. I believe there is no automatic replacement for careful thinking and awareness.
Ensuring the tests fail first is a good practice, which should be made into a habit.
Apart from the things you mention, I often set wrong values in asserts in new tests, to check that the test really runs and fails. (Then I fix it of course :-) This is less obtrusive than editing the production code.

A: I don't really think that forcing the test to fail without an assert is really helpful. Having an assert in a test is not a goal in itself - the goal is to write useful tests.
The missing assert is just an indication that the test may not be useful. The interesting question is: Will the test fail if something breaks?. If it doesn't, it's obviously useless.
If all you're testing for is that the code doesn't crash, then assert_nothing_raised around it is just a kind of comment. But testing for "no explosions" probably indicates a weak test in itself. In most cases, it doesn't give you any useful information about your code (because "no crash != correct"), so why did you write the test in the first place? Plus I rather prefer a method that explodes properly to one that just returns a wrong result.
I found the best regression test come from the field: Bang your app (or have your tester do it), and for each problem you find write a test that fails. Fix it, and have the test pass.
Otherwise I'd test the behavior, not the absence of crashes. In the case that I have "empty" tests (meaning that I didn't write the test code yet), I usually put a #flunk inside to remind me.