text:
Q: How to get limited amount of recent posts in django I am a DJANGO beginner and I am making a biography app as my first project. I want my homepage to show a limited number of recent posts. I am providing my Django files so you'll look up and help me with this problem. Thanks
#views.py
from django.views.generic import TemplateView, ListView, DetailView
from .models import About

# Create your views here.

class Home(ListView):
    """docstring for Home"""
    template_name = 'home.html'
    model = About
    recents = About.objects.all()
    for recent in recents:
        if recent.was_published_recently():
            print (recent.id)

class BiographyDetail(DetailView):
    """docstring for BiographyDetail"""
    model = About
    template_name = 'details.html'

class About(TemplateView):
    """docstring for BiographyDetail"""

    template_name = 'about.html'
    model = About

class Contacts(TemplateView):
    """docstring for BiographyDetail"""

    template_name = 'contact.html'
    model = About

class Projects(TemplateView):
    """docstring for BiographyDetail"""

    template_name = 'projects.html'
    model = About

class Search(TemplateView):
    """docstring for BiographyDetail"""

    template_name = 'search.html'
    model = About

#models.py I have defined a function was_published_recently which tells whether any posts was published in that certain interval as you can figure that out by its name
from django.db import models
from django.utils import timezone
import datetime
# Create your models here.

TYPE = (
    ('politician','POLITICIAN'),
    ('poet','POET'),
    ('author','AUTHOR'),
    ('actor','ACTOR'),
    )

class About(models.Model):
    name = models.CharField(max_length = 200, default='')
    quote = models.CharField(max_length = 200, default='')
    born = models.DateField(verbose_name = 'Born on', null = True)
    born_at = models.CharField(max_length = 200, default='')
    died = models.DateField(verbose_name = 'Died on', null = True)
    died_at = models.CharField(max_length = 200, default='')
    main = models.TextField(default='')
    category = models.CharField(choices = TYPE , default = 'poet', max_length = 10)
    image = models.ImageField(blank=True, default='', upload_to='static')
    created_on = models.DateTimeField(auto_now_add = True)
    updated_on = models.DateTimeField(auto_now = True)

    def __str__(self):
        return self.name

    def was_published_recently(self):
        return self.created_on >= timezone.now() - datetime.timedelta(days=15)

home.html
{% extends 'base.html' %}

{% block content %}

            JOURNEY

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

                    <svg class="bi bi-filter-left" width="1.5em" height="1.5em" viewBox="0 0 16 16" fill="white" xmlns="http://www.w3.org/2000/svg">
                        <path fill-rule="evenodd" d="M2 10.5a.5.5 0 01.5-.5h3a.5.5 0 010 1h-3a.5.5 0 01-.5-.5zm0-3a.5.5 0 01.5-.5h7a.5.5 0 010 1h-7a.5.5 0 01-.5-.5zm0-3a.5.5 0 01.5-.5h11a.5.5 0 010 1h-11a.5.5 0 01-.5-.5z" clip-rule="evenodd"/>
                    </svg>

            </button>

About

Contact

Projects

Search

                                <input type="text" class="form-control" placeholder="Search" aria-label="Search" aria-describedby="button-addon2">

                                    <button class="btn btn-outline-secondary search-button" type="button" id="button-addon2">
                                        <svg class="bi bi-search" width="1em" height="1em" viewBox="0 0 16 16" fill="white" xmlns="http://www.w3.org/2000/svg">
                                            <path fill-rule="evenodd" d="M10.442 10.442a1 1 0 011.415 0l3.85 3.85a1 1 0 01-1.414 1.415l-3.85-3.85a1 1 0 010-1.415z" clip-rule="evenodd"/>
                                             <path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 100-11 5.5 5.5 0 000 11zM13 6.5a6.5 6.5 0 11-13 0 6.5 6.5 0 0113 0z" clip-rule="evenodd"/>
                                        </svg>
                                    </button>

#this is where I am using for loop for recents

                            {% for about in object_list %}
                                {% load static %}

{{ about.name}}

                            {% endfor %}

Recent Posts

                            {% for post in recents %}

                                            {{ recent.name }}

                            {% endfor %}

{% endblock content %}

A: You can limit the results of the query
recents = About.objects.all()[:10]


text:
Q: Filling the values of an array with values of other table I have a table (my_table2) in postgresql which contains a column with array type. I want values of column val1 of my_table1 to be first elements of my array (array_col) and val2 to be second elements of array_col. I came up with this query:
update my_table2
set array_col=array[
    (
    select val1 from my_table1)
    , (select val2 from my_table1)
    ]

but I got an error when I run it:
ERROR:  more than one row returned by a subquery used as an expression
Is there a method to do it?

A: Your subqueries, select val1 from my_table1 or select val2 from my_table1, are returning more than one row.  If you're going to specific a subquery for each element, then it can only return one element.
Depending on what you have...you might be looking at something more like :
Concat the two together?
update my_table2 set array_col=array(select val1 from my_table1)||array(select val2 from my_table1)
Just get one from each?
update my_table2 set array_col=array[(select val1 from my_table1 limit 1),(select val2 from my_table1 limit 1)]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dedekind cut corresponding to the limit of a Cauchy sequence Let $a : \mathbb{N} \rightarrow \mathbb{Q}$ be a Cauchy sequence of rationals. Then is it correct to say that
$$\lim_{n \rightarrow \infty} a_n = \{x \in \mathbb{Q} : \exists n \in \mathbb{N} : \forall m \in \mathbb{N} : m > n \rightarrow x < a_m\}$$
where the right side is interpreted as a lower Dedekind cut? That is, can we use this expression to convert any Cauchy sequence to a Dedekind cut that represents its limit?

A: Yes, that would be correct. In other words: if $(a_n)_{n\in\mathbb N}$ is a Cauchy sequence which is convergent in $\mathbb R$ (note that this is equivalent to the assertion that it is a Cauchy sequence), then its limit $l$, seen as Dedekind cut is precisely the set$$\{x\in\mathbb Q\,|\,(\exists n\in\mathbb N)(\forall m\in\mathbb N):m\geqslant n\implies x<a_m\}$$(I used $\leqslant$ here instead of $<$ just for a matter of taste).


text:
Q: Lavasfy client is not a constructor I'm working on a music bot project, the error said LavasfyClient is not a constructor, the code was scrapped because I switch from erela.js-spotify to lavasfy, I don't know what I do wrong and I've read the documentation of lavasfy.
Some parts might be empty because I delete them (like clientID, lavalink host, password, etc)
Here's my code:
    Manager
  } = require("erela.js"),

    LavasfyClient = require("lavasfy"),
    Deezer = require("erela.js-deezer"),
    Facebook = require("erela.js-facebook"),
    config = require(`${process.cwd()}/botconfig/config.json`),
    clientID = process.env.clientID || config.spotify.clientID,
    clientSecret = process.env.clientSecret || config.spotify.clientSecret;
  module.exports = (client) => {
      if (!clientID || !clientSecret || clientID.length < 5 || clientSecret.length < 5) {
        client.manager = new Manager({
      plugins: [
        new Deezer(),
        new Facebook(),
      ],
          send(id, payload) {
            var guild = client.guilds.cache.get(id);
            if (guild) guild.shard.send(payload);
          },
        });
      } else {
        client.manager = new Manager({
          nodes: collect(config.clientsettings.nodes),
          plugins: [
            new LavasfyClient({
              clientID: "",
              clientSecret: "",
            }),
          ],
          send(id, payload) {
            var guild = client.guilds.cache.get(id);
            if (guild) guild.shard.send(payload);
          },
        });
      }
      //require the other events
      require("./node_events")(client)
      require("./client_events")(client)
      require("./events")(client)
      require("./musicsystem")(client)

  };

  function collect(node) {
    return node.map(x => {

      if (!x.host) throw new RangeError('"host" must be provided');
      if (!x.password) throw new RangeError('"password" must be provided');
      if (typeof x.port !== 'number') throw new RangeError('"port" must be a number');
      if (x.retryAmount && typeof x.retryAmount !== 'number') throw new RangeError('Retry amount must be a number');
      if (x.retryDelay && typeof x.retryDelay !== 'number') throw new RangeError('Retry delay must be a number');
      if (x.secure && typeof x.secure !== 'boolean') throw new RangeError('Secure must be a boolean');

      return {
          host: x.host ? x.host : '',
          password: x.password ? x.password : '',
          port: x.port && !isNaN(x.port) ? Number(x.port) : 443,
          identifier: x.identifier || x.host,
          retryAmount: x.retryAmount ? Number(x.retryAmount) : 5,
          retryDelay: x.retryDelay ? Number(x.retryDelay) : 5000,
          secure: x.secure ? x.secure : false
      };
    });
}

A: LavasfyClient is not a default export. You need to destructure it like this:
const { LavasfyClient } = require("lavasfy");

// ...
// ...
// ...

plugins: [
  new LavasfyClient({
    clientID: "",
    clientSecret: "",
  }),
],


text:
Q: cffunction/cfargument pass unsigned int32 I'm working on building a function that will convert an unsigned int32 to an ipv4 address and it all works great until I test with the upper half of the range.
<cffunction name="Int32ToIPv4" returntype="string" output="false" access="public" hint="returns IPv4 address for int32 number">
    <cfargument name="nInt32" type="numeric" required="yes" hint="int32 to convert to ipv4 address">

    <cfreturn
        bitAnd((arguments.nInt32 / 16777216), 255) & "."
        & bitAnd((arguments.nInt32 / 65536), 255) & "."
        & bitAnd((arguments.nInt32 / 256), 255) & "."
        & bitAnd(arguments.nInt32, 255)
    >
</cffunction>

ColdFusion appears to interpret type="numeric" to be a signed 32-bit integer.
This example works:
Int32ToIPv4(nInt32 = 1181772947) = #Int32ToIPv4(nInt32 = 1181772947)# (expected value = 70.112.108.147)

This example fails:
Int32ToIPv4(nInt32 = 3401190660) = #Int32ToIPv4(nInt32 = 3401190660)# (expected value = 202.186.13.4)

The error message is: "Cannot convert the value 3.40119066E9 to an integer because it cannot fit inside an integer."
Will I have to pass this number in as a string and convert it to a Java unsigned int before using it?
I'll want to do something similar with ipv6 addresses (unsigned 128-bit integer) at some point.  Any advice for this type of data-type would be appreciated.

A: It is actually bitAnd() imposing the 32 bit integer limitation, not cfargument.
Interestingly, if you check each calculation separately, the first three (3) work fine. Due to the division, the values passed into bitAnd() are actually small enough to fit inside an INT. However, the last one uses the raw value which is obviously too big, and that is what causes the error with this specific number.
 bitAnd(  (3401190660 / 16777216), 255 )  // Actual => 202.7267611032, 255
 bitAnd(  (3401190660 / 65536), 255 ) // Actual => 51898.05084233, 255
 bitAnd(  (3401190660 / 256), 255 )  // Actual =>13285901.0156, 255
 bitAnd(3401190660, 255) // Too big!

Since most of the relevant math functions in CF are limited to 32 bit integers, I am not sure if (or how simply) it can be done with CF alone. Assuming you are using Java 8+, you also have access to the new unsigned methods like Integer.parseUnsignedInt(String).
Personally I think this would be a great learning exercise. However, unless you are very familiar with the details of signed versus unsigned and how it relates to IP4 and IP6 addresses, you might just want to use an existing java library to avoid common pitfalls. Such as Guava's InetAdress:
// IP4
input = 3401190660;
uint = createObject("java", "java.lang.Integer").parseUnsignedInt(input);
inet = createObject("Java", "com.google.common.net.InetAddresses");
result = inet.fromInteger(uint).getHostAddress();

A: I did come up with a native Java solution that involved passing in an unsigned 32-bit int.  So, @Leigh is correct about cfargument working properly.
<cffunction name="UInt32ToIPv4" returntype="string" output="no" access="public" hint="returns IPv4 address for uint32 number">
    <cfargument name="nUInt32" type="numeric" required="yes" hint="uint32 to convert to ipv4 address">

    <cfset local['JavaLangInteger'] = CreateObject("java", "java.lang.Integer")>
    <cfset local['JavaMathBigInteger'] = CreateObject("java", "java.math.BigInteger")>
    <cfset local['JavaNetInetAddress'] = CreateObject("java", "java.net.InetAddress")>

    <cfif arguments.nUInt32 EQ 0>
        <cfreturn "">
    </cfif>

    <cftry>
        <cfset local['vcIPv4'] = local.JavaNetInetAddress.getByAddress(local.JavaMathBigInteger.valueOf(local.JavaLangInteger.parseUnsignedInt(arguments.nUInt32)).toByteArray())>
        <cfreturn reReplace(local.vcIPv4, "[^0-9\.]", "", "all")>
        <cfcatch type="any">
            <cfreturn "">
        </cfcatch>
    </cftry>
</cffunction>

Let me know if there are any problems with this solution as I think that I will use it instead of a public java library.
I have written functions for ipv6 to handle the conversions (unsigned 128-bit int to/from ipv6).  Not sure that there is an interest in those functions.  If there is, I'll create separate questions/answers with that code.


text:
Q: NOQUEUE: reject: RCPT Relay access denied on AWS ubuntu I have installed Postfix on AWS ubuntu(18.04).
When I am trying to send email from my EmailId to configured postfix mail server i.e ceo@visitormanagementsystem.co.in, getting below log:

Sep 30 15:12:05 mailer postfix/smtpd[17712]: connect from
  mail-pg1-f178.google.com[209.85.215.178] Sep 30 15:12:06 mailer
  postfix/smtpd[17712]: NOQUEUE: reject: RCPT from
  mail-pg1-f178.google.com[209.85.215.178]: 454 4.7.1
  : Relay access denied;
  from= to=
  proto=ESMTP helo=

My /etc/postfix/mail.cf has following configuration:
smtpd_banner = $myhostname ESMTP $mail_name ($mail_version)
biff = no
append_dot_mydomain = no
readme_directory = no
mailbox_size_limit = 0
recipient_delimiter = + .
inet_interfaces = all
inet_protocols = all
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
compatibility_level = 2
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = mailer.visitormanagementsystem.co.in
myorigin = /etc/mailname
mydestination = $myhostname, mailer.visitormanagementsystem.co.in, localhost.visitormanagementsystem.co.in, localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128

A: You're only defining how users can relay through your postfix instance, not how you can receive mail.  You'll need to configure the other smtpd transport types to ensure mail can be delivered.
smtpd_recipient_restrictions
smtpd_client_restrictions
smtpd_sender_restrictions


text:
Q: Does Django makes additional query on accessing prefetched M2M field through "values()" or "values_list()"? models.py:
class DemoA(models.Model):
    M = < M2M-Field to DemoB>

class DemoB(models.Model):
    title = < CharField >

Queryset with prefetch:
qs = DemoA.objects.all().prefetch_related('M')

prefetch_related works good when used with .all() as stated in the docs.
Eg:
# This is the expected use case and will not make any additional query
for row in qs:
    print(row.M.all())

1) Now what if I try to access it using .values() or .values_list() methods ? Will it make additional query(s) ?
Eg:
print(qs.values('M'))

# OR

print(qs.values_list('M'))

2) Additional:
What if I access the property of M in a similar way? Will it make any additional query?
Eg:
print(qs.values('M__title'))

If it does make query(s) in both the cases, what is the perfect way to do the same? Is it good to loop over all and extract their properties?

A: Yes. It will make additional query.
Reason:
The "prefetched" queryset is of DemoB model class. When accessing through row.M.all(), the queryset which is used is of DemoB model class, and the query remains the same. Whereas in case of print(qs.values('M')) the queryset which is used if of DemoA model class, and hence the built query is different.
And as per the docs:

Remember that, as always with QuerySets, any subsequent chained methods which imply a different database query will ignore previously cached results, and retrieve data using a fresh database query.


text:
Q: REACT, setInterval keeps returning NAN even though state is a number I'm pretty new to react and I'm trying to create a countdown timer, however, when I call the setInterval function onClick, my state changes to NAN and does not decrement, even though the initial state is a number
  interval = () => {
    this.myInterval = setInterval(() => {
      this.setState(({seconds}) => ({
        second: parseInt(seconds) - 1
      }))
    }, 1000)
  }

          <button onClick={this.interval} className="start">START</button>

A: You have a typo, you are decrementing from seconds (which doesn't exists that's where the NaNcomes from) and setting the value to second.

A: Make sure your state variable is set to greater than 0 and you should stop your interval when state value is 0, or just remove parseInt from setState so that it will not create any issue.
And one more thing you didn't use this.state.seconds inside setState
because the variable you mentioned inside parseInt method which is not valid without this.state
this.state = { second: 0 }

interval = () => { this.myInterval = setInterval(() => { this.setState({second: this.state.seconds - 1}) }, 1000)}


text:
Q: Calling function in views.py from template using jaavascrpt Is it possible to call a function in views.py from a template without having url?
I have two droplists on for authors and the other one for the books.
When someone selects an author I need to call a function in views.py to got books that related to the author so the second droplist should include books that belong to the author.


text:
Q: Paypal IPN and PDT in MVC 4.0 I beginner of MVC and i am trying to paypal payment process using the following link
http://www.arunrana.net/2012/01/paypal-integration-in-mvc3-and-razor.html
Please guide me
How to implement Paypal IPN and PDT
and how to get success and Transaction id from Paypal that i want to save in database
Thanks in Advance

"
public class CheckoutController : Controller
{
    CartContext _CartCotext = new CartContext();
    CartItemContext _CartItemContext = new CartItemContext();

    Tbl_OrderContext _OrderContext = new Tbl_OrderContext();
    OrderDetailContext _OrderDetailContext = new OrderDetailContext();
    ProductContext _ProductContext = new ProductContext();

    const string PromoCode = "FREE";

    [HttpPost]
    public ActionResult AddressAndPayment(CheckoutViewModel values)
    {

        var cart = ShoppingCart.GetCart(this.HttpContext);
        var _CartItems = Session["CartItems"];
        var list = (List<Cart>)Session["CartItems"];

        values.CartItems = list;

        var order = new CheckoutViewModel();
        order.CartItems = list;
        TryUpdateModel(order);

        {
            try
            {
                if (order.Tbl_Order == null)
                {
                    return View(order);
                }
                else
                {
                    order.Tbl_Order.Username = User.Identity.Name;
                    order.Tbl_Order.OrderDate = DateTime.Now;
                    order.Tbl_Order.CartTotal = order.CartTotal;
                    Session["carttotal"] = order.CartTotal;
                    order.Tbl_Order.Status = "Pending";

                    //Save Order

                    _OrderContext.OrderEntries.Add(order.Tbl_Order);
                    _OrderContext.SaveChanges();

                    //Process the order
                    string username = User.Identity.Name;
                    ShoppingCart obj = new ShoppingCart();
                    int i = obj.CreateOrder(order.Tbl_Order, order.CartItems, username);

                    //return RedirectToAction("Complete",
                    //   new { id = order.Tbl_Order.OrderId });
                    return RedirectToAction("PosttoPaypalShow");
                }

            }
            catch
            {
                //Invalid - redisplay with errors
                return View(order);
            }
        }

    }

    [HttpGet]
    public ActionResult PosttoPaypalShow()
    {

        SportsStore.Models.Paypal payPal = new Paypal();
        payPal.cmd = "_xclick";
        payPal.business = ConfigurationManager.AppSettings["BusinessAccount"];
        bool useSendBox = Convert.ToBoolean(ConfigurationManager.AppSettings["useSendbox"]);
        if (useSendBox)
        {
            ViewBag.actionURL = "https://www.sandbox.paypal.com/cgi-bin/webscr";
        }
        else
        {
            ViewBag.actionURL = "https://www.paypal.com/cgi-bin/webscr";
        }
        payPal.cancel_return = System.Configuration.ConfigurationManager.AppSettings["CancelUrl"];
        payPal.@return = ConfigurationManager.AppSettings["ReturnURL"];
        payPal.notify_url = ConfigurationManager.AppSettings["NotifyURL"];
        payPal.currency_code = ConfigurationManager.AppSettings["currencycode"];
        //payPal.item_Name = ProductName;
        payPal.item_Name = "test1";
        payPal.Descriptions = "tes2";
        payPal.amount = String.Format("{0:0.##}", Session["carttotal"]); //Convert.ToString(Session["carttotal"].ToString("0.00"));
        return View(payPal);
    }
    public ActionResult PaypalAddressAndPayment()
    {

        Tbl_Order order = new Tbl_Order();
        var cart = ShoppingCart.GetCart(this.HttpContext);

        // Set up the ViewModel
        var viewModel = new CheckoutViewModel
        {
            CartItems = cart.GetCartItems(),
            CartTotal = cart.GetTotal(),
            Tbl_Order = order
        };
        Session["CartItems"] = viewModel.CartItems;
        return View(viewModel);
        //return View(order);
    }
    string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
    {

        string paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
            : "https://www.paypal.com/cgi-bin/webscr";

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);

        // Set values for the request back
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";

        byte[] param = Request.BinaryRead(Request.ContentLength);
        string strRequest = Encoding.ASCII.GetString(param);

        StringBuilder sb = new StringBuilder();
        sb.Append(strRequest);

        foreach (string key in formVals.Keys)
        {
            sb.AppendFormat("&{0}={1}", key, formVals[key]);
        }
        strRequest += sb.ToString();
        req.ContentLength = strRequest.Length;

        //for proxy
        //WebProxy proxy = new WebProxy(new Uri("http://urlort#");
        //req.Proxy = proxy;
        //Send the request to PayPal and get the response
        string response = "";
        using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
        {

            streamOut.Write(strRequest);
            streamOut.Close();
            using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
            {
                response = streamIn.ReadToEnd();
            }
        }

        return response;
    }

    public ActionResult IPN()
    {

        var formVals = new Dictionary<string, string>();
        formVals.Add("cmd", "_notify-validate");

        string response = GetPayPalResponse(formVals, true);

        if (response == "VERIFIED")
        {

            string transactionID = Request["txn_id"];
            string sAmountPaid = Request["mc_gross"];
            string orderID = Request["custom"];
            string pay_Status = Request["payment_status"];

            //_logger.Info("IPN Verified for order " + orderID);

            //validate the order
            Decimal amountPaid = 0;
            Decimal.TryParse(sAmountPaid, out amountPaid);

            //Order order = _orderService.GetOrder(new Guid(orderID));
            Tbl_Order order = null;
            //check the amount paid

            if (AmountPaidIsValid(order, amountPaid))
            {

                Tbl_Order add = new Tbl_Order();
                add.Username = User.Identity.Name;
                //add.FirstName = Request["first_name"];
                //add.LastName = Request["last_name"];
                //add.Email = Request["payer_email"];
                //add.Address = Request["address_street"];
                //add.City = Request["address_city"];
                //add.State = Request["address_state"];
                //add.Country = Request["address_country"];
                //add.PostalCode = Request["address_zip"];
                add.TransactionId = transactionID;
                add.Status = pay_Status;
                add.CartTotal = Convert.ToDecimal(sAmountPaid);

                //process it
                try
                {
                    _OrderContext.OrderEntries.Add(add);
                    _OrderContext.SaveChanges();
                    //_pipeline.AcceptPalPayment(order, transactionID, amountPaid);
                    //_logger.Info("IPN Order successfully transacted: " + orderID);
                    //return RedirectToAction("Receipt", "Order", new { id = order.ID });
                }
                catch
                {
                    //HandleProcessingError(order, x);
                    return View();
                }
            }
            else
            {
                //let fail - this is the IPN so there is no viewer
            }
        }

        return View();
    }
    bool AmountPaidIsValid(Tbl_Order order, decimal amountPaid)
    {

        //pull the order
        bool result = true;

        if (order != null)
        {
            if (order.CartTotal > amountPaid)
            {
                //_logger.Warn("Invalid order amount to PDT/IPN: " + order.ID + "; Actual: " + amountPaid.ToString("C") + "; Should be: " + order.Total.ToString("C") + "user IP is " + Request.UserHostAddress);
                result = false;
            }
        }
        else
        {
            //_logger.Warn("Invalid order ID passed to PDT/IPN; user IP is " + Request.UserHostAddress);
        }
        return result;

    }

}

public class Address
{
    public string FirstName { set; get; }
    public string LastName { set; get; }
    public string Email { set; get; }
    public string Street1 { set; get; }
    public string City { set; get; }
    public string StateOrProvince { set; get; }
    public string Country { set; get; }
    public string Zip { set; get; }

}"

and
following the web.config file configuration
  <add key="BusinessAccount" value="anilcs_1361585097_biz@gmail.com" />
    <add key="useSendbox" value="true" />
    <add key="currencycode" value="USD" />
    <add key="ReturnURL" value="http://localhost:49424/Checkout/IPN" />
    <add key="CancelUrl" value="http://localhost:49424/SportsStore/CancelFromPaypal" />
    <add key="NotifyURL" value="http://localhost:49424/SportsStore/NotifyFromPaypal" />

    <add key =" MerchantAccountID" value="RCERFF5KTC784"/>

This is my cart
@model SportsStore.Models.Paypal
@{
    Layout = null;
}

<title>Index</title>

<form id="frm" action="@ViewBag.Actionurl">

@Html.HiddenFor(Model => Model.cmd)
@Html.HiddenFor(Model => Model.business)
@Html.HiddenFor(Model => Model.no_shipping)
@Html.HiddenFor(Model => Model.@return)
@Html.HiddenFor(Model => Model.cancel_return)
@Html.HiddenFor(Model => Model.notify_url)
@Html.HiddenFor(Model => Model.currency_code)
@Html.HiddenFor(Model => Model.item_Name)
@Html.HiddenFor(Model => Model.amount)

</form>

        Redirecting to Paypal

after that i will filled up the shipping details  and my page redirect to paypal
{
@model SportsStore.Models.CheckoutViewModel
@{
    ViewBag.Title = "Address And Payment";
}

@using (Html.BeginForm("AddressAndPayment", "Checkout"))
{

                    @Html.LabelFor(m => m.Tbl_Order.OrderId, "OrderId")

                    @Html.TextBoxFor(m => m.Tbl_Order.OrderId, new { disabled = "disabled", @readonly = "readonly" })

                    @Html.LabelFor(m => m.Tbl_Order.OrderDate, "OrderDate")

                    @Html.EditorFor(m => m.Tbl_Order.OrderDate, "OrderDate")
                    @Html.EditorFor(m => m.CartItems, "CartItems")

                    @Html.LabelFor(m => m.Tbl_Order.FirstName, "First Name")

                    @Html.EditorFor(m => m.Tbl_Order.FirstName, "First Name")

                    @Html.LabelFor(m => m.Tbl_Order.LastName, "Last Name")

                    @Html.EditorFor(m => m.Tbl_Order.LastName, "Last Name")

                    @Html.LabelFor(m => m.Tbl_Order.Address, "Address")

                    @Html.EditorFor(m => m.Tbl_Order.Address, "Address")

                    @Html.LabelFor(m => m.Tbl_Order.City, "City")

                    @Html.EditorFor(m => m.Tbl_Order.City, "City")

                    @Html.LabelFor(m => m.Tbl_Order.State, "State")

                    @Html.EditorFor(m => m.Tbl_Order.State, "State")

                    @Html.LabelFor(m => m.Tbl_Order.PostalCode, "PostalCode")

                    @Html.EditorFor(m => m.Tbl_Order.PostalCode, "PostalCode")

                    @Html.LabelFor(m => m.Tbl_Order.Country, "Country")

                    @Html.EditorFor(m => m.Tbl_Order.Country, "Country")

                    @Html.LabelFor(m => m.Tbl_Order.Phone, "Phone")

                    @Html.EditorFor(m => m.Tbl_Order.Phone, "Phone")

                    @Html.LabelFor(m => m.Tbl_Order.Email, "Email")

                    @Html.EditorFor(m => m.Tbl_Order.Email, "Email")

                    @Html.LabelFor(m => m.CartTotal, "Total")

                    @*   @Html.EditorFor(m => m.CartTotal, "Total" ) *@ @*  @Html.TextBoxFor(m => m.CartTotal, new { disabled = "disabled", @readonly = "readonly" })*@
                    @* @Html.DisplayTextFor(m => m.CartTotal)*@
                    @Html.TextBoxFor(m => m.CartTotal, new { @readonly = "readonly" })

                Continoue with paypal

                    @* @Html.ActionLink("Sure to payment", "PosttoPaypalShow", "Checkout")*@
                    <input type="submit" value="Submit" />

}

1 Question - this is proper way which i have done ?
2 Question - how to return custom value from Paypal
3 and also see the web.config file after the payment should i called the PIN ?
Please guide me ...... and how to do payment process

A: I was looking for information on this recently as well. There is sample code on the paypal site, but I find it quite terse and it is hard to put it into context in your application. The best that I could find is the video and sample by Rob Conery.
First, look at the video. It is called "ASP.NET MVC Storefront Part 1: Architectural Discussion and Overview". Currently it can be found here. Skip ahead to 15:21 to get to the paypal part.
Then download the source code. You are looking for 'ASP.NET MVC Storefront sample code which can currently be found here.
Once you have extracted the code, search for IPN() for IPN method and PDT() for PDT method.


text:
Q: Getting Garbage Output Java I'm trying to implement a constructor in Java and I don't know if I'm doing something wrong, but I keep getting garbage outputs.
This is the variable I'm trying to assign values to:
private static Employee employee;

This is how I'm trying to assign it:
employee = new Employee(empType, empFName, empLName, empBDate, empGender, empHireDate, empReleaseDate, empBaseSalary);

And here is the class and constructor:
public class Employee {

    private String Type;
    private String FName;
    private String LName;
    private Date BDate;
    private String Gender;
    private Date HireDate;
    private Date ReleaseDate;
    private double BaseSalary;

    public Employee(String type, String fname, String lname, String bdate, String gender, String hire, String release, double salary){

        this.Type = type;
        this.FName = fname.toUpperCase();
        this.LName = lname.toUpperCase();
        this.BDate = new Date(bdate);
        this.Gender = gender;
        this.HireDate = new Date(hire);
        if (release == "null"){
            this.ReleaseDate = null;
        }
        else if(release != "null"){
            this.ReleaseDate = new Date(release);
        }
        this.BaseSalary = salary;

    }

}

When I try to print, just to test it, this is how I'm printing it:
System.out.println(employee);

And this is what I get every time:
Employee@4c264dd8

Could someone tell me what i'm doing wrong?

A: Java doesn't know anything about how you want an object printed unless you tell it what to do by implementing toString(). If you don't, it will default to Object.toString() to get a string representation of your object. Object.toString() returns
getClass().getName() + '@' + Integer.toHexString(hashCode())

which explains the output you're seeing.

A: If you print Object in Java ,it will print class Name with Hexadecimal value.
If you want your own thing you have to override toString().
public void toString()
{
   //print here  this.Type +":"+   this.FName  for fields you want.
}

A: Every Java Object comes with a toString() method. You will have to override it to get the desired output.I believe hashCode of the object (memory address) is being printed!

A: From the Object.toString() docs:

Returns a string representation of the object. In general, the
  toString method returns a string that "textually represents" this
  object. The result should be a concise but informative representation
  that is easy for a person to read. It is recommended that all
  subclasses override this method.
The toString method for class Object returns a string consisting of
  the name of the class of which the object is an instance, the at-sign
  character `@', and the unsigned hexadecimal representation of the hash
  code of the object. In other words, this method returns a string equal
  to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Therefore, you must provide your own toString method by doing this:
@Override

public void toString(){ return myString; }


text:
Q: AngularJS templates not loading correctly I recently started learning web development basics by myself, and at the moment, I try to start with AngularJS. But unfortunately my first project won't work out. I tried to fix it by myself, but I can't find the problem. In my opinion, I simply failed to include or import the Angular code in the right way.
My Problem: Instead of computing the results of the angular script app.js, it shows: {{ here should be Angular related stuff }}
I hope you may help me with my annoying debugging problem. I also would love to hear other feedback about my first code and which things are useless or what else I need to do or to think about.
Thank you very much for your help and time.
my folder tree:

*

*App

*

*app.js

*bower_components

*

*angular

*bootstrap

*d3

*jquery

*css

*

*style.css

*js

*

*index.js

*node_modules

*bower.json

*index.html

// Define the `SmartIndustryInterfaceApp` module
var smartIndustryInterface = angular.module('SmartIndustryInterface', []);

smartIndustryInterface.controller('WaelzlagerListController',
    function WaelzlagerListController($scope) {
        $scope.WaelzlagerList[
    {
      name: 'Nexus S',
      snippet: 'Fast just got faster with Nexus S.'
    }, {
      name: 'Motorola XOOM™ with Wi-Fi',
      snippet: 'The Next, Next Generation tablet.'
    }, {
      name: 'MOTOROLA XOOM™',
      snippet: 'The Next, Next Generation tablet.'
    }
  ];
});

        <title>Smart Industry Interface</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />

        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.css">
        <link rel="stylesheet" href="../css/style.css">

Dieser Text wird noch geladen... ... ... ...

                {{waelzlager.name}}

{{waelzlager.snippet}}

 {{firstName + "" + lastName}}

A: The main issues are:
1 - wrong character § when it should be $.
§scope.firstName = "John";
should be
$scope.firstName = "John";
2 - Missing equal sign in $scope.WaelzlagerList = [...]
I cleaned up the code a bit by moving the inlined controller to together with the first one.

// Define the SmartIndustryInterfaceApp module
var smartIndustryInterface = angular.module('SmartIndustryInterface', []);

smartIndustryInterface.controller('WaelzlagerListController',
    function ($scope) {
        $scope.WaelzlagerList = [
    {
      name: 'Nexus S',
      snippet: 'Fast just got faster with Nexus S.'
    }, {
      name: 'Motorola XOOM with Wi-Fi',
      snippet: 'The Next, Next Generation tablet.'
    }, {
      name: 'MOTOROLA XOOM',
      snippet: 'The Next, Next Generation tablet.'
    }
  ];
});
smartIndustryInterface.controller("testing", function($scope) {
                    $scope.firstName = "John";
                    $scope.lastName = "Doe";
                 });

//angular.element(document).ready(function () {
//    angular.bootstrap(document, ['SmartIndustryInterface']);
//});

        <title>Smart Industry Interface</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />

        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.css">
        <link rel="stylesheet" href="../css/style.css">

Dieser Text wird noch geladen...

                {{waelzlager.name}}

{{waelzlager.snippet}}

{{firstName + ' ' + lastName}}

A: A couple of things so far:
The array of objects is badly defined:
        $scope.WaelzlagerList = [
    {
      name: 'Nexus S',
      snippet: 'Fast just got faster with Nexus S.'
    }, {
      name: 'Motorola XOOM™ with Wi-Fi',
      snippet: 'The Next, Next Generation tablet.'
    }, {
      name: 'MOTOROLA XOOM™',
      snippet: 'The Next, Next Generation tablet.'
    }
  ];

And then the Inline JS has a dodgy char in it:
**§**scope.firstName = "John";

You perhaps need to ask yourself why this needs to be inline, it will make testing harder for you. There are other issues, but those are the two to kick off with. There seems to be a load order issue with the "testing" controller too. See if that helps.
Add plunkr, thanks VRPF:
plunkit


text:
Q: What type of number is x? Problem. Let $\left \{ a_{n} \right \}_{n\in \mathbb{N}}$ be a sequence where $a_{n}\in \mathbb{N}$, $a_{n}<a_{n+1}$, $a_{n+1}\leqslant 10\cdot a_{n}$ for $\forall n\in \mathbb{N}$. What type of number is $x=0.a_{1}a_{2}a_{3}...a_{n}...$ (concatenation)? (I.e. rational or irrational)
Example: $a_{1}=1, a_{2}=10, a_{3}=100, ... a_{n}=10^{n-1}$ and $x=0.110100...10000...$

A: I assume $x=0.a_1 a_2 a_3...a_n...$ just means to concatenate all the $\{a_{n}\}$ to form the decimal expansion of $x$.  So the number could be $$0.123456789101112...\qquad(a_{n+1}=a_{n}+1),$$ or $$0.110100100010000...\qquad(a_{n+1}=10a_{n}),$$or whatever.  What it can't be is ultimately periodic.
Let $l_{i}$ be the length (in digits) of $a_{i}$.  Since $a_{n+1}>a_{n}$, we have $a_{n}\rightarrow\infty$ and hence $l_{n}\rightarrow\infty$; and since $a_{n+1}\le 10a_{n}$, we have $l_{n+1}\le l_{n}+1$.  In other words, the sequence of lengths $\{l_n\}$ grows indefinitely without skipping any values. Now suppose $x$ is periodic with period $P$ after the $N$-th digit.  Then there must be some $M\ge N+1$ for which $l_{M}$ is a multiple of (say, $k$ times) the periodicity $P$.  Hence, $a_M$ falls in the periodic portion of $x$ (since it starts at digit $(\sum_{i=1}^{M-1}l_i) \ge M-1 \ge N$ after the decimal point), and it covers exactly $k$ repeats of the periodic substring.  Now, the next $l_{M+1}$ digits of $x$, either $kP$ or $kP+1$, must coincide with $a_{M+1}$.  But neither of these cases is possible: the next $kP$ digits are just $a_{M}$ again, and we know that $a_{M+1}>a_{M}$; while the next $kP+1$ digits are $a_{M}$ with a single nonzero digit (the first digit of $a_{M}$) appended, i.e., a number that is strictly greater than $10a_{M}$, and we know that $a_{M+1}\le 10a_{M}$.
We've shown that $x$ can't be ultimately periodic, and hence it must be irrational.


text:
Q: Calibre on Ubuntu 18.04 installed in wrong language I have installed Calibre via Apps and a momentary lapse means it is now running in Chinese. Removed it, restart, reinstall, no change. Removed it via GUI, then tried in terminal
ls /opt/calibre

and message file or directory not found.
Do I need reinstall it, but then use instead
rm -fr /opt/calibre

And after reinstalling use this line from site https://calibre-ebook.com/download_linux
sudo -v && wget -nv -O- https://download.calibre-ebook.com/linux-installer.sh | sudo sh /dev/stdin

I am worried about potential incompatibilities.
Thanks for your help!

A: Check out this file - it's a configuration file for Calibre:
/home/[username]/.config/calibre/global.py.json

Look for "language" string and change it to "en". Example of my config:
"isbndb_com_key": "",
"language": "en",
"library_path": "/home/mp/1/ebooks/calibre",

A: Thanks for your suggestion, Michal. I edited the file in a text editor and changing language to "en" did the trick!


text:
Q: Baby Step Giant Step Algorithm for Discrete Log: Incorrect Giant Step So I am trying to implement the Baby Step Giant Step algorithm to calculate discrete logs. Below is my code:
# trying to solve 8576 = 3^x (mod 53047)
p = 53047
a = 3
B = 8576

m = int(math.ceil(math.sqrt(p-1)))

baby = []
giant = []
for j in range(0,m-1):
    baby.append((a**j)%p)

for k in range(0,m-1):
    val = a**(-1)%p
    val2 = val**(k*m)%p
    giant.append((B*val2)%p)
    for i in xrange(len(baby)):
        if giant[k] == baby[k]:
            x = j + m*k

I think there is something incorrect with my giant step because I am getting very tiny values as outputs and no matches. The correct answer is  x = 1234. Can someone tell me what I am doing wrong?

A: Modular inverses are not computed by taking real number inverses and then taking the modulus of the result. To find the multiplicative inverse of a mod p -- you need to find an integer b with ab = 1 (mod p). This can be done either by using the Extended Euclidean Algorithm or (as a shortcut) by using Fermat's Little Theorem:
a**(p-1) = 1 (mod p)

This implies that a**(p-2) (mod p) is the inverse of a.

A: # trying to solve 8576 = 3^x (mod 53047)
p = 53047
a = 3
B = 8576

P should be always >B how could (a^x mod P = B and B > P) take a look a again on it
best luck


text:
Q: Instagram API count limits using HTTP header According to Instagram you can check API limit count remaining using the HTTP headers that they supply with the call. I am quite new to this and am unable to find relevant data on how to access this information with PHP. Could anyone please clarify this for me?
I found the following from the Instagram API developers forum on Google Groups:

"We just rolled this out to production; all API calls now have the
  additional HTTP headers:

*

*X-Ratelimit-Limit (total # of possible calls per hour)

*X-Ratelimit-Remaining (how many calls are left for this particular token or client ID)"

A: If you're using file_get_contents to make the request (or anything that uses the HTTP wrapper for that matter), the special variable $http_response_header contains an array of lines with the HTTP response headers of the most recent request.
Maybe something like this:
// Make your API request here
...
file_get_contents('http://example.com', false, $context);

// Check HTTP response headers
foreach ($http_response_header as $line) {
    if(preg_match('!X-Ratelimit-Remaining: ([0-9]+)!i', $line, $matches)) {
        $remaining = $matches[1];
        break;
    }
}

// Do something based on the number of remaining attempts
echo "Remaining attempts: $remaining";


text:
Q: Covering map of a Torus How would I draw (describe) a covering map given by

*

*$T^{2}\#T^{2}\#T^{2}\#T^{2}\#T^{2}\#T^{2}\ \rightarrow T^{2}\#T^{2}$

*$T^{2}\#T^{2}\#T^{2}\#T^{2}\rightarrow T^{2}\#T^{2}$

and what would be the degree of this covering? I know the surfaces are orientable of genus $g$ and can be constructed from a polygon with $4g$ sides, and they become a union of $2g$ circles in the surface, so I guess that union would be a covering map and its degree would be the $g$.
Could somebody help with it?
Thanks

A: Imagine a closed chain of tori (that is, torus $i$ is connected-summed to tori $i+1$ and $i-1$ mod $2k.$) That is a (cyclic) $k$-fold cover of a double torus (surface of genus $2.$).

A: The first figure correspond to a 7 degree cover of the double torus, and the second one to a 4 degree cover!


text:
Q: issues with preg_match PHP I have a string:
$str="(94896)content is here(/94896)(94897)content is here(/94897)(94898)content is here(/94898)(94899)content is here(/94899)";

the (number) and (/number) act as tags to take certain content out of the string.
and I have a preg_match to take the content out:
if(preg_match('/(94896)\"(.*)\"(\/94896)/',$str,$c)) {echo "I found the content, its:".$co[1];}

Now for some reason, it doesn't find a match in the string ($str), though its clearly there....
Any ideas on what im doing wrong here?

A: You need to take the double-quotes out of your regex string, since they don't appear in $str, but are expected by the regex.
'/(94896)\"(.*)\"(\/94896)/'
//       ^^    ^^
//        These aren't in the string.

EDIT: I think you'll also need to escape your brackets, since they will be getting read as grouping operators, not actual brackets.
Your expression should be:
'/\(94896\)(.*)\(\/94896\)/'

A: Parentheses are used in a regex to denote subpatterns. If you want to search these characters in a string, you must escape them:
preg_match('/\(94896\)(.*)\(\/94896\)/',$str,$c)

If the pattern is found:
echo "I found the content, its:".$c[0];

Oh, and as Karl Nicoll says, why are the quotations in your pattern?

A: To match all content:
$str="(94896)content is here(/94896)(94897)content is here(/94897)(94898)content is here(/94898)(94899)content is here(/94899)";

$re = '/\((\d+)\)(.*)\(\/\1\)/';
preg_match_all($re, $str, $matches,PREG_SET_ORDER);
var_dump($matches);

Number will be in $matches[*][1], content in $matches[*][2].


text:
Q: How can I safely change listeners? I have an application where I need to change font sizes frequently.  A question posted a year ago on this forum (Change just the font size in SWT) gave me some of the information I needed, but I've still got some unknowns I haven't figured out yet.
In particular, someone signing as hudsonb offered a helpful code fragment which I'd like to reproduce below:
FontData[] fontData = label.getFont().getFontData();
for(int i = 0; i < fontData.length; ++i)
    fontData[i].setHeight(14);

final Font newFont = new Font(display, fontData);
label.setFont(newFont);

// Since you created the font, you must dispose it
label.addDisposeListener(new DisposeListener() {
    public void widgetDisposed(DisposeEvent e) {
        newFont.dispose(image);
    }
});

Suppose I used code like this to change font sizes frequently.  Aren't I creating a whole sequence of DisposeListeners, and adding them to the label's listener queue?  Don't I need to remove the previous listener each time before adding a new listener?  Or is there some mechanism I don't understand that makes this unnecessary?

A: You probably should remove the old listeners. Do this with:
private DisposeListener listener = null;
//...
if (listener != null)
    label.removeDisposeListener(listener);
listener = new DisposeListener() {
    public void widgetDisposed(DisposeEvent e) {
        newFont.dispose(image);
    }
}
label.addDisposeListener(listener);

A: An alternative would be to add a DisposeListener that maintains a list of Fonts it needs to dispose of when finished with, e.g.
class FontDisposer implements DisposeListener {
    private List<Font> toDispose;

    public FontDisposer() {
        toDispose = new ArrayList<Font>();
    }

    @Override
    public void widgetDisposed(DisposeEvent e) {
            // Dispose all fonts in toDispose
    }

    public void registerFont(Font f) {
        toDispose.add(f);
    }
}

class UIWotsit extends SomeUIClass {
    private FontDisposer disposer;

    public UIWotsit() {
        disposer = new FontDisposer();
        addDisposeListener(disposer);
    }

    public void changeFont(Font f) {
        disposer.registerFont(f);
        // Do all the font changing stuff
    }
}

This may not suit your particular application but having something that maintains a list of Fonts is probably a reasonable start. You could also use an anonymous DisposeListener that calls a method in whatever code manages the Font creation/changing/disposal:
class OtherFontDisposer implements DisposeListener {
    @Override
    public void widgetDisposed(DisposeEvent e) {
        myCleverFontManager.disposeOfAll();
    }
}

It all depends on whether you are creating new labels or not, and whether you want to dispose of Fonts immediately or only when the UI is disposed of.

A: If you change your font size often, you'll probably also change back to sizes, that you've already used. So you might want to cache your Font instances. To do so, you can use the FontRegistry from JFace (JavaDoc) instead of a list. You won't need to dispose the Fonts, as this is done by the registry when your Display is disposed.
You still have to put your FontData into the registry if it doesn't contain the size you need yet.


text:
Q: post back selected radio button in adaptive card in .NET I am using .NET SDK for adaptive cards which is having radio buttons and submit action.
I want to get selected radio button as post back question like imBack in Herocards.
Is there any way to get button selected value as post back question in adaptive cards?


text:
Q: NodeJs Upload csv string content to s3 I have tried to upload csv  content data to s3 but its some how not working
Below My code to store csv data into csv.gz file
var filename= "ff1.csv.gz"
var csvData = "username,email,year,month\n"
csvData = csvData + username +","+email+","+year_data+","+month_data+"\n"

var paramsu = {
    Bucket: bucket1,
    Key: filename,
    Body: csvData,
    ContentType: 'application/octet-stream'

  };

var res = await s3.putObject(paramsu).promise();

It is showing  corrupted gzfile not able to extract
Any help would really save my day

A: if you don't have the file ready, you can create a writestream and use it to pass to s3 sdk.
The question is answered here https://stackoverflow.com/a/50291380/2688699

A: WE can Upload IMAGE/ CSV/ EXCEL files to AWS s3 using multer-s3.
Im using .single(fieldname) method for uploading single file.
const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');

const s3 = new aws.S3({
  accessKeyId: process.env.AWS_ACCESS_KEY,
    secretAccessKey: process.env.AWS_SECRET_KEY,
    region: process.env.REGION,
});

 const upload = multer({
   storage: multerS3({
     s3: s3,
     bucket: process.env.AWS_S3_BUCKET,
     metadata: function (req, file, cb) {
       cb(null, {fieldName: 'Meta_Data'});
     },
     key: function (req, file, cb) {
      cb(null, file.originalname);
     },
     limits: {
        fileSize: 1024 * 1024 * 5 //  allowed only 5 MB files
    }
   })
 }).single('file');

exports.uploadfile = async(req,res,next)=>{
   try{
         upload(req,res, function(err){
             if(err){
                 console.log(err);
             }
             console.log(req.file.location);
   })
})
}catch (err){
   res.status(400).json({
       status : 'fail',
       message : err.message
   });
}
}

In Routes file
router.route('/')
      .post(imageController.uploadfile);


text:
Q: Stuck in an infinite loop in a function I'm stuck in an infinite loop in this function:
let rec showGoatDoorSupport(userChoice, otherGuess, aGame) =
    if( (userChoice != otherGuess) && (List.nth aGame otherGuess == "goat") ) then otherGuess
    else showGoatDoorSupport(userChoice, (Random.int 3), aGame);;

And here's how I'm calling the function:
showGoatDoorSupport(1, 2, ["goat"; "goat"; "car"]);

In the first condition in the function, I compare the first 2 input parameters (1 and 2) if the are different, and if the item in the list at index "otherGuess" is not equal to "goat", I want to return that otherGuess.
Otherwise, I want to run the function again with a random number between 0-2 as the second input parameter.
The point is to keep trying to run the function until the second parameter doesnt equal the first, and that slot in the List isn't "goat", then return that slot number.

A: Don't use ==, it checks for physical equality.  Use =.  Two different strings will never be physically equal, even if they contain the same sequence of characters.  (This is necessary, because strings are mutable in OCaml.)
$ ocaml
        OCaml version 4.00.0

# "abc" == "abc";;
- : bool = false
# "abc" = "abc";;
- : bool = true

A: Another to do that is to use the String.compare. An example:
 if String.compare str1 str2 = 0 then (* case equal *)
 else (* case not equal *)


text:
Q: How much functional programming expertise can programmers be expected to have? I'm coding in a non-functional language with functional mechanisms (C# to be specific, but you could substitute, say C++ and use function pointers, or what have you) on a small team.  It's my habit to use functional techniques -- passing delegates (objects representing functions) as arguments, using closures, occasional anonymous functions, etc -- and I try to document this better than I think a reasonable programmer would need them documented.  Looking at code I see online and on Stack Exchange communities, I think my style is pretty normal among C# developers.
Our team, however, isn't sophisticated in these techniques and I end up having to explain (and defend) myself -- my high level of documentation is actually used as evidence by them that I shouldn't code the way I do for the sake of readability.
Now, given the make-up of my team, I understand that I might just give up the good fight here and code to their standards, understanding its better for the team.  Does anyone have successful experience using empirical studies, accreditation criteria or best practices lists published by respectable sources that suggest that programmers today have more experience in these functional programming idioms, and that, therefore, we don't need to shy away from them for purposes of maintainability?

A: In C#, functional programming is a proper tool when you have to navigate through collections. In those cases, functional programming makes the code much shorter and helps focusing on the problem instead of its implementation, while reducing the risk of making mistakes.
You can hardly be accountable of reducing the codebase and the margin for errors by using a proper tool.
The issue you have with your colleagues, I have it in the company I'm currently working in. Most programmers there don't know very well neither C#, nor programming in general, which makes me a not so popular person, given that my colleagues have a hard time understanding the code which uses parallel programming, functional paradigms, code contracts and other features of .NET Framework.
One of the rules each developer should follow is that their code should be understandable in a given context. This conflicts with the fact that one shouldn't be forced to reduce code quality just because he works with unskilled people.
There are two solutions:

*

*Teach your colleagues functional programming and other things you know and they don't, trying to increase their level at yours. This is what I've chosen in my case and what I would suggest to anyone.
Pros: the quality of the codebase will only increase, and you may appreciate better to work with more skilled colleagues.
Cons: many programmers don't want to learn things. They work for money, and they don't care about their work. Trying to teach them anything would be an extremely difficult task and one should be ready to receive heavy resistance.

*Start writing crappy code written for beginners. Given that this may be disastrous for the motivation, this solution should be taken only when working with people who are unable and/or unwilling to learn and in a circumstance when you can quit soon.
Pros: this can enhance relations with coworkers if they don't want to learn things and don't want to make effort reading your code.
Cons: this will decrease the quality of the codebase. Working on badly done projects which would inevitably fail is not very motivating.
Finally, should programmers know functional programming? It depends. It would be mandatory for any person who works daily with C# to know what are anonymous types and lambda expressions and how to use them in C#; on the other hand, I wouldn't say that the same person who don't know what a monad is should be treated as an incompetent.
The difference is that anonymous types and lambda expressions are the inherent part of C# nowadays, while the term monad doesn't exist in C# world.
On the other hand, I'm expecting a developer to be familiar to functional programming concepts like monads, even if this developer never used them. This is because developers are expected not only to write code in a given language, but have enough general culture and curiosity beyond the tools they use daily.

A: I would expect any professional C# or web developer in 2013 to be familiar with anonymous functions, closure basics, and the concept of passing methods around. .NET 3.5 has been out for years now, and should be pervasive.
I would expect most professional developers (of any sort) to understand other tangential concepts to functional programming like immutability and pure functions, and how these apply to program design. These concepts too have been around in mainstream programming for ages (and more prevalently in the past 5 or so).
That said, I would not be surprised if more than half of applicable professional developers were completely oblivious to these concepts - and you are largely correct that you should conform to what is best for the team, just like they're largely correct that high levels of documentation is a smell towards unreadable code.
So conform for now and work at training people up, likely through some combination of explicit training and gradual use of more complicated functional structures (where appropriate).


text:
Q: React useEffect renders change on 2nd click? I have a NavBar component and I want certain items on the NavBar to be left off when one of the other selections is chosen.
It works somewhat. The problem is that the elements that should disappear require a second click.
I want them to disappear from the menu selections with the first click.
I am missing something with useEffect. Am I trying to do something that is a little more complex than my solution is attempting?
Snippet is not working properly

const { React, ReactDOM, PropTypes, w3color } = window
const { useEffect, useState, useRef } = React
const { render } = ReactDOM
import { NavLink } from 'react-router-dom'
const rootNode = document.getElementById('app')

const NavBar = (props) => {
const [menustatus, changeMenusStatus] = useState(null)

const changeContext = async (input) => {
    // console.log(input)
    changeMenusStatus(input)
  }

return (
    <>

<ReactLogo />Base React App for Testing Development

        <NavLink className="navitem" to="/">Home</NavLink>
        <NavLink className="navitem" to="/select1">Selection 1</NavLink>
        <NavLink className="navitem" to="/select2">Selection 2</NavLink>
          {menustatus !==  'restrict' && (
            <>
            <NavLink className="navitem" to="/select3">Selection 3</NavLink>
            <NavLink className="navitem" to="/select4">Selection 4</NavLink>
            </>
            )
          }

        <NavLink className="navitem" to="/restrict" onClick={() => changeContext('restrict')}>RESTRICT</NavLink>
        <NavLink className="navitem" to="/about">About</NavLink>

    </>
  );
}

const App = () => {

    <NavBar />

}

render(<App />, rootNode);

The Problem:
The issue is that it takes 2 clicks for the NavBar to re-render without the excluded items. I want the excluded items not to appear when the selected link navigates to the proper page.
NavBar.jsx
import React, { useState, useEffect } from 'react'
import { NavLink } from 'react-router-dom'
import './Nav.css'
import ReactLogo from '../ReactLogo/ReactLogo'
const Nav = (props) => {
  const [menustatus, changeMenusStatus] = useState(null)
  const NavContext = React.createContext("")
  console.log(`[Nav context] = ${props.navcontext}`)

  const changeContext = async (input) => {
    console.log(input)
    changeMenusStatus(input)
  }

  useEffect(() => {
    if (menustatus) {
      console.log(menustatus)
    } else {
      console.log(`menustatus not set.`)
    }
  }, [menustatus]);

  return (
    <>

<ReactLogo />Base React App for Testing Development

    <NavContext.Provider value={menustatus}>

        <NavLink className="navitem" to="/">Home</NavLink>
        <NavLink className="navitem" to="/select1">Selection 1</NavLink>
        <NavLink className="navitem" to="/select2">Selection 2</NavLink>
        <NavContext.Consumer>
          {(context) =>
            (context ==='restrict') ? null
            :
            <>
            <NavLink className="navitem" to="/select3">Selection 3</NavLink>
            <NavLink className="navitem" to="/select4">Selection 4</NavLink>
            </>
          }
        </NavContext.Consumer>
        <NavLink className="navitem" to="/restrict" onClick={() => changeContext('restrict')}>RESTRICT</NavLink>
        <NavLink className="navitem" to="/about">About</NavLink>

    </NavContext.Provider>
    </>
  );
}

export default Nav;

App.js
import React, { Component } from 'react';
import { Routes, Route } from 'react-router-dom';
import './App.css';

import Home from './screens/Home/Home'
import About from './screens/About/About';
import ScreenOne from './screens/ScreenOne/ScreenOne'
import ScreenTwo from './screens/ScreenTwo/ScreenTwo'
import ScreenThree from './screens/ScreenThree/ScreenThree'
import ScreenFour from './screens/ScreenFour/ScreenFour'
import ScreenFive from './screens/ScreenFive/ScreenFive'
import PersonList from './components/PersonList/PersonList'

class App extends Component {
  state = {people: []}
  render() {
    return (

        <Routes>
          <Route path="/" element={<Home navcontext="one" />} />
          <Route path="/about" element={<About navcontext="one" />} />
          <Route path="/select1" element={<ScreenOne navcontext="one" />} />
          <Route path="/select2" element={<ScreenTwo navcontext="two" />} />
          <Route path="/select3" element={<ScreenThree navcontext="three" />} />
          <Route path="/select4" element={<ScreenFour navcontext="four" />} />
          <Route path="/restrict" element={<ScreenFive navcontext="restrict" />} />
        </Routes>
        <PersonList people={this.state.people} />

    );
  }
}

export default App;

A: I think the issue is that you are declaring the NavContext context each render cycle inside the Nav component. If you need to use a React Context then be sure to declare it outside any React component.
I don't see the point in using a React Context here though when you can just conditionally render the menu items on the menustatus state locally.
Example:
const Nav = (props) => {
  const [menustatus, changeMenusStatus] = useState(null);

  const changeContext = (input) => {
    console.log(input);
    changeMenusStatus(input);
  };

  useEffect(() => {
    if (menustatus) {
      console.log(menustatus);
    } else {
      console.log(`menustatus not set.`);
    }
  }, [menustatus]);

  return (
    <>

        <ReactLogo />
        Base React App for Testing Development

        <NavLink className="navitem" to="/">Home</NavLink>
        <NavLink className="navitem" to="/select1">Selection 1</NavLink>
        <NavLink className="navitem" to="/select2">Selection 2</NavLink>
        {menustatus !== 'restrict' && (
          <>
            <NavLink className="navitem" to="/select3">Selection 3</NavLink>
            <NavLink className="navitem" to="/select4">Selection 4</NavLink>
          </>
        )}
        <NavLink className="navitem" to="/restrict" onClick={() => changeContext('restrict')}>RESTRICT</NavLink>
        <NavLink className="navitem" to="/about">About</NavLink>

    </>
  );
}


text:
Q: $G$ is non abelian simple group of order $<100$ then $G\cong A_5$ Question is to Prove that :
$G$ is non abelian simple group of order $<100$ then $G\cong A_5$
Hint is to "Eliminate all orders but $60$". Which i think is not so easy to check.
First of all, I eliminate all Primes (cyclic groups)  $2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97.$ (including 1)
Only numbers i am left with are, $\{4,6,8,9,10,12,14,15,16,18,20,21,22,24,25,26,27,28,30,32,33,34,35,36,38,39,40,42,44,45,46,48,49,50,51,52,54,55,56,57,58,60,62,63,64,65,66,68,69,70,72,74,75,76,77,78,80,81,82,84,85,86,87,88,90,91,92,93,94,95,96,98,99\}$
Now, I eliminate all prime squares $p^2$ (which are abelian)
$4,9,16,25,36,49,64,81$
Only numbers i am left with are, $\{6,8,10,12,14,15,18,20,21,22,24,26,27,28,30,32,33,34,35,38,39,40,42,44,45,46,48,50,51,52,54,55,56,57,58,60,62,63,65,66,68,69,70,72,74,75,76,77,78,80,82,84,85,86,87,88,90,91,92,93,94,95,96,98,99\}$
Now i eliminate all prime powers $p^n$ (which have non trivial center hence not simple)
$2^3=8,2^5=32$ and $3^3=27$
Only numbers i am left with are, $\{6,10,12,14,15,18,20,21,22,24,26,28,30,33,34,35,38,39,40,42,44,45,46,48,50,51,52,54,55,56,57,58,60,62,63,65,66,68,69,70,72,74,75,76,77,78,80,82,84,85,86,87,88,90,91,92,93,94,95,96,98,99\}$
Now i eliminate all groups of order $pq$ where $p$ and $q$ are distinct (they have either normal sylow p or sylow q subgroup)
From 2 - $\{2p=6,10,14,22,26,34,38, 46,58,62,74,82,86,94\}$
Only numbers i am left with are, $\{12,15,18,20,21,24,28,30,33,35,39,40,42,44,45,48,50,51,52,54,55,56,57,60,63,65,66,68,69,70,72,75,76,77,78,80,84,85,87,88,90,91,92,93,95,96,98,99\}$
From 3 - $\{ 3p=15,21,33,39,51,57,69,87,93\}$
Only numbers i am left with are, $\{12,18,20,24,28,30,35,40,42,44,45,48,50,52,54,55,56,60,63,65,66,68,70,72,75,76,77,78,80,84,85,88,90,91,92,95,96,98,99\}$
From 5- $\{5p= 10,15,35,55,65,85,95\}$
Only numbers i am left with are, $\{12,18,20,24,28,30,40,42,44,45,48,50,52,54,56,60,63,66,68,70,72,75,76,77,78,80,84,88,90,91,92,96,98,99\}$
From 7 - $\{7p= 14,21,35,49,77,91,\}$
Only numbers i am left with are, $\{12,18,20,24,28,30,40,42,44,45,48,50,52,54,56,60,63,66,68,70,72,75,76,78,80,84,88,90,92,96,98,99\}$
Remaining products $pq$ repeats.
Now i eliminate all groups of order $p^2q$ (which are not simple as they have either normal sylow p or sylow q subgroup)
From 2 - $4p=\{ 8,12,20,28,44,52,68,76,92,\}$
Only numbers i am left with are, $\{18,24,30,40,42,45,48,50,54,56,60,63,66,70,72,75,78,80,84,88,90,96,98,99\}$
From 3 - $9p= \{ 18,27,45,63,99\}$
Only numbers i am left with are, $\{24,30,40,42,48,50,54,56,60,66,70,72,75,78,80,84,88,90,96,98,\}$
From 5 - $25p =\{50,75 \}$
Only numbers i am left with are, $\{24,30,40,42,48,54,56,60,66,70,72,78,80,84,88,90,96,98,\}$
From 7 - $49p= \{ 98\}$
Only numbers i am left with are, $\{24,30,40,42,48,54,56,60,66,70,72,78,80,84,88,90,96,\}$
Now i eliminate all groups of order $pqr$, p,q,r are distinct primes (which are not simple as they have either normal sylow p or sylow q subgroup or sylow r subgroup)
Only numbers we left with are $\{24,30,40,42,48,54,56,60,66,70,72,78,80,84,88,90,96\}$
$30=2.3.5$ So, $30$ Is eliminated
$42=2.3.7$ So, $42$ is eliminated
$66=2.3.11$ So, $66$ is eliminated
$70=2.5.7$ So, $70$ is eliminated
$78=2.3.13$ So, $78$ is eliminated
Only numbers we are left with are $\{ 24,40,48,54,56,60,72,80,84,88,90,96\}$
$\textbf{EDIT}$
Assuming $G$ is simple, $|G|=24$. as $24=2^3.3$ No. of sylow 3 subgroups $1+3k$ divides $8$.thus, no of sylow $3$ subgroups has to be $4$. Suppose $n_2=3$ each sylow 3 subgroup has 2 non identity elements totally 8 non identity elements. each sylow 2 subgrousp has 7 non identity elements as we can not assume sylow 2 subgroups intersection is non trivial,$\textbf{INCOMPLETE}$
Only numbers we are left with are $\{40,48,54,56,60,72,80,84,88,90,96\}$
$40=2^3.5$ no.of sylow 5 dubgroups $1+5k$ divides $8$ Thus,sylow 5 sbgroup is unique and hence group is not simple.
Only numbers we are left with are $\{48,54,56,60,72,80,84,88,90,96\}$
$48=2^4.3$ No. of sylow 3 subgroups $1+3k$ divides $16$ No. of sylow 2 subgroups $1+2k$ divides 3 suppose $n_2=3$ and $n_3=16$ Contribution from $P_3$(sylow 3 subgroup) is 45 and contribution from $P_2$ (sylow 2 subgroup) is 3 which adds up to 48 and with identity element we have 49 elements. Thus at least one of $n_3$ or $n_2$ is $1$ So, G is not simple.
Only numbers we are left with are $\{54,56,60,72,80,84,88,90,96\}$
$54=2.3^3$ No. of sylow 3 sbgroups, $1+3k$ divides $2$ Thus sylow 3 subgroup is normal and hence group is not simple.
Only numbers we are left with are $\{56,60,72,80,84,88,90,96\}$
$\textbf{EDIT}$ : Consider group $G$ of order $56$, for this we have $56=2^3.7$.
Assuming this being simple group we would end up with the case that $n_2=7,n_7=8$.
$n_p$ denotes no. of sylow p subgroups.
each sylow $7$ subgroup has $6$ non identity elements, totally there are $8\times 6=48$ non identity elements in all sylow $7$ subgroups.\
each sylow $2$ subgroup has $7$ non identity elements. As there is a possibility that intersection of two sylow $2$ subgroups to be non trivial, there would be one more (non identity) element different from these seven non identity elements, adding upto 8 non identity elements, with $1$ identity element and adding upto $1+8+48=57$ ($48$ elements from sylow $7$ subgroups) contradicting the cardinality of order of group $|G|=56$.
Thus, either $n_2=1$ or $n_7=1$.Thus, there exists a unique sylow $2$ subgroup or a unique sylow $7$ subgroup.Thus,$G$ is not simple.
Only numbers we are left with are $\{60,72,80,84,88,90,96\}$
$80=2^4.5$ Possibilities for $n_2$ are $1,5$ possibilities for $n_5$ are $1,16$. Suppose
Suppose $n_2=5$ and $n_5=16$, then $P_5$ contributes $64$ elements and atleast $16$ non identity elements from $P_2$ adding up to $80$ excluding identity. Thus G is not simple
Only numbers we are left with are $\{60,72,84,88,90,96\}$
$84=2^2.3.7$ with out much difficulty, one can see $n_7=1$ and thus, G is not simple.
Only numbers we are left with are $\{60,72,88,90,96\}$
$88=2^3.11$ with out much difficulty, one can see that $n_{11}=1$ thus G is simple.
Only numbers we are left with are $\{60,72,90,96\}$
I somehow managed to show groups of order $72,90,96$ are not simple. (My hands are paining I can not write more than this :D)
So, I am left with group of order $60$ and we have $A_5$ with $|A_5|=60$ and $G\cong A_5$
I would be thankful if someone can check whether this is clear (or) not (even with any typos) and If possible give a hint for a simple way to arrive at required result.
Thank You.
P.S : To be frank, I have no idea how to solve this before writing this. I thought i would say at-least i know cyclic groups (prime order) are not simple and leave the rest to the other users and then I realized $p^2$ are not simple and so on tried eliminating one by one. at the time i came to the case of $72,90,96$ I got fed up ad blindly decided to assume they are simple (:P). I would write about that cases in a while in detail.
P.S $2$ : Could any one please help me in concluding a group of order 24 being simple. I have edited a blunder in my argument. But could not able to proceed further.I am hoping for a proof which  use counting argument and no other results :)

A: Regarding a group of order $24$.
We know that $n_2$ is either 1 or 3.
If $n_2=1$ we are done. If $n_2=3$ then let $X$ be the set of the three $2$-Sylow groups. $G$ acts transitively on $X$ by conjugation. In particular, the action is not trivial. The group action can be thought of as a homomorphism $\phi\colon G\to S_X=S_3$.
Since $1<\left|Im(\phi)\right|\le 6$ we have $8\le \left|\ker\phi\right|<24$, so $G$ is not simple.

You can significantly shorten the proof with the following lemma.
If $\left|G\right|=p^km$ where $p$ is a prime, $p\nmid m$ and $p^k\nmid (m-1)!$ then $G$ is not simple.
Proof: Let $P$ be a $p$-Sylow subgroup. Then $G$ acts transitively on the cosets $G/ P$ by left multiplication. Since $\left[G\colon P\right]=m$ this action is a homomorphism $\phi\colon G\to S_m$.
If $G$ is simple then $\ker\phi=\{e\}$ so $\phi$ is an injection. That is, $G$ is isomorphic to a subgroup of $S_m$. Hence $p^km=\left|G\right| \mid m!$ so $p^k\mid (m-1)!$ which is a contradiction.

There is a small mistake in your argument, 36 is not a prime squared.

A: Here's a possibly shorter way to do the problem from "scratch" (assuming only Sylow's theorem, and not assuming Burnside's $pq$-theorem) than what's done in OP:
Let $G$ be a simple nonabelian group of order $n < 100$. Let $f(n)$ be the largest prime dividing $n$.
Case-0: $n = p^k$. Then the center is nontrivial, and by cauchy on the center we can find a normal subgroup of order $p$. This is a proper subgroup when $k > 1$, and if $k = 1$ then $G$ is abelian. So assume $n$ is not a prime power. Thus if any sylow-$p$ group is normal, we will be done in the other cases (since that would be a proper normal subgroup)
Case-1: $f(n) > 7$. Then obviously $f(n) > 10$. Now, I claim the sylow-$f(n)$ group is normal. If it's not, then $n_{f(n)}(G) \geq 1 + f(n)$, so the group has order atleast $f(n)(f(n)+1) > 100$, a contradiction.
Case-2: $f(n) = 7$. Then $n_7(G) = 7k + 1$, and $7(7k+1) \leq 100 \Rightarrow n_7(G) \in \{1, 8 \}$. If $n_7(G) \neq 1$, then the $7 \cdot n_7 = 56$ divides the order of the group, which forces $n = 56$. If the sylow-$8$ group is not normal either, then $n_8 = 7$. Thus there are atleast $(7-1) \cdot n_7 + 1 + (8-1) + 1 > 56$ elements a in a group of order $56$, a contradiction.
Case-3: $f(n) = 5$. Using similar bounding, if the sylow-5 group is not normal, then $n_5(G) \in \{6, 11, 16 \}$.

*

*If $n_5(G) = 16$, then $5 \cdot n_5 = 80 | n \leq 100 \Rightarrow n =80$. If the sylow-$16$ group is not normal, the $n_{16} = 5$. For two distnict sylow-16 groups $H_1, H_2$, note that $|H_1 \cap H_2| \leq 8$, so $|H_1 \cup H_2| = |H_1| + |H_2| - |H_1 \cap H_2| \geq 24$. Thus, there are exactly $(5-1) \cdot n_5 = 64$ elements of order exactly $5$, and atleast $24$ elements of order dividing $16$. But then $64 + 24 = 88 > 80$, a contradiction.

*If $n_5(G) = 11$, then $11$ divides $n$ and this reduces to first case.

*If $n_5(G) = 6$, then $30 | n$, so $n$ is either $30, 60, 90$. Now, note that a group of order $2k$ with $k$ odd has a normal subgroup of size $k$ (sketch: Let $G$ act on itself by left action, giving a faithful morphism $G \mapsto S_{|G|}$, compose with with the sign map $\pi \mapsto sgn(\pi)$ to get a map $G \mapsto \{1, -1 \}$. $G$ has an element of order $2$, and it's not hard to see this maps to $-1$, so the kernel of this map is the desired normal subgroup). So this gives the only possibility as $n = 60$
Case-4: Thus $n = 2^a 3^b$ for some $b$ with $a \geq 1$ (otherwise it's Case-0), and $1 \leq b \leq 4$).

*

*$b = 4$. Then $n \geq 2 \cdot 3^4 = 162$, a contradiction.

*$b = 3$. Then $n = 54 = 2 \cdot 27$, so it's handled by the $2k$ lemma (in $n_5(G) = 6$ case)

*$b = 2$. Then $n = 2^k 9$ for $1 \leq k \leq 3$. Now, if $n_9 \neq 1$, then $n_9 = 10$ ($n_9 = 19$ is too large). But then $5 | n$, which reduces it to previous case.

*$b = 1$. Then $n = 3 \cdot 2^k$.

*

*$n = 6$ is handled by the $2k$ lemma

*$n > 6$. Note that if $G$ is simple, and $H$ is a proper subgroup of $G$, then $G$ is isomorphic to a subgroup of $S_k$ where $k = [G:H] > 1$ (proof is easy, the action of $G$ on the left-cosets of $H$ by multiplication gives a map from $G$ to $S_k$. If the kernel is nontrivial, by simplicity it must be all of $G$, thus in particular $gH = H$ which is nonsense. Thus the kernel is trivial, and we conclude by first isomorphism). Thus in particular, $|G| \leq S_k = k!$ which (take $H$ to be sylow-$2^k$ group) is $6$ in this case. Again, a contradiction.

A: By using some more powerful results, it is possible to do this a lot easier.
The two main ingredients for this will be the following:
Burnside's $pq$-Theorem: If only two distinct primes divide the order of $G$, then $G$ is solvable.
Burnside's Transfer Theorem: If $P$ is a $p$-Sylow subgroup of $G$ and $P\leq Z(N_G(P))$ then $G$ has a normal $p$-complement.
So when looking for a non-abelian simple group, the first result immediately tells us that we can assume at least $3$ distinct primes divide the order of $G$.
The way we will use the second result is the following:
Let $P$ be a $p$-Sylow subgroup where $p$ is the smallest prime divisor of $|G|$. We will show that if $|P| = p$ then $P\leq Z(N_G(P))$ (and then the above result says that $G$ is not simple).
To see this, we note that $N_G(P)/C_G(P)$ is isomorphic to a subgroup of $\rm{Aut}(P)$ (this is known as the N/C-Theorem and is a nice exercise), which has order $p-1$, and since the order of $N_G(P)/C_G(P)$ divides $|G|$, this means that $N_G(P) = C_G(P)$ and hence the claim (since we had picked $p$ to be the smallest prime divisor).
The same argument actually shows that if $p$ is the smallest prime divisor of $|G|$, then either $p^3$ divides $|G|$ or $p = 2$ and $12$ divides $|G|$. The reason for this is that if the $p$-Sylow is cyclic of order $p^2$ the precise same argument carries through, since in that case all prime divisors of $|\rm{Aut}(P)|$ are $p$ or smaller.
If $P$ is not cyclic then the order of $\rm{Aut}(P)$ will be $(p^2-1)(p^2 - p) = (p+1)p(p-1)^2$ and the only case where this can have a prime divisor greater than $p$ is when $p = 2$ in which case that prime divisor is $3$, and we get the claim.
In summary we get that the order of $G$ must be divisible by at least $3$ distinct primes, and either the smallest divides the order $3$ times, or the smallest prime divisor is $2$ (actually, by Feit-Thompson, we know this must be the case, but I preferred not to also invoke that), and $3$ must also divide the order.
This immediately gives us $60$ as a lower bound on the order of $G$, and the next possible order would be $2^2\cdot 3\cdot 7 = 84$ and all further orders are greater than $100$. So we are left with ruling out the order $84$ (which you have done), and showing that the only one of order $60$ is $A_5$.


text:
Q: asymptotic behavior of generating function of partitions $p(n)$ I want to show the following asymptotic behavior.
Let $P(q)=\sum_{n=1}^{\infty}p(n)q^n$ be the generating function of the partitions $p(n)$ and $q=\exp(2\pi i \tau).$
I want to prove the following asymptotic behavior using the modularity of the dedekind $\eta$ function.
$\eta(\tau+1)=\eta(\tau)\exp(\frac{\pi i}{12}).$
$\eta(-\frac{1}{\tau})=\eta(\tau)\sqrt{-\tau i}.$
And we get $P(q)=\frac{q^{\frac{1}{24}}}{\eta(\tau)}.$

Prove
  $P(q)\sim \sqrt{-\tau i}\exp(\frac{\pi i}{12\tau})$ for $\tau \to 0$ where $\tau \in \mathbb H.$

Dedekind eta function

A: We start with the definition
$\;P(\tau) := \exp(\pi i\tau/12)/\eta(\tau)\;$ where $\tau \in \mathbb H.$
Replacing $\tau$ with $-1/\tau$ gives
$\;P(-1/\tau) \exp(\frac{\pi i}{12\tau}) = 1/\eta(-1/\tau).\;$
Using modularity  gives
$\;1/(\eta(\tau)\sqrt{\tau/i}) =  1/\eta(-1/\tau).$
Combining the last two equations gives
$\;P(-1/\tau)\sqrt{\tau/i}\exp(\frac{\pi i}{12\tau}) = 1/\eta(\tau).\;$
Substituting this in the definition of $P(\tau)$ gives
$\;P(\tau) = \exp(\pi i\tau/12) P(-1/\tau)\sqrt{\tau/i}\exp(\frac{\pi i}{12\tau}).$
Since the first two factors approach $1$ as $\tau\to0$ we have our asymptotic result $\;P(q)\sim \sqrt{\tau/i}\exp(\frac{\pi i}{12\tau}).$


text:
Q: Not able make post request to third party app I've written this code in my nodeJs backend
  const url = "localhost:8080/job/test/build";
  const username = "admin";
  const password = "116c197495ef372f129b85a8a2ca4aadc2";
  const token = Buffer.from(`${username}:${password}`, "utf8").toString(
    "base64"
  );
  const data = {
  }
  axios
    .post(url, {
      headers: {
        Authorization: `Basic ${token}`,
      },
    })
    .then((response) => res.send(response)).catch((e) => {console.log(e)});

I'm getting the following error

The same request with same credential is working in postman.

A: use http in url, like this"
 const url = "http://localhost:8080/job/test/build";


text: Q: Visual Studio Windows application not working on another computer Source explorer screenshotI have created a small windows application using visual studio and crystal report. I created the setup file also. when trying to install the application on my computer and is working perfectly. Tried installation on another computer it seems nothing happening after clicking the application.There is no problem in installing but launching the app not showing anything.


text:
Q: Controller can view related field, but does not display it in add or edit action Hello CakePhp developers,
CakePHP 2.5.2
I have a database with an Agreements table. It belongs to Adults, Children, Groups, Prices and Courses tables.
My Controller has 3 actions: index, add and edit.
The first one, index, works fine, displays all related tables in one page.
But problem is with the edit and add actions.
My Controller has arrays with related data, and its arrays do not have real names of Children, Adults, Groups and so on. Only the numbers 1,2,3, etc.
My AgreementsController.php is sending data to View by this commands:
$this->Agreement->recursive = 1;
$adults = $this->Agreement->Adult->find('list');
$childrens = $this->Agreement->Children->find('list');
$groups = $this->Agreement->Group->find('list');
$prices = $this->Agreement->Price->find('list');
$courses = $this->Agreement->Course->find('list');
$this->set(compact('adults', 'childrens', 'groups', 'prices', 'courses'));

I think that this arrays $adults, $children, have only numbers. Why they do not retrieve real item numbers. My Agreements/add.ctp is:
<?php echo $this->Form->create('Agreement'); ?>

    <?php
        echo $this->Form->input('date_of_agreement');
        echo $this->Form->input('number');
        echo $this->Form->input('year');
        echo $this->Form->input('adult_id', array (
                        'type' => 'select',
                        'options' => $adults
                        )
                );
                print_r($adults);
        echo $this->Form->input('children_id');
        echo $this->Form->input('status_id');
        echo $this->Form->input('city_id');
        echo $this->Form->input('price_id');
        echo $this->Form->input('course_id');
        echo $this->Form->input('group_id');
    ?>

<?php echo $this->Form->end(__('Submit')); ?>

Even adding 'options' parameter is not solving problem.
I've spent 50h on that and i do not know why?
I have inspected array it looks like this :
Array ( [1] => 1 [2] => 2 )
Can you help me with this?

A: In your db tables rename fields:

*

*adult first_name > first_name,

*adult_last_name > last_name,

*children_first_name > first_name,

*children_last_name > last_name,

*group > name

*...

In your models create virtual fields:
public $virtualFields = array(
'name' => "CONCAT(Adult.first_name, ' ', Adult.last_name)"
);

clear cache and test.
EDIT
Or you can in your find list method add options, eg:
$adults = $this->Agreement->Adult->find('list',array(
        'fields'=>array('Adult.id','Adult.first_name')
        ));


text:
Q: active admin: are there more detailed documentation or resources? I only come across this:
http://activeadmin.info/documentation.html
but I think many of the features one can choose from are not covered here.

A: If you're looking for API docs these seem to be current and updated (as of 2018-06-28): https://www.rubydoc.info/gems/activeadmin

A: You can find a lot of code samples and more documentation in the following places:

*

*Google Group - groups.google.com/group/activeadmin

*Issue Tracker - https://github.com/gregbell/active_admin/issues
Please remember to use the issue tracker only for technical issues, and the Google Group for advice, code samples, etc. You are always welcome to improve the documentation if you can


text:
Q: Erro ao rodar o docker-compose up para subir o traefik Após montar o docker-compose.yml da seguinte forma:
version: '3'

services:
    proxy:
        image: traefik
        command: --web --docker --docker.domain=docker.localhost --logLevel=DEBUG
        networks:
            - webgateway
        ports:
            - 80:80
            - 8080:8080
        volumes:
            - /var/run/docker.sock:/var/run/docker.sock
            - /dev/null:/traefik.toml
networks:
    webgateway:
        driver: bridge

Tento iniciar o container com o comando:
docker-compose up

Porém obtenho a seguinte mensagem de erro:
Creating network "traefik_webgateway" with driver "bridge"
Creating traefik_proxy_1 ... done
Attaching to traefik_proxy_1
proxy_1  | 2019/09/23 00:18:38 command traefik error: invalid node traefik: no child
traefik_proxy_1 exited with code 1

Tentei criar um arquivo chamado traefik.toml para espelhar no container com o seguinte conteudo:
# traefik.toml
logLevel = "DEBUG"
defaultEntryPoints = ["http", "https"]
[entryPoints]
  [entryPoints.http]
  address = ":80"

Porém também tive o erro:
Creating network "traefik_webgateway" with driver "bridge"
Creating traefik_proxy_1 ... done
Attaching to traefik_proxy_1
proxy_1  | 2019/09/23 00:23:55 command traefik error: read /traefik.toml: is a directory
traefik_proxy_1 exited with code 1

Já tentei diversas vezes iniciar o traefik mas todas sem êxito. Segui este tutorial da Digital Ocean e obtive também o erro:
2019/09/23 00:16:46 command traefik error: field not found, node: entrypoint

OBS: Experimentei em 4 máquinas diferentes, todas as vezes obtendo erros parecidos:

*

*No Windows com o Docker desktop

*No Ubuntu a partir do WSL (No windows)

*No Ubuntu 18 limpo em uma máquina criada no AMI da Amazon

*Em uma máquina pré-configurada pela BITNAMI com a MEAN stack

A: [Resolvido]
O que fiz:
version: "3.3"

services:
  traefik:
    image: "traefik:v2.0.0-rc3"
    container_name: "traefik"
    command:
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
      - "--defaultentrypoints=http,ws"
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"


text:
Q: Misplaced \PropertyValue with xsim package using own exercise definition I had to create a new definition for exercise with xsim package, because the hungarian heading text is reversed for the original. I did it as the manual shown, with only the necessary changes. Now the points, when used with property value, appears before the exercise text, as shown on the picture.
My code is:
\documentclass[a4paper,11pt]{article}
\usepackage{tasks}
\usepackage{xsim}
    \DeclareExerciseTranslation{magyar}{exercise}{feladat}
    \DeclareExerciseEnvironmentTemplate{magyar}{
        \subsection*
            {%
                \GetExerciseProperty{counter}.\nobreakspace%
                \XSIMmixedcase{\GetExerciseName}%
                \IfInsideSolutionF
                    {%
                        \GetExercisePropertyT{subtitle}%
                            { {\normalfont\itshape\PropertyValue}}%
                    }%
            }
        \GetExerciseProperty{points}
            {
                \marginpar
                    {%
                        \IfInsideSolutionF{\rule{1.2em}{1pt}\slash}%
                        \GetExercisePropertyT{points}\printgoal{\PropertyValue}}%
                        \GetExercisePropertyT{bonus-points}{~ (+\printgoal{\PropertyValue})}%
                        ~\XSIMtranslate{point-abbr}%
                    }%
            }
    }
    {}
    \xsimsetup{
        exercise/name=\XSIMtranslate{exercise},
        exercise/within=section,
        exercise/template=magyar,
        exercise/the-counter=\arabic{exercise}
    }
\usepackage{lmodern}
\usepackage[magyar]{babel}

\title{Fizika feladatok}
\author{Benkó Tamás}

\frenchspacing

\begin{document}

\maketitle
\begin{exercise}[points=10]
    Miért ráz meg a bevásárlókocsi?
    \begin{tasks}(2)
        \task Mert a boltba lépéskor a kinti és a benti levegő összeütközik, és emiatt villámlani fog.
        \task Mert a cipőtalp és a bolt kövezete érintkezésekor elektromos töltések jelennek meg.
        \task Mert mágia van a levegőben, és néha túltöltődik vele, ami így ürül ki.
        \task Mert az embert felvillanyozza, hogy milyen új dolgokat vehet.
    \end{tasks}
\end{exercise}
\end{document}

A: *

*Comment the line \GetExerciseProperty{points}

*There is a missing { in \GetExercisePropertyT{points}\printgoal{\PropertyValue}}% just before \printgoal
%
The entire code
\documentclass[a4paper,11pt]{article}
\usepackage{tasks}
\usepackage{xsim}
    \DeclareExerciseTranslation{magyar}{exercise}{feladat}
    \DeclareExerciseEnvironmentTemplate{magyar}{
        \subsection*
            {%
                \GetExerciseProperty{counter}.\nobreakspace%
                \XSIMmixedcase{\GetExerciseName}%
                \IfInsideSolutionF
                    {%
                        \GetExercisePropertyT{subtitle}%
                            { {\normalfont\itshape\PropertyValue}}%
                    }%
            }
        %\GetExerciseProperty{points}
            {
                \marginpar
                    {%
                        \IfInsideSolutionF{\rule{1.2em}{1pt}\slash}%
                        \GetExercisePropertyT{points}{\printgoal{\PropertyValue}}% <----------------
                        \GetExercisePropertyT{bonus-points}{~ (+\printgoal{\PropertyValue})}%
                        ~\XSIMtranslate{point-abbr}%
                    }%
            }
    }
    {}
    \xsimsetup{
        exercise/name=\XSIMtranslate{exercise},
        exercise/within=section,
        exercise/template=magyar,
        exercise/the-counter=\arabic{exercise}
    }
\usepackage{lmodern}
\usepackage[magyar]{babel}

\title{Fizika feladatok}
\author{Benkó Tamás}

\frenchspacing

\begin{document}

\maketitle
\begin{exercise}[points=1]
    Miért ráz meg a bevásárlókocsi?
    \begin{tasks}(2)
        \task Mert a boltba lépéskor a kinti és a benti levegő összeütközik, és emiatt villámlani fog.
        \task Mert a cipőtalp és a bolt kövezete érintkezésekor elektromos töltések jelennek meg.
        \task Mert mágia van a levegőben, és néha túltöltődik vele, ami így ürül ki.
        \task Mert az embert felvillanyozza, hogy milyen új dolgokat vehet.
    \end{tasks}
\end{exercise}
\end{document}


text:
Q: Solving the matrix quadratic equation: A.X.X + B.X + C == 0 analytically I'm having difficulty figuring out how to solve a matrix quadratic of the form, $AXX + BX = -C$ analytically for $X$. Where $A$, $X$, $B$, and $C$ are $N \times N$ matrices.
I tried using Solve, but got a message saying the system cannot be solved with methods available to Solvep. Is there any other way?
Edit
If no analytical solution exists, it is possible to derive conditions on when the numerical solution exists?

A: You can try
n = 3;
X = Array[x, {n, n}];
a = RandomReal[{-1, 1}, {n, n}];
b = RandomReal[{-1, 1}, {n, n}];
c = RandomReal[{-1, 1}, {n, n}];
f = (a.X + b).X + c;
sol = FindRoot[Thread[Flatten[f] == 0], Table[{Flatten[X][[i]], 0 }, {i, 1, n n}]]
f /. sol

Depending on the generated matrices, the result could be wordless. Some systems may not have real solutions.


text:
Q: Expansión de variadic template Supongamos una función que debe recibir un número aleatorio de valores para sacarlos por pantalla separando dichos valores con un separador determinado.
La idea pasa por aprovechar las características de los nuevos estándares de C++ así que la solución debería provechar los variadic templates.
El primer intento resulta prometedor, la plantilla es capaz de imprimir una secuencia de números:
template <typename... Args>
void print(Args... args)
{
   (std::cout << ... << args) << '\n';
}

int main()
{
  print(1,2,3,4,5);
}

Ahora intento meter el separador y es cuando comienzan los problemas:
template <typename... Args>
void print(Args... args)
{
   (std::cout << ... << ',' << args) << '\n';
}

Detalles del error:
prog.cc:8:29: error: expression not permitted as operand of fold expression
   (std::cout << ... << ',' << args) << '\n';
                        ~~~~^~~~~~~
                        (      )

¿De qué manera se podría añadir el separador a la secuencia? La idea es obtener una secuencia tal que:
1,2,3,...,N

A: A continuación expongo algunas otras formas de solucionar este problema aunque no son las únicas:
Sobrecarga de la plantilla
Por defecto se llamará a la versión variadic de la plantilla y solo se llamará a la versión no variadic cuando únicamente quede un elemento a imprimir.
La versión variadic, al llamarse siempre que haya 2 o más elementos puede asumir tranquilamente que debe insertar un separador después del primer elemento.
template<typename T>
void print(T item)
{
  std::cout << item;
}

template<typename T, typename... Args>
void print(T item, Args... args)
{
  print(item);
  std::cout << ',';
  print(args...);
}

Uso de lambdas (v1)
Una lambda con estado es ideal para controlar la impresión del separador.
Al explotar los argumentos se realizaran numerosas llamadas a la lambda, que imprimirá un separador en cada una de las mismas salvo en la primera.
template <typename... Args>
void print(Args... args)
{
    auto separador = [primero = true](auto param) mutable
    {
      if( !primero ) std::cout << ',';
      primero = false;
      return param;
    };

    ((std::cout << separador(args)), ...);
}

Uso de lambdas (v2)
Idéntica a la versión anterior, únicamente cambia la declaración de la variable booleana, que pasa a ser propiedad de la plantilla para evitar un warning en tiempo de compilación.
template <typename... Args>
void print(Args... args)
{
    bool primero = true;
    auto separador = [&](auto param)
    {
      if( !primero ) std::cout << ',';
      primero = false;
      return param;
    };

    ((std::cout << separador(args)), ...);
}

Uso de if constexpr
Como el compilador ya sabe el número exacto de argumentos que recibe la función podemos hacer uso de if constexpr para que se realice una llamada recursiva únicamente mientras haya más de un elemento a imprimir. Este código podría entenderse como una mejora del primer ejemplo.
template <typename Item, typename... Args>
void print(Item item, Args... args)
{
    std::cout << item;
    if constexpr( sizeof...(args) > 0 )
    {
      std::cout << ',';
      print(args...);
    }
}

A: Tenía una respuesta a punto justo antes de la edición en la que dejas claro que la salida esperada es 1,2,3,...,N y no 1,2,3,...,N, como pensé al principio. Para el primer caso puede valer simplemente:
#include <iostream>

template<typename... Args>
void print(Args... args)
{
    ((std::cout << args << ','), ...);
}

Al no querer la coma después del último elemento la cosa se complica...
No se si será la mejor opción, pero se puede plantear de la siguiente forma modificando mi idea inicial:
#include <iostream>

template<typename Arg, typename... Args>
void print(Arg first, Args... args)
{
    std::cout << first;
    if (sizeof...(args) != 0)
        ((std::cout << ',' << args), ...);
}

int main()
{
    print(1);
    std::cout << '\n';
    print(1,2,3,4,5);
    std::cout << '\n';
    print("ab","c",3,4,"de");
    return 0;
}

Imprimimos el primer argumento y posteriormente nos valemos de un condicional para ver si hay algún argumento en args que desempaquetar o no.
Salida:

1
  1,2,3,4,5
  ab,c,3,4,de

Prueba online en Ideone

A: Pienso que usted puede expandir la secuencia que recive el template hacia otra funcion a la cual le pasa los de args
#include <iostream>
using namespace std;

int print_test(int i)
{
    std::cout << ',' << i << '\n';
    return 0;
}

template <typename... Args>
void print(Args... args)
{

    using  expandir = int[];
    (void) expandir {0, ((void)print_test(args), 0)...};

    (std::cout << ... << args) << '\n'; // se deja para contrastar

}

int main() {
    // your code goes here
    print(1,2,3,4,5);
    return 0;
}

Test Ideone

La explancion de los paquetes "Pack expansion" segun entiendo solo pueden ser expandidos en contextos de expancion de los mismo "si quizas es un poco confuso siento no poder explicarme mejor" por citar alguno inicializacion Braced o este en el que se basa el ejemplo inicializaciones de array.
info alguna info:

*

*http://en.cppreference.com/w/cpp/language/fold
pero en el se muestra como usted lo esta usando, no se si sera de utilidad para usted esa parte, pero en las definiciones de paquete "pack" "init" quizas lo ayude.

Update:

Esto creo que funciona como usted quiere.
template <typename... Args>
void print(Args... args)
{
    int chapuza = 0;
    const int n = sizeof...(args);

    using  expandir = int[];
    (void) expandir {0, ((void)print_test(args), chapuza++, chapuza == n ? std::cout << '\n' : std::cout << ','  << '\n', 0)...};

}

Test Ideone
Tras su update si es sin el salto de linea usar:
//..
(void) expandir {0, ((void)print_test(args), chapuza++, chapuza == n ? std::cout << '\n' : std::cout << ',', 0)...};
//..

cambiando std::cout << ','  << '\n' por std::cout << ','

Siguiendo con el enfoque anterior, se podria simplificar de la siguiente manera y prescindiendo de el print_test
    using  expandir = int[];
    (void) expandir {0, (chapuza++, chapuza == n ? std::cout << args << '\n' :
                                                   std::cout << args<< ',', 0)...};

Test Ideone

Nota: quizas sea una chapuza y quizas exista una mejor forma, pero me dio curiosidad tras su comentario, y esto fue lo que salio, espero le ayude.