text:
Q: How to prevent submit if user inputs a link? I have run into a bit of a problem recently.
I am still in the process of learning JS so i couldn't figure this one out alone :( .
I have been getting a lot of spam recently through this form I have on a website and I cant seem to fix it...I tried a few solutions with Jquery and JS but I cant get it to work so I just deleted them.
100% of the spam I receive has a link in the message so I would like to make it so the submit button stay disabled unless 2 conditions are met :

*

*The message must contain more than 12 characters

*The textarea must NOT contain any link

here is the html i got :
<form action="php/contact.php" method="POST">

Contact-us

  <input type="text" id="name" name="name" placeholder="Name" required>
  <input type="email" id="email" name="email" placeholder="Email" required>
  <input type="tel" id="tel" name="tel" placeholder="Phone" required>
  <input type="text" class="subject" id="subject" name="subject" placeholder="Subject" required>
  <textarea name="message" id="messag" class="textarea" placeholder="Message" required></textarea>
  <button type="submit" class="submit" name="submit" id="disabled">Send</button>
</form>

also I am preventing a page refresh using ajax, and any JS i tried would conflict or be ignored by the ajax request, here is the code :
                $(function () {
                    $('form').on('submit', function (e) {
                        e.preventDefault();
                        $.ajax({
                          type: 'POST',
                          url: '/php/contact.php',
                          data: $('form').serialize(),
                          success: function () {
                             alert('Your message was sent successfully');
                          }
                        });
                     });
                  });

a fairly simple form i think...any help is greatly appreciated !
Thanks

A: Message length and filtering links still leave a number of options for spammers to breach your form.
You can quite easily implement a Google Recaptcha or implement your own in whatever backend language you're using.
The conditions you're looking for in your OP are,

*

*if ($('#messag').html().length > 12)

*if ($('#messag').html.indexOf('href') >= 0)

Cheers

A: You can probably check to make sure that the body of the message sent by the user doesn't have a link using a regex to match links.
The regex I used was taken directly from the answer of this question: Detect URLs in text with JavaScript

$("#my-form").on("submit", ev => {
  ev.preventDefault();

  const urlRegex = /(https?:\/\/[^\s]+)/gm;
  const message = $("#message-field").val();

  if(! message.match(urlRegex)){
    // you can send the message with ajax
    // ...ajax code

    alert("message sent");
  } else {
    // there was a link in the message, give a warning or something
    alert("link detected");
  }

});

<form id="my-form">

Message:

  <textarea name="message" id="message-field" placeholder="Try adding text like https://google.com" style="width:200px;height:100px;"></textarea/>

  <button>submit</button>
</form>

This is only a front-end solution. Make sure you also have a check on the backend because javascript based validation can be easily bypassed.


text:
Q: C# MessageBox popup AFTER form load I'm trying to make a MessageBox appear after a form loads, but the problem is that the MessageBox appears before the actual form.
This is the code I currently have:
private void LoadUsers()
{
        DataRow lockrow = DataManager.Documents.Users.LTLock.Get(UserID);
        if (lockrow != null)
        {
            DevExpress.XtraEditors.XtraMessageBox.Show("Warning! Document already in use!");
        }
}

How could I make the MessageBox appear after the form has visibly loaded? Thanks!

A: I have never used devexpress before but in winforms there is a form event Shown which is called immediately after the form is laoded. This is how it would be done in winforms so it would need applying to devexpress.
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //do stuff
    }

    private void Form1_Shown(object sender, EventArgs e)
    {
        MessageBox.Show("someString");
    }
}

A: You can use Form Shown (More information here);

Code below;
    private void Formshown(object sender, EventArgs e)
    {
            MessageBox.Show("Hello");
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to alter characteristics of high frequency EM waves I would know if it possible to alter characteristics of high frequency EM waves, ie altering the frequency, phase and/or amplitude.
I found it is possible to change frequency of ELF waves: http://rexresearch.com/puharelf/puharich.htm
If it is possible, what would be the simplest practical way to do it?

A: This is best done today using a frequency generator and modern ones will allow you to program quite complex waveforms. Isuggest your questionis best answered on the electronic stack exchange as your question seems more of a technical implementation or engineering.


text:
Q: How to find the inverse of a number in a congruence relation I have an equation like this : $$39x \equiv 1 \mod 257$$
To solve this I need to find $39^{-1}$ in $\mathbb{Z_{257}}$.
Or am I thinking in the wrong way?
How can I find the inverse of a number in a congruence relation?

A: With the modular multiplicative inverse of an integer $x$ you want to compute the smallest $y$ such that

$$xy\equiv1\mod(n)\iff y\equiv x^{-1}\mod(n)$$

In order to compute these values, you can either use the extended Euclidean algorithm or Euler's theorem (since I find the EEA more useful, I'll use this algorithm instead of Euler's theorem.)

With the extended Euclidean algorithm:
The first part of the EEA for $a,b:a>b$ is just like the standard Euclidean algorithm, which proceeds by a succession of Euclidean divisions whose quotients are not used, only the remainders are kept. More precisely, it consists in computing the following sequence
$$a=q_1·b+r_1$$
$$b=q_2·r_1+r_2$$
$$r_1=q_3·r_2+r_3$$
$$.$$
$$.$$
$$r_n=q_{n+2}·r_{n+1}+0$$
Where $q_k$ are the quotients (note that $q_k=\lfloor \frac{r_{k-2}}{r_{k-1}}\rfloor$) and $r_k$ the reminders after performing the Euclidean division. The algorithm stops when $r_{n+2}=0$ and results in $gcd(a,b)=r_{n+1}$
For instance for $a=97, \;b=21$
$$97=4·21+13$$
$$21=1·13+8$$
$$13=1·8+5$$
$$8=1·5+3$$
$$5=1·3+2$$
$$3=2·1+1$$
$$2=2·1+0$$
$$\Rightarrow gcd(97,21)=1$$
Now in the EEA, you have to perform the standard EA solving for the remainders as a linear combination of $a$ and $b$
$$97=4·21+13 \iff 13=97-4·21$$
$$21=1·13+8\iff 8=21-1·13=21-1·(97-4·21)=5·21-97$$
$$13=1·8+5 \iff 5=13-8=97-4·21-(5·21-97)=2·97-9·21$$
$$8=1·5+3 \iff 3=8-5=5·21-97-(2·97-9·21)=14·21-3·97$$
$$5=1·3+2 \iff 2=5-3=2·97-9·21-(14·21-3·97)=5·97-23·21$$
$$3=2·1+1 \iff 1=3-2=14·21-3·97-(5·97-23·21)=37·21-8·97$$
This last expression is known as Bézouts identity or Bézouts Lemma, which states that for any integers $a$ and $b$ with lcd$(a,b)=d$, $\exists$ coefficients $j$ and $i$ such that $$aj+bi=d$$ The greatest common divisor of two integers $a,b$ is, by the way, the smallest linear combination of these numbers you can make, which you can compute with the EEA. Having that said, note that $$aj+bi \equiv aj\equiv d\mod(b)$$ So, if gcd$(a,b)=1$, (and only under this condition $\exists$ a multiplicative inverse) the modular multiplicative inverse of $$a\mod(b)$$ is the coefficient $j$ of $a$ in Bézout's identity.
So for your example

 $$39x \equiv 1 \mod 257$$ $$257=6·39+23\iff 23=257-6·39$$ $$39=1·23+16 \iff 16=39-23=39-(257-6·39)=7·39-257$$ $$23=1·16+7 \iff 7=23-16=257-6·39-(7·39-257)=2·257-13·39$$ $$16=2·7+2 \iff 2=16-2·7=7·39-257-2·(2·257-13·39)=33·39-5·257$$ $$7=3·2+1\iff 1=7-3·2=...=17·257\mathbf{-112}·39$$ $$\therefore -112\equiv 145\equiv 39^{-1} \mod 257 \iff 145·39 \equiv 1 \mod 257$$

A: Here's the standard layout for the E.E.A.. It is based on the result that in the standard Euclidean algorithm, the remainder at each step is a linear combination of the given numbers.
$$\begin{array}{rrrl}
r_i&u_i&v_i&q_i\\ \hline
257& 0&1 \\
39&1&0&6\\ \hline
23&-6&1&1\\
16&7&-1&1 \\
7 &-13 &2 &2 \\
2&33&-5&3\\
1&-112&17 \\ \hline
\end{array}$$
hence we have the Bézout's identity
$$-112\cdot 39+17\cdot 257=1,$$
which implies
$$39^{-1}\equiv -112\equiv 145\mod 257.$$


text: Q: After you've clipped the lockout chip's 4th pin on a toaster-style NES, do you still get the flashing red light and screen with no cartridge? Just curious as I have not yet performed the fix, and it seems like logically, if this 1-second cyclic reset is chip-associated behavior, you'd just see a solid lavender or black/grey screen with no cartridge after the lockout fix. Can anyone confirm?  I'll update this if and when I go ahead with that and test.


text:
Q: JAX_RS - MessageBodyProviderNotFoundException: MessageBodyWriter not found for ArrayList I am writing a JAX_RS application using Jersey. All endpoints which return a single object as JSON work fine in Tomcat and WildFly.
One endpoint which returns a collection of objects works absolutely fine in Tomcat. However, when I deploy the same service in WildFly 10.1.0 it fails.
Function is given below:
@POST
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response searchForActivities(ActivitySearch search) {
    System.out.println(search.getDescriptions() + ", " + search.getDurationFrom());

    List<Activity> activities = activityRepository.findByConstraints(search);

    if(activities == null || activities.size() <= 0) {
        return Response.status(Status.NOT_FOUND).build();
    }

    return Response.ok().entity(new GenericEntity<List<Activity>> (activities) {}).build();

}

Stack trace is given below:
javax.servlet.ServletException: org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=class java.util.ArrayList.
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)

However, a function simply returning List<Activity> works in Tomcat and WildFly without any issue. See the definition of the function below:
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public List<Activity> getAllActivities() {
    return activityRepository.findAllActivities();
}

A: The example seems to be tied heavily to Jersey. You'd need to modify the POM to use the WildFly BOM (org.wildfly.bom:wildfly-javaee7-with-tools:10.1.0.Final). Then import the JAX-RS dependencies or use the Java EE 7 maven coordinates (also helpful).
If you want a more generic JAX-RS client example that should work with any Java EE 7 complient container have a look at the WildFly JAX-RS Client quickstart. Or any of the Java EE Samples.


text:
Q: How to make a drop shadow on a custom shape I want something like this:

I have the shape
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item >
    <shape android:shape="rectangle"  >
        <solid android:color="@color/white"/>
        <corners android:radius="15dip" />
        <stroke android:width="1dip" android:color="@color/shadow" />
    </shape>
</item>
</selector>

But my problem is the shadow, is there a way I can do this?

A: Use CardView to create shadow view in android
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="@android:color/white"
    android:foreground="?android:attr/selectableItemBackground"
    card_view:cardElevation="3dp"
    card_view:cardCornerRadius="4dp">

*

*card_view:cardElevation="3dp" this is for shadow

*card_view:cardCornerRadius="4dp" this is for corner radius


text:
Q: How can duplicate the data records based on period? I have a data set as periodic. However, these periods are not consecutive. My data pattern is like that
Period  Customer_No Date        Product
1       111         01.01.2017  X
3       111         05.09.2017  Y
8       111         02.05.2018  Z
6       222         02.02.2017  X
9       222         06.04.2017  Z
12      222         05.09.2018  B
15      222         02.01.2019  A

End of the period should be 15 for all customers. I want to create consecutive periods based on customers and fill them with previous data like below:
Period  Customer_No Date        Product
1       111         01.01.2017  X
2       111         01.01.2017  X
3       111         05.09.2017  Y
4       111         05.09.2017  Y
5       111         05.09.2017  Y
6       111         05.09.2017  Y
7       111         05.09.2017  Y
8       111         02.05.2018  Z
9       111         02.05.2018  Z
10      111         02.05.2018  Z
11      111         02.05.2018  Z
12      111         02.05.2018  Z
13      111         02.05.2018  Z
14      111         02.05.2018  Z
15      111         02.05.2018  Z
6       222         02.02.2017  X
7       222         02.02.2017  X
8       222         02.02.2017  X
9       222         06.04.2017  Z
10      222         06.04.2017  Z
11      222         06.04.2017  Z
12      222         05.09.2018  B
13      222         05.09.2018  B
14      222         05.09.2018  B
15      222         02.01.2019  A

create table tbl_cust(period int,Customer_No int, Date date, Product varchar)

insert into tbl_cust values(1,111,'01.01.2017','X')
insert into tbl_cust values(3,111,'05.09.2017','Y')
insert into tbl_cust values(8,111,'02.05.2018','Z')
insert into tbl_cust values(6,222,'02.02.2017','X')
insert into tbl_cust values(9,222,'06.04.2017','Z')
insert into tbl_cust values(12,222,'05.09.2018','B')
insert into tbl_cust values(15,222,'02.01.2019','A')

A: You can use a recursive CTE to generate the rows that you want.  Then you need to fill them in with the most recent data.  What you really want is lag(ignore nulls), but SQL Server does not support that functionality.
There are only up to 15 rows per customer, so apply is a reasonable alternative:
with cte as (
      select min(period) as period, customer_no
      from tbl_cust
      group by customer_no
      union all
      select period + 1, customer_no
      from cte
      where period < 15
     )
select cte.period, cte.customer_no, c.date, c.product
from cte cross apply
     (select top (1) c.*
      from tbl_cust c
      where c.customer_no = cte.customer_no and
            c.period <= cte.period
      order by c.period desc
     ) c
order by cte.customer_no, cte.period;

Here is a db<>fiddle.

A: You can try this.
select ID as period, Customer_No, [Date], Product from
    (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15)) P(ID)
        OUTER APPLY( SELECT *, ROW_NUMBER() OVER(PARTITION BY Customer_No ORDER BY period desc) RN
            FROM tbl_cust C WHERE C.period <= P.ID ) X
WHERE X.RN = 1
ORDER BY Customer_No, ID

Result:
period      Customer_No Date       Product
----------- ----------- ---------- -------
1           111         2017-01-01 X
2           111         2017-01-01 X
3           111         2017-05-09 Y
4           111         2017-05-09 Y
5           111         2017-05-09 Y
6           111         2017-05-09 Y
7           111         2017-05-09 Y
8           111         2018-02-05 Z
9           111         2018-02-05 Z
10          111         2018-02-05 Z
11          111         2018-02-05 Z
12          111         2018-02-05 Z
13          111         2018-02-05 Z
14          111         2018-02-05 Z
15          111         2018-02-05 Z
6           222         2017-02-02 X
7           222         2017-02-02 X
8           222         2017-02-02 X
9           222         2017-06-04 Z
10          222         2017-06-04 Z
11          222         2017-06-04 Z
12          222         2018-05-09 B
13          222         2018-05-09 B
14          222         2018-05-09 B
15          222         2019-02-01 A


text:
Q: Why do I get the error Uncaught TypeError: Cannot set property 'display' of undefined in Javascript? I am attempting the understand the use of the document object type and to challenge myself I am trying to hide all the div tags. When I execute the function, I am returned the error Uncaught TypeError: Cannot set property 'display' of undefined however am unsure what it means exactly. What is undefined?
The output of the code can be found at http://jsfiddle.net/Bdbtq/
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <meta http-equiv="content-language" content="en-us" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="pragma" content="no-cache" />
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <meta name="author" content="" />
    <meta name="copyright" content="© 2012" />
    <meta name="robot" content="noindex, nofollow" />

    <title>js features</title>

    <base href="" />

    <link rel="stylesheet" type="text/css" media="all" href="" />

This is sample content

© 2012

Click to hide

A: getElementsByTagName returns an array. So you need:
    var divs = document.getElementsByTagName("div");

    for(var i = 0; i < divs.length; i = i + 1) {
        divs[i].style.display="none";
    }

A: Div is an array of elements, not a single element. Try this:
for(var i = 0; i < div.length; i = i + 1) {
    div[i].style.display="none";
}

I think it would be easier to avoid these mistakes if you call your variable divs, or something similar that indicates that it isn't an element.

A: Your variable div is at this point a node list, not a single variable, as getElementsByTagName() returns a node list.  You need to access it via its array index from your loop as in div[i]
for(var i = 0; i < div.length; i = i + 1) {
    // div[i] holds the current loop iteration
    div[i].style.display="none";
}


text:
Q: Finding highest normal form of a relation of database What is the highest normal form of relation R(A,B,C,D), given FDs A--> B; CD--> B; A--> CD; CD--> A ? Please not only give the answer but also give a step by step approach to solve a problem of this kind.

A: The candidate keys are A and CD, which you can determine by inspection in this case. (It's a simple problem; you can determine the closures in your head.) A->B, A->CD; that's all the attributes. CD->A, CD->B; again, that's all the attributes.
Since all the arrows are arrows out of candidate keys, it's in at least BCNF. (That's the informal definition of BCNF.)
All database textbooks include at least one algorithm for determining all the candidate keys, and for normalizing a set of relations to 5NF. If you don't have one, Maier's The Theory of Relational Databases is available free a the author's faculty web site.


text:
Q: Token Mismatch Exception I don't know what happened but I just want to Login on my Laravel App. I used the internal Auth system of Laravel. I try to register but it kept on returning
TokenMismatchException in compiled.php line 3227:

I already tried inserting {{ csrf_field() }} to the Login and Register blade but it still doesn't work.
I am debugging this for hours now. I need help. Thanks.

A: You can try it:  <input type="hidden" name="_token" value="{{csrf_token()}}">
or
{{ csrf_field() }}
{{ method_field('POST') }}
Hope it help u.

A: Please Try it:
<form>
{{csrf_field()}}
</form>

or
<form>
<input type="hidden" name="_token" value="{{csrf_token()}}">
</form>

A: I had the solution I had to remove the Verify Token Class. Because no matter what I do the Verify token error keeps on coming.


text:
Q: Copying a variable's value to another? I have two variables, I need to move the values from string1 to string2.
string1 DB 20, 22 dup('?')
string2 DB 20, 22 dup('?')

I know how to do this with a register (si) and a loop, something like:
LEA si, string1
LEA di, string2
mov cx, 5
change:
mov ax, [si]
mov [di], ax
loop change

I want to know if there is a shorter method.

A: What you're looking for are REP (Repeat) and MOVSB (A mnemonic for *MOV*e *S*tring *B*yte).
Example:
lea     si,[string1] ;si points to string1
lea     di,[string2] ;di points to string2
mov     cx,5         ;number of bytes in string1
rep     movsb        ;copy the string

See also:
MOVSW (Move String Word - Copies 2 bytes at a time)
MOVSD (Move String DWord - Copies 4 bytees at a time)


text:
Q: Trigger sendgrid template email using meteor I am using sendgrid to send an email. I want to send template as an email to users. Below code is just sending the simple text based email instead of defining the headers part and using the template id.
if (Meteor.isServer) {
    Email.send({
        from: "from@mailinator.com",
        to: "abc@mail.com",
        subject: "Subject",
        text: "Here is some text",
        headers: {"X-SMTPAPI": {
            "filters" : {
                "template" : {
                    "settings" : {
                        "enable" : 1,
                        "Content-Type" : "text/html",
                        "template_id": "3fca3640-b47a-4f65-8693-1ba705b9e70e"
                    }
                }
            }
        }
        }

    });
}

Your help will highly be appreciated.
Best

A: To send SendGrid transactional templates you have different options
1) Via the SendGrid SMPT API
In this case we can use Meteor email package (as you were trying).
To add meteor email package we need to type in the sell:

meteor add email

In this case, according to SendGrid docs:

The text property is substituted into the <%body%> of the text template and html is substituted into the <%body%> of the HTML template. If the text property is present, but not html, then the resulting email will only contain the text version of the template, not the HTML version.

So in your code you need to provide http property too, that's all.
This could be your server code:

// Send via the SendGrid SMTP API, using meteor email package
Email.send({
  from: Meteor.settings.sendgrid.sender_email,
  to: userEmail,
  subject: "your template subject here",
  text: "template plain text here",
  html: "template body content here",
  headers: {
    'X-SMTPAPI': {
      "filters": {
        "templates": {
          "settings": {
            "enable": 1,
            "template_id": 'c040acdc-f938-422a-bf67-044f85f5aa03'
          }
        }
      }
    }
  }
});

2) Via the SendGrid Web API v3
You can use meteor http package to use SendGrid Web API v3 (here docs). In this case we can use the Meteor http package.
To add Meteor http package type in the shell:

meteor add http

Then in your server code you can use
// Send via the SendGrid Web API v3, using meteor http package
var endpoint, options, result;

endpoint = 'https://api.sendgrid.com/v3/mail/send';

options = {
  headers: {
    "Authorization": `Bearer ${Meteor.settings.sendgrid.api_key}`,
    "Content-Type": "application/json"
  },
  data: {
    personalizations: [
      {
        to: [
          {
            email: userEmail
          }
        ],
        subject: 'the template subject'
      }
    ],
    from: {
      email: Meteor.settings.sendgrid.sender_email
    },
    content: [
      {
        type: "text/html",
        value: "your body content here"
      }
    ],
    template_id: 'c040acdc-f938-422a-bf67-044f85f5aa03'
  }
};

result = HTTP.post(endpoint, options);


text:
Q: Webstorm unable to get local issuer certificate When I try to checkout from a local Github then I get a SSL certificate error "fatal: unable to access ... SSL certificate problem: unable to get local issuer certificate". However the server's certificate is known to Webstorm (9.0.0). I also checked the "automatically accept certificates" box.
How can I analyze / fix this issue?

A: By now I found out that this is not a Webstorm issue at all. Git did not want to checkout from the commandline either. I followed the solution from here. Once Git was able to clone Webstorm was also able to clone. Obviously this is because Webstorm reuses the git configuration.


text:
Q: $[A, B] = 0 \Rightarrow E_\lambda(A) \cap E_\mu(B) = E_{\lambda\mu}(AB)$? $E_\lambda(A)$ stands for the eigenspace of an operator (say, a matrix) with eigenvalue $\lambda$.
It probably doesn't matter whether the antecedent stands for the commutator or a general Lie bracket, but is this true in general? Because I just encountered a case in my research in which it is. (Decomposing a representation space under the action of SU(3).)
If it's true we may have some fun with it, because there's maybe some categorical way of putting it. Say, the part of some functor in which the domain category has eigenspaces as objects and intersection as morphisms. And the codomain (do they call that target?) category also has eigenspaces as objects, but the morphisms are matrix multiplication.
Please tell me how I'm wrong :)

A: This is not true. E.g. when $A=\operatorname{diag}(1,0)$ and $B=\operatorname{diag}(0,1)$, $E_0(A)\cap E_1(B)$ is one-dimensional but $E_0(AB)$ is two-dimensional.
The above counterexample can be modified so that $A$ and $B$ are nonsingular. Consider $A=\operatorname{diag}(1,-1),\,B=\operatorname{diag}(-1,1)$ and $E_1(A)\cap E_{-1}(B)$ for instance. Briefly speaking, the geometric multiplicity of $\lambda\mu$ in $AB$ can be greater than the multiplicity of $\lambda$ in $A$ or the multiplicity of $\mu$ in $B$.


text:
Q: gspread TypeError: login() takes no arguments (2 given) I have installed gspread and gdata in my virtual environment using pip. And when I try to login with email and password following the documentation, as shown:
import gspread
gc = gspread.login('533ghimiresantosh@gmail.com','password')

It throws this error: TypeError: login() takes no arguments (2 given)
gspread is installed properly which is confirmed by successful execution of line import gspread in the python console. Is there some dependency issue that I am unaware of or anything?

A: You have to login like this
c = gspread.Client(auth=('user@example.com', 'qwertypassword'))
c.login()

source http://burnash.github.io/gspread/#gspread.Client.open

A: Using the latest version I can still do it: gc = gspread.login(USERNAME, PASSWORD)


text:
Q: Hierarchy in ER and OO Model So, it might be a very fundamental question, but I'm pretty confusing right now...
It's all about Element and ElementCategory: an element belongs to a category, a categoty can have many elements - a straightforward one to many relationship.
At the database level, I have two tables:

Element(element_id, category_id, element_name)
Category(category_id, category_name)

At the application level (Java), I would have:

class Element { int id; String name; Category category; }
class Category { int id; String name; Collection elements; }

My question: did I have the right approach, both at the database level and application level? What kind of relationship is that in OOD? has-a, is-a, inheritance, generalization relationship or whatsoever...
Thanks in advance for any constructive comments and answers.

A: I agree with @Samuel that your database tables look correct.

*

*The database relationship looking from the Element end is one to one - an element must have one and only one Category.

*The database relationship looking from the Category end is zero to many. A category may have zero to many Elements.

The only restriction on adding new records is that the Category must be added before any element that is in that category.
On the OOD/Java side, things get a little more interesting.

*

*Your Element class is fine. It reflects the underlying database table. There is a has a relationship to Category. Any good Java ORM will map this nicely.

*In general, the Category class should not have a collection of Elements, as the performance will suffer. If you let the ORM populate this collection, then retrieving a single Element by ID will load the single Category for that element, and the ORM will then load all Elements that are in that Category to populate the collection. This is almost always not what you want. There are work-arounds involving lazy loading, but these can be messy to use when the database access layer is on a remote server (e.g. As in almost all web apps).

*If you need to lookup elements by Category, it is usually limited to a single category at a time (e.g. Show me all the Lamborginis we have in stock), and often needs a specialist SQL query (e.g. Show me all the 2016 red Toyotas in stock). To do these queries efficiently, your database service layer will need specialist functions that return a collection of Elements.

So my advice is to remove the collection of Elements from Category, and add database queries to handle any use case that needs to lookup elements by category. Note that a good ORM (MyBatis is my favorite) will still handle the mapping from the query results to the collection of Elements.

A: You have a circular dependency between Category and Element in your code. Meaning Category depends on Element and Element depends on Category. This could cause problems trying to populate this structure from the database:
1. Populate element A
2. Populate element A's category
3. Populate element A's category's elements (which includes A)
4. Populate element A's category's elements' categories
5. Populate element A's category's elements' categories' elements
etc.

It also creates an ambiguity of how you should update an element's category. Should you change Element.category, or should you add/remove the element from Category.elements? To avoid these kinds of problems you should make the relationship unidirectional.
Your tables have a unidirectional relationship and they look good. To fix your code models you just need to remove elements from Category.
class Element { int id; String name; Category category; }

class Category { int id; String name; }


text:
Q: How to get 2 different classes text in a div I'm trying to do a web scraping using Python and BeautifulSoup, but I hit a wall. Here is the original page markup:

target 1
updated 25th January 2019

I need just the first part ("target 1")
I tried to find the class "name" with
mgroup[0].a.findAll("div",{"class":"name"})

or
mgroup[0].a.findAll("div",)[1].div

but it always returns

target 1
updated 25th January 2019

but if I use the class "date" like this
mgroup[0].a.findAll("div",{"class":{"date"})

I get:

updated 25th January 2019

I'm not sure if this is because the div is inside a unclosed div or if the tag "name" might be a reserved term or something similar even tried
mgroup[0].a.findAll("div",{"class":["name"}])

with same result
  [
target 1
updated 25th January 2019

]

How should I tackle this?

A: It is returning the BS4 element itself. You can access the contents of the element like this:
hit = mgroup[0].a.findAll("div",{"class":"name"})
print(hit.contents[0])


text:
Q: how to Read page respond of the payment result MVC basically my application is similar to the link but mine is on MVC C#.
-Make a payment request. -Read the Respond. -Pass the respond to our api.
https://developer.2c2p.com/docs/prepare-payment-request
my payment request code:
function CreateForm(parameters)
{
    var form = $('<form id="PaymentForm1"></form>');
    var path = url;

    form.attr("method", "post");
    form.attr("action", path);

    $.each(parameters, function (key, value) {
        var field = $('<input></input>');
        field.attr("type", "hidden");
        field.attr("name", key);
        field.attr("value", value);
        console.log(key, value);
        form.append(field);
    });
    $(document.body).append(form);
    form.submit();
}

So my problem now is the response result on how to read it... and pass it in our api.
(similar to this but on MVC https://developer.2c2p.com/docs/read-payment-response)
I try to use this code..  WebRequest request = WebRequest.Create(resultURL); but will reload the page, data will be gone.
[HttpGet]

        public ActionResult getResultValues()
        {
            WebRequest request = WebRequest.Create(resultURL);
            request.Method = "GET";
            request.UseDefaultCredentials = true;
            request.PreAuthenticate = true;
            request.Credentials = CredentialCache.DefaultCredentials;

            WebResponse response = request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();

            reader.Close();
            response.Close();

            return View(responseFromServer);

        }

Is there a better way to do it? I'm also new on MVC

A: @chenz101
Looking my code
Make a class for below formats
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AspNetMvcJqueryAjaxSerializeForm.Models
{
    public class FriendModel
    {
        public string FriendName { get; set; }
        public string Phone { get; set; }
        public string State { get; set; }
    }
}

Controller
// POST: Friend/AddFriend
[HttpPost]
public ActionResult AddFriend(FriendModel fm)
{
          //Write your database insert code / activities
            return RedirectToAction("create");
}

This is the your MVC view html page code
<form id="friendform">

            Friend Name
            <input id="txtFriendName" name="FriendName" type="text" />

            Phone
            <input id="txtPhone" name="Phone" type="text" />

            State
            <input id="txtState" name="State" type="text" />

 <input id="btnsubmit" type="button" value="Submit"/>
</form>

This is the your ajax call code


text:
Q: Gimp plugin Bimp - problem with config I have problem with bimp plugin, its a gimp plugin for batch image manipulation [download link]. After installation its works only when i run gimp from terminal as root - when i run it from icon, plugin is inactive. Can you please help me understand why its works like that and what is an issue ?
Its how i install this plugin:

*

*Download tar

*Unzip

*Sudo -i and then navigate to  plugin folder

*make && make install, apt-get upgrade && update

A: As indicated in the README.md file, you should either run
make
make install

to install the plugin in your own ~/.gimp-2.8/plug-ins directory, or run
make
sudo make install-admin

to install system-wide. Do not make the plain install target with sudo, since this will place a root-owned version of the plugin into your home directory.


text:
Q: Rotating text on graphic display I am trying to modify this library to add the ability to rotate text on a graphic display.  I'm using an e-paper display but the library supports other graphic displays.  I have made it as far as rotating the text on the display but I can't work out getting the spin center correct.  From researching similar questions, I see that I need to temporarily move the origin to the point of rotation.  However, I am having trouble seeing how to do that with this code. drawString calls several functions until finally a function to set the pixel color (that is where I inserted the code to rotate the affected pixels).  I think I need to move the rotation further upstream.
I added setTextRotation which precomputes the sin/cos that is later passed to the first two lines in setPixel (at the bottom of the code block below).  It may be easier to see the changes in the first link above.  I tried solving (thanks Wolfram) a system of equations to compute a x and y that would cause the rotated pixels in the setPixel function to have the same origin as the original x and y passed to drawString but no joy. Plus, I feel like I am severely over complicating the issue.
I'm not a programmer by trade (and barely one by hobby).  Any advice on how to proceed?
Thanks!
Relevant portions (see links above for complete code):
int16_t txtRotation=0;
float sin_angle=0;
float cos_angle=1;

void MiniGrafx::setTextRotation(int16_t r) {
  int16_t txtAngle=r;
  Serial.print ("Text Angle=");
  Serial.println (txtAngle);
  do
  {
    if (txtAngle>=360) txtAngle=txtAngle-360;
      Serial.println (txtAngle);
  }while (txtAngle>360);
    do
  {
    if (txtAngle<=-360) txtAngle=txtAngle+360;
      Serial.println (txtAngle);
  }while (txtAngle<-360);
  if (txtAngle<0) txtAngle=360+txtAngle;
    txtRotation=txtAngle;

  switch (txtRotation){
    case 0:
      sin_angle=0;
      cos_angle=1;
    break;
    case 45:
      sin_angle=0.707106781;
      cos_angle=0.707106781;
    break;
    case 90:
      sin_angle=1;
      cos_angle=0;
    break;
    case 135:
      sin_angle=0.707106781;
      cos_angle=-0.707106781;
    break;
    case 180:
      sin_angle=0;
      cos_angle=-1;
    break;
    case 225:
      sin_angle=-0.707106781;
      cos_angle=-0.707106781;
    break;
    case 270:
      sin_angle=-1;
      cos_angle=0;
    break;
    case 315:
      sin_angle=-0.707106781;
      cos_angle=0.707106781;
    break;
    default: //compute sin and cos if not a cardinal direction.
      float angle_rad=0.017453*(float)txtRotation; //convert degrees to radians
      sin_angle = sin (angle_rad);          // Pre-calculate the time consuming sin
      cos_angle = cos (angle_rad);          // Pre-calculate the time consuming cosine
    break;
  }

}

void MiniGrafx::drawString(int16_t xMove, int16_t yMove, String strUser) {
  uint16_t lineHeight = pgm_read_byte(fontData + HEIGHT_POS);

  // char* text must be freed!
  char* text = utf8ascii(strUser);

  uint16_t yOffset = 0;
  // If the string should be centered vertically too
  // we need to now how heigh the string is.
  if (textAlignment == TEXT_ALIGN_CENTER_BOTH) {
    uint16_t lb = 0;
    // Find number of linebreaks in text
    for (uint16_t i=0;text[i] != 0; i++) {
      lb += (text[i] == 10);
    }
    // Calculate center
    yOffset = (lb * lineHeight) >> 2;
  }

  uint16_t line = 0;
  char* textPart = strtok(text,"\n");
  while (textPart != NULL) {
    uint16_t length = strlen(textPart);
    drawStringInternal((xMove, yMove - yOffset + (line++) * lineHeight, textPart, length, getStringWidth(textPart, length));
    textPart = strtok(NULL, "\n");
  }
  free(text);
}

void MiniGrafx::drawStringInternal(int16_t xMove, int16_t yMove, char* text, uint16_t textLength, uint16_t textWidth) {
  uint8_t textHeight       = pgm_read_byte(fontData + HEIGHT_POS);
  uint8_t firstChar        = pgm_read_byte(fontData + FIRST_CHAR_POS);
  uint16_t sizeOfJumpTable = pgm_read_byte(fontData + CHAR_NUM_POS)  * JUMPTABLE_BYTES;

  uint8_t cursorX         = 0;
  uint8_t cursorY         = 0;

  switch (textAlignment) {
    case TEXT_ALIGN_CENTER_BOTH:
      yMove -= textHeight >> 1;
    // Fallthrough
    case TEXT_ALIGN_CENTER:
      xMove -= textWidth >> 1; // divide by 2
      break;
    case TEXT_ALIGN_RIGHT:
      xMove -= textWidth;
      break;
  }

  // Don't draw anything if it is not on the screen.
  if (xMove + textWidth  < 0 || xMove > this->width ) {return;}
  if (yMove + textHeight < 0 || yMove > this->height) {return;}

  for (uint16_t j = 0; j < textLength; j++) {
    int16_t xPos = xMove + cursorX;
    int16_t yPos = yMove + cursorY;

    byte code = text[j];
    if (code >= firstChar) {
      byte charCode = code - firstChar;

      // 4 Bytes per char code
      byte msbJumpToChar    = pgm_read_byte( fontData + JUMPTABLE_START + charCode * JUMPTABLE_BYTES );                  // MSB  \ JumpAddress
      byte lsbJumpToChar    = pgm_read_byte( fontData + JUMPTABLE_START + charCode * JUMPTABLE_BYTES + JUMPTABLE_LSB);   // LSB /
      byte charByteSize     = pgm_read_byte( fontData + JUMPTABLE_START + charCode * JUMPTABLE_BYTES + JUMPTABLE_SIZE);  // Size
      byte currentCharWidth = pgm_read_byte( fontData + JUMPTABLE_START + charCode * JUMPTABLE_BYTES + JUMPTABLE_WIDTH); // Width

      // Test if the char is drawable
      if (!(msbJumpToChar == 255 && lsbJumpToChar == 255)) {
        // Get the position of the char data
        uint16_t charDataPosition = JUMPTABLE_START + sizeOfJumpTable + ((msbJumpToChar << 8) + lsbJumpToChar);
        drawInternal(xPos, yPos, currentCharWidth, textHeight, fontData, charDataPosition, charByteSize);
      }

      cursorX += currentCharWidth;
    }
  }
}

void MiniGrafx::setTextAlignment(TEXT_ALIGNMENT textAlignment) {
  this->textAlignment = textAlignment;
}

uint16_t MiniGrafx::getStringWidth(const char* text, uint16_t length) {
  uint16_t firstChar        = pgm_read_byte(fontData + FIRST_CHAR_POS);

  uint16_t stringWidth = 0;
  uint16_t maxWidth = 0;

  while (length--) {
    stringWidth += pgm_read_byte(fontData + JUMPTABLE_START + (text[length] - firstChar) * JUMPTABLE_BYTES + JUMPTABLE_WIDTH);
    if (text[length] == 10) {
      maxWidth = max(maxWidth, stringWidth);
      stringWidth = 0;
    }
  }
  return max(maxWidth, stringWidth);
}

void inline MiniGrafx::drawInternal(int16_t xMove, int16_t yMove, int16_t width, int16_t height, const char *data, uint16_t offset, uint16_t bytesInData) {
  if (width < 0 || height < 0) return;
  if (yMove + height < 0 || yMove > this->height)  return;
  if (xMove + width  < 0 || xMove > this->width)   return;

  uint8_t  rasterHeight = 1 + ((height - 1) >> 3); // fast ceil(height / 8.0)
  int8_t   yOffset      = yMove & 7;

  bytesInData = bytesInData == 0 ? width * rasterHeight : bytesInData;

  int16_t initYMove   = yMove;
  int8_t  initYOffset = yOffset;

  uint8_t arrayHeight = (int) ceil(height / 8.0);
  for (uint16_t i = 0; i < bytesInData; i++) {
    byte currentByte = pgm_read_byte(data + offset + i);

    for (int b = 0; b < 8; b++) {
      if(bitRead(currentByte, b)) {
        uint16_t currentBit = i * 8 + b;
        uint16_t pixelX = (i / arrayHeight);
        uint16_t pixelY = (i % arrayHeight) * 8;
        setPixel(pixelX + xMove, pixelY + yMove + b);
      }
    }
    yield();

  }
}

void MiniGrafx::setPixel(uint16_t x, uint16_t y) {

  uint16_t newX = (int) (((float)x * cos_angle) - ((float)y * sin_angle));
  uint16_t newY = (int) (((float)y * cos_angle) + ((float)x * sin_angle));

  if (newX >= width || newY >= height || newX < 0 || newY < 0 || color < 0 || color > 15 || color == transparentColor) return;
  uint16_t pos = (newY * width + newX) >> bitShift;
  if (pos > bufferSize) {
    return;
  }
  uint8_t shift = (newX & (pixelsPerByte - 1)) * bitsPerPixel;
  uint8_t mask = bitMask << shift;
  uint8_t palColor = color;
  palColor = palColor << shift;
  buffer[pos] = (buffer[pos] & ~mask) | (palColor & mask);
}


text:
Q: Python matplotlib.plot the pointe messed up due to the picture size?
Hey everyone! I use the python matplotlib.plot to draw a line

Here is my data
x = ['1000', '5950', '10900', '15850', '20800', '25750', '30700', '35650', '40600', '45550', '50500', '55450', '60400', '65350', '70300', '75250', '80200', '85150', '90100', '95050', '100000']
y = ['0.003383', '0.16341', '0.543723', '1.19463', '2.12827', '3.33978', '4.70849', '6.46607', '8.52736', '11.2711', '14.3101', '18.176', '26.1123', '32.0252', '31.692', '43.1399', '48.2962', '48.2436', '52.6464', '61.8072', '68.8354']

I write this in IPython
import matplotlib.pyplot as plt
plt.plot(x,y)
plt.show()

and it gived me this
check this

I mean, according to the x y list, it should a Increasing curve.
So, can someone can assist?
I will appreciate if you give any advice:)

A: This happens because the lists you are using contain strings. What you actually want are integers for x, and floats for y. In order to do this you can cast the contents of the lists to either int or float using a list comprehension.
import matplotlib.pyplot as plt

x = ['1000', '5950', '10900', '15850', '20800', '25750', '30700', '35650', '40600', '45550',
     '50500', '55450', '60400', '65350', '70300', '75250', '80200', '85150', '90100', '95050', '100000']
y = ['0.003383', '0.16341', '0.543723', '1.19463', '2.12827', '3.33978', '4.70849', '6.46607',
     '8.52736', '11.2711', '14.3101', '18.176', '26.1123', '32.0252', '31.692', '43.1399', '48.2962', '48.2436',
     '52.6464', '61.8072', '68.8354']

# Convert contents of lists
new_x = [int(i) for i in x]
new_y = [float(j) for j in y]

fig, (ax1, ax2) = plt.subplots(1,2)
ax1.plot(x,y)
ax1.set_title("List of strings")

ax2.plot(new_x,new_y)
ax2.set_title("Lists have been converted")

plt.show()

Which produces:


text:
Q: Laptop doesn' t want to wake up My laptop (Notebook HP Pavilion g7t-1100 CTO) have been working fine till today, I enabled Virtual Technology in BIOS and from that time laptop doesn't want to wake up after I slept it. When I disable VT it works fine again. I have installed two softwares: Windows 7 and Ubuntu and on both of them it doesn't want to wake up. Do you have any ideas how I can fix it?

A: This happened to me about two months ago. Don't worry chances are that it is locked up. If your computer has an external battery pull it out.
If your computer doesn't have a battery, close it flip it upside-down, then there is a pin hole. if your computer has this use a paperclip or staple to press the button inside the hole. (kinda like the reset buttons on old hand-held football games).
If this doesn't work, take it to best buy (hear me out) they'll fix it for free if all they have to do is a restart. Just make sure you ask if its free.


text:
Q: Firebase and json-server I'm currently using json-server repo to emulate my back-end db and server for a prototype. To use/start json-server, I need to execute npm run json:server.
I've deployed my project to firebase but can't find a way to access a cmd or run that command from my own git-bash.
Is there any way of doing so or firebase doesn't allow to run commands on their end?

A: If you want to run small Node.js snippets on Firebase, have a look at the integration between Firebase Hosting and Cloud Functions.
Also see the Firebase documentation on what can you host on Firebase? and the overview documentation for running micro-services on Firebase Hosting and Cloud Functions.


text:
Q: How can I add 'pages' in addition to 'tags' with acts-as-taggable-on I am just in the last few months learning Ruby from a client project, and have now decided to port my legacy CMS into Ruby.
I have successfully installed the gem and implemented acts-as-taggable-on with tags and taggings so that I have tags working in my Post controller.  I can add tags to my edit form, and they are linked in my posts as expected.
What I am hoping to do is use the enhanced features of acts-as-taggable-on to define another set of 'tags' which are actually pages.  In my current application I have a table called Pages, and the Posts have a field called PageID.  The Pages table holds the name of the page, as well as some config features for that page, such as layout and css.  Posts can only appear in the Page they were assigned/created from.
Since all Posts are stored in the same table, I was hoping to extend the acts-as-taggable-on to handle both my tagging and pages, if this makes sense.
I understand how the same tagging model can be extended to other controllers such as Photos, Video etc, but I am unsure how I would go about applying 2 different 'tagging' models to the same Controller.  If I don't use tagging for the pages, I am unsure about how I would define the 'pages' in a Ruby context, since I need the page names to be dynamic per user.  I understand theoretically how to do this in routes.rb but am stuck as how to define my pages.
Thanks for any help!  Let me know what .rb file code to post to illustrate what I am doing now.

A: You could use the following approach:
Create two classes "Page" and "Post" that inherit from a base "UserContent" class. The "Page" and "Blog" classes would have to each have their own controller.
You could route to each of them with something like:
scope '/blog' do
  resources :posts
end

scope '/about' do
  resources :posts
end

To use the post name instead of an id, I would highly recommend you checkout stringex which will allow you to do just that. It will involve adding a url attribute to your models but I'll let you check out their documentation to find out how it all works. This should be the answer to your original question and it should be a better tool for dynamic page/post page names than acts-as-taggable-on.
This setup should give you "site.com/about/page-name" for pages and "site.com/blog/post-name" for posts.


text:
Q: Is there a way to make GEKKO work with pandas? I'm trying to make GEKKO maximize the function "Profit" but I can't make it work. I always end up with the error below.
I need GEKKO solver to choose the best values for (Weight1, Weight2, Weight3... Weight8) so the "Result" returned by the function "Profit" is the highest possible.
Each Weight can be any value between 0 (0%) and 15 (15%) and the sum of all Weights must be 100 (100%).
All DataFrames are required to calculate the final profit of eack Pick (Pick1, Pick2, Pick3... Pick8) and the Benchmark.
In the end the "Result" is the sum of each Pick's profit minus the Benchmark's profit.
So:
Weights are the Variables;
Their bounds are from 0 to 15;
The constraint is their sum must be 100.
So far I could only find examples of GEKKO Maximizing defined equations. Can it do something like this?
Here is my code:
from gekko import GEKKO
import pandas as pd

m = GEKKO()

Weight1 = m.Var(value=15,lb=0, ub=15)
Weight2 = m.Var(value=15,lb=0, ub=15)
Weight3 = m.Var(value=15,lb=0, ub=15)
Weight4 = m.Var(value=15,lb=0, ub=15)
Weight5 = m.Var(value=15,lb=0, ub=15)
Weight6 = m.Var(value=15,lb=0, ub=15)
Weight7 = m.Var(value=15,lb=0, ub=15)
Weight8 = m.Var(value=15,lb=0, ub=15)

m.Param(Weight1 + Weight2 + Weight3 + Weight4 + Weight5 + Weight6 + Weight7 + Weight8 == 100) #Sum of Weights must be 100%

def Profit(Weight1, Weight2, Weight3, Weight4, Weight5, Weight6, Weight7, Weight8):

    RETURNS  = OPTIMIZATION_TABLE

    PICKS = RETURNS[["picks"]].drop_duplicates()
    PICKS["Weights"] = ""

    PICKS.loc[(PICKS['picks']== "pick2") ,'Weights'] = Weight1/100
    PICKS.loc[(PICKS['picks']== "pick1") ,'Weights'] = Weight2/100
    PICKS.loc[(PICKS['picks']== "pick3") ,'Weights'] = Weight3/100
    PICKS.loc[(PICKS['picks']== "pick4") ,'Weights'] = Weight4/100
    PICKS.loc[(PICKS['picks']== "pick5") ,'Weights'] = Weight5/100
    PICKS.loc[(PICKS['picks']== "pick6") ,'Weights'] = Weight6/100
    PICKS.loc[(PICKS['picks']== "pick7") ,'Weights'] = Weight7/100
    PICKS.loc[(PICKS['picks']== "pick8") ,'Weights'] = Weight8/100

    COMPLETE = pd.merge(RETURNS, PICKS, left_on="picks", right_on="picks", how="left")
    COMPLETE["final_return"] = COMPLETE.Weights * COMPLETE.daily_return

    DATE_GROUP = pd.DataFrame(COMPLETE.groupby(['date'],as_index=False)['final_return'].sum())
    DATE_GROUP = DATE_GROUP.sort_values("final_return", ascending=True)
    DATE_GROUP = DATE_GROUP.reset_index(drop=True)

    BENCHMARK_GROUP = BENCHMARK[["date", "daily_return"]]
    BENCHMARK_GROUP = BENCHMARK_GROUP.sort_values('daily_return', ascending=True)
    BENCHMARK_GROUP = BENCHMARK_GROUP.reset_index(drop=True)

    FINAL_TABLE = pd.merge(BENCHMARK_GROUP, DATE_GROUP, left_index=True, right_index=True)
    FINAL_TABLE["dif"] = FINAL_TABLE.final_return - FINAL_TABLE.daily_return

    Result = sum(FINAL_TABLE.dif)

    return Result

m.Maximize(Profit)

m.solve(disp=True)

And this is what I get in the end:
    --------- APM Model Size ------------
 Each time step contains
   Objects      :            0
   Constants    :            0
   Variables    :            9
   Intermediates:            0
   Connections  :            0
   Equations    :            1
   Residuals    :            1

 @error: Model Expression
 *** Error in syntax of function string: Invalid element: <functionsolverat0x000
 001c63000dfc0>

Position: 1
 <functionsolverat0x000001c63000dfc0>
 ?

Can someome help me, please?
Thank you for your time!

A: Gekko builds a symbolic form of a model the first time through and then compiles the variables and equations into byte-code with automatic differentiation for the gradient-based solvers. This means that any function call is only used when building the model, not when solving the model.
There are ways to reformulate the model with binary variables for selections. Here is an example of a binary variable.
x = m.Var(lb=0,ub=1,integer=True)

Other logical conditions include if statements such as m.if3(x,0,1) and sos1 (special ordered sets of type-1). The SOS is a combination of binary variables with only one that is allowed to be non-zero. Chose one from a set of possible numeric values that are mutually exclusive options.
from gekko import GEKKO
m = GEKKO()
y = m.sos1([19.05, 25.0, 29.3, 30.2])
m.Obj(y) # select the minimum value
m.solve()
print(y.value)

Numpy, Pandas or other functions that create a symbolic representation of the equation are allowed in Gekko.


text:
Q: После звонка с приложения, статус бар меняет цвет так я настроил StatusBar и NavigationBar в didFinishLaunchingWithOptions
static func setParamsBars(){
let bounds = UIScreen.main.bounds

UIApplication.shared.statusBarView?.backgroundColor = .clear

UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName: UIFont(name: "SFUIDisplay-Regular", size: 18)!]

let imagebar : UIImage = UIImage(color: UIColor(red: 136.0/255.0, green: 136.0/255.0, blue: 136.0/255.0, alpha: 0.8), size: CGSize(width: bounds.size.width, height: 84))!
UINavigationBar.appearance().setBackgroundImage(imagebar, for: .default)
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().isTranslucent = true
}

мой первый скрин кода все ок:

теперь я звоню с приложения:

когда возвращаюсь после звонка обратно в приложение то статус бар уже такого цвета:
Я понятия не имею что происходит, суть в том что статус бар у меня прозрачного цвета. Мб какие то слои накладываются. Буду рад любой помощи.
EDIT:
Проблема на iphone5 и iPhone 5s. На 6 iPhone все норм.
UPDATE:
скрины Debug View Hierarchy
До звонка:

после звонка:


text:
Q: mongodb dot notation with $pop Using MongoDB, (web console available here) I have some data:
db.foo.insert({
    item: "stuff",
    qty: 17,
    test: {
        bob: 1,
        alice: 2,
        candice: 3,
        myarray: ["a","b","c","d"]
    }
})

How do I pop from myarray?
I've tried:
db.foo.update(
    {'test.bob':1},
    { $pop: {'test.myarray': -1}}
)

and:
db.foo.update(
    {'test.bob': 1},
    { $pop: {'test': {'myarray': -1}}}
)

I know the query portion is correct, just not the $pop portion, because the following returns a correct result:
db.foo.find(
    {'test.bob': 1}
)

I've researched $pop, dot-notation, a random question I found that had no response, and even a github commit that shows a working example of nearly what I'm trying to do (albeit with a $pull instead of a $pop on line 357). The error code I keep receiving is:

SyntaxError: invalid property id @(shell):3:6

A: Turns out the code listed in the question actually works: I was using an older version of MongoDB likely when that feature was not added. Another poster mentioned this but for some reason the answer has disappeared.
For reference, use db.version() to get the version
The version running on jdoodle at the time of this post is 3.2.4, which is not the current version of Mongo (which is 3.6 at the time of this post).


text:
Q: Is calling c function from lua faster than from c? Im kind of new to lua (well, I actually learned basic lua and how to use lua from c), and I am working on a simple tetris game using lua in c. (it sounds weird, but just for practice :D)
And I have a few questions:

*

*I was wondering if calling c function from lua is faster.

*if Q1 is yes, is it ok to call drawing functions in c from lua?
Doesn't it cause any slow down in my program?

*What is the recommended Lua_C programming (just my way to call the program that uses lua as a script language) structure?

Ex) what kind of code should be written in Lua? What kind of code should be written in C? (drawing code, logic code, and etc.)

A: *

*Simple answer: No. It won't be faster. There is going to be some overhead related to the function call from Lua to C.

*Calling the drawing function is okay, since the actual drawing will take a lot more time than the function call anyways.

*The rule of thumb is usually to write the logic using a scripting language (in this case, Lua) and let C handle any performance intensive parts, such as rendering and heavy calculations. For example, you probably won't gain any performance by letting C handle the character movement and stuff like that. You could use a profiler to figure out which parts that might gain performance from a C implementation.


text:
Q: Visualization issues with vim using Go-Global One of the new student in our lab is using her PC laptop to connect to our server using Go-Global for Unix v.2.3.0. There are two steps involved:

*

*Opening a Xterm session in Go-Global gets her into a server accessible from outside of the school

*She then ssh to our main server (step 1 is mandatory).

On the intermediate server, everything works just as expected. However, on the main server, we are experiencing some issues with Vim and its display. For example, if we go into insert mode, start typing something then erase it with backspace, the erased characters are still showing. I verified that the deleted characters that are still showing are indeed deleted by yanking and pasting the line somewhere else in the code. Also, after going out of insert mode, the --- INSERT --- sign at the bottom does not disappear.
The main server uses a bash shell and Vim version 7.4. The dummy server is using tcsh but I doubt this is related to the present issue.


text:
Q: How to parse nested table from HTML link using BeautifulSoup in Python? All,
I am trying to Parse table from this link http://web1.ncaa.org/stats/StatsSrv/careersearch.
Please Note: For searching  under "School/Sport Search"  select All for School, Year -2005-2006, Sport -Football, Division I. The column I am trying to Parse is the School Names, and if you click on School Name.More information will output. From that link/Table I would like to Parse "Stadium Capacity" for each and every School. My question is Is something like this possible ? If yes,how ? I am new to python and BeautifulSoup, if you can provide explanation that will be Great!
Note: There are 239 results,
To Summarize: so Basically I would like to parse School Names along with their Stadium Capacity and convert it into Pandas Data-frame
import requests
from bs4 import BeautifulSoup
URL = "http://web1.ncaa.org/stats/StatsSrv/careerteam"
r = requests.get(URL)

soup = BeautifulSoup(r.content, 'html5lib')
print(soup.prettify())

A:
My question is Is something like this possible ?

Yes.

If yes,how ?

There is a lot going in the code below. But the main point is to figure out the post requests being made by the browser and then emulate that using Requests. We can find out the request being made through the  "network" tab in the inspect tool.
First we make the 'search' post request. This gives a left and right table. Clicking on the left table gives us the schools in that area. But if we observe carefully clicking on the area link also is a post request (which we have to do using requests)
Eg. Clicking on 'Air Force - Eastern Ill.' gives us a table containing the links of schools in that area. Then we have to go to that school link and figure out the capacity.
Since clicking on each of the school link is also a post request we have to emulate and this returns the school page. From here we scrape the school name and capacity.
You can read Advanced Usage of requests to know about Session objects, Making a request to read about making request with Requests.
import requests
from bs4 import BeautifulSoup
import pandas as pd
end_list=[]
s = requests.Session()
URL = "http://web1.ncaa.org/stats/StatsSrv/careersearch"
data={'doWhat': 'teamSearch','searchOrg': 'X', 'academicYear': 2006, 'searchSport':'MFB','searchDiv': 1}
r = s.post(URL,data=data)
soup=BeautifulSoup(r.text,'html.parser')
area_list=soup.find_all('table')[8].find_all('tr')
area_count=len(area_list)#has no of areas + 1  tr 'Total Results of Search:  239'
for idx in range(0,area_count):
    data={
    'sortOn': 0,
    'doWhat': 'showIdx',
    'playerId':'' ,'coachId': '',
    'orgId':'' ,
    'academicYear':'' ,
    'division':'' ,
    'sportCode':'' ,
    'idx': idx
    }
    r = s.post(URL,data=data)
    soup=BeautifulSoup(r.text,'html.parser')
    last_table=soup.find_all('table')[-1]#last table
    for tr in last_table.find_all('tr'):
        link_td=tr.find('td',class_="text")
        try:
            link_a=link_td.find('a')['href']
            data_params=link_a.split('(')[1][:-2].split(',')
            try:
                #print(data_params)
                sports_code=data_params[2].replace("'","").strip()
                division=int(data_params[3])
                player_coach_id=int(data_params[0])
                academic_year=int(data_params[1])
                org_id=int(data_params[4])
                #print(sports_code,division,player_coach_id,academic_year,org_id)
                data={
                'sortOn': 0,
                'doWhat': 'display',
                'playerId': player_coach_id,
                'coachId': player_coach_id,
                'orgId': org_id,
                'academicYear': academic_year,
                'division':division,
                'sportCode':sports_code,
                'idx':''
                }
                url='http://web1.ncaa.org/stats/StatsSrv/careerteam'
                r = s.post(url,data=data)
                soup2=BeautifulSoup(r.text,'html.parser')
                institution_name=soup2.find_all('table')[1].find_all('tr')[2].find_all('td')[1].text.strip()
                capacity=soup2.find_all('table')[4].find_all('tr')[2].find_all('td')[1].text.strip()
                #print([institution_name, capacity])
                end_list.append([institution_name, capacity])

            except IndexError:
                pass

        except AttributeError:
            pass
#print(end_list)
headers=['School','Capacity']
df=pd.DataFrame(end_list, columns=headers)
print(df)

Output
                School Capacity
0            Air Force   46,692
1                Akron   30,000
2              Alabama  101,821
3         Alabama A&M;   21,000
4          Alabama St.   26,500
5          Albany (NY)    8,500
6               Alcorn   22,500
7      Appalachian St.   30,000
8              Arizona   55,675
9          Arizona St.   64,248
10     Ark.-Pine Bluff   14,500
11            Arkansas   72,000
12        Arkansas St.   30,708
13     Army West Point   38,000
14              Auburn   87,451
15         Austin Peay   10,000
16                 BYU   63,470
17            Ball St.   22,500
18              Baylor   45,140
19     Bethune-Cookman    9,601
20           Boise St.   36,387
21      Boston College   44,500
22       Bowling Green   24,000
23               Brown   20,000
24            Bucknell   13,100
25             Buffalo   29,013
26              Butler    5,647
27            Cal Poly   11,075
28          California   62,467
29   Central Conn. St.    5,500
..                 ...      ...
209               UCLA   91,136
210              UConn   40,000
211                UNI   16,324
212               UNLV   36,800
213          UT Martin    7,500
214               UTEP   52,000
215               Utah   45,807
216           Utah St.   25,100
217                VMI   10,000
218         Valparaiso    5,000
219         Vanderbilt   40,350
220          Villanova   12,000
221           Virginia   61,500
222      Virginia Tech   65,632
223             Wagner    3,300
224        Wake Forest   31,500
225         Washington   70,138
226     Washington St.   32,740
227          Weber St.   17,500
228      West Virginia   60,000
229      Western Caro.   13,742
230       Western Ill.   16,368
231        Western Ky.   22,113
232      Western Mich.   30,200
233     William & Mary   12,400
234          Wisconsin   80,321
235            Wofford   13,000
236            Wyoming   29,181
237               Yale   64,269
238     Youngstown St.   20,630

[239 rows x 2 columns]

Note:
This will take a long time. We are scraping >239 pages. So be patient. Might take 15 mins or longer.


text:
Q: How to disable keyboard but enable UITextFields when using UIDatePicker? This one is kind of hard to explain, so ask any questions you need to clarify the question. I have an iPad app (XCode 4.2, iOS 6, ARC and Storyboards).
In this app, I have a UIPopover that contains a UIView with two (2) UITextFields in it and a UIDatePicker. (see image).  When I go to that scene, I have unchecked userInteractionEnabled on both textFields to prevent the keyboard from responding, which works, but doesn't allow the other UITextField to be accessed after the first one. I tried [oFinishTime setInputView:oTimePicker]; but it takes the timepicker and moves it outside of the popover, which is unacceptable.

I have touchUpInside events "wired" for each of the textFields, but neither one gets called when tapped due to UserInteractionEnabled being unchecked.  I could remedy this whole thing if I could have it enabled and set a flag in the action event.
How can I enable both UITextFields yet prevent the keyboard from showing?  I will be happy to post any relevant code you need to see.

A: - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;        // return NO to disallow editing.

assign delegate for each textfield and in the delegate method verify if its the one which should open picker instead of keyboard.
If it is the one then return NO
else YES
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
      if (textfield == startTimeTextField)
       {
          [self openPicker];
          return NO;
        }
    return YES;
}

A: May be I did not understand your problem correctly , but it seems like you all you are trying to do is Open a picker on tap and display the value set in UIPicker.  You are not really using any functionality of a UItextField. A label or a button might serve the same purpose and save you from doing the extra work of disabling the keyboard.
In any case if you want to use textfield and disable keyboard picker appearing as the input view and have your own input view to it, you could do
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [textField resignFirstResponder];
}

You could take a look at this:
Display datepicker on tapping on textfield


text:
Q: Adding a custom form field in a Shopify JSON Template I have a Shopify store using the new Dawn template, which includes JSON templates. I'd like to add a textarea where customers can write text they'd like to have engraved on their items, which seems to be a common usecase.
I added a "Custom liquid" element to my product page and inserted a form field generated by the Shopify UI Element generator. However, I noticed that this field isn't inside the <form> element, so it wasn't getting included in the order.
I looked at the source of the product page, and noticed the form has an ID like product-form-template--14290791497780__main. I copied that ID and set it as the form attribute on my textbox, and now everything's working but it feels fragile.
In the JSON templates, what generates that ID for the form field? Is there a way to refer to it from the liquid template without having to hard code the ID?
EDIT:
Here's my product.json template
The important part is this bit
        "728d07ea-3e35-4ab1-bed3-ac9d9f35875c": {
          "type": "custom_liquid",
          "settings": {
            "custom_liquid": "<p class=\"line-item-property__field\">\n  <label for=\"engraving\">Engraving<\/label>\n  <p>\n<textarea id=\"engraving\" name=\"properties[Engraving]\"\nform=\"product-form-template--14302685823028__main\"><\/textarea>\n<\/p><\/p>"
          }
        },
        "buy_buttons": {
          "type": "buy_buttons",
          "settings": {
            "show_dynamic_checkout": true
          }
        },

As far as I can tell, the "buy_buttons" block is what creates the submission form for the product. My custom liquid block includes form=\"product-form-template--14302685823028__main\", which is the ID of the form I got by viewing source on the page. I'd like to replace that with some liquid expression, like {{ product_form.id }} or whatever, but I don't know how to refer to other blocks in the JSON template from a custom liquid block.

A: Ok, I figured out out. The actual template is in sections/main-product.liquid.  I added a section there for my custom field, added my new block to the schema at the end of the template, and added it to the json for my customizable product page.

A: You need to go customize a theme and just click on the Products option go to any of your templates and click the add block of the product information and add the Custom Liquid.
enter image description here
and go to the Custom Liquid and add your HTML code and save it,after saving you can check your chenges
enter image description here


text:
Q: iphone collision detection problem using chipmunk I have 2 slight problems :
chipmunk collision detection : i'm developping a game where i detect collisions between a ball and some static polygon shapes.
this is working but "partially", meaning that it works for around 5 game scenes (level 1 - 5 , for ex.) but fails for the 6th one, and then on the 7th scene everything works ok etc..
basically, the collision detection is working but fails at times..
I don't think its a problem with setting spaces, bodies etc.. because everything works ok for a while and the error only occurs once after a series of "correct scenes".
At 1st i thought the problem was my not removing shapes and bodies from the space after a scene is over, but the problem still continues after removed the bodies and shapes from the space.
cocos2d : as for cocos2d, i have the impression that the accelerometer activation fails at times.
has anyone come across any of these problems? any suggestions are welcome, thanks.
Posts: 1
Joined: Wed Jun 24, 2009 2:34 pm

A: Are you only using chipmunk for collision detection?
If so, don't. Just define the collision between the two shapes (assuming the polygons are similar). Here is an example for two circles:
http://kwigbo.com/wp/2009/03/04/cocos2d-circle-to-circle-collision-detection/
In my own game I defined a collision between two rectangular sprites by checking through the array objects and seeing if they were withing a certain range on either side of my hero, and also a certain distance with the top or bottom. Doing this for a funky shape would be tricky, but worth it.


text:
Q: How to display an image if the file name in the folder is different from the file name in the database? I am currently displaying the file name from the database on my PHP page. However, some file names on the server's folders have a different case. So the database may say image1.jpg and the file name on the server may say "image1.JPG" in upper case.  This is random with some of the files.  These files do not get displayed.  Is there a way that I can use a function so that it can be displayed.  We are talking about more than 1000 files here.  So any help would be highly appreciated.

A: I would run a custom file_exists() function to check for which case the image's extension is.
Use this custom function to check for the correct case (pass it lowercase, then use lowercase if it returns a 1, or use uppercase if it returns a 2):
function file_exists_case($strUrl)
{
    $realPath = str_replace('\\','/',realpath($strUrl));

    if(file_exists($strUrl) && $realPath == $strUrl)
    {
        return 1;    //File exists, with correct case
    }
    elseif(file_exists($realPath))
    {
        return 2;    //File exists, but wrong case
    }
    else
    {
        return 0;    //File does not exist
    }
}

You really should go in and make all your file name extensions lowercase when you get the time, though.
The way you would do that is by running a glob() through the directories:  http://php.net/manual/en/function.glob.php  and renaming every file extension to lowercase using strtolower(): http://php.net/manual/en/function.strtolower.php

A: Not sure if converting the extensions to lowercase is an option.  But if there are no other systems that depend on certain extensions to be capitalized then you could run something like this:
find . -name '*.*' -exec sh -c '
a=$(echo {} | sed -r "s/([^.]*)\$/\L\1/");
[ "$a" != "{}" ] && mv "{}" "$a" ' \;

A: Use file_exists to do a check. And expand that out to compensate for the issues you are facing. I am using the function called replace_extension() shown here.
<?php

// Full path to the file.
$file_path = '/path/to/the/great.JPG';

// Call to the function.
echo check_if_image_exists($file_path, $file_ext_src);

// The function itself.
function check_if_image_exists ($file_path) {

    $file_ext_src = end(explode('.', $file_path));

    if (file_exists($file_path)) {
        return TRUE;
    }
    else {

        if (ctype_lower($file_ext_src)) {
            $file_ext_new = strtoupper($file_ext_src); // If lowercase make it uppercase.
        }
        else if (ctype_upper($file_ext_src)) {
            $file_ext_new = strtolower($file_ext_src); // If uppercase make it lowercase.
        }

        // Now create a new filepath with the new extension & check that.
        $file_path_new = replace_extension($file_path, $file_ext_new);
        if (file_exists($file_path_new)) {
            return TRUE;
        }
        else {
            return FALSE;
        }
    }
}

// Nice function taken from elsewhere.
function replace_extension($filename, $new_extension) {
    $info = pathinfo($filename);
    return $info['filename'] . '.' . $new_extension;
}

?>


text:
Q: Establish TCP connection to computer on different network without the recipient having to go into their router settings? Overview
I'm trying to establish a connection between two computers on different networks without requiring the recipient to have to mess with their router's port forwarding settings
Scenario
I'm currently using a Rust script to establish a tcp connection between 2 ports on the same computer and all that it is supposed to do is print Hello, world! to the terminal running recipient.exe. It works perfectly.
Question
Say I distribute this application to a bunch of users. Each user would have both recipient.exe and sender.exe, and would run either depending on if they wanted to send or receive information to/from another user.
How do I let one user connect to the other without having to make them open their router settings?
Is there a different protocol I can use? Is there a universally-open port I can use? Can the machine running the program force the router to open a port temporarily?
I've wondered this for a while and I finally ran into actually needing to solve it
recipient.rs
use std::net::TcpStream;
use std::net::TcpListener;
use std::io::{Error, Read, Write};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        println!("Connection established!");

        handler(stream).unwrap_or_else(|error| eprintln!("{:?}", error));
    }
}

fn handler(mut stream: TcpStream) -> Result<(), Error> {
    println!("Connection from {}", stream.peer_addr()?);
    let mut buffer = [0; 128];
    loop {
        let nbytes = stream.read(&mut buffer)?;
        if nbytes == 0 {
            return Ok(());
        }

        print!("Received data: ");

        for i in 0..nbytes {
            print!("{}", buffer[i] as char);
        }
        println!("");

        stream.flush()?;
    }
}

sender.rs
use std::io::prelude::*;
use std::net::TcpStream;

fn main() -> std::io::Result<()> {
    let mut stream = TcpStream::connect("127.0.0.1:7878")?;

    stream.write(&"Hello, world!".as_bytes())?;
    stream.read(&mut [0; 128])?;
    Ok(())
}


text:
Q: Using unix 'mail' command from CGI - dangerous? I am adding a feedback form to a web page and would like to know if it is safe to simply filter the contents of the TEXTAREA element (after decoding) through the 'mail' command to send an e-mail to the page's maintainer.
I have looked at the man page and cannot see a way to abuse this, in particular as long as 'mail' does not run in interactive mode, tilde escapes are disabled and '.' on a line by itself does not terminate the message body.
But is there any other danger I should be aware of?
The command looks something like:
echo "$MESSAGE_BODY" | mail webmaster@mydomain.com -s 'Website feedback'

A: Yes it is dangerous. The mail message can contain lines beginning with a tilde ~ character that are treated as escape sequences by the mail program. This includes shell escapes and adding new recipients. (mmmm, spam!)
Just have a look at
$ man mail

To see what I mean.

A: It's great that you're asking this - many people just want to get the job done, and so introduce a whole bunch of vulnerabilities on the bases that "Ahhh... It'll be fine".
Having said that, I think it's fine to do what you're doing - but as long as you use a filter - and not a filter you've written yourself, but one that is open source (hence open to public scrutiny), mature (has been around for a while).  I'd also make sure the filter strips out any HTML tags and content that may be nesting some nasty XSS attacks.
Use an open-source library where you can find one is basically what I'm getting at.  (Don't ever use any closed security applications - they're all doomed to fail - and I can sign my name on that comment).

A: I'd try to avoid calling any commands from a CGI. I am sure whatever language you're using should have a library to send emails.

A: It's a huge security hole. Here's a resource for writing safe CGI code.
Just to give you an idea, here's a list of characters with special uses that you need to be aware of:
Character Name   Character   Problems
backslash        \   quoting
double quote     "   quoting
single quote     '   quoting
dollar sign      $   variable substitution
ampersand        &   command separator
greater than     >   I/O redirection
less than        <   I/O redirection
asterisk         *   file globbing
question mark    ?   file globbing
left bracket     [   file globbing
right bracket    ]   file globbing
left paren       (   word separator
right paren      )   word separator
pipe             |   command separator
backtick         `   subcommand execution
semicolon        ;   command separator
pound sign       #   comment character (sh only)
caret            ^   command separator (sh only)
exclamation      !   history execution (csh only)
tilde            ~   username expansion (csh only)
carriage return  <ascii 13>   command separator
line feed        <ascii 10>   command separator
space            word separator
tab              ascii 9   word separator
NULL             ascii 0   truncates input

Use a library where someone that someone else has already implemented and debugged. Email forms have been done before, don't re-invent the wheel!

A: What kind of CGI do you use?
Most cgi languages / frameworks have support for sending mails.
They are always better than calling external commands. Well PHP's mail() is really bad, but still better that calling external commands.
From the security perspective sending mails with SMTP (e.g. to localhost) is recommended.

A: Don't use mail, which is meant to be a line-oriented end-user program. Use the "sendmail" command (but don't use that cursed piece of shblip that is the sendmail program) included in most MTA. It's meant to be used programatically. I know that postfix and qmail, for example, include it.
cat mailmessage.txt | sendmail -ffrom@yourhost recipient@theirhost

Addendum: it's not necessarily "dangerous" to call a program from a CGI, as long as you know what you're doing. In particular, just as in this case, make sure that the program you're calling is not intended for end-users or is not called in interactive mode (most such programs will allow spawning a shell!)


text:
Q: Table column values calculation using jQuery I have some table & i need to calculate Column values.In my scenario i need to calculate Total Item Price 99 + 55 = 154 to Sub Total Row.In here my SubTotal Calculation not working.

My Code(part of my Table Creation)
  $option.each(function () {
            if ($(this).prop('selected')) {
                var txtId = 'txtQty' + i;
                var lblId = 'lblQty' + i;
                var row = $('
' + $(this).text() + '	' + $(this).attr('RetailPrice') + '	' + $(this).attr('WholesalePrice') + '	' + '<input type="text" id="' + txtId + '">' + '	 <button type="button" class="btn btn-warning btn-xs btncalc">Calculate</button>
');

                table.append(row);
                i++;
            }

        });
 var row2 = $('
' + "SubTotal" + '
');
        table.append(row2);
        $('#product-load-tbl').append(table);
    });

Calculation Part
    $('.btncalc').live('click', function () {
            debugger;
            var row = $(this).parents("tr:first");
            var rowval = $(row).find("td:eq(1)").html();
            var inpval = $(row).find("td:eq(3) input").val();

            if (inpval != null || inpval != 0) {
                var result = (rowval * inpval);
            }
            else {
                var result = 0;
            }
            $(row).find("td:eq(5)").html(result);

            var lstrow = $(this).parents("tr:last"); // this sub total calculation not working
            $.each($('.tot'), function (element) {

                $(lastrow).find("td:eq(5)").html(element);

            });

        })

A: You can change this:
$.each($('.tot'), function (element) {
   $(lastrow).find("td:eq(5)").html(element);
});

to this:
var total = 0; // intialise a var with value 0
$('.tot').each(function (i, element) { // loop the selected item in each row
   total += +$(this).text(); // cast the string to integer and add it to total
});
$(lastrow).find("td:eq(5)").text(total); // then at last place the total

Short demo

And for a short note:
.live() is now removed from the latest jQuery versions, so if you are using version 1.7+ then you can move your code to .on() method to delegate the event. Syntax is something like this for event delegation:
$(static_parent).on(event, selector, callback);

$(static_parent) is the element which was available when the relative dom is ready and it was available at that time before appending any dynamic dom element in the page.
so in your case:
$('table_ID/Class').on('click', '.btncalc', function(){
    //...all the stuff with .live goes here
});


text:
Q: Canvas zooming in android for my project I use a canvas to display two images, and I try to zoom in according to the position of the fingers but before arriving there when I click on the image it gives me a boolean error and I do not understand this that I need to do
private void drawBitmap(Canvas canvas) {
    canvas.save();
    canvas.translate(mPositionX,mPositionY);
    canvas.scale(mScaleFactor,mScaleFactor);
    canvas.drawBitmap(background,null,rect,null);
    canvas.drawBitmap(tank,(dWidht/2-tankWidth/2),dHeight-tankHeight,null);
    canvas.restore();
}

  public boolean onTouchEvent(MotionEvent event){
  mScaleDetector.onTouchEvent(event);
  switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
    refX =event.getX();
    refY=event.getY();

    paint((int)((refX-mPositionX)/mScaleFactor),(int)((refY-mPositionY)/mScaleFactor));
break;

case MotionEvent.ACTION_MOVE:
    float nX=event.getX();
    float nY=event.getY();

    mPositionX += nX-refX;
    mPositionY +=nY-refY;
    refX=nX;
    refY=nY;
    invalidate();
 }
   return true;
}

and here is the error
2020-11-22 17:58:06.788 21138-21138/? E/InputEventReceiver: Exception dispatching input event.
2020-11-22 17:58:06.788 21138-21138/? E/MessageQueue-JNI: Exception in MessageQueue callback:
handleReceiveCallback
2020-11-22 17:58:06.789 21138-21138/? E/MessageQueue-JNI: java.lang.NullPointerException:
Attempt to invoke virtual method 'boolean
android.view.ScaleGestureDetector.onTouchEvent(android.view.MotionEvent)' on a null object
reference
    at com.example.myapplication.GameView.onTouchEvent(GameView.java:92)
    at android.view.View.dispatchTouchEvent(View.java:13551)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3088)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2724)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3088)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2724)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3088)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2724)
    at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:497)
    at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1853)
    at android.app.Activity.dispatchTouchEvent(Activity.java:4061)
    at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:455)
    at android.view.View.dispatchPointerEvent(View.java:13812)
    at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5649)
    at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5449)

A: the problem is solved I rewrote my code completely


text:
Q: Python connect and send message to socket.io 1.0? Currently using the latest version of socket.io. I'm wondering how to connect to a namespaced socket via python (using the websocket module for instance).
My main goal is to send a message to the server. Just that. Is there anyone who knows how I can achieve this ?
I saw the SocketIO-client package on Pypi but it seems that it only works with Python 2.7 and I'm using 3.3.4.
I tried this what is said on this post and adaptating it to my python version. Though that's what I get in my hskey object :
>>> h = http.client.HTTPConnection('localhost:8008')
>>> h.request('POST', '/socket.io/1')
>>> resp = h.getresponse()
>>> hskey = resp.read()
>>> hskey
b'{"code":0,"message":"Transport unknown"}'


text:
Q: Excel COM Object in PowerShell SharePoint Online has a mostly undocumented method of populating a list of SharePoint Online sites that an administrator pushes out to its users.  Based on the presence/values of some registry keys, the client workstation knows when to ask SharePoint Online for an updated list of the SharePoint sites.
The problem I'm having is that the only way to kick off that process is by opening the FILE - Open or FILE - Save dialog box in an Office application (Excel 2013 in my case).
[I'd love to be wrong about this, but I can't find any other way this works.]
After opening that dialog box, it checks the registry keys for timestamps and URLs and if everything is cool it grabs the updated list of published SharePoint sites.
I'm trying to write a simple PowerShell script that people can run in order to force this process.  My question is simple -- how do I close the dialog box that I'm opening in the last line of the code posted below?
$global:excel = new-object -com Excel.Application
$excel.visible = $true
sleep 1
$excel.GetOpenFilename()

My script never leaves the GetOpenFilename() method until the user manually hits Cancel.  I'd like to press Cancel programmatically.
Any suggestions?  Am I going about this the wrong way?  Does anyone know what underlying method is being called to populate the SharePoint Sites folder when this dialog box opens and is there any way I can just call that directly in my script?


text:
Q: How to mount the newly created linux partitions? It seems repetitive even to myself asking this but I've searched this forum and have not been able to fix my issue. I had created one extended partition and installed my UBUNTU 14.04 on it.
Now I have 440 GB available so have recently created two new primary partitions on the free space. But when I click them to mount and access them from the "Places" menu (I have installed Ubuntu-mate) the only thing there I would have is a window opened and I can not create anything on it.
I figured it may have been mounted as root and I have not a single clue how to change it to my username. Could you please  help me?

A: This is as I suppose by mounting your partition read only, so either you have to remount with write permissions or add to fstab to automount automatically.
Get the UUID
Run the command:
sudo blkid

Then open /etc/fstab:
sudo gedit /etc/fstab

Now  add the line to the bottom of /etc/fstab:
UUID=UUID /mounting-point ext4 defaults  0      2

Replace UUID with result of your UUID of /dev/sdX
Replace /mounting-point with path to mount the partition on
Replace ext4 with your partition filesystem type

A: Ok, This can be the solution:
1- Type the "lsblk" command to see the drives that are seen by your distribution and decide which one you want to mount (in my case it was /dev/sda3) and where you want to set to be its mount point (I chose it to be /mnt/EXTRA_I).
2-use the mount command using sudo like this:
sudo mount -Rc /dev/sda3/ /mnt/EXTRAS_I
(you can learn more about the commands above by typing the command name first, and a --help after it. example:mount --help`)
3-Now type your password as you've been asked to do so.
4-Type lsblk again, and observe that your drive chosen is mounted (one of the fields below "MOUNTPOINT" now contains a strins value. in my case: /mnt/EXTRAS_II).
5-it is time to change the owner from "root" to your own. It was "koorosh" in my case. Example: sudo chown -Rc koorosh:koorosh /mnt/EXTRAS_I
6-Observe the prompts of output that declares the mount point is now yours.
7-Congradulations, You have succeeded, and the next time you want to mount the drive (in my case: EXTRAS_I) and view the contents of it, you will have to just double-click on its name in your file manager.
lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 465.8G  0 disk
├─sda1   8:1    0   2.8G  0 part [SWAP]
├─sda2   8:2    0     1K  0 part
├─sda3   8:3    0 210.9G  0 part
├─sda4   8:4    0 219.5G  0 part
├─sda5   8:5    0   7.5G  0 part /
└─sda6   8:6    0  25.1G  0 part /home
sr0     11:0    1  1024M  0 rom

sudo mount /dev/sda3/ /mnt/EXTRAS_I
lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 465.8G  0 disk
├─sda1   8:1    0   2.8G  0 part [SWAP]
├─sda2   8:2    0     1K  0 part
├─sda3   8:3    0 210.9G  0 part /mnt/EXTRAS_I
├─sda4   8:4    0 219.5G  0 part
├─sda5   8:5    0   7.5G  0 part /
└─sda6   8:6    0  25.1G  0 part /home
sr0     11:0    1  1024M  0 rom

sudo chown -Rc cockroach:cockroach /mnt/EXTRAS_I
changed ownership of /mnt/EXTRAS_II/lost+found' from root:root to cockroach:cockroach
changed ownership of /mnt/EXTRAS_II' from root:root to cockroach:cockroach

sudo umount /dev/sda3


text:
Q: Save matrices to .txt from a list I have 32 matrices with different names need to be saved to .txt. I tried to add each matrix to a list and wanted to use loop to save from the list. I was trying with just one matrix called mat_dis_func_742 first.
lsMatrix<-list()
name <- paste("mat_dis_func_", 742, sep="")
mat_dis_temp <- get(name)
lsMatrix[[name]] <- mat_dis_temp
write.table(lsMatrix[1],file=paste("Results/Test.txt"), row.names=FALSE, col.names=TRUE, sep=";",quote=FALSE)

What is saved at the end is:
mat_dis_func_742.Class;mat_dis_func_742.Lower.bound;mat_dis_func_742.Upper.bound;mat_dis_func_742.n.x.;mat_dis_func_742.h.x.;mat_dis_func_742.f.x.
1;0.0908181818181818;0.339572192513369;2;0.666666666666667;0.666666666666667
2;0.339572192513369;0.588235294117647;1;0.333333333333333;1

And what i want is:
Class;Lower bound;Upper bound;n(x);h(x);f(x)
1;0.0908181818181818;0.339572192513369;2;0.666666666666667;0.666666666666667
2;0.339572192513369;0.588235294117647;1;0.333333333333333;1

So the column name is mixed with mat_dis_func_742.. I don't know how to fix it but i am not sure if this is the correct way to save many matrices.

A: Use write.table(lsMatrix[[1]],...) instead of write.table(lsMatrix[1],...). Here is an example:
# Problem
mat_742 <- diag(5)
colnames(mat_742) <- paste("column", 1:5, sep = "")
colnames(mat_742)
lsMatrix<-list()
name <- paste("mat_", 742, sep="")
mat_dis_temp <- get(name)
lsMatrix[[name]] <- mat_dis_temp
write.table(lsMatrix[1],file=paste("Test.txt"),
            row.names=FALSE, col.names=TRUE, sep=";",quote=FALSE) #check file

# Solution
write.table(lsMatrix[[1]],file=paste("Test.txt"),
            row.names=FALSE, col.names=TRUE, sep=";",quote=FALSE) #check file