text:
Q: conditioning in XML parsing - PHP Its been a while since the last time I was coding, and I am a little rusty. I am trying to parse an xml file and having a problem with the condition. Spent hours trying to figure out where is the problem, but without success...
PHP CODE:

    <?php
    $cat_img="images/cat.png";
    $logo_path="logos/";

    $file = simplexml_load_file('stores.xml');
    $old_cat="";

    foreach($file->store as $store){
        if($store->cat != $old_cat){
            echo "
".$store->cat."

";
            $old_cat=$store->cat;
        }

        echo "
logo."' alt='logo'>
";
        echo "<store_name>".$store->name."</store_name>";
        echo "<phone>".$store->phone."</phone><phone>טל: </phone>
";
    }
    ?>

STORES.XML
<?xml version="1.0" encoding="UTF-8"?>

<stores>

    <store><logo>renuar.jpg</logo>
    <name>renuar</name>
    <phone>052-6059962</phone>
    <cat>clothing</cat></store>

    <store><logo>yoop.jpg</logo>
    <name>YOOP</name>
    <phone>08-6601451</phone>
    <cat>clothing</cat></store>

....

</stores>

The idea is to print every store, when category changes it should print the category divider and keep printing the stores. Somehow the condition is always true and I have no idea why...
p.s
If anyone has a better idea on how to divide the categories, a different method, I would be happy to hear.
Thanks!!!

A: $store->cat will be SimpleXMLElement object and two object will not be same even with same category name. You need to cast it to string for comparison
Like (string) $store->cat, try this:
<?php
$cat_img = "images/cat.png";
$logo_path = "logos/";
$file = simplexml_load_file('test.xml');
$old_cat = "";
foreach ($file->store as $store) {
    if ((string) $store->cat != $old_cat) {
        echo "
category: " . $store->cat . "

";
        $old_cat = (string) $store->cat;
    }
    echo "
logo . "' alt='logo'>
";
    echo "<store_name>" . $store->name . "</store_name>";
    echo "<phone>" . $store->phone . "</phone><phone>טל: </phone>
";
}
?>


text:
Q: Product dimensions in Magento 2.2.5 update I have installed Magento 2.2.5 locally with sample data.
Now three new attributes Length, Width, Height Added. These are the default attributes, created by Magento 2.2.5 or by some third party extensions.
And how to get these attribute values Cart/Checkout.

A: The attributes ts_dimensions_length / ts_dimensions_width / ts_dimensions_height are part of the Temando_Shipping module that ships with Magento 2.
[ Source: Line 32 - 34 in vendor/temando/module-shipping-m2/Setup/SetupData.php ]

You should be able to get their values by using the code snippet below:
$product->getTsDimensionsLength();
$product->getTsDimensionsWidth();
$product->getTsDimensionsHeight();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Armazenar dados de formulários temporariamente antes de gravar no banco de dados Como faço para armazenar dados de um formulário temporariamente antes de inserir no banco?
Tenho um formulário com um conjunto de campos. Após o usuário preencher o conjunto de campos, terá a opção de adicionar mais um conjunto com os mesmos campos para inserir novos valores. Gostaria de fazer a inserção no banco apenas quando o usuário finalizar o preenchimento. Cada conjunto de campos deve ser um registro na tabela. Como posso fazer isso?

A: Você pode criar um array na $_SESSION e para cada conjunto você adiciona um novo índice no array. Para isso busque o tamanho do array e:
$_SESSION[$tamanho+1]['nome'] = $_POST['nome'];


text:
Q: Java ExecutorService that dynamically scale the number of threads I have a list of work-unit and I want to process them in parallel. Unit work is 8-15 seconds each, fully computational time, no I/O blocking. What I want to achieve is to have an ExecutorService that:

*

*has zero threads instantiated when there is no work to do

*can dynamically scale up to 20 thread if needed

*allow me to add all work-units at once (without blocking the submission)

Something like:
Queue<WorkResult> queue = new ConcurrentLinkedDeque<>();
ExecutorService service = ....
for(WorkUnit unit : list) {
    service.submit(() -> {
        .. do some work ..
        queue.offer(result);
    );
}
while(queue.peek() != null) {
    ... process results while they arrive ...
}

What I tried with no success is:

*

*Using a newCachedThreadPool() creates too many threads

*Then I've used its internal call new ThreadPoolExecutor(0, 20, 60L, SECONDS, new SynchronousQueue<>()), but then I noticed that submit() is blocking due to the synchronous queue

*So I've used new LinkedBlockingQueue(), just to find out that the ThreadPoolExecutor spawns only one thread

I'm sure there is official implementation to handle this very basic use-case of concurrency.
Can someone advice?

A: Create the ThreadPoolExecutor using a LinkedBlockingQueue and  20 as corePoolSize (first argument in the constructor):
new ThreadPoolExecutor(20, 20, 60L, SECONDS, new LinkedBlockingQueue<>());

If you use the LinkedBlockingQueue without a predefined capacity, the Pool:

*

*Won't ever check maxPoolSize.

*Won't create more threads than corePoolSize's specified number.

In your case, only one thread will be executed. And you're lucky to get one, since you set it to 0 and previous versions of Java (<1.6) wouldn't create any if the corePoolSize was set to 0 (how dare they?).
Further versions do create a new thread even if the corePoolSize is 0, which seems like ... a fix that is ... a bug that... changes ... a logical behaviour?.

Thread Pool Executor
Using an unbounded queue (for example a LinkedBlockingQueue without a
predefined capacity) will cause new tasks to wait in the queue when
all corePoolSize threads are busy. Thus, no more than corePoolSize
threads will ever be created. (And the value of the maximumPoolSize
therefore doesn't have any effect.)

About scaling down
In order to achieve removing all threads  if there's no work to do, you will have to close the coreThreads specifically (they don't terminate by default). To achieve this, set  allowCoreThreadTimeOut(true) before starting the Pool.
Be aware of setting a correct keep-alive timeout: for example, if a new task is received on average at every 6 seconds, setting the keep-alive time to 5 seconds could lead to unnecessary erase+create operations(oh dear thread, you just had to wait one second!). Set this timeout based on the task reception income speed.

 allowCoreThreadTimeOut
Sets the policy governing whether core threads may time out and
terminate if no tasks arrive within the keep-alive time, being
replaced if needed when new tasks arrive. When false, core threads are
never terminated due to lack of incoming tasks. When true, the same
keep-alive policy applying to non-core threads applies also to core
threads. To avoid continual thread replacement, the keep-alive time
must be greater than zero when setting true. This method should in
general be called before the pool is actively used.

TL/DR

*

*Unbounded LinkedBloquingQueue as task queue.

*corePoolSize replacing maxPoolSize's meaning.

*allowCoreThreadTimeOut(true) in order to allow the Pool to scale down using a timeout based mechanism that also affects coreThreads.

*keep-alive value set to something logical based on the task reception latency.

This fresh mix will lead to an ExecutorService that 99,99999% percent of the time won't block the submitter (for this to happen, the number of tasks queued should be 2.147.483.647), and that  efficiently scales the number of threads in base of the work load, fluctuating (in both directions) between  { 0 <--> corePoolSize } concurrent threads.
As a suggestion, the queue's size should be monitorized, as the non-blocking behaviour has a price: the probability of getting OOM exceptions if it keeps growing without control, until INTEGER.MAX_VALUE is met (f.e: if the threads are deadlocked for an entire day while the submitters keep inserting tasks). Even if the task's size in memory could be small, 2.147.483.647 objects with its corresponding link wrappers, etc... is a lot of extra load.

A: The simplest way would be to use the method
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)

Of class Executors. This gives you a simple out-of-the-box solution. The pool that you get will expand and shrink as per need. You can further configure it with methods dealing with core threads timeout etc. ScheduledExecutorService is an extension of ExecutorService class and is the only one that is out of the box may dynamically expand and shrink.


text:
Q: Have to point two dimensional graph(x,y) co ordinates networkx python I am getting information from a spatial database the values are like line string(spatial) format and  i need to add this info to networkx graph later need to draw a graph in a matplot lib
I have written this code
cursor.execute("SELECT AsText(roadstring) FROM road1")
for row in cursor.fetchall():
    a=row[0][12:-2]
    a=str(a)
    a=a.split(",")
    for i in a:
        i=i.split(" ")
        i[0]=float(i[0])
        i[1]=float(i[1])
        weig=abs(i[0]-i[1])
        G.add_node((i[0],i[1]))

I unable to get how to add two dimensional edges for roads (x1,y1) to (x2,y2) even i need to add weight to these edges for distance between them
Any suggestions??
The line string of every road  are like these 643715.202,2499149.0506 643752.61523545,2499089.86084203 643773.6038,2499056.6558 643773.73878609,2499056.44011079 643793.20162482,2499025.34111554 643813.55943268,2498992.81212045 643826.6563,2498971.8852
I am getting this error I have matplotlib installed I tried by copying your code

Traceback (most recent call last):   File "D:\python\gis\new.py", line
  2, in
      from matplotlib import pyplot as plt   File "C:\Python27\lib\site-packages\matplotlib__init__.py", line 133, in

      from matplotlib.rcsetup import (defaultParams,   File "C:\Python27\lib\site-packages\matplotlib\rcsetup.py", line 19, in

      from matplotlib.colors import is_color_like   File "C:\Python27\lib\site-packages\matplotlib\colors.py", line 54, in

      import matplotlib.cbook as cbook   File "C:\Python27\lib\site-packages\matplotlib\cbook.py", line 15, in

      import new   File "D:\python\gis\new.py", line 2, in
      from matplotlib import pyplot as plt   File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 20, in

      from matplotlib import _pylab_helpers, interactive ImportError: cannot import name interactive

A: I'm not completely sure what you want to accomplish, but here's how I interpret
it.
You have roads defined as coordinates along the road and you want to draw these
coordinates as nodes and the road between them as edges. You also want the edge
weight to be the distance between the two nodes.
This can quite easily be accomplished by saving the previous node and using the Pythagorean theorem to calculate the distance. This is
how I did it:
import networkx as nx
from matplotlib import pyplot as plt
import math

G = nx.Graph()

row = '643715.202,2499149.0506 643752.61523545,2499089.86084203 ' +\
    '643773.6038,2499056.6558 643773.73878609,2499056.44011079 ' +\
    '643793.20162482,2499025.34111554 643813.55943268,2498992.81212045 ' +\
    '643826.6563,2498971.8852'

a=row.split(" ")
# Saving the previous node to be able to calculate the distance
prev_point = None
# Save the positions in a dictionary to be able to draw
# the nodes at the correct positions
pos = {}
for i in a:
    cur_point = tuple([float(x) for x in i.split(',')])
    assert len(cur_point) == 2
    if prev_point is not None:
        # Calculate the distance between the nodes with the Pythagorean
        # theorem
        b = cur_point[1] - prev_point[1]
        c = cur_point[0] - prev_point[0]
        a = math.sqrt(b ** 2 + c ** 2)
        G.add_edge(cur_point, prev_point, weight=a)
    G.add_node(cur_point)
    pos[cur_point] = cur_point
    prev_point = cur_point
nx.draw(G, pos=pos)
plt.savefig('roads.png')

In this example I assume that a space separates the node positions and each
position's x and y coordinate is comma separated, but this can easily be changed. The above code will output something like this:

This will put the nodes at their "correct" positions, although it can cause some issues if there are big differences in road length. In the above example you can see that two nodes are more or less on top of each other. But that's a different question.


text:
Q: Extend Membership API, MembershipUser I created my own database schema to store user information.
CREATE TABLE [dbo].[MyCustomMembership_Users](
[UserId] [uniqueidentifier] NOT NULL,
[UserName] [nvarchar](256) NOT NULL,
[LoweredUserName] [nvarchar](256) NOT NULL,
[MobileAlias] [nvarchar](16) NULL,
[IsAnonymous] [bit] NOT NULL,
[LastActivityDate] [datetime] NOT NULL,
[FirstName] [nvarchar](256) NULL,
[MiddleName] [nvarchar](256) NULL,
[LastName] [nvarchar](256) NULL)

Then I extend the MembershipProvider and MembershipUser and create the overriden methods.
How can I pass the additional information when I call the CreateUser Method? I am aware I can use profile for this but I also want to be able to do it this way and if it comes out to be too complicated that I will go the profile route.
public class MyMembershipProvider : MembershipProvider
{
  public override MembershipUser CreateUser(string username, string password,
string email, string passwordQuestion, string passwordAnswer, bool isApproved,
object providerUserKey, out MembershipCreateStatus status)
    {
        throw new NotImplementedException();
    }
}
public class MyMembershipUser : MembershipUser
{
    private string _firstName;
    public string FirstName { get { return _firstName; } set { _firstName = value; } }

    private string _middleName;
    public string MiddleName { get { return _middleName; } set { _middleName = value; } }

    private string _lastName;
    public string LastName { get { return _lastName; } set { _lastName = value; } }

    public MyMembershipUser() : base()
    {
        this.FirstName = _firstName;
        this.MiddleName = _middleName;
        this.LastName = _lastName;
    }
}

A: You could pass a MyMembershipUser in the providerUserKey object


text:
Q: Can a function and its derivative have different input variables?
The problem above is from Khan Academy. The correct answer is "C" and I know how to get it. This is what I have trouble with:
Whenever I see a function and its derivative, both the function and its derivative use the same input variable. For example $f(x)$ and $f'(x)$ both use $x$. In the Khan Academy problem, the function is called $f(x)$ so the derivative should be called $f'(x)$. But, since the answer is C, it is impossible for the derivative to be called $f'(x)$ because $f'(\frac{\pi}{2})=\lim_{x\to \frac{\pi}{2}}\frac{sin(x)-sin(\frac{\pi}{2})}{x-\frac{\pi}{2}}$. In other words, you can only write the derivative as $f'($any variable other than $x)$. So, if the function and its derivative in this problem have different input variables, how can you graph them on the same coordinate plane? I think this issue has more to do with how to graph stuff than calculus.

A: Always think of a function as being a conceptual machine that accepts some type of input (specified as its domain) and produces some output. We write "$f : S → T$" to denote that $f$ is a function with domain $S$ such that when you give it any input in $S$ it produces an output in $T$. We write "$f(x)$" to denote the output of $f$ when applied to input $x$.
$
\def\lfrac#1#2{{\large\frac{#1}{#2}}}
$
Now to define a function you must specify both its domain as well as its rule for what input yields what output. For example, we could define a function $g$ with domain $\mathbb{Z}$ such that $g(k) = k^2 - 3·k$ for every $k∈\mathbb{Z}$. Observe that the variable "$k$" here is solely used to define the input-output rule; it does not make any difference if we used any other variable such as "$x$" or "$h$".
Many teachers and textbooks are sloppy in defining functions. For instance, your quoted question from Khan academy appears to define function $f$ by the input-output rule $f(x) = \sin(x)$, but failed to specify its domain, so it is technically an incorrect question. However, we can guess that it wants $f$ to have domain $\mathbb{R}$.
Take any function $f : D → \mathbb{C}$ where $D⊆\mathbb{C}$. We define pointwise differentiability as follows:

Given any $x∈D$, we say that $f$ is differentiable at $x$ iff $\lim_{y→x}^{y∈D} \lfrac{f(y)-f(x)}{y-x}$ exists (in $\mathbb{C}$).

Then we define the derivative of $f$, denoted by "$f'$", as follows:

$\boldsymbol{f'}$ is the function with domain $E = \{ x : \text{$x∈D$ and $f$ is differentiable at $x$} \}$ such that $f'(x) = \lim_{y→x}^{y∈D} \lfrac{f(y)-f(x)}{y-x}$ for every $x∈E$.

Again observe that the variables $x,y,E$" in the above definitions are solely used within the definitions, and we could have substituted them for any three distinct variables.
The whole point is that it is incorrect to say that a function uses an input variable, but it is not your fault because many people teach the concepts wrongly. Rather, you need to use a variable when specifying the input-output rule in defining a function, but that variable is not in any way tied to the function itself. In fact, such variables are called dummy variables, as they only serve to link their occurrences, and do not have meaning outside of the definition.
As to the question in your comments, you have to distinguish between the function and its graph, which unfortunately is another frequent conflation by teachers. Given a function $f : \mathbb{R} → \mathbb{R}$, the graph of $f$ is defined as the set of points $\{ (x,f(x)) : x∈\mathbb{R} \}$, and you can plot the graph of the equation "$y = f(x)$" on the $(x,y)$-plane in the manner you have encountered. You can of course plot the graphs of more than one equation, such as the graph of "$y = f(x)$" and "$y = f'(x)$" on the same $(x,y)$-plane. Note that the choice of variables matters; if you plot the graph of "$x = f(y)$" on the $(x,y)$-plane, you will get a different plot from the graph of $y = f(x)$".

A: You're thinking about the derivative incorrectly.
$f^\prime(a) = \displaystyle\lim_{x\rightarrow a}\frac{f(x)-f(a)}{x-a}$. When this limit exist and is finite, we say the function is differentiable at a. So the x value in the limit as approaching the input value $a$.


text:
Q: UbuntuStudio installer does not allow partition resize? I'm running FC18 + virtualbox and trying to install Ub.Studio 12.10 64bit. It works "fine" as live CD (except jackd, the main audio server, isn't working.. supposedly there is a fix for this) but when trying to install it I have problems..
The installer demands 8.5GB of disk space. I gave it 12GB thru VirtualBox (allocating as needed; not all up front). Yet without custom partitioning (ie clicking 'Something else') it halts shortly into the installation, saying there is not enough space.
When the partition dialogue comes up, if I select the device (here, /dev/sda) and click 'New partition table...' I'm not allowed to modify it b/c it is 'In use by LVM volume group ubuntu-studio.' I cannot change the sizes of, or delete/add partitions, as the plus/minus keys are grayed out. All I can change are partition formats, whether partition is formatted, and its mount point.
So, in order to get the installer to work, I had to switch the home, root, and swap volumes, as that was the only thing the installer would let me do.
Now I have an ~8gb root volume, ~4gb home volume, and a ~255mb swap space. It's actually not bad for my purposes, but it sure would be nice if I could, myself, change the sizes of each partition at install time..
Any way to do this?
Thanks!

A: Why bother to make separate partitions if you are running Virtualbox? If you let the Ubuntu-installer make the decision, it will make one partition of 12 gb, and then you don't have the split problem.


text:
Q: Strongly typed data control throws compilation error: The name 'Item' does not exist In Visual Studio 2015 I'm trying to use a strongly typed RadGrid as described in ASP.NET and Telerik documentation, but with no success.
When I try to run the following page I get a compilation error:
CS0103: The name 'Item' does not exist in the current context

WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebAppNamespace.WebForm1" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>

<telerik:RadGrid runat="server"
    ItemType="ModelNamespace.SomeEntity"
    SelectMethod="GetTheStuff"
    AutoGenerateColumns="false">
    <MasterTableView>
        <Columns>

            <telerik:GridTemplateColumn>
                <ItemTemplate>
                    <%# Item.SomeProperty%>
                </ItemTemplate>
            </telerik:GridTemplateColumn>

        </Columns>
    </MasterTableView>
</telerik:RadGrid>

WebForm1.aspx.cs
using ModelNamespace;
using System.Linq;
using System.Web.UI;

namespace WebAppNamespace
{
    public partial class WebForm1 : Page
    {
        SomeContext db = new SomeContext();
        public IQueryable<SomeEntity> GetTheStuff()
        {
            return db.SomeEntity;
        }
    }
}

The code completion in Visual Studio doesn't work either.
Shoudn't Item be available when I use the ItemType attribute in the RadGrid control as described in the documentation? What am I missing?

A: For the Item object to be available in bind expressions, the ItemType property has to be specified on the MasterTableView element, i.e.:
<telerik:RadGrid runat="server"
    SelectMethod="GetTheStuff"
    AutoGenerateColumns="false">
    <MasterTableView ItemType="ModelNamespace.SomeEntity">
        <Columns>
        ...


text:
Q: Better alternative for x-requested-with: XMLHttpRequest header With the evolution of JS we (modern js app developers) mostly use JSON to transfer data. Moreover XMLHttpRequest() method also became legacy because Fetch API is replacing it.
We neither transfer XML nor use  XMLHttpRequest() but we still add the x-requested-with: XMLHttpRequest header to inform the server about the async request type.
Is there a better, modern header for this purpose. All research leads to this legacy header.


text:
Q: GraphQL Subscription fields not able to access context of resolver I'm following along with the book Learning GraphQL and I came across a problem when implementing subscriptions. A resolver for one of the fields of the object being sent to the subscription doesn't work when viewing it from a subscription, but strangely works for mutations and queries. The resolver in question looks like this:
Photo: {
    postedBy: (parent, args, {db}) => db.collection('users').findOne({githubLogin: parent.userID})
}

When I make the following mutation, I receive postedBy back just fine:
mutation($input: PostPhotoInput!) {
    postPhoto(input: $input) {
        name
        url
        postedBy {
            name
        }
    }
}

Same when I make a query that returns that type:
{
    allPhotos {
        name
        postedBy {
           name
        }
    }
}

But when I start the following subscription and make a mutation that it's listening for:
subscription {
    newPhoto {
        name
        url
        postedBy {
            name
        }
    }
}

I get the error Cannot read property 'collection' of undefined.
I don't get an error if I use the subscription without the postedBy field. I can only assume that the undefined object is db, which is passed in from the context. Why does this work with queries and mutations, but not subscriptions?
For more context, here's the resolver for the subscription:
Subscription: {
        newPhoto: {
            subscribe: () => pubsub.asyncIterator('photo-added')
        }
}

and here's the resolver for the mutation that published the event the subscription is listening for:
async postPhoto(parent, {input}, {db, currentUser}) {
            if (!currentUser)
                throw new Error('Only an authorized user can post a photo');

            const newPhoto = {
                ...input,
                userID: currentUser.githubLogin,
                created: new Date()
            };
            const {insertedId} = await db
                .collection('photos')
                .insertOne(newPhoto);
            newPhoto.id = insertedId;

            pubsub.publish('photo-added', {newPhoto});

            return newPhoto;
        }

A: I found out what was wrong. It turns out that instead of getting context from the context function that passed to the constructor of ApolloServer, subscriptions get their context from the onConnect function that gets passed to the constructor of SubscriptionServer as described in the docs.

A: if you are using apollo v3 and getting this error..
This is what i had to do.

*

*need to pass the context in the "useServer" instead of in the ApolloServer.
2.inside the subscribe function in the resolver we need to get the context but it's nested one more level deep.

*Here one can see the result.
Please refer to the images attached.
God Speed!
Document Reference.


text:
Q: How to use newsletter subscription checkbox on any section of MyAccount in Magento? I am trying to implement the functionality which we get in the My Account section as shown in the screenshot.(Default functionality, but I want to use it in some custom phtml file. )

I am using the following code to implement this in My account section of the Magento as I have some design customization in phtml file.This functionality I want to provide to the Logged in customers only.
<?php echo $this->getLayout()->createBlock('customer/newsletter')->setTemplate('customer/form/newsletter.phtml')->toHtml(); ?>

But when I click on save I am redirected to 404 page.
Please suggest.

A: I did following
<?php echo $this->getLayout()->createBlock('customer/newsletter')->setTemplate('customer/form/newsletter_custom.phtml')->toHtml(); ?>

Then I copied all the content of the \template\customer\form\newsletter.phtml to the newsletter_custom.phtml and changed the
<form action="<?php echo $this->getAction() ?>" method="post" id="form-validate">

To
<form action="<?php echo Mage::getBaseUrl() ?>newsletter/manage/save/" method="post" id="form-validate">

So no 404 error coming now.


text:
Q: Problems Implementing CleanTalk I am trying to implement an online service called CleanTalk which requires me to deploy scripts on my boss' website pages. CleanTalk prevents spambots from filling out website forms and email signup fields. I followed their instructions carefully but have been unsuccessful in getting it to work.
If I put the script before any HTML code, all the following html on the rest of the page doesn't get displayed. When I put the code at the end of the page, then I can see all the HTML, fill out the form and submit it, but nothing goes through. There are also no spambot blockings recorded in my CleanTalk account, even when I use their spam email tester in the form fields.
Here is the php code provided by CleanTalk:

    <?php
    session_start();
    require_once (dirname(__FILE__) . '../javajq/cleantalk.class.php');
    // Take params from config
    $config_url = 'http://moderate.cleantalk.org/api2.0/';
    $auth_key = 'nere2usu5ehe'; // Set Cleantalk auth key
    if (count($_POST)) {
    $sender_nickname = 'John Dow';
    if (isset($_POST['login']) && $_POST['login'] != '')
    $sender_nickname = $_POST['login'];
    $sender_email = 'stop_email@example.com';
    if (isset($_POST['email']) && $_POST['email'] != '')
    $sender_email = $_POST['email'];
    $sender_ip = null;
    if (isset($_SERVER['REMOTE_ADDR']))
    $sender_ip = $_SERVER['REMOTE_ADDR'];
    $js_on = 0;
    if (isset($_POST['js_on']) && $_POST['js_on'] == date("Y"))
    $js_on = 1;
    $message = null;
    if (isset($_POST['message']) && $_POST['message'] != '')
    $message = $_POST['message'];
    // The facility in which to store the query parameters
    $ct_request = new CleantalkRequest();
    $ct_request->auth_key = $auth_key;
    $ct_request->agent = 'php-api';
    $ct_request->sender_email = $sender_email;
    $ct_request->sender_ip = $sender_ip;
    $ct_request->sender_nickname = $sender_nickname;
    $ct_request->js_on = $js_on;
    $ct_request->message = $message;
    $ct_request->submit_time = time() - (int) $_SESSION['ct_submit_time'];
    //Additional parameters. You could the description at the bottom of the page.
    $ct = new Cleantalk();
    $ct->server_url = $config_url;
    // Check
    $ct_result = $ct->isAllowMessage($ct_request);
    if ($ct_result->allow == 1) {
    echo 'Message allowed. Reason ' . $ct_result->comment;
    } else {
    echo 'Message forbidden. Reason ' . $ct_result->comment;
    }
    echo '

';
    }
    else
    {
    $_SESSION['ct_submit_time'] = time();
    }
    ?>

And here is my html form code with the CleanTalk code I am required to add to it:

<form action="form.php" method="post" name="contact form" style="padding-bottom: 55px;">

    <input class="formstyle round bgcolor purpleb" style="width: 631px;" type="text" name='name' placeholder="Full Name" required>

    <input class="formstyle round bgcolor purpleb" type="email" name='email' required placeholder="Email" value="" style="float: left; width: 295px; margin-right: 15px;">

    <input class="formstyle round bgcolor purpleb" type="tel" name='tel' required placeholder="Phone" style="float: left; width: 295px;">

    <textarea class="formstyle round bgcolor purpleb messagebox" type="text" name='message' required style="height: 160px;" placeholder="Message"></textarea>

    <input type="checkbox" id="spambot" name="spambot" value="Yes" required>   Yes, I'm human

    <input type="hidden" name="js_on" id="js_on" value="0" />

    <input type="submit" class="purpleb round formstyle bgcolor sendform" value="SEND" name='submit' style="float:left">
         PRIVACY POLICY

</form>

Here is a link to the CleanTalk API installation instructions. If you need anything else just let me know.
Here are the error message I'm getting:
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php:19) in /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php on line 72
Warning: require_once(/hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact../javajq/cleantalk.class.php): failed to open stream: No such file or directory in /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php on line 73
Fatal error: require_once(): Failed opening required '/hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact../javajq/cleantalk.class.php' (include_path='.:/usr/local/lib/php-5.5.22-amd64/lib/php') in /hermes/bosnacweb01/bosnacweb01bh/b2702/myd.bkholodov/public_html/webservice2/contact/index2.php on line 73


text:
Q: setting useLegacyAuth=1 in Workbench 6.0 I have been trying the useLegacyAuth=1 setting in the advanced option box, unfortunately its not holding the line. This line disappear immediately after I connect!! any clues please?
Workbench version: 6.0.7
I can connect to the server (by checking the disable secure auth checkbox), but when I do a backup its keep failing. Please help.

A: try to add "useLegacyAuth=1" in "Others" area, located in "Advanced" pill on connection configuration. (with quotes)

A: In advanced pane, check the box use the old authentication protocol


text:
Q: Rewrite rule depending on optional parts of the parser rule in ANTLR3 I'm trying to modify a rule depending on it's context with as few copy/paste as possible. I'll best begin with a pseudocode variant of what I'm trying to achieve:
module[boolean isParam]: 'module' id=identity?
        declaration+
        update+
        'endmodule' -> ^(MODULE ({if (isParam)} IS_PARAMETER {else} $id) declaration+ update+);

If isParam is set I want the module to not match the identity rule but create a IS_PARAMETER token in its place. I'm sure I can do this with two separate module rules but is there a cleaner way with less code duplication or without splitting the module rule into a number of smaller rules?

A: I believe something like this works:
module[boolean isParam]: 'module' id=identity?
        declaration+
        update+
        'endmodule' -> {isParam}? ^(MODULE IS_PARAMETER declaration+ update+)
                    ->            ^(MODULE $id declaration+ update+);

A: As already suggested, this would work:
module[boolean isParam]
 : 'module' id=identity? declaration+ update+ 'endmodule'
   -> {isParam}? ^(MODULE IS_PARAMETER declaration+ update+)
   ->            ^(MODULE $id? declaration+ update+)
 ;

(note the optional $id however!)
But by looking at your rule, I get the impression that whenever an identity is not present, you want to have a IS_PARAMETER node in your AST. If this is the case, you can handle this without parameters and predicates, which is IMO preferred:
module
 : 'module' ( identity declaration+ update+ 'endmodule' -> ^(MODULE identity declaration+ update+)
            | declaration+ update+ 'endmodule'          -> ^(MODULE IS_PARAMETER declaration+ update+)
            )
 ;


text:
Q: Pong Collision Pygame I'm writing code for a one paddle pong game in pygame where the ball will bounce off of the 3 walls the paddle is not on, and when it does hit the paddle's wall instead of the paddle, it makes you lose a life. My problem is that I cannot figure out the collision detection to do this. Here is what I've done so far:
import pygame, sys
from pygame.locals import *

pygame.init()

screen_width = 640
screen_height = 480
Display = pygame.display.set_mode((screen_width, screen_height), 0, 32)
pygame.display.set_caption('Lonely Pong')

back = pygame.Surface((screen_width, screen_height))
background = back.convert()
background.fill((255, 255, 255))

paddle = pygame.Surface((80, 20))
_paddle = paddle.convert()
_paddle.fill((128, 0, 0))

ball = pygame.Surface((15, 15))
circle = pygame.draw.circle(ball, (0, 0, 0), (7, 7), 7)
_ball = ball.convert()
_ball.set_colorkey((0, 0, 0))

_paddle_x = (screen_width / 2) - 40
_paddle_y = screen_height - 20
_paddlemove = 0
_ball_x, _ball_y = 8, 8
speed_x, speed_y, speed_circle = 250, 250, 250
Lives = 5

clock = pygame.time.Clock()
font = pygame.font.SysFont("verdana", 20)
paddle_spd = 5

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                _paddlemove = paddle_spd
            elif event.key == K_LEFT:
                _paddlemove = -paddle_spd
        elif event.type == KEYUP:
            if event.key == K_RIGHT:
                _paddlemove = 0
            elif event.key == K_LEFT:
                _paddlemove = 0

    Livespr = font.render(str(Lives), True, (0, 0, 0))
    Display.blit(background, (0, 0))
    Display.blit(_paddle, (_paddle_x, _paddle_y))
    Display.blit(_ball, (_ball_x, _ball_y))
    Display.blit(Livespr, ((screen_width / 2), 5))

    _paddle_x += _paddlemove

    passed = clock.tick(30)
    sec = passed / 1000

    _ball_x += speed_x * sec
    _ball_y += speed_y * sec

    pygame.display.update()

Another problem I've been having is that when I start it up, the ball doesn't appear at all. Could somebody please point me in the right direction?

A: first things first, the ball doesn't appear because you are not filling the surface, you are setting the color_key:
_ball.set_colorkey((0, 0, 0))

should be
_ball.fill((0, 0, 0))

Second, for collision detection, pygame offers some functions such as collidepoint and colliderect.
https://www.pygame.org/docs/ref/rect.html#pygame.Rect.collidepoint
which means you will need the rectangles of the surfaces. do this by:
my_surface.get_rect()

https://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_rect
In order to collide with the edges of the screen, you can always do
if _ball_x <= 0 or _ball_y <= 0 or _ball_x >= 640 or _ball_y >= 480:
    # collision detected


text:
Q: Use Kendo UI sortable widget on MVVM table I am using kendo UI MVVM to populate this table.

                #
                Image
                Description
                Actions

I want to be able to move the table rows in the UI by clicking on the user account.
If I add data-role="sortable" to the table, nothing works. Ref: https://www.telerik.com/forums/sortable-handler-inside-kendo-template
How do I get kendo sortable and its handlers to work inside the MVVM observable?

A: Try using the jQuery equivalent kendoSortable widget. Using sortable inside MVVM templates seems to cause inconsistent compilations. This might cause the handlers to not work correctly inside the sortable widget. See: kendo sortable widget mvvm UI glitch.
Assign an id to the parent
 wrapping the
 and create the sortable object on it.
Then you can bind observable methods to the jQuery widget handlers as a proxy:
kendo.jQuery("#" + id).kendoSortable({
    filter: ">div.container",
    cursor: "move",
    placeholder: function (element) {
        return element.clone().css("opacity", 0.1);
    },
    hint: function (element) {
        return element.clone().removeClass("k-state-selected");
    },
    change: viewModel.updatePositions.bind(viewModel, e)
});


text:
Q: Quit and remove application from RAM I have 6 activities in my application.
In 2 activities, I have coded quit button, but whenever I quit my application with that button, and start that app from "Recent applications" section, it continues from that activity.
How to code it in such a way that when I restart it from "Recent applications" section, it starts from the very first activity.
This is my code.
public void clickexit(View v)
    {
        moveTaskToBack(true);
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

In XML file,
android:onClick="clickexit"

A: So if your Android version is 4.1 or higher use this
finishAffinity();

System.exit(0);  // try this one

else you can try this
ActivityCompat.finishAffinity(YourActivity.this);

For more details refer to this

A: Read this document: document
If you put android:excludeFromRecents in your manifest will do it. Also you can find more tools with that link.


text:
Q: pyfpdf: FPDF error: Undefined font: calibri B I added the font calibri.fft,calibrii.fft, and calibrib.fft but error still exist.
pdf.add_font('Calibri','','Calibri.ttf',uni=True)
pdf.add_font('Calibri I','','Calibrii.ttf',uni=True)
pdf.add_font('Calibri B','','Calibrib.ttf',uni=True)
Underline works fine.

A: Looks like i messed up my syntax, fixed it using this syntax:
pdf.add_font('Calibri','I','Calibrii.ttf',uni=True)
pdf.add_font('Calibri','B','Calibrib.ttf',uni=True)


text:
Q: ruby on rails - are there any packages or modules that are not written in pure ruby? I am really new to ruby on rails. I heard ruby on rails needs to java virtual machine to be run.
I would like to ask some basic stuff about the ruby on rails.
It seems like ruby on rails can have some native code in the source code.
From what I have researched about ruby on rails, the code is usually runnable on the same platform that the code is written.
So when we need to run the code on different platform, using the Bundler ( rubygems ), it can automatically download the right version of package.
Is this correct??
Also, for the packages, are there any packages or modules that are not written in pure ruby??
I am not sure if there is any. If there is, I think the package manager cannot automatically download the right version and developers need to pull it out and make changes to deploy on the other machines.
I wasn't sure how to look at package dependencies in the package.
Is there a way to find the package dependency??

A: It is not clear what question you are asking however perhaps I can resolve some of your confusion.
Rails is a framework, distributed as a Ruby gem package which runs as part of a Ruby app on one of several available Ruby interpreters.
Neither Ruby nor Rails depend on the JVM. The JRuby interpreter allows you to run Ruby code within the JVM if you choose to do so.
Many Ruby gems include native extensions which may be platform dependent. Bundler allows you to express platform specific dependencies in cases where you need to use different gems to supply the same interface on different platforms. Take a look at Bundler's platform command as a way to check if your current platform satisfies the requirements of a given gemfile.
For example the sqlite3 gem requires native C extensions which cannot be compiled to run on the JRuby platform. Projects which support JRuby must swap in an alternative like the activerecord-jdbcmysql-adapter gem.


text:
Q: very slow wordpress theme DOMcontentLoaded takes 6sec i have a wordpress site Migau and it loads very slowly.
I did a speed test and this the result came back with a 6 sec load of my DOMcontentloaded.
Can anyone help with this matter
Thanks

A: Can you enable Gzip?
According to the Google PageSpeed browser extension, enabling gzip would reduce file size (of the plain text files which can be compressed) by 74%.
Also, try consolidating external resources (CSS and JS) to reduce HTTP requests. More info from the Yahoo Developer Network
Along the same lines, I like to utilize jQuery from the Google CDN (with a local fallback) as this increases the chances of it being cached, and your Google Webfont requests should likely be consolidated.
I also usually use a caching plugin like W3 Total Cache to speed things up a bit.


text:
Q: Pivot tables - how to correct a date error Months go wrong after September
I am having trouble with this issue where the dates start to go wrong after September. Instead of October, it says '>September'. I have selected 'this year' in the date filters so I'm not sure why it won't continue with 'October', 'November' and 'December' and is just bunching them all together as anything after September! I am a very basic Excel user so your simple replies would be appreciated!

A: Better to recreate your pivot table.
Not have seen your pivot table, just guess that may October, November, December are not clearly addressed in your source data.


text:
Q: Execute Logical Operator Filters On GraphQL OnlyOn JSON Objects Thank you for help. I am trying to execute AND/OR operator in GraphQL without Database.
Below is Query need to execute on dataset not database. Please understand, I don't have authority to connect to any database.
    {
    customVisualsData(_filter: {and: [{expression: {field: "Country", like: "Canada"}},{expression: {field: "Profit", gt: "5000"}}]}) {
    Country
    DiscountBand
    Product
    Segment
    Profit
    }
    }

Transform dataset/JSON Object look like this.

    [

     {
    "Country": "Canada",
    "DiscountBand": "High",
    "Product": "Paseo",
    "Segment": "Government",
    "COGS": 1477815,
    "GrossSales": 2029256,
    "ManufacturingPrice": 70,
    "UnitsSold": 12230.5,
    "Profit": 300289.99999999994
     },
     {
    "Country": "United States of America",
    "DiscountBand": "High",
    "Product": "VTT",
    "Segment": "Small Business",
    "COGS": 1461250,
    "GrossSales": 1753500,
    "ManufacturingPrice": 750,
    "UnitsSold": 5845,
    "Profit": 74288
     }

    ]

Schema Builder, I used to create GraphQL Query builder.
var schema = buildSchema(`
        type customVisualObject {
            Country: String
            DiscountBand: String
            Product: String
            Segment: String
            COGS: Float
            GrossSales: Float
            ManufacturingPrice: Int
            UnitsSold: Float
            Profit: Float
        }
        type Query {
            customVisualsData(_filter: FilterInput): [customVisualObject]
        }
        input FilterExpressionInput {
            field: String!
            eq: String
            gt: String
            gte: String
            like: String
        }
        input FilterInput {
            expression: FilterExpressionInput
            and: [FilterInput!]
            or: [FilterInput]
            not: [FilterInput!]
        }
`);

Please let me know, if anyone know How to set resolver for this on graphQL?
Does anyone one know JSON-ata Or GraphQL library to execute such complex Query on JSON Object Not databse?
I appreciate your help.


text:
Q: Custom Devise: Sessions Controller Failure My custom Devise Sessions controller isn't letting me sign in. I've had several difficulties trying to customize the Devise controllers, but I can't figure out what's going on here.
When I try to sign in, the page (sessions#new) simply re-renders. How can I get my custom controller back to full functionality?
# controllers/sessions_controller

class SessionsController < Devise::SessionsController
  skip_before_filter :store_last_attempted_location
  skip_after_filter  :store_last_successful_location

  def new
    super
  end

  def create
    super
  end

  def destroy
    super
  end
end

My routes
#config/routes.rb

devise_for :users, :controllers => { :sessions => "sessions", :registrations => "registrations"  }

Thanks in advance.

A: If the sign in page is re-rendered after entering the user credentials then it means that  the credentials are invalid which is resulting in the re-rendering. But that should have resulted in a flash message on the re-rendered page as Devise uses flash messages to let the application users know if sign in was successful or failure.
Make sure that you are displaying flash messages in application.html.erb as:
<% flash.each do |name, msg| %>
  <%= content_tag :div, msg %>
<% end %>


text:
Q: Get ami_name from inside a script in packer I have a script in provisioner's section of my Packer template, which requires the variable $ami_name. Is there any way that I can reliably get this information?
Provisioners section
"provisioners": [
    {
      "type":            "shell",
      "execute_command": "sudo {{.Vars}} bash '{{.Path}}'",
      "scripts": [
        "./scripts/packer/myscript.sh"
      ]
    }
  ]

./scripts/packer/myscript.sh:
#!/usr/bin/env bash
aminame=$ami_name
make_an_external_call "$aminame"

Here I need to get the ami_name from Packer. As this provisioners stage happens after Packer does a pre-validation of AMI Name, there should be a way I can get this right?


text:
Q: Getting errors related to threads and arrayLists Hi im writting a very simple game. Player can use mouse to move spaceship and every 200ms new beam is shoot. This beam is moved in while(true) loop and when its y is 0 or 400 (bounds of frame) i use break to end the loop (and thread). Every beam has its own thread. There are also stars which move in background. Every of them moves like beams and has its own thread. So as you can see there are often add and removes from arrayLists. Everything works but from time to time I get such errors:
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
    at java.util.ArrayList$Itr.next(ArrayList.java:791)
    at spacecommander.MainPanel.paintComponent(MainPanel.java:50)

They doesnt make any problems in game but how can I eliminate them? Maybe I should use synchronization or something?
EDIT: HERE IS THE CODE
public class MainPanel extends JPanel {
    private Player player = new Player(100, 100, 3, 3);
    private Point2D targetPoint = new Point2D.Float(130, 350); //Poczatkowa pozycja statku
    private ArrayList<Beam> beams = new ArrayList<Beam>();
    private InputMap imap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    private ActionMap amap = getActionMap();
    private Random rand = new Random();

    public MainPanel() {
        setPreferredSize(new Dimension(300, 400));

        addMouseMotionListener(new MouseMotionHandler());

        //Rozpoczynanie watkow
        Thread t = new Thread(new PlayerMoveRunnable());
        t.start();
        Thread t2 = new Thread(new PlayerShootRunnable());
        t2.start();
    }

    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        g2.setColor(Color.BLACK);
        g2.fillRect(0, 0, 300, 400);
        //Rysowanie gracza
        g2.drawImage(player.getImage(), (int)player.getX(), (int)player.getY(), null);
        //Rysowanie pociskow
        for (Beam beam : beams) {
            g2.drawImage(beam.getImage(), (int)beam.getX(), (int)beam.getY(), null);
        }
    }

    public void makeShortcut(String name, String keys, AbstractAction action) {
        imap.put(KeyStroke.getKeyStroke(keys), name);
        amap.put(name, action);
    }

    //Watek dziala caly czas bo gracz i tak caly czas sie rusza
    private class PlayerMoveRunnable implements Runnable {
        public void run() {
            try {
                while (true) {
                    player.moveToPoint(targetPoint);
                    repaint();
                    Thread.sleep(15);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //Takze dziala caly czas. Dodaje nowy pocisk co 200ms
    private class PlayerShootRunnable implements Runnable {
        public void run() {
            try {
                while (true) {
                    //Wybranie pocisku do wystrzelenia w zaleznosci od mode gracza
                    Thread t;
                    switch (player.getBeamMode()) {
                    case 1:
                        t = new Thread(new BeamMoveRunnable(new Beam1(100, 100, 10, 10, 10)));
                        break;
                    }
                    t.start();
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private class BeamMoveRunnable implements Runnable {
        private Beam beam;

        public BeamMoveRunnable(Beam beam) {
            this.beam = beam;
        }

        public void run() {
            Beam beam = this.beam;
            beams.add(beam);
            try {
                while (true) {
                    if (beam.getY() <= 0) {
                        beams.remove(beam);
                        break;
                    }
                    beam.move();
                    repaint();
                    Thread.sleep(20);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private class MouseMotionHandler extends MouseAdapter {
        public void mouseMoved(MouseEvent event) {
            targetPoint = event.getPoint();
        }
    }
}

A: This seems to be a synchronization issue, as you suspected. Probably while your drawing code is iterating the beams-list, a BeamMoveRunnable modifies the list at the same time (either adding or removing a beam), and causes the ConcurrentModificationException. Personally I wouldn't use separate threads to move the beams, but a simple loop which first updates the game (moving all the beams one at a time etc.) and then redraws the screen. However, you can also just synchronize the access to the list so only a single thread can access it at a time.

A: This typically happens when you try to add or remove an item from a list while iterating:
for (String s : list) {
    list.add("abc"); //ConcurrentModificationException
}

It is difficult to be more specific without seeing the code that is around line 50 of your MainPanel class (cf. stacktrace: at spacecommander.MainPanel.paintComponent(MainPanel.java:50)).
EDIT
Following your edit, a simple change would be to use a CopyOnWriteArrayList which is thread safe, instead of an ArrayList, to hold your Beam objects.

A: Since you are using multiple threads different threads are trying to modify your beams arraylist. You can use synchronized block to avoid concurent modification exception as below
Looping the list
synchronized (beams) {
    for (Iterator it = beams.iterator(); it.hashNext(); ) {
        Beam beam = (Beam) it.next();
       g2.drawImage(beam.getImage(), (int)beam.getX(), (int)beam.getY(), null);
    }
}

Adding item to the list
syncronized (beams) {
    beams.add(beam);
}

removing item from the list
syncronized (beam) {
    list.remove(beam);
}


text:
Q: Show AutoCompleteTextView's drop down on button click I have a AutoCompleteTextView which returns the list of places according to the text entered. The AutoCompleteTextView is working fine and returning the required data. However, I am facing a slight problem.
Consider that i am wrote  lo in AutoCompleteTextView and then pressed a button to search the matching places. The search is working correctly and loading the drop down list of AutoCompleteTextView with suggested places. But i can only see the drop down if i enter a 3rd word i.e. lon or i edit the word as l.
I want the drop down to be visible as soon as the drop down list gets updated.

A: For showing drop down on button click use this:
autoCompleteTextView.showDropDown();


text:
Q: XAMPP MySQL server won't start on Mac OS High Sierra I've spent several days on this problem, I've been searching the forums / Google to see if anyone has a solution. I need to run an older version of XAMPP (5.6) and the MySQL server fails to start on Mac OS X. The XAMPP application manager will not start the MySQL server, so I used Terminal
sudo /Applications/XAMPP/bin/mysql.server start

to force the server to run. But I got an error message:
"Starting mysqld daemon with databases from /Applications/XAMPP/xamppfiles/var/mysql
/Applications/XAMPP/xamppfiles/bin/mysqld_safe_helper: Can't create/write to file '/Applications/XAMPP/xamppfiles/var/mysql/UserName.local.err' (Errcode: 13 "Permission denied")
/Applications/XAMPP/bin/mysql.server: line 260: kill: (3256) - No such process
ERROR!"
Get the same error when logging into Terminal as ROOT.
The privileges for the "UserName.local.err" file was:
-rwxrwx---   1 UserName  admin   2500041 Oct 28 16:22 UserName-MacBook-Pro.local.err
So I gave the file all privileges - I will delete the entire XAMPP folder (a copy) after printing out the SQL table structure and data.
The privileges for the file are now:
-rwxrwxrwx   1 UserName  admin   2500041 Oct 28 16:22 UserName-MacBook-Pro.local.err
The error message has now changed a bit:
"Starting mysqld daemon with databases from /Applications/XAMPP/xamppfiles/var/mysql
/Applications/XAMPP/bin/mysql.server: line 260: kill: (4738) - No such process
ERROR!"
Any idea as to getting this server to run? Thanks so much for your help!
Cheers,
Rick

A: Well, this is odd. I cycled through the steps (and the problem) over and over again. I re-installed the old version of XAMPP a number of times and had the same issue. I re-installed it one last time, and the mysql.server started up. Can't say why though...
Thanks anyway,
Rick


text:
Q: How to Change Image on click and get back again on clicking I am Building a Javascript app
Now I want to have a image button that I have given already now I want to change the image to another image on clicking current image.
When i click again I want to get back the old image  please any one help me by giving a coding example pls..

A: Try this:
function diffImage(img)
{
   if(img.src.match(/blank/)) img.src = "black.jpg";
   else img.src = "blank.jpg";
}

HTML
<img src="black.jpg" id="image1" onclick=diffImage(this) />

Just try to change image path as per your requirements or you can add multiple images.
DEMO.
Hope this work.

A: You could also do it with only using CSS if you wanted to.
Just make a checkbox so you can click it without having to trigger an event and put the image in there and then have a different image for when it has been clicked.
<input type="checkbox"/>

And your CSS:
input[type="checkbox"] {
    content: url(image url here);
}
input[type="checkbox"]:checked {
    content: url(different image here);
}

I don't remember where I learned this trick, but it's worked for me in the past.


text:
Q: On this integral $\int_0^1 \ln\left(\zeta(s)\right)ds$ I am interested in the integral over the log-zeta function$$I=\int_0^1 \ln\left(\zeta(s)\right)ds$$
My attempts:
Sub $u=1-s$ to get $$I=\int_0^1 \ln\left(\zeta(1-u)\right)du=\int_0^1 \ln(\zeta(u))-u\ln2-(u-1)\ln\pi-\ln\left(\sin(\frac{\pi u}{2})\right)-\ln\left(\Gamma(1-u)\right) du$$ This doesn't seem to lead anywhere unfortunately. I also tried to set up  a parameter $a$ as
$$I(a)=\int_0^1 \ln\left(\zeta(s+a)\right)ds$$
$$I'(a)=\int_0^1 \frac{\zeta'(s+a)}{\zeta(s+a)}ds=\ln\left(\zeta(s+a)\right)|_{s=0}^{s=1}=\ln\left(\zeta(a+1)\right)-\ln\left(\zeta(a)\right)$$ From this point on I am not sure of what to do as integrating with respect to $a$ to recover $I(a)$ does not simplify the integral. If anybody has any idea of how to approach finding a closed form of this integral then please let me know. Thank you in advance.


text:
Q: Post method not allowing data in body request Laravel 9 (postman) I've created an api an it works however there is a weird behavior it doesnt allow me to send data in the body of the request.
Here's my code:
api.php
Route::controller(AuthController::class)->group(function () {
    Route::post('login', 'login');
    Route::post('register', 'register');
    Route::post('logout', 'logout');
    Route::post('refresh', 'refresh');
    Route::get('me', 'me');
});

AuthController.php
class AuthController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login','register']]);
    }

    public function register(Request $request){
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $token = Auth::login($user);
        return response()->json([
            'status' => 'success',
            'message' => 'User created successfully',
            'user' => $user,
            'authorisation' => [
                'token' => $token,
                'type' => 'bearer',
            ]
        ]);
    }
}

if i send data like this
localhost:8000/api/register?name=odlir4&email=odlirgz4@gmail.com&password=password

it works fine but if i send it like this

this doesn't work, anyone knows why this is happening? i think it should work or am i wrong?
Thank you!

A: in the route register you define the POST method
api.php
Route::post('register', 'register');

in postman you send data using GET method because it passes parameter
localhost:8000/api/register?name=odlir4&email=odlirgz4@gmail.com&password=password

it should be like this in Tab Body
https://www.postman.com/postman/workspace/published-postman-templates/request/631643-083e46e7-53ea-87b1-8104-f8917ce58a17

A: You need to get form-data in your controller using below method
public function register(){

  $datarequest = $this->input->post();

// other code

}

OR if you want to send request in json
public function register(){

  $datarequest = json_decode(file_get_contents('php://input'),true);

// other code

}


text:
Q: Not using anonymous function and having access to this and e I would like to put the script inside an anonymous function in a separate function so that I can use it on various elements without duplicating the code.  The script needs to have access to both this and e.  myID1 is using an anonymous function before trying to use a separate function.  myID2 works, but I have a feeling isn't the preferred way.  myID3 has access to this, but I couldn't figure out how to access e.  How is this done?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
        <title>Testing</title>

Click Me

Click Me

Click Me

A: The function (or function reference) passed to on gets called with one parameter: the eventObject. You can reference that however you want...e is fine.
Then, the value of this, which is implicitly defined (not a parameter), is automatically set as the element that the event was triggered for. So if you want to pass a reference, set up the reference like:
function someFunction(e) {
    console.log(e, this);
}

You only need to set the one parameter, and this is automatically defined properly.
If you want to call a different function from the event handler, like you do with #myID2 and someFunction2, you can pass those explicitly (like you have), or use call.
References:

*

*this: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this

*on: http://api.jquery.com/on/

*call: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call

A: For otherFunction3() to access e, simply declare e in the parameter list.  The parameter is passed by jQuery automatically, even if it's not declared:
function otherFunction3(e) { ... }

For #myID2 you need to .call() the otherFunction2:
$('#myID2').on("click", "a.myClass", function(e) {
    otherFunction2.call(this, e);
});

at which point within otherFunction2 the this variable will be set as usual, and you can remove the This parameter that you passed.

A: JavaScript doesn't allow method overloading. It uses a different approach: the arguments object that is available in each function scope. You can access provided parameters of the function through this object as if using an array. So you could use this:
function otherFunction3(){console.log(this, arguments[0])}

Also, regarding otherFunction2, it is a better approach to use the call method which is a native method on all instances of the Function "class". Alternatively you can use apply. The difference being that call takes an infinite amount of parameters to be passed to your function while apply accepts only 2. The first in both cases will always be your this scope, all succeeding resemble your parameters. Apply will accept an array as second parameter containing all your parameters to pass to your function.
The code would look like this:
$('#myID2').on('click', 'a.myClass', function(e){otherFunction2.call(this, e);});

Respectively you would remove the This parameter and replace it with the lowercase "equivalent" in your console.log call. I trust this is actually needless to state...


text:
Q: C# Sockets TCP client/serve I have a client and a server that I'm trying to get to speak to eachother over my local network (127.0.0.1).
First, I start the 'server' application:
public override void StartListening(int port, IPAddress address) {
            listenClient = new TcpListener(address, port);
            listenClient.Start();
            listenDelimiter = new IPEndPoint(address, port);
            if (listenThread != null) listenThread.Abort();
            listenThread = new Thread(new ParameterizedThreadStart(ListenThread));
            listenThread.IsBackground = true;
            listenThread.Start(port);
        }

        public void ListenThread(object o) {
            while (true) {
                try {
                    Socket incomingConnection = listenClient.AcceptSocket();
                    NetworkStream conStream = new NetworkStream(incomingConnection);
                    NetworkConnection nc = new NetworkConnection((incomingConnection.RemoteEndPoint as IPEndPoint).Port, (incomingConnection.RemoteEndPoint as IPEndPoint).Address);
                    Clients.Add(nc);
                    nc.MonitorTCPStream(conStream, this);
                }
                catch (Exception e) {
                    Console.WriteLine("Server has crashed. Networking error: " + e.Message);
                    Console.WriteLine("Will restart in 60 seconds...");
                    Thread.Sleep(60000);
                    StartListening(WORLDMAP_PORT, IPAddress.Any);
                }
            }
        }

Then the 'client':
try {
                    if (worldMapConnection != null) worldMapConnection.Close();
                    worldMapConnection = new TcpClient(address.ToString(), port);
                    worldMapConnection.Connect(WORLDMAP_ADDRESS, WORLDMAP_PORT);
                    if (worldMapThread != null) worldMapThread.Abort();
                    worldMapThread = new Thread(new ParameterizedThreadStart(WorldMapListener));
                    worldMapThread.IsBackground = true;
                    worldMapThread.Start();
                    if (Engine.Renderer.GetTopMenu().GetType() == typeof(MenuContainerConnecting)) Engine.Renderer.CloseMenu();
                }
                catch (System.Net.Sockets.SocketException e) {
                    if (Engine.Renderer.GetTopMenu().GetType() == typeof(MenuContainerConnecting)) Engine.Renderer.CloseMenu();
                    switch (e.SocketErrorCode) {
                        case SocketError.AddressAlreadyInUse: {
                                Engine.Renderer.OpenMenu(new MenuContainerNotice("Connection Error", "You already have a copy of the game connected to the game server.", "Okay"));
                            } break;
                        case SocketError.ConnectionRefused: {
                                Engine.Renderer.OpenMenu(new MenuContainerNotice("Connection Error", "The connection was refused by the game server.", "Okay"));
                            } break;
                        case SocketError.HostUnreachable: {
                                Engine.Renderer.OpenMenu(new MenuContainerNotice("Connection Error", "Could not connect to the game server. Check your internet connection.", "Okay"));
                            } break;
                        default: {
                                Engine.Renderer.OpenMenu(new MenuContainerNotice("Connection Error", "Could not connect to the game server. The server may be down for maintenance.", "Okay"));
                            } break;
                    }
                }
                catch (Exception) {
                    if (Engine.Renderer.GetTopMenu().GetType() == typeof(MenuContainerConnecting)) Engine.Renderer.CloseMenu();
                    Engine.Renderer.OpenMenu(new MenuContainerNotice("Connection Error", "Could not connect to the game server. An unknown error has occoured.", "Okay"));
                }

WORLDMAP_ADDRESS is 127.0.0.1. The port used is the same on both applications (8269).
However, when I run the client, it catches a System.Net.Sockets.SocketException, whose message in the debugger is:

"A connect request was made on an already connected socket 127.0.0.1:8269"

I don't understand this, because my server is using a TcpListener, and the client a TcpClient. Surely this shouldn't be an issue?

A: These two lines in the client are redundant:
                worldMapConnection = new TcpClient(address.ToString(), port);
                worldMapConnection.Connect(WORLDMAP_ADDRESS, WORLDMAP_PORT);

Constructing the TcpClient object with an address and port is sufficient to get it to connect.


text:
Q: Linq Where Clause - Accessing a tables column name I need a bit of inspiration from somewhere and hoping someone, anyone could help.
This stems from a previous thread i created whereby I want to be able to do a autocomplete search on a complete data table i.e. all the data from all the columns.
I have created a stored procedure that pulls together the autocomplete items and the columns these items are derived from i.e.
tblAutoCompleteItems:
  Item Column
Item1 Product
Item2 Product
Item3 Product
Red   Category1
Green Category1
Blue  Category1
Small Category2
Medium   Category2
Large Category2

I've sorted the textbox autocomplete and that works fine. Based upon the client selection, a label displays which associated column this item is generated from (so the client can check they are happy with what their search will return). Lovely.
However, the tricky bit, and the bit I need help with, is pulling back another data set based upon the criteria they have selected. The other data set looking something along the lines of...
tblProductInfo:
Product        Category1   Category2
Item1       Red       Big
Item2       Red       Small
Item3       Blue        Small

For example, a user autocompletes for 'Item1', the textbox shows this and the label displays 'Product' Alternatively, a user may want to search by Category1 so searches for 'Red', this is presented in the text box and the label displays 'Category1'
When looking at tblProductInfo, I need to somehow query the dataset so that it looks at the autocomplete column and the autocomplete item.
So when I hit a button or whatever, the linq looks at the column first, says "oh I know, I need to look at Category1 and then pull back anything with Red in it" or "ok that's a Product, I'll head over to the Product column first and then pull back the data associated with Item1"
I'm struggling in two parts (1) How to access the column names within a table and (2) construct the where clause in the linq.
Any help, tips or advice gratefully received - even if it means a complete strategy rethink.
I'm attmepting this using c#, LINQ and asp.net.
By the by - I realise it is not ideal having the autocomplete look across a complete table but this is out of my hands...sadly.

A: There are a few ways to get the metadata; you can pull it from the database through a stored procedure (SQL, Oracle have views that can extract a table's metadata), or if you are using LINQ to SQL, you can use Reflection to reflect on the class that represents tblProductInfo.
To construct the where clause, you will want to use dynamic LINQ: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
As this allows you to use string column names to perform the query.
HTH.

A: Unbelievably, I've worked it out myself! If anyone stumbles across this and looking for something similar, here is some lovely pseudo code:
public static List<tblInfo> GetProductInfo(string memberid, string locationid, string column, string acitem)
        {

           MyEntities getproductinfo = new MyEntities ();

            var r = (from p in getproductinfo.tblProductInfo
                     where p.MemberId == memberid &&
                              p.LocationId == locationid
                     select p);

            if (column == "Product")
                r = r.Where(p => p.Product == acitem);

            if (column == "Category1")
                r = r.Where(p => p.Category1 == acitem);

return r.OrderBy(p => p.Product).ThenBy(p => p.Category1).ToList();

*

*Where column = the label text (in the example above)
acitem = the entry in the autocomplete textbox
memberID & locationID are just sessions used throughout.

A: I didn't run it through the compiler, but I think the syntax is good.  Should result in a IEnumerable
var r = (from p in getproductinfo.tblProductInfo
         where p.MemberId == memberid
            && p.LocationId == locationid
            && column == "Product" ? p.Product == acitem :
               column == "Category1" ? p.Category1 == acitem : true
         orderBy p.Product
         thenBy p.Category1
         select p);

A: A slight modification on yours:
 MyEntities getproductinfo = new MyEntities ();

 var r = (from p in getproductinfo.tblProductInfo
          where p.MemberId == memberid &&
              p.LocationId == locationid
          order by p.Product, p.Category1
          select p);

 if (column == "Product")
       r = r.Where(p => p.Product == acitem);

 if (column == "Category1")
       r = r.Where(p => p.Category1 == acitem);

 return r.ToList();

LINQ will put the Where in the proper place.


text:
Q: How can I control bash's brace expansion to do the right thing (which zsh does automatically)? In zsh, I get the expected result from both of these brace expansions:
$ touch file-{001..100}
$ touch file-{1..100}

The first one gives me files named file-001, file-002, etc., all the way to file-100.  The second one gives me files named file-1, file-2, etc., all the way to file-100.
In bash, however, both give me files named file-1, file-2, etc.  This strikes me as a pretty major bug (or design flaw) in bash's brace expansion.
Is there any way to configure bash to do the right thing in this case?

A: This is a bug in older versions of bash, fixed in bash 4.1 alpha. From the changelog:

mm. Fixed a bug that in brace expansion that caused zero-prefixed terms to not contain the correct number of digits.


text:
Q: Hydrogen Emission vs Absorption Wavenumbers I am used to using the formula $ R_H (\frac{1}{n^2_{final}}-\frac{1}{n^2_{initial}}) $ to calculate the transition wavenumbers when an electron in a  Hydrogen atom emits a photon. Can you use the same formula to calculate the wavenumber when a electron absorbs a photon?

A: Yes, the energy (and therefore the photon wavelength) required for the transition between two energy levels is independent of the "direction". One way to see this is observing absorption and emmision spectra of the hydrogen, where the position of the lines for both types is the same.


text:
Q: What does TCP recv actually DO? I'm having a hard time figuring the best way to word my question... once you have a TCP socket connection established and you are consuming data sent from another server, what part does recv play in this?
My understanding is that once a connection is established, data will "appear" in my client's receive buffer when the remote socket sends it - it doesn't wait for me to ask for the data by calling recv, the drivers handle this behind the scenes?
So does this mean recv (or library implementations e.g Socket.Receive in .Net) is simply monitoring the local receive data buffer? It seems it can't be otherwise it wouldn't know the difference between waiting for data, and en error state where the connection is lost.
If local data is already buffered then I believe recv does simply operate on this local data, but what does it do when I request data that isn't already buffered?
the docs for Win32 recv say "The recv function is used to read incoming data" but it doesn't appear to clarify - does the sender wait for recv before sending data from it's send buffer? Or does my receive buffer fill up regardless?
Put another way does recv:

*

*Say to the remote socket "please send me some data"

*Check local buffer "do I already have some data"?

The docs also say

If no incoming data is available at the socket, the recv call blocks
  and waits for data to arrive according to the blocking rules defined
  for WSARecv with the MSG_PARTIAL flag not set unless the socket is
  nonblocking. In this case, a value of SOCKET_ERROR is returned with
  the error code set to WSAEWOULDBLOCK. The select, WSAAsyncSelect, or
  WSAEventSelect functions can be used to determine when more data
  arrives.

This seems to be the key section but I just don't understand it - it waits for dat to arrive but how can it tell if there is an error simply by waiting?

A: To answer your questions simply:

does recv:

*

*Say to the remote socket "please send me some data"

*Check local buffer "do I already have some data"?

It checks a local buffer.

what does it do when I request data that isn't already buffered?

The recv call blocks and waits for data to arrive (or for an error to happen).

it waits for data to arrive but how can it tell if there is an error simply by waiting?

It's job is to simply wait, it's the OS job to fill the buffer with the received bytes, and notify it when data becomes available (or an error happen).


text:
Q: Does main thread execute the Promise code or does it get added to an js engine api? Javascript engine executes code in the single main thread.
The main thread will not block on an async function call unless the await keyword is used await fnnane();
When there is an async fucntion like setTimeout or fetch, then it is handed over to the respective Javascript engine api to work on separate to the main thread.
The response (and subsequent function code) is added to the task queue.
But when there is a Promise as shown below, then where does it get passed or does the main thread execute it?
async function foo(i) {
  await new Promise(resolve => setTimeout(resolve, 5000));
  console.log('Completed foo', i);
}


text:
Q: How to fix error using Kafka-node in Vue? Anyone encounter this error using kafka-node in vue.js
Uncaught TypeError: Cannot read properties of undefined (reading 'prototype')
at Object.inherits (app.js:143477:46)
at ./node_modules/kafka-node/lib/wrapper/BrokerReadable.js (app.js:85751:6)
at __webpack_require__ (app.js:221491:42)
at ./node_modules/kafka-node/lib/wrapper/BrokerWrapper.js (app.js:85806:22)
at __webpack_require__ (app.js:221491:42)
at ./node_modules/kafka-node/lib/kafkaClient.js (app.js:81658:23)
at __webpack_require__ (app.js:221491:42)
at ./node_modules/kafka-node/lib/producerStream.js (app.js:83390:21)
at __webpack_require__ (app.js:221491:42)
at ./node_modules/kafka-node/kafka.js (app.js:77699:26)

A: Kafka is an event streaming thing (usually wired to a database somehow I guess).
Node.js is a backend runtime.
Both of those things are totally unrelated to a frontend like VueJS (especially if not using anything like Nuxt), so you're probably mistaking the fact that you can mix both.
We don't have more context but as of right now, just reading the title indicates something totally not compatible right from the start.


text:
Q: Excel Table Resize - Expand and Contract based on fetched data from the database- VBA Code I need some help on VBA code to resize Excel Tables.
I have written a macro to populate data in an excel table within the same sheet and across the sheets.
a) The data is pulled from a database
b) The database table name is a list. The user has an option to select any listed tables from the dropdown
c) Once the user clicks Validate, the table header gets populated with the column names fetched from the database
d) When the use clicks Import, the table data gets populated
e) Based on the user selection of the table name, the excel table expands to accommodate the fetched dataset.
Till here everything works well. Now the challenge is

*

*If the database table size is less than what is defined in the excel table, then my excel still shows the extra columns from the previous fetch.

I tried multiple approaches to clear contents of the extra columns or deleting the table columns or recreating the table but none of the method looks good and creates flickers on the user screen.
Looking for cleaner way to reset/resize the table to both expand and contract based on the number of columns pulled from the database maintaining the original formatting and styles.
Any help on this is greatly appreciated.
Public Sub DeleteTableRows()
Dim table As ListObject
Dim SelectedCell As Range
Dim tableName As String
Dim ActiveTable As ListObject
Dim lastCol As Integer
Dim startCol As Integer ' Column index to start deleting the table after reset
Dim startRow As String ' Row name to select the start range for deleting table records
Dim objCount As Integer

 startCol = 0
 'select number of sheets want to this to run

Application.ScreenUpdating = False      'Prevent screen flickering while doing the refresh
For i = 2 To 4
If (i = 2) Or (i = 3) Then
    startCol = 7
    startRow = "A10"
ElseIf (i = 4) Then
    startCol = 7
    startRow = "A7"
End If

Sheets(i).Select

Range(startRow).Select
Set SelectedCell = ActiveCell
Selection.AutoFilter

'Determine if ActiveCell is inside a Table
On Error GoTo NoTableSelected
objCount = ActiveSheet.ListObjects.Count

tableName = SelectedCell.ListObject.Name
Set ActiveTable = ActiveSheet.ListObjects(tableName)
On Error GoTo 0

'Clear first Row
ActiveTable.DataBodyRange.Rows(1).ClearContents

'Delete all the other rows `IF `they exist
On Error Resume Next

 ActiveTable.DataBodyRange.Offset(1,0).Resize (ActiveTable.DataBodyRange.Rows.Count - 1, _
 ActiveTable.DataBodyRange.Columns.Count).Rows.Delete
 Selection.AutoFilter
 On Error GoTo 0

Range(tableName & "[#Headers]").Select
' Range("Table4[#Headers]").Select
Selection.ClearContents

lastCol = ActiveSheet.ListObjects(tableName).Range.Columns.Count

'''''''''Autofit the columns'''''''''''

ActiveSheet.Columns("A:Z").AutoFit

'''''''''''''''delete Columns''''''''''
If (startCol < lastCol) And (i <> 4) Then
    Range(tableName & "[[#All],[Column" & startCol & "]:
 [Column" & lastCol & "]]").Select
    For j = startCol To lastCol
        Selection.ListObject.ListColumns(7).Delete
        Next j

End If

 'Execute to clear the 2nd table within the sheet as the above code is
  handling only one table per sheet'''''
If (i = 4) Then
    Range(startRow).Select
    Set SelectedCell = Range("J7:S7")
    Selection.AutoFilter

    'Determine if ActiveCell is inside a Table
    On Error GoTo NoTableSelected
    objCount = ActiveSheet.ListObjects.Count

    tableName = SelectedCell.ListObject.Name
    Set ActiveTable = ActiveSheet.ListObjects(tableName)
    On Error GoTo 0
    Range(tableName & "[#Headers]").Select
    ' Range("Table4[#Headers]").Select
    Selection.ClearContents

    lastCol = ActiveSheet.ListObjects(tableName).Range.Columns.Count
    ActiveSheet.Columns("A:Z").AutoFit
End If
Next i

ThisWorkbook.Worksheets(2).Activate

Application.ScreenUpdating = True

 Exit Sub
'Error Handling
NoTableSelected:
MsgBox "There is no Table currently selected!", vbCritical

End Sub


text:
Q: Find coordinate of a cell in an array of characters How would I find a coordinate of a cell in a 2d char table. For example if my table would display something like this:

*

*.....@@@@.....

*.........@@@.....

*.....@@@@.....

I want to find the second '@' in second row, as this would produce a square of 3x3. The squares Im trying to find are made of odd numbers 3x3, 5x5... And if There are two squares of same dimensions next to each other they need to be separated.
I am storing all the values in a table c[row][column] and thought of using mod 2=1 to find the odd number, but Im not sure how I would find the coordinate and make sure it doesn't repeat if there are two squares next to each other.
So far I've got:
for (int r = 0; r < row; r++) {
    for (int col = 0; col < column; col++) {
        if (c[r][col] != '.') {
            if (c[r][col] != '.' && c[r + 1][col] != '.' && c[r + 2][col] != '.') {
                if (c[r][col + 1] != '.' && c[r + 1][col + 1] != '.' && c[r + 2][col + 1] != '.') {
                    if (c[r][col + 2] != '.' && c[r + 1][col + 2] != '.' && c[r + 2][col + 2] != '.') {
                        System.out.println(r + " " + col);
                    }
                }
            }
        }
    }
}

A: Well you could look through the array first:
  for (int i=0; i< row.size; i++){
      for (int j=0; j<column.size; j++){
             if (c[i][j] != '.'){
                 System.out.print (i + " " + j);
             }
        }
    }

Not sure about how to find the middle cell so it makes a square with the odd number of cells, sorry :(


text:
Q: DWF Viewer Library - Android I want to create an Android app which needs to open DWF files within the app and I don't want to launch any other app to view them. I have not found any DWF viewer libraries that can be integrated with our app as in case of PDF, libraries are available.
I came to know that Auto Desk provides DWFToolkit that let developers to create our own DWF Viewer with C++ libraries. But I am not familiar with C++ and I have no idea to proceed.
I wonder some applications(like DWGSee) are available in PlayStore to view DWF files and How have they would have created them.
Please provide your suggestions and help me out.

A: I would suggest the Autodesk View & Data, a viewer that can be user on your app on a phone compatible with WebGL (most newer Android devices). Check a Android sample here.
The DWF Toolkit it very hard to modify and it's intended to manipulate (read/write) files, not for viewing.


text:
Q: makefile error when using string.h I realize this has probably been answered but I just cannot find it.  When using "make" to compile the following file:
#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    // get line of text
string s = GetString();

// print string, one character per line
for (int i = 0; i < strlen(s); i++)
{
    char c = s[i];
    printf("%c\n", c);
}
return 0;
}

I get the following message:
$ make example
cc     example.c   -o example
Undefined symbols for architecture x86_64:
  "_GetString", referenced from:
      _main in example-iPNXBe.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [example] Error 1

A: Judging from the cs50 page you probably need something like -lcs50 at the end of the cc command.

Or you can just use the cs50.o object file and link with it.
cc example.c cs50.o -o example


text:
Q: Camel isn't propagating exceptions when they are thrown inside of a multicast when the route is transacted I have a usecase where i have to multicast the input to multiple routes.
I do this by using apache camel's multicast component.
If there are any exception i handle it using Exception clause.
I have also marked the route to not handle the error by marking it as shown below
<camel:route errorHandlerRef="noErrorHandler">
        <camel:from uri="direct://SequenceFlow_5"/>
        <camel:transacted ref="sapdatastoretransacted"/>
        <camel:setBody id="CallActivity_3_1477551532659">
            <camel:simple>${in.body}+2</camel:simple>
        </camel:setBody>
        <camel:setHeader headerName="Branch B" id="CallActivity_10_1477551532662">
            <camel:constant>236</camel:constant>
        </camel:setHeader>
        <camel:log message="End of multicast branch encountered" loggingLevel="INFO" id="EndEvent_1_1477551532665"/>
    </camel:route>

when the route is marked as "noErrorHandler" any error from the route is thrown back to caller.
In my use case this works perfectly, when the route is non transactional.
But when the route is transactional the error is not thrown to the caller in case of multicast.
What i want to achieve is to handle error from subroutes created by multicast and handle the error from the route which invoked the multicast.


text:
Q: php number problem $num = 9;
   switch ($num){
    case $num > 0 && $num < 5:
        echo 5;
    break;
    case $num > 5 && $num < 10:
        echo 10;
    break;
    case $num > 10 && $num < 15:
        echo 15;
    break;
     ....
}
result: 10

stupid code.
Do you have any good idea for this?
Thank you.

A: $result = ceil($num/5)*5;

Is that what you're looking for?

A: You could convert it to ASCII art:
  _                                    ___
  | |                         ______   / _ \ _
 / __)_ __  _   _ _ __ ___   |______| | (_) (_)
 \__ \ '_ \| | | | '_ ` _ \   ______   \__, |
 (   / | | | |_| | | | | | | |______|    / / _
  |_||_| |_|\__,_|_| |_| |_|            /_/ ( )
                                            |/

                  _ _        _        ___                      __    __
                 (_) |      | |      / / |                     \ \  / /
     _____      ___| |_  ___| |__   | / __)_ __  _   _ _ __ ___ | || |
    / __\ \ /\ / / | __|/ __| '_ \  | \__ \ '_ \| | | | '_ ` _ \| / /
    \__ \\ V  V /| | |_| (__| | | | | (   / | | | |_| | | | | | | \ \
    |___/ \_/\_/ |_|\__|\___|_| |_| | ||_||_| |_|\__,_|_| |_| |_| || |
                                     \_\                       /_/  \_\

                             _                         __      ___                     _                            __  _____
                            | |                        \ \    / _ \    ___    ___     | |                          / / | ____|_
       ___  __ _ ___  ___  / __)_ __  _   _ _ __ ___    \ \  | | | |  ( _ )  ( _ )   / __)_ __  _   _ _ __ ___    / /  | |__ (_)
      / __|/ _` / __|/ _ \ \__ \ '_ \| | | | '_ ` _ \    > > | | | |  / _ \/\/ _ \/\ \__ \ '_ \| | | | '_ ` _ \  < <   |___ \
     | (__| (_| \__ \  __/ (   / | | | |_| | | | | | |  / /  | |_| | | (_>  < (_>  < (   / | | | |_| | | | | | |  \ \   ___) |_
      \___|\__,_|___/\___|  |_||_| |_|\__,_|_| |_| |_| /_/    \___/   \___/\/\___/\/  |_||_| |_|\__,_|_| |_| |_|   \_\ |____/(_)

                    _             _____
                   | |           | ____|_
           ___  ___| |__   ___   | |__ (_)
          / _ \/ __| '_ \ / _ \  |___ \
         |  __/ (__| | | | (_) |  ___) |_
          \___|\___|_| |_|\___/  |____/( )
                                       |/

      _                    _
     | |                  | |    _
     | |__  _ __ ___  __ _| | __(_)
     | '_ \| '__/ _ \/ _` | |/ /
     | |_) | | |  __/ (_| |   <  _
     |_.__/|_|  \___|\__,_|_|\_\( )
                                |/

                             _                         __     _____                    _                            __  __  ___
                            | |                        \ \   | ____|   ___    ___     | |                          / / /_ |/ _ \ _
       ___  __ _ ___  ___  / __)_ __  _   _ _ __ ___    \ \  | |__    ( _ )  ( _ )   / __)_ __  _   _ _ __ ___    / /   | | | | (_)
      / __|/ _` / __|/ _ \ \__ \ '_ \| | | | '_ ` _ \    > > |___ \   / _ \/\/ _ \/\ \__ \ '_ \| | | | '_ ` _ \  < <    | | | | |
     | (__| (_| \__ \  __/ (   / | | | |_| | | | | | |  / /   ___) | | (_>  < (_>  < (   / | | | |_| | | | | | |  \ \   | | |_| |_
      \___|\__,_|___/\___|  |_||_| |_|\__,_|_| |_| |_| /_/   |____/   \___/\/\___/\/  |_||_| |_|\__,_|_| |_| |_|   \_\  |_|\___/(_)

                    _             __  ___
                   | |           /_ |/ _ \ _
           ___  ___| |__   ___    | | | | (_)
          / _ \/ __| '_ \ / _ \   | | | | |
         |  __/ (__| | | | (_) |  | | |_| |_
          \___|\___|_| |_|\___/   |_|\___/( )
                                          |/

      _                    _
     | |                  | |    _
     | |__  _ __ ___  __ _| | __(_)
     | '_ \| '__/ _ \/ _` | |/ /
     | |_) | | |  __/ (_| |   <  _
     |_.__/|_|  \___|\__,_|_|\_\( )
                                |/

                             _                         __     __  ___                     _                            __  __ _____
                            | |                        \ \   /_ |/ _ \    ___    ___     | |                          / / /_ | ____|_
       ___  __ _ ___  ___  / __)_ __  _   _ _ __ ___    \ \   | | | | |  ( _ )  ( _ )   / __)_ __  _   _ _ __ ___    / /   | | |__ (_)
      / __|/ _` / __|/ _ \ \__ \ '_ \| | | | '_ ` _ \    > >  | | | | |  / _ \/\/ _ \/\ \__ \ '_ \| | | | '_ ` _ \  < <    | |___ \
     | (__| (_| \__ \  __/ (   / | | | |_| | | | | | |  / /   | | |_| | | (_>  < (_>  < (   / | | | |_| | | | | | |  \ \   | |___) |_
      \___|\__,_|___/\___|  |_||_| |_|\__,_|_| |_| |_| /_/    |_|\___/   \___/\/\___/\/  |_||_| |_|\__,_|_| |_| |_|   \_\  |_|____/(_)

                    _             __ _____
                   | |           /_ | ____|_
           ___  ___| |__   ___    | | |__ (_)
          / _ \/ __| '_ \ / _ \   | |___ \
         |  __/ (__| | | | (_) |  | |___) |_
          \___|\___|_| |_|\___/   |_|____/( )
                                          |/

      _                    _
     | |                  | |    _
     | |__  _ __ ___  __ _| | __(_)
     | '_ \| '__/ _ \/ _` | |/ /
     | |_) | | |  __/ (_| |   <  _
     |_.__/|_|  \___|\__,_|_|\_\( )
                                |/

       _ _ _ _
      (_|_|_|_)

 __
 \ \
  | |
   \ \
   / /
  | |
 /_/

                     _ _       __  ___
                    | | |  _  /_ |/ _ \
  _ __ ___ ___ _   _| | |_(_)  | | | | |
 | '__/ _ | __| | | | | __|    | | | | |
 | | |  __|__ \ |_| | | |_ _   | | |_| |
 |_|  \___|___/\__,_|_|\__(_)  |_|\___/

A: That's not how switch works, this will create comparisons like 9 == (9 > 0 && 9 < 5), which is not what you want. The easiest way is probably this:
if ($num < 5) {
    ...
} else if ($num < 10) {
    ...
} ...

("Easiest way" as in "easiest way to express logic like this." The easiest way for this particular operation is the application of basic math.)

A: switch does not work for this scenario, it only evaluate once
$num = 9;
$div = ceil($num/5);

switch ($div)
{
  case 1:
    echo 5;
    break;
  case 2:
    echo 10;
    break;
  case 3:
    echo 15;
    break;
  ...
}