text:
Q: Adding edges dynamically in a DCEL/half-edge based graph? I'm trying to implement a vector graphics "drafting" system, where, in essence, users can draw lines on the screen and interact with the regions created by intersecting lines. I'm struggling with determining/evaluating what these regions are.
I've tried a few different solutions to this problem, chiefly keeping a list of edges and running a BFS to find shortest cycles, but this brought up a myriad of issues where the BFS would shortcut in illegal ways, and holes and degenerate edges caused more problems than I could count, so I moved on to a DCEL, half-edge system.
I've read seemingly everything I can on this topic, including two articles referenced frequently on here: http://kaba.hilvi.org/homepage/blog/halfedge/halfedge.htm and http://www.flipcode.com/archives/The_Half-Edge_Data_Structure.shtml. However, neither of these seem to answer this problem that I have when it comes to dynamically adding edges to the graph.
Let's say I start out with this single edge. Image
The half-edges connect with each other in a cycle, and the global, unbounded "outside face" is connected to one of the half edges. Easy, got that.
Then we add another edge, attached to the center vertex: Image
The new half-edges work fine, and we update the edges that flow into v1's next pointers to be the only other edges available that aren't their twins. Again, makes sense to me.
What confuses me to no end is what happens here, when we add a third edge to the center vertex: Image
I know that's what it's supposed to look like and link up to be, but I am so bewildered on how to achieve that programmatically, because I'm not sure how I can determine whether the edge (4,1) should point to edge (1,2), or edge (1,3) (similarly for what edge should point to (1,4)).
The answer seems obvious when looking at the image, but when you try to rationalize it in a robust, airtight algorithmic way, my brain melts and I can't figure it out.  The textbook I'm reading (Computational Geometry, Mark de Berg et al., pg 35), just says

"[to test where the edge] should be in the cyclic order of the edges
  around vertex v".

The algorithm given in the hilvi.org article for finding the outgoing and incoming edges to link up with doesn't even seem to work, as it will take vertex 1, and follow its outgoing edge's twin until it finds a "free" edge, which in this case, is (2,1) which is wrong. (Unless I'm understanding it incorrectly, I could be understanding this whole problem wrong.)
So I'm absolutely stumped. My only idea now is to create some sort of heading attribute for each half edge, where I measure the angle created by the edge, and choose the edges that way, and maybe that's right, but that seems so against what the half-edge structure seems to support, at least in the articles I'm reading about it, nothing seems to mention anything like that. Any help would be extremely appreciated. I've been on this problem for over a week now and just can't seem to get unstuck.

A: Right, so I've spent a lot of time thinking about this problem, and to be honest I'm kinda surprised that I can't find a direct answer to this issue. So, in case anyone in the future runs into a similar problem of wanting to populate a half-edge graph from the ground up, here's a solution that works. I don't have a blog, so I'm writing it here.
I have no idea if it's the best answer, but it works in linear time and seems simple to me.
I'll be dealing with the following objects/classes, that vary slightly from the conventional DCEL:
class Vertex {
    x;
    y;

    edges = []; //A list of all Half Edges with their origin at this vertex.
                //Technically speaking this could be calculated as needed,
                  and you could just keep a single outgoing edge, but I'm not
                  in crucial need of space in my application so I'm just
                  using an array of all of them.
}

class HalfEdge {
    origin; //The Vertex which this half-edge emanates from

    twin; // The half-edge pair to this half-edge

    face; // The region/face this half-edge is incident to

    next; // The half-edge that this half-edge points to
    prev; // The half-edge that points to this half-edge

    angle; //The number of degrees this hedge is CW from the segment (0, 0) -> (inf, 0)
}

class Face {
    outer_edge; //An arbitrary half-edge on the outer boundary defining this face.
    inner_edges = []; //A collection of arbitrary half-edges, each defining
                      //A hole in the face.

    global; //A boolean describing if the face is the global face or not.
            //This could also be done by having a single "global face" Face instance.
            //This is simply how I did it.
}

For initializing a vertex at(x,y):

*

*Verify that a vertex with the given (x,y) coordinates does not already exist. If it does, you don't have to do anything (except maybe return this existing vertex if you're using it immediately).

*If it doesn't, allocate space for and create a new vertex with the corresponding x,y values, and with its incident edge null.
For initializing an edge from vertex A to vertex B:

*

*Similarly to many of the articles about this topic, we create two new instances of HalfEdge, one from vertex A to B, one from B to A. They link to each other in that we set their twin, prev, and next pointers all to the other half-edge (hedge).

*We also set the angle of the hedge. The angle is calculated clockwise from the positive x-axis. The function I implemented is below. This is super important to making this data structure work properly, and that fact that I haven't read anything in the literature about this being important makes me think there has to be a better way, but I digress.
    setAngle(){
        const dx = this.destination().x - this.origin.x;
        const dy = this.destination().y - this.origin.y;

        const l = Math.sqrt(dx * dx + dy * dy);
        if (dy > 0) {
            this.angle = toDeg(Math.acos(dx / l));
        } else {
            this.angle = toDeg(Math.PI * 2 - Math.acos(dx / l));
        }

         function toDeg(rads) {
             return 180 * rads / Math.PI;
         }

     }

*Next, we pair the vertices with their new edges by adding them to their Vertex's edge list, and then we sort the edge list by the hedge's angles from smallest (0) to largest (359).

*Then and this is the crucial step, in order to link everything up properly, we grab the closest hedge to the new hedge we're trying to link up in CCW order. Basically, wherever our new hedge ends up in the edge list, it's that index - 1 (if index = 0, we return edges[edges.length - 1]). Take that edge's twin, and that becomes our AIn described in the hivli article above. BOut = AIn.next.

*We set AIn.next = hedgeAB and similarly, hedgeAB.prev = AIn, then hedgeBA.next = AOut, AOut.prev = hedgeBA. Perform steps 3-5 for the hedgeBA as well, except running the CCW search on vertex B.

*Then, if both vertex A and B were "old" vertices, meaning their edge lists now have at least 2 elements each, a new face has potentially been added, and we need to find it (the edge case is having two isolated edges and connecting them to create an unbounded bucket or cap shape)
For initializing a Face:

*

*We need to find all the cycles in a graph. For my first implementation of this, I recalculated all of the cycles every single time, resetting all the faces. This isn't necessary, but it also isn't too expensive, since we're not running a search, everything is in linear time with respect to the number of cycles and number of vertices in each cycle.

*To do this, we get a list of all the hedges in the graph. It doesn't really matter how you do this, I decided to keep an array of every hedge that I passed into my cycle-finder function each time.

*Then we look through that list, while the list isn't empty, we take the first item and run its cycle, removing every hedge we find along the way from the list, and adding it into a new cycle, which we add to another list

*With this new list of cycles, we need to determine whether the cycle is an inside/outside cycle. There are a lot of ways to do this, and the Computational Geometry book mentioned above has a great section about it. The one that I used is to calculate the area defined by each cycle. If the area is >= 0, the cycle is defined by "inside" hedges. Otherwise, it's defined by "outside" hedges.

*The last step is to set all the face records, again, the aforementioned textbook has a lot of great details about this, but the basic idea is to basically create a virtual "graph" of these cycles, and connect outside cycles (which are holes in faces), to their corresponding inside cycles, which are the outer boundaries of faces. To do this, you look at the leftmost vertex of the cycle and extend a ray out infinitely to the left, and "connect" the cycle with the first downward-facing hedge of a cycle the ray hits (I'll leave the implementation up to you, I have no idea if my way is the best, in short, I checked every cycle with a leftmost vertex left of the current cycle and calculated the rightmost intersection with the y value of the leftmost vertex of the current cycle, and then checked if that was facing downward).

*With this graph of cycles, run a BFS/DFS starting from each "inside-hedge" cycle (not the holes), and create a face with an arbitrary hedge from the inside-hedge cycle as the outer edge, (or null if it's the global face), and an arbitrary hedge from each found hole-cycle to the face's inner components.
Hey presto, that's it. If you check everything every time, that handles everything. It handles face splitting like a charm and is very robust and quick. I don't know if it's right, but it works.


text:
Q: Is it possible to capture the data with PROCESS BUILDER while deleting a record? I have X & Y objects, on deleting record of X object i need to create record on Y object with deleted record data.
NOTE : USING PROCESS BUILDER.

A: As of the Winter 16 release, you can only run a process when a record is either:
A) Created
B) Created or Edited
To do what you're describing though could be done quite easily with an apex trigger.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I declare types properly to be able to create groups of redux action creators with shared name parts using createAction? I'm trying to use template literal types to create typed groups of Redux actions like "FETCH/START", "FETCH/PENDING", etc.
I want to use @reduxjs/toolkit createAction to make my action creators, like this:
import { createAction, ActionCreatorWithoutPayload, ActionCreatorWithOptionalPayload } from "@reduxjs/toolkit";

interface IFluxAction<T extends string, P> {
  Started: ActionCreatorWithOptionalPayload<P, `${T}/START`>;
  Pending: ActionCreatorWithoutPayload<`${T}/PENDING`>;
}

const createAsyncActions = <P>() => <T extends string>(type: T):
  IFluxAction<T, P> => {
    return {

// Type 'undefined' is not assignable to type 'P'.
// 'P' could be instantiated with an arbitrary type which
// could be unrelated to 'undefined'.

      Started: createAction<P, `${typeof type}/START`>(`${type}/START`),
      Pending: createAction(`${type}/PENDING`),
    };
};

enum DocActions {
  Fetch = 'Fetch',
  Delete = 'Delete',
};

export const documentActions = {
  Fetch: createAsyncActions<number>()(DocActions.Fetch),
};

const a = documentActions.Fetch.Started(1);

REPL: https://replit.com/@AlexanderBausk/VibrantOffbeatChapters#src/main.ts
I cannot call createAction properly when I need it to return an action creator with payload of type P. createAction is conditionally typed and I just can't seem to get it right. I'm not sure if this is related to me trying to use template literal types, or just improperly structuring my typing.
Would appreciate any help or ideas on how to achieve typed groups of action creators in a better way.

A: My first answer is don't try to generate actions like this yourself.  Instead, use the createAsyncThunk API in Redux Toolkit to handle creating and dispatching actions related to async requests.  That should eliminate almost all the code you've got here.


text:
Q: Catch alternative strings from OR operator with a Regex in Python? I'd like to catch a certain part of strings where there are alternative Regex branches. How can I safely refer to defined spots in alternative paths. I thought about doing
m=re.match("(A(?P<name>.+)B|C(?P<name>.+)D)", text)
match=m.group("name")

but there is a conflict with redefining the name. Using m.group by an index would be troublesome, since these Regex come from configuration files and I cannot guarantee the nesting level/index value which will lead to the match.
EDIT:
In the setup there are texts to match and regex from separate sources. I'd like to achieve
import re

for text in ["ABBC", "DEEEF", "GHHI"]:
    for regex in ["(A(.+)C|D(.+)F)", "G(.+)I"]:
        m=re.match(regex, text)
        if m:
            print(m.group(1)) # should actually match the middle characters, but doesn't work generally
            break

The number of possible regex can grow in the future, so it has to be a general solution

A: A possible solution is to use lookahead assertions. If you replace (A(.+)C|D(.+)F) regex with
^(?=A.+C$|D.+F$)[A-Z](.+)[A-Z], then group(1) will generally match middle characters.
It says: if you are at the beginning of a string (^) and one of lookahead assertions within (?=...) succeeds, match [A-Z](.+)[A-Z] string.

A: Your example can be made to work by changing
            print(m.group(1))

to
            print(filter(None, m.groups())[0])

(simply taking the group which contains the match).


text:
Q: Getting to use Power Within more than once? Is there a way to increase the amount of times that I can use Power Within before resting at bonfires?

A: Not without entering NG+ and finding the spell again.
In Dark Souls 2, they included a feature that increases spell uses when you increase your attunement enough, but in Dark Souls 1, the only way you can increase spell castings is to find and attune another spell.
Side note: You can use the Lingering Dragoncrest Ring to increase the duration of the spell.
For clarification - the Dusk Crown Ring does grant additional castings, but only an additional 50%, rounded down, at the cost of half of your health. So in this case, not only is it redundant, but it just makes things harder with no payoff.


text:
Q: magento multistore with global accounts but with different address per website I have a magento 1.9.2.4 with multistore (3 websites), and it has configured global accounts.
I need to filter the customer addresses by website.
For example, let's say the countries are France, Germany and UK.
If a customer with a french shipping address logs in the german website, I need that the french address is not available in the german website (or the Uk website).
If a customer with a german shipping address logs in the UK website, it shouldn't have available the german address in the UK website (or french).
But I have no clue where I should begin with this....
EDIT:
In system > configuration > SALES > Shipping Methods > Ship to Applicable Countries I have set Specific Countries option and selected a different country by website.
Now, customers can't ship to a different country, but I need to not list at all the addresses from another countries and the other countries addresses are still there.
EDIT 2:
I'm still searching, and I've tracked this code in app/design/frontend/rwd/myproject/template/opc/onepage/billing.phtml
<?php if ($this->customerHasAddresses()): ?>

        <?php echo $this->__('Select a billing address from your address book or enter a new address.') ?>

            <?php echo $this->getAddressesHtmlSelect('billing') ?>

<?php endif; ?>

and getAddressesHtmlSelect leads me to:
public function getAddressesHtmlSelect($type)
{
    if ($this->isCustomerLoggedIn()) {
        $options = array();
        foreach ($this->getCustomer()->getAddresses() as $address) {
            $options[] = array(
                'value' => $address->getId(),
                'label' => $address->format('oneline')
            );
        }

        $addressId = $this->getAddress()->getCustomerAddressId();
        if (empty($addressId)) {
            if ($type=='billing') {
                $address = $this->getCustomer()->getPrimaryBillingAddress();
            } else {
                $address = $this->getCustomer()->getPrimaryShippingAddress();
            }
            if ($address) {
                $addressId = $address->getId();
            }
        }

        $select = $this->getLayout()->createBlock('core/html_select')
            ->setName($type.'_address_id')
            ->setId($type.'-address-select')
            ->setClass('address-select')
            ->setExtraParams('onchange="'.$type.'.newAddress(!this.value)"')
            ->setValue($addressId)
            ->setOptions($options);

        $select->addOption('', Mage::helper('checkout')->__('New Address'));

        return $select->getHtml();
    }
    return '';
}

A: Finally I've found a solution, I copy it here because it maybe helps somebody in the future:
I had to override app/code/core/Mage/Checkout/Block/Onepage/Abstract.php with app/code/local/Mage/Checkout/Block/Onepage/Abstract.php, and there I changed the function getAddressesHtmlSelect() with this code:
public function getAddressesHtmlSelect($type)
{
    if ($this->isCustomerLoggedIn()) {
        $options = array();
        $store_id = Mage::app()->getStore()->getStoreId();
        $all_addresses = $this->getCustomer()->getAddresses();

        if (Mage::getStoreConfig('carriers/flatrate/sallowspecific', $store_id)) {
            $allowed_countries = explode( ',', Mage::getStoreConfig('carriers/flatrate/specificcountry', $store_id) );
            foreach ($all_addresses as $address) {

                if (in_array($address->getCountryId(), $allowed_countries)) {
                    $options[] = array(
                        'value' => $address->getId(),
                        'label' => $address->format('oneline')
                    );
                }

            }
        } else {
            foreach ($all_addresses as $address) {
                $options[] = array(
                    'value' => $address->getId(),
                    'label' => $address->format('oneline')
                );
            }
        }

        if (!empty($options)) {

            $addressId = $this->getAddress()->getCustomerAddressId();
            if (empty($addressId)) {
                if ($type=='billing') {
                    $address = $this->getCustomer()->getPrimaryBillingAddress();
                } else {
                    $address = $this->getCustomer()->getPrimaryShippingAddress();
                }
                if ($address) {
                    $addressId = $address->getId();
                }
            }

            $select = $this->getLayout()->createBlock('core/html_select')
                ->setName($type.'_address_id')
                ->setId($type.'-address-select')
                ->setClass('address-select')
                ->setExtraParams('onchange="'.$type.'.newAddress(!this.value)"')
                ->setValue($addressId)
                ->setOptions($options);

            $select->addOption('', Mage::helper('checkout')->__('New Address'));

            return $select->getHtml();
        }
        return false;
    }
    return '';
}

next stop is to change the app/design/frontend/rwd/myproject/template/opc/onepage/billing.phtml and app/design/frontend/rwd/myproject/template/opc/onepage/shipping.phtml with following code:
<?php if ($this->customerHasAddresses()): ?>

       <?php echo $this->__('Select a shipping address from your address book or enter a new address.') ?>

           <?php $select_address = $this->getAddressesHtmlSelect('shipping'); ?>  // this is for shipping.phtml, remember to change the argument 'shipping' for 'billing' in the billing.phtml
            <?php echo $select_address ?>

<?php endif ?>
<li id="shipping-new-address-form"<?php if ($this->customerHasAddresses() && $select_address ): ?> style="display:none;"<?php endif ?>>

And in the end there is only rest to comment the values of the billing/shipping form inputs to not being autocompleted with the default address.


text:
Q: ViewPager is not working after adding ScrollView to layout I added ViewPager () to the layout (root is RelativeLayout)
Problem is if I try to keep the root into  so that I can slide the screen,but content of Viewpager is not visible, without adding Scrollview it is showing the content.
My Code activity_profile.xml
<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/header_imageview"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
            android:src="@drawable/header" />

        <LinearLayout
            android:id="@+id/informations_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/header_imageview"
            android:gravity="center"
            android:orientation="vertical"
            android:paddingBottom="32dp"
            android:paddingTop="32dp"
            android:weightSum="1">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Test Header"
                android:textSize="17dp"
                android:textStyle="bold" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="4dp"
                android:gravity="center"
                android:text="Doctor Certificate"
                android:textColor="#FF707070" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="2nd line description"
                android:textColor="#FF909090" />

            <net.thrymr.mednetwork.SlidingTabLayout
                android:id="@+id/sliding_tabs"
                android:layout_width="15dp"
                android:layout_height="0dp"
                android:layout_weight="0.20"
                android:background="?attr/colorPrimaryDark" />

        </LinearLayout>

        <ImageView
            android:layout_width="75dp"
            android:layout_height="75dp"
            android:layout_above="@+id/informations_container"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="-16dp"
            android:src="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/informations_container"
            android:orientation="vertical">

            <net.thrymr.mednetwork.SlidingTabLayout
                android:id="@+id/sliding_tabs_profile"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimaryDark" />

            <android.support.v4.view.ViewPager
                android:id="@+id/pager"
                android:layout_width="match_parent"
                android:layout_height="0px"
                android:layout_weight="0.24"
                android:background="@android:color/white" />

        </LinearLayout>

    </RelativeLayout>
</ScrollView>

ProfileActivty.java
  mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
  mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mAppSectionsPagerAdapter);

    slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs_profile);
    //  mViewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), titles));
    slidingTabLayout.setViewPager(mViewPager);
    slidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.accentColor);
        }
    });

A: I tried this same thing some time back and had this exact same problem as I remember.
You need to add android:fillViewport="true" to the ScrollView element and everything will be perfect.


text:
Q: Determine the set X Let $A=\{\,2013^{30n^2+4n+2013}: n \in \mathbb{N}\,\}$. Let $X$ be the set of remainders when dividing all numbers in $A$ by $21$. Determine the set $X$.

A: HINT:
$$2013\equiv-3\pmod{21}$$
$$(-3)^1\equiv-3\equiv18,(-3)^2\equiv9,(-3)^3\equiv-27\equiv15\pmod{21}$$
$$(-3)^4=81\equiv18$$
So, the cycle begins
$$\text{Now, }30n^2+4n+2013\equiv n\pmod 3$$


text:
Q: How to save python script as txt? I wrote this to create a new file. I want the python script that I am in to all be saved into a txt file.  What should I do next?
f = open("Data.txt", "x")

A: Does this works out fine for you?
First read in the python file and save it in a variable and them simply write it out on another file.
def write_python_file(filename):
    with open(filename) as f:
        data = f.read()
        f.close()

    with open("Data.txt", mode="w") as f:
        f.write(data)
        f.close()

write_python_file("filename.py") # Replace with your python file.

Hope so this is useful information for you.


text:
Q: Position of adverbs in relation to the objects of a sentence Although the placement of adverbs doesn't pose a problem to me anymore, I sometimes find myself wondering which of the two options will sound more natural to a native ear.

1a) Brad Pitt slowly walked past Angelina Jolie.
1b) Brad Pitt walked past Angelina Jolie slowly.
2b) He loudly pounded on the door.
2a) He pounded on the door loudly.

EDIT:
Or maybe it's the third option that sounds more idiomatic?

1c) Brad Pitt walked slowly past Angelina Jolie.
2c) He pounded loudly on the door.


text:
Q: Java Web - Canonical Url unlimited redirection At the moment I am trying to make my own canonical links in Java web.
I got this in my web.xml
<servlet-mapping>
    <servlet-name>ControllerServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

ControllerServlet will call a factory that will use the getPathInfo() to call the correct class to handle this. The method that will handle the requests looks like
public void handleRequest(HttpServletRequest request, HttpServletResponse response) {
    try {
        RequestDispatcher view =  request.getRequestDispatcher("../Overview.jsp");
        view.forward(request, response);
    } catch (Exception ex) {
         System.out.println("error");
    }
}

Now when I want to visit my page I will surf to
http://localhost/firstfolder/overview

The pathinfo I get is /firstfolder/overview, this redirects correctly to /Overview.jsp but after that it keeps redirecting to /Overview.jsp and ultimately crash. Leaving the end user with an empty page. Any idea how I can stop this unlimited looping and just serve the page?


text:
Q: Network is not connected - spatstat package in R I am learning spatstat in R. As a first step I am converting my shapefile to be suitable for spatstat algorithms. When I use as.linnet to converted to linear network (the last line in the code below), I get a warning network not connected
roads<-readShapeSpatial("OnlyHigwayroads.shp")
spatstat.roads<-as.psp(roads)
final_roads<-as.linnet(spatstat.roads)
Warning message:
Network is not connected

I do not understand what it means. I took the shapefile back into arcgis and queried for dangles and there was not report of dangles. I also randomly checked few intersections, but I did not find any breaks in the connections.
So what does spatstat mean by network is not connected?
Thanks.

A: This is a warning, not an error.
A road network is connected if it is possible to drive between any two points on the network using only those roads.
If your network consists of several highways (to the exclusion of other types of roads) and there are two highways in your network which are joined only by a minor road, then the highway network is not connected.


text:
Q: Computer goes super-sluggish but Task Manager shows no CPU usage At times, for instance after running a resource-intensive program, my normally quite stable Windows7 PC becomes virtually unresponsive for as long as a couple of minutes. Even changing directory in Explorer can show the green progress bar for several seconds, clicking a tab in Chrome causes it to detach in a separate window for 10s, etc.
During this, the CPU usage is virtually zero, nothing is taking more than 1% CPU in TaskManager and the total CPU is often only 2% or so.
Over time, things slowly "heal" to the normal state of responsiveness but computers don't need to heal themselves after working hard!
What problem is this indicative of and what can I do about it? I am running MSE virus-scanner but that's about it for real-time protection.

A: I've found such problems before; as others have said, it was often due to HDD failure, but also I've seen it with Windows XP on a solid-state HDD in a HP Mini 110 netbook, some years ago. When the disk was busy writing, the whole thing would often be quite unusable. The problem did not manifest with other OSes, such as Ubuntu, and I can't say about Windows 7.
It may be worth looking for a driver update or trying a different OS (even from a Live CD or similar).
In Windows, it is useful to look at the Performance Monitor (as distinct from the Resource Monitor), and in the Performance > Monitoring tools > Performance Monitor tree, add (green plus icon) and under the Physical Disk part of the tree, add the entries that relate to the Queue Size. I suspect you'll find that one of your disks will have a queue size that is often very high for long periods of time.

A: CPU time can also be consumed in kernel mode by device drivers and those will not show up as CPU% in task manager.
Get Process Explorer and check what System and Interrupts and DPCs do.
You can also open the CPU usage graph (double click the first graph in the toolbar). It shows kernel mode in red and user mode in green.


text:
Q: Using a text inside a math environment in a pgfplots label How is it possible to have a \text{} field inside of a math environment of a pgfplots label. A minimum not working example is displayed below:
\begin{tikzpicture}
    \begin{axis}[ylabel=$c^\text{ref}$]
    \addplot coordinates {
        (0,0)
        (1,1)
    };
    \end{axis}
\end{tikzpicture}

Note that $c^\text{ref}$ is a valid latex syntax.
The error message thrown looks like
! Undefined control sequence.
\pgfplots@label@ ->$c^\text
                            {ref}$
l.26    \end{axis}

A: The error
! Undefined control sequence.
\pgfplots@label@ ->$c^\text
                            {ref}$
l.26    \end{axis}

indicates that the macro \text is not defined. This happens when you don't load amsmath package since the macro \text is defined by the package amsmath.
With the following code:
\documentclass[a4paper,10pt]{article}
\usepackage{amsmath}   %% comment this line to get the error.
\usepackage{pgfplots}
\pgfplotsset{compat=1.12}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[ylabel=$c^{\text{ref}}$]
    \addplot coordinates {
        (0,0)
        (1,1)
    };
    \end{axis}
\end{tikzpicture}
\end{document}

with amsmath loaded, the error goes away.


text:
Q: Most of the audience is/are Should I use are or is in the following sentence?

Most of the audience is/are sleeping.

A:
Most of the audience is/are sleeping.

"Of the audience" is a prepositional phrase and can essentially be struck from the sentence to look at the rest of the structure. So look at:

Most of the audience is/are sleeping.

Here it it obvious that the phrase should be "Most are..."

A: Both are correct. It actually depends if you want to use audience as singular or plural.
We have to look at two different things here: first, we need to identify the subject of the sentence; second, we need to determine whether the collective noun is singular or plural.

Determining the subject of the sentence.

Most of the audience is/are sleeping.

The subject in your sentence is Most, not audience. Audience is the object.
Most is a determiner and an indefinite pronoun. It can be singular or plural based on the object of the preposition that follows. If the noun after of is singular, use a singular verb; if it is plural, use a plural verb.

Is the collective noun singular or plural?
As @lurker already stated in his/her answer:

When expressed as a group, audience is singular.
  When expressed as individuals within a whole, audience is plural

Audience is a collective noun; it can be singular or plural depending on the author's intent.

Note: Americans tend to treat collective nouns as single units. In British usage, it's the opposite.

A: When expressed as a group, audience is singular:

Do not expect massive page views at 3 AM when your target audience is sleeping.

When expressed as individuals within a whole, audience is plural:

You can tell a movie is poor when many in the audience are sleeping.


text:
Q: Possible to have a rounded/curved side, not corners? Trying to build something similar to the image below.
The container would be 100% width, the header would be fixed height, but the body height would be dynamic.
I was able to almost get what I want by doing the following to the "Body" div
border-radius: 50% 50% 0 0 / 15px 15px 0 0;
-moz-border-radius: 50% 50% 0 0 / 15px 15px 0 0;
-webkit-border-radius: 50% 50% 0 0 / 15px 15px 0 0;

Theoretically, I would like to have the "Header" div be curved, and the body go underneath, but I dont think that's possible (the header will contain a filled image)
EDIT: forgot to mention. With the above code, and margin-top:-15px added to the bottom div, it did work in Firefox and IE, but not in Chrome and Safari. Maps and sliders still went over to the Header div and did not get cut off.
EDIT 2 http://jsfiddle.net/ShKNu/4/
^ This is how I currently have it. As you can see, the map does not get cut off on the curve, and goes right into the header.

A: You were headed in the right direction
Putting the curve on the "body" or .main section with overflow: hidden and a negative margin-top is a good way to go. To resolve your issue with 3rd party content that is position: absolute, you just need to make sure your .main has position: relative.
Here is a fiddle with both positioned and non-positioned content inside .main (note: I tweaked the curve to be a bit more prominent for the demonstration).
It tests fine in IE9+, Chrome, and FF. Obviously, any 3rd party content that is being placed in the header or elsewhere outside of .main will not necessarily be hidden, but that should be expected. Yet even that can be worked around with proper positioning (relative) and z-indexing (main higher than header) set, as this fiddle shows.

A: Try using margin:-20px or another measurement.


text:
Q: Falling into a black hole – how can my perspective change from outside-observer to inside-observer? I study molecular biology; my skills in maths aren't the best – so I'm asking for answers that aren't purely mathematical, if possible. I ask you to elaborate on formulas or diagrams, if included in the answer.
I have a long standing interest in black holes/event horizons (I started reading up on them, every now and then, more than 10 years ago) and many of the concepts/problems that lay-people on this site ask about, and the corresponding answers, are not new to me. So I am not asking for ELI5-type answers either – if possible.
If this question has been asked before I would be thankful for a link. I did not find any answers, neither on this nor on other boards.
To the question:
The title basically says it.
I want to talk about Schwarzschild black holes/corresponding event horizons (for simplicity).
As I "understand" it, to an outside observer an event horizon seems to be unreachable. An infalling object appears to freeze or "get stuck" just above the horizon, and vanish by redshifting.
So let's suppose I start falling towards the EH myself:
How can I change my outside-observer-POV to an inside-observer-POV? When would that happen (on my clock)?
I heard that there seems to be no experiment that I could conduct, to tell the moment when I cross the horizon. But the transition from outside to inside has to happen anyway, whether I realize it or not – doesn't it?
Closely related question (as I understand it, it is the same problem as above, just framed differently):
I throw something toward the BH.
I see it approach, get closer, slow down, redshift.
I start moving toward the "frozen object".
As I get ever closer, it appears to recede ever farther away – it is impossible for me to pick it up, even if I move close to the speed of light.
Doesn't that mean that the EH itself appears to recede from me? Don't I have an infinite amount of space (and time) to cross, to get to the EH (or the object, for that matter)?

A:
So let's suppose I start falling towards the EH myself: How can I change my outside-observer-POV to an inside-observer-POV? When would that happen (on my clock)?

If you are freely falling towards a black hole then you really want to use better coordinates that express your situation. These are called Eddington-Finkelstein coordinates. In these you are going to be able to derive a proper time to cross the event horizon and also a proper time before you get crunched at the singularity.

As I get ever closer, it appears to recede ever farther away – it is impossible for me to pick it up, even if I move close to the speed of light. Doesn't that mean that the EH itself appears to recede from me? Don't I have an infinite amount of space (and time) to cross, to get to the EH (or the object, for that matter)?

Let's say you are a mile away from the event horizon of a huge black hole. In such a situation it could occur that tidal effects are negligible at the event horizon so that you wouldn't notice crossing it. To remain where you are you must be accelerating because the black hole will be pulling you. You let your apple fall from your grasp. The light that you see emanating from the apple is being redshifted due to your acceleration. You never see it cross the event horizon but just fade from sight.
Now you decide to take the plunge, i.e you turn your jets off. You are now freely falling after your apple - switch to E-F coordinates. The acceleration between you both is pretty constant so you are just moving after it and follow it into the event horizon. The red-shift is less. You are correct that you could accelerate to catch up with it to eat it. You don't need to go near the speed of light, just fast enough.
However, the singularity may be far away but crunch-time and spaghettification is coming!

A: (Disclaimer: purely layman in terms of relativity - specifics are probably way more complicated than how my thinking works- hopefully this makes sense though)
In reality there are no strictly "insider" or "outsider" viewpoints - It is a continuum of different frames of reference depending what's your position or movement with regards to the infalling object.
How I visualize this mentally is having "shells" around the event horizon with different speeds of time. Then how one might observe time for other objects (falling in or not) depends not only on their time dilation but yours as well. So close to event horizon time might run 10000x faster, but if you are observing it from the same shell, passing of time for that object would look perfectly normal for you (while objects away from BH would appear to fast-forward and objects closer to BH would appear slower). Whether you can simply add/divide these factors (probably not) is not really relevant for understanding how it works in general.
So, in theory, the outsider point of view is assumed to be located at infinity to negate any effect of the BH to that observer (especially no time dilation from the BH); in my visualization this shell is infinitely far away and thus has no time dilation factor (ie say time runs at 1x speed); obviously simply being infinitely long away from the infalling object would mean it'll take infinitely long for light to arrive to the observer thus meaning in reality no observations. So it's more a thought experiment than a real experimental setting.
Edit:
So to answer your actual answer, as a summary, if you are falling towards a black hole, you will always be viewing it as from an "insider" point of view. You may see other objects falling into a black hole which are closer to the black hole, and you would have sort-of outsider point of view for those objects (i.e. relative time dilation). As long as you eventually cross the event horizon, in theory you should be able to also observe these objects crossing the event horizon too. However, if you somehow back up or would remain hovering outside the event horizon, you'd remain as an outside observer for those in falling objects (i.e. never see the cross the event horizon; since relative time dilation between you and them grows asymptotically towards infinity)


text:
Q: Carving an SVG Path into a Rect, leaving the rect with a "hole" The idea is pretty simple:
I have an SVG path and an Rect,
I need to make the path carve through the Rect, the resulting "hole" should be see-through.
Here's jsfiddle with a copy of how it's looking right now:
https://jsfiddle.net/9u0jyhr7/embedded/result/
current HTML example:
<div id="container">
  <svg id="theSVG" xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" xmlns:xlink="http://www.w3.org/1999/xlink">
    <rect id="theRect" width="100%" height="100%" fill="#ffffff"></rect>
    <path id="thePath" d="M7 25.69305419921875L7 25.6875L7.00505256652832 25.6875L293.9971923828125 25.6875L294 25.6875L294 25.709388732910156L294 90.67454528808594L294 90.6875L294.0021667480469 90.6875L321.85845947265625 90.6875L321.8607482910156 90.6875L294 183.69180297851562L294 206.421142578125L294 206.42408752441406L294 206.42701721191406L294 228.93441772460938L294 228.936279296875L294 228.93814086914062L294 248.68634033203125L294 248.6875L294.0007629394531 248.6875L304.7754211425781 248.6875L304.7763671875 248.6875L304.7773132324219 248.6875L306.581298828125 248.6875L306.581298828125 248.6875L306.582275390625 248.6875L306.582275390625 248.6875L306.583251953125 248.6875L306.583251953125 248.6875L324.73028564453125 248.6875L324.7316589355469 248.6875L324.7330017089844 248.6875L330.1683044433594 248.6875L330.1697998046875 248.6875L330.1712951660156 248.6875L357.22027587890625 248.6875L357.22265625 248.6875L357.2250061035156 248.6875L360.99749755859375 248.6875L361 248.6875L507 172.48577880859375L507 342.3311767578125L507 342.3337097167969L502.9844665527344 341.6875L436.00836181640625 341.6875L436 341.6875L436 341.6893615722656L436 378.0494079589844L436 378.051513671875L436 378.0536193847656L436 406.68511962890625L507 448.48748779296875L507 448.4908447265625L507 578.6819458007812L507 578.6875L506.9949951171875 578.6875L479.0045166015625 578.6875L479 578.6875L289.9993591308594 341.6875L279.00048828125 341.6875L279 341.6875L278.99951171875 341.6875L273.92425537109375 341.6875L273.9237976074219 341.6875L273.92333984375 341.6875L270.4071350097656 341.6875L270.4067077636719 341.6875L270.4062805175781 341.6875L265.60040283203125 341.6875L265.6000061035156 341.6875L265.5995788574219 341.6875L264.8004150390625 341.6875L264.79998779296875 341.6875L264.7995910644531 341.6875L263.8423156738281 341.6875L263.8419189453125 341.6875L263.84149169921875 341.6875L263.2403869628906 341.6875L263.239990234375 341.6875L263.2395935058594 341.6875L253.1584930419922 341.6875L253.15809631347656 341.6875L253.15769958496094 341.6875L251.40040588378906 341.6875L251.39999389648438 341.6875L251.39959716796875 341.6875L245.081787109375 341.6875L245.0813446044922 341.6875L245.08090209960938 341.6875L223.00071716308594 341.6875L223 341.6875L9.995001792907715 578.6875L7.00505256652832 578.6875L7 578.6875L7 578.6819458007812 " fill="#000000"></path>
    </svg>
  </div>

Here's an image of what it would probably look like if we can carve that hole:
http://i.stack.imgur.com/5fjBR.png
The Path is dynamically generated and can be quite complex, so I can't really eyeball the result.
It has to be done in javascript (or with some very clever usage of styles).
I need the result to be a DOM node that I can eventually move between z-indexes (could be grouped? a resulting "difference" path calculated in js?).
Performance and experimental features are not an issue, this is aimed at nwjs app.
Some other notes:

*

*I'm already using jQuery, svg.js and a bunch of other libraries, so adding
new libraries is not a problem.

*The rect could also be replaced by just a color filled div, if that helps solve the problem.

*Ive already tried masks and clips but couldnt come to a working solution.
Any help appreciated, Thank you in advance.

A: A mask is what you need.  I'm not sure what you tried before, but it should do what you want.
Just create a mask like so:
<defs>
    <mask id="theMask">
        <rect width="100%" height="100%" fill="white"/>
        <path id="thePath" d="..." fill="#000000"></path>
    </mask>
</defs>

Either move the original path into the mask, or copy it and hide the original.
Then apply the mask to the rect
#theRect {
    mask: url(#theMask);
}

Demo fiddle here


text:
Q: Group multidimensional array data based on two column values and sum values of one column in each group I have an array which is created as a combination of two database queries from two separate databases, it looks similar to:
$arr1 = [
    ['part' => '1', 'address' => 'aaa', 'type' => '1', 'count' => 5],
    ['part' => '1', 'address' => 'bbb', 'type' => '1', 'count' => 5],
    ['part' => '1', 'address' => 'ccc', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'aaa', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'bbb', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'ccc', 'type' => '2', 'count' => 5]
];

I am looking for a way to group this array by part and type values. I also need to know the total of the count values as they are grouped.
The results would be something like:
$arr2 = [
    ['part' => '1', 'type' => '1', 'count' => 15],
    ['part' => '2', 'type' => '1', 'count' => 10],
    ['part' => '2', 'type' => '2', 'count' => 5]
];

but I just can't see how to do this. I have seen a few examples of grouping by a single key/value, but not by multiple values at once.

A: This function should do the job.
function groupByPartAndType($input) {
  $output = Array();

  foreach($input as $value) {
    $output_element = &$output[$value['part'] . "_" . $value['type']];
    $output_element['part'] = $value['part'];
    $output_element['type'] = $value['type'];
    !isset($output_element['count']) && $output_element['count'] = 0;
    $output_element['count'] += $value['count'];
  }

  return array_values($output);
}

If both databases are on the same database server you would be able to do this using SQLs GROUP BY feature.

A: The following:
$arr2 = array();
foreach ($arr1 as $a) {

  unset($a['address']);
  $key = $a['type'] . '-' . $a['part'];

  if (isset($arr2[$key])) {
    $arr2[$key]['count'] += $a['count'];
  } else {
    $arr2[$key] = $a;
  }

}
$arr2 = array_values($arr2);

Would output
array
  0 =>
    array
      'part' => string '1' (length=1)
      'type' => string '1' (length=1)
      'count' => int 15
  1 =>
    array
      'part' => string '2' (length=1)
      'type' => string '1' (length=1)
      'count' => int 10
  2 =>
    array
      'part' => string '2' (length=1)
      'type' => string '2' (length=1)
      'count' => int 5

A: Something like
 $newarr=array();
 foreach ( $arr as $Key => $Value ) {
 $newarr[$Value[part]][]=$arr[$key];
 }

 foreach ( $newarr[part] as $Key => $Value ) {
 ...
 }

A: Full answer for multi-keys arrays grouping is
// *    $arr - associative multi keys data array
// *    $group_by_fields - array of fields to group by
// *    $sum_by_fields - array of fields to calculate sum in group

function array_group_by($arr, $group_by_fields = false, $sum_by_fields = false) {
    if ( empty($group_by_fields) ) return; // * nothing to group

    $fld_count = 'grp:count'; // * field for count of grouped records in each record group

    // * format sum by
    if (!empty($sum_by_fields) && !is_array($sum_by_fields)) {
        $sum_by_fields = array($sum_by_fields);
    }

    // * protected  from collecting
    $fields_collected = array();

    // * do
    $out = array();
    foreach($arr as $value) {
        $newval = array();
        $key = '';
        foreach ($group_by_fields as $field) {
            $key .= $value[$field].'_';
            $newval[$field] = $value[$field];
            unset($value[$field]);
        }
        // * format key
        $key = substr($key,0,-1);

        // * count
        if (isset($out[$key])) { // * record already exists
            $out[$key][$fld_count]++;
        } else {
            $out[$key] = $newval;
            $out[$key][$fld_count]=1;
        }
        $newval = $out[$key];

        // * sum by
        if (!empty($sum_by_fields)) {
            foreach ($sum_by_fields as $sum_field) {
                if (!isset($newval[$sum_field])) $newval[$sum_field] = 0;
                $newval[$sum_field] += $value[$sum_field];
                unset($value[$sum_field]);
            }
        }

        // * collect differencies
        if (!empty($value))
            foreach ($value as $field=>$v) if (!is_null($v)) {
                if (!is_array($v)) {
                    $newval[$field][$v] = $v;
                } else $newval[$field][join('_', $v)] = $v; // * array values
            }

        $out[$key] = $newval;
    }
    return array_values($out);
}

A: If this task was necessary in one of my projects, I would craft a snippet that would not need reference variables or any iterated function calls.
Inside the loop, declare the composite temporary key as a variable (since it is used more than once).  Push the new row into the result array using the composite key as the temporary first-level key.
Use the null coalescing operator to use the pre-existing count for a given group or zero if the group has not yet been encountered.  Then add the new count value to the previously accumulated count.
This technique will unconditionally overwrite the encountered group every time it is repeated.  In doing so, the data will be updated with the correct part, type, and count values throughout the iterative process.
When the loop finishes, re-index the result array by calling array_values().
Code: (Demo)
$arr1 = [
    ['part' => '1', 'address' => 'aaa', 'type' => '1', 'count' => 5],
    ['part' => '1', 'address' => 'bbb', 'type' => '1', 'count' => 5],
    ['part' => '1', 'address' => 'ccc', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'aaa', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'bbb', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'ccc', 'type' => '2', 'count' => 5]
];

$result = [];
foreach ($arr1 as $row) {
    $compositeKey = $row['part'] . '-' . $row['type'];
    $result[$compositeKey] = [
        'part' => $row['part'],
        'type' => $row['type'],
        'count' => ($result[$compositeKey]['count'] ?? 0) + $row['count']
    ];
}
var_export(array_values($result));

Output:
array (
  0 =>
  array (
    'part' => '1',
    'type' => '1',
    'count' => 15,
  ),
  1 =>
  array (
    'part' => '2',
    'type' => '1',
    'count' => 10,
  ),
  2 =>
  array (
    'part' => '2',
    'type' => '2',
    'count' => 5,
  ),
)

p.s. Ideally, this task probably could/should be performed in the sql but we don't have the details to provide any specific guidance.


text:
Q: How can i get this function to check for an empty field? I'm wondering why the validateForm() function isn't working. I am trying to check if theres empty fields in the textarea tags in my form but it isn't working and just proceeds onto the addEntry.php page without performing the validateForm function. Here is my HTML and Javascript code :
<form id ="myForms" action="addEntry.php" onsubmit="return validateForm()" method="post" name= "myForm" required>

Add Blog

            <textarea id = "title" type="text" placeholder="Title" name="content"style="height:2em" name="fname"></textarea>

            <textarea id = "content" type="text" placeholder="Enter your text here..." name="content"style="height:12em" name="fname"></textarea>

            <input id = "submit" type="submit" value = "Post" onclick = "validateForm()">
            <input class = "reset" type = "button" onclick = "myFunction()" value = "Clear">

</form>

A: *

*action="addEntry.php":
The form action will always send data to 'addEntry.php' - even if validation fails.  You should use document.getElementById("myForm").submit(); once validation has completed successfully! Read the docs about event.preventDefault() when using a button/input with type="submit".

*textarea name:
You have multiple textarea elements with two names - and they are the same name! (content, content, fname, fname)... Always use unique names.

*textarea id:
You have multiple elements that share the same ID! (title, title, content, content)... Always use unique IDs or reuse a class.
With JS it is best to use ID id="myTitleTextarea" to select a unique element. With PHP you must use the name="myContentTextarea" to reference input (you used the POST method so - $title =  $_POST['myContentTextarea'];)

*input type='submit':
Inputs / buttons with the type of submit will always 'submit' the data to the 'action' of the form. This may prevent validation from ever occurring.

*input class='reset' onclick='myFunction()':
Any input or button with type='reset' will already reset the form - your function 'myFunction()' is not required (unless you want to prompt and make sure the user wants to reset)

*validateForm() event:
The function validateForm() was not passed an event... there is no need for event.validateForm() - also this would loop infinitely, if it worked.

*validateForm() var x:
Use more sensible names like var fnameValue = .... When selecting elements with JS - it may be easier to use ID's instead of names - getElementById('content')

*document.getElementsByName["myForm"]["fname"].value:
TypeError: document.getElementsByName.myForm is undefined...
Use the developer console when testing!!! Check out DevTools as this will notify and may explain any errors you encounter!
Chrome https://developer.chrome.com/docs/devtools/
Firefox https://developer.mozilla.org/en-US/docs/Tools


text:
Q: iTunes Connect add in app purchases I'm following along with this https://www.raywenderlich.com/122144/in-app-purchase-tutorial  tutorial for setting up In App Purchases in iOS Apps,  and having problems creating the In App purchase for the first time in iTunes Connect. The option to create a non consumable iap is not available.  I think I'm missing something.
See http://imgur.com/21ArPr9 for a screenshot.
IAP is enabled in my app, I've uploaded my app to iTunes connect. Not sure what's going on. Any advice?  I'm on XCode 8, Swift 3.


text:
Q: Toggle not working on checkbox I've tried all sorts, using answers from stackoverflow and others, its becoming very frustrating because it should work. Am trying to make a label change colour when clicked on to select the checkbox. Below are my codes;

$("input[type=checkbox]").change(function() {
  $(this).parent().toggleClass("color_change");
});
})
.style_check {
  padding: 20px;
  background: yellow;
}
.color_change {
  background: red;
}

  <input type="checkbox" name="roles" value="1" />
  Block User

What exactly can I do to make it work?

A: With your posted code - I just removed }) and your example works.

$("input[type=checkbox]").change(function() {
  $(this).parent().toggleClass("color_change");
});
.style_check {
  padding: 20px;
  background: yellow;
}
.color_change {
  background: red;
}

  <input type="checkbox" name="roles" value="1" />
  Block User

A: Should work if you remove the extra }) and if you've the correct HTML with correct relation between checkbox's and label's, check the sample below.
Hope this helps.

$("input[type=checkbox]").change(function () {
  $(this).parent().toggleClass("color_change");
});
.color_change{
    color: red;
}

  <input type="checkbox" />
  Checkbox 1

  <input type="checkbox" />
  Checkbox 1

  <input type="checkbox" />
  Checkbox 1

  <input type="checkbox" />
  Checkbox 1

Your case snippet :

$("input[type=checkbox]").change(function () {
  $(this).parent().toggleClass("color_change");
});
.style_check {padding:20px; background:yellow;}
.color_change {background:red;}

  <input type="checkbox" name="roles" value="1"  />
  Block User

  <input type="checkbox" name="roles" value="1"  />
  Block User

  <input type="checkbox" name="roles" value="1"  />
  Block User

  <input type="checkbox" name="roles" value="1"  />
  Block User

A: You have some extra }) at your javascript. So might be syntax issues. I have set up working example on jsfiddle:
HTML:
<form >
  <input type="checkbox" name="vehicle" value="Bike" > I have a bike

</form>

JS:
$("input[type=checkbox]").change(function () {
  $(this).parent().toggleClass("color_change");
});

CSS:
.color_change {
  color: red;
}


text:
Q: Where to deploy Java XMPP server application? I have XMPP serwer written in Java SE using Smack 4.3.0. It is command line application.
It is working locally. Now I want to deploy it on the some kind of web container in the Internet.
I do not really know how to do it and where I can upload my serwer app.
I found some cloud like HEROKU etc. but all the hosting places's tutorial are about Java Web App with Servlet etc.
I just want to run my CMD app on the Internet.
Also I have MySql DB which I want to run on the same container.
Can you provide some URL where can I do it?
Or maybe my approach are bad...
But there must be place for this kind of app. What about simple application handling WebSocket? Where are they running?

A: I can recommend to try Digital Ocean, it needs some manual work but it's very easy. I like it for their simplicity and also because they have lots of ready-to-go guides for newbies
Step-by-Step Guide:

*

*Create Digital Ocean account or sign in if you have an existing one

*Create a Droplet from the Digital Ocean Control Panel. Droplets are something similar to virtual machines. I recommend to try with a very basic shape which costs only 5$ per month. You can easily scale it after in a single click. I also recommend to choose an Ubuntu image with no additional software for your droplet — Ubuntu is an OS that is super easy in setup if you do not have much experience.

*Once droplet is ready — you need to perform an Initial Server Setup. There are a few configuration steps that you should take early on as part of the basic setup. This will increase the security and usability of your server and will give you a solid foundation for subsequent actions.

*Install MySQL server

*Install Java

*Put your app source code into server (via git or via scp command)

*Simply run it in background - nohup java -jar myapp.jar &

*Now you can check your java app process: ps aux | grep myapp
Additional stuff:

*

*Register and add a domain to you site, e.g. example.com. To set up a domain name, you need to do two things. First, you need to purchase a domain name from a domain name registrar. Second, you need to set up DNS records for your domain by using a DNS hosting service. This DNS Quickstart guide will explain it in details.

*It's also good to setup HTTPS for you site. The following How To Install an SSL Certificate from a Commercial Certificate Authority guide will explain it in details.


text:
Q: Tratamento específico para Grupos de Objetos inseridos na Caixa de Ferramentas do VBA (Excel) Devido a ações repetitivas com grupos de objetos que crio para funcionarem como se fossem um único objeto, agrupei alguns destes objetos (com o botão direito do mouse e selecionando agrupar...), e arrastei para dentro da caixa de ferramentas do VBA.
Para minha surpresa deu certo, surgiu um ícone editável e que permite que eu recrie de uma única vez cada grupo de objetos que preciso usar repetidamente em partes diferentes do projeto ou mesmo em outros projetos.
Porém, há alguns inconvenientes em se trabalhar desta forma, listo alguns deles que são importantes para mim:

*

*O "grupo" criado não é identificado como um novo objeto (evidentemente), então deve-se trabalhar com cada objeto de um grupo como se ele fosse um objeto colocado individualmente. continuando esses objetos agrupados ou não (de fato são simplesmente novos objetos colocados individualmente no formulário).

*Pelo fato de serem objetos distintos, a mesma lógica de nomeação sequencial de cada objeto é seguida, por exemplo, cada grupo que tenha um único Label inserido no formulário gera o Label1, Label2, Label3, etc. Então se entre um grupo e outro for colocado no formulário alguns objetos do mesmo tipo de alguns que existam nestes grupos, um Label que seria o Label7 na inclusão do grupo, passa a ser Label9, pois dois Labels foram colocados antes deste grupo. Portanto, é preciso verificar "objeto a objeto" do grupo, que nome ele recebeu para tratar no código.
Mostro a seguir um exemplo meramente didático.

*

*Neste formulário estão presentes os objetos: Frame1, Image1, Label1, commandButton1 e commandButton2.

*Estes objetos foram agrupados (botão direito do mouse):

*O grupo resultante foi arrastado para a caixa de ferramentas (vide o ícone do planeta terra, modifiquei para ficar claro a adição do grupo):

*Na sequência foram criados um grupo (à direita do primeiro), um Label normal (abaixo deles) e mais um grupo (abaixo do Label):

O nome dos novos objetos ficaram assim:

*

*Frame2, Image2, Label2, commandButton3 e commandButton4 para o segundo grupo

*Label3 para o Label inserido no formulário

*Frame3, Image3, Label4, commandButton5 e commandButton6 para o terceiro  grupo
Repare que o Label do terceiro grupo fica com o valor 4 e não acompanha os demais do grupo, o que impede um tratamento rígido no código.
PERGUNTA:
Há uma forma de se fazer isso obtendo nomes diferentes para os objetos ou gerar propriedades para esse grupo da caixa de ferramentas?
Por exemplo, se o nome de cada objeto do grupo da caixa de ferramentas (por absurdo) pudesse receber um nome qualquer, cada novo objeto criaria estes objetos com a numeração esperada (o Label do grupo poderia chamar Legenda, gerando Legenda1, Legenda2, Legenda3, etc. não interferindo com a nomeação dos Labels que não sejam de um desses grupos).
Uma forma que também resolveria é se para esse grupo fossem associadas propriedades, o que permitiria, por exemplo, registrar uma "id" para cada grupo criado, ou mesmo algum texto de referência.
Tem como fazer?
Tenho certo conhecimento e pouca experiência em linguagens voltadas a eventos ou objetos, portanto, acredito que tenha uma forma mais adequada de se tratar este caso.

A: A solução apresentada abaixo (código e formulário com o resultado dos testes) foi feita usando "Controls" para tratar os objetos de cada grupo.
Private Sub CommandButtonTeste_Click()

    Dim Bandeira As Variant

    'Pega o ícone da bandeira desejada
    Set Bandeira = LoadPicture("F:\Teste\Japao.ico")

    'Teste #1: Altera todos os dados do primeiro grupo
    GrupoDeObjetos 1, True, True, _
                   "Japão", _
                   Bandeira, _
                   "Arroz", _
                   "Perda", _

                   "Troca"

    'Teste #2: Torna os objetos do Segundo grupo invisíveis
    GrupoDeObjetos 2, False, True

    'Teste #3: Desabilita os objetos do terceiro grupo
    GrupoDeObjetos 3, True, False

    'Teste #4: Força um erro, pois o grupo 4 não existe
    GrupoDeObjetos 4, True, True

End Sub

Public Sub GrupoDeObjetos( _
           ByVal IndiceDoGrupo As Integer, _
           ByVal GrupoVisivel As Boolean, _
           ByVal GrupoHabilitado As Boolean, _
  Optional ByVal LegendaDoFrame As String = "", _
  Optional ByVal Imagem As Variant = "", _
  Optional ByVal LegendaDaImagem As String = "", _
  Optional ByVal LegendaDoBotao1 As String = "", _
  Optional ByVal LegendaDoBotao2 As String = "")

    Dim i As Integer

    'Verifica o índice
    If IndiceDoGrupo < 1 Or IndiceDoGrupo > 3 Then

        Beep

        MsgBox "Índice do Grupo de Objetos inválido!" & _
                Chr(13) & Chr(13) & _
               "Índice: " & IndiceDoGrupo

        Exit Sub

    End If

    'Tratamento dos objetos do grupo
    ' Atualiza o índice do grupo com o valor
    ' do índice dos controles no formulário
    Select Case IndiceDoGrupo

        Case 1

            'Índice do Frame1 no formulário
            IndiceDoGrupo = 0

        Case 2

            'Índice do Frame2 no formulário
            IndiceDoGrupo = 5

        Case 3

            'Índice do Frame3 no formulário
            IndiceDoGrupo = 11

    End Select

    'Atualiza dados do objeto se os dados foram passados
    If LegendaDoFrame <> "" Then Me.Controls(IndiceDoGrupo).Caption = LegendaDoFrame
    If Imagem <> "" Then Me.Controls(IndiceDoGrupo + 1).Picture = Imagem
    If LegendaDaImagem <> "" Then Me.Controls(IndiceDoGrupo + 2).Caption = LegendaDaImagem
    If LegendaDoBotao1 <> "" Then Me.Controls(IndiceDoGrupo + 3).Caption = LegendaDoBotao1
    If LegendaDoBotao2 <> "" Then Me.Controls(IndiceDoGrupo + 4).Caption = LegendaDoBotao2

    'Trata os objeto do grupo (Visible/Enabled)
    For i = 0 To 4

        'Grupo visível ou não
        Me.Controls(IndiceDoGrupo + i).Visible = GrupoVisivel

        'Grupo habilitado ou não
        Me.Controls(IndiceDoGrupo + i).Enabled = GrupoHabilitado

    Next i

End Sub

Observe no código que o IndiceDoGrupo é uma única variável tratada de dois modos diferentes:
1. Ao se chamar a rotina este índice aponta para o grupo desejado, neste caso os grupos de valores 1, 2 e 3.
2. No código, conforme o grupo escolhido para tratar, esta variável recebe o valor do índice do Frame do grupo, neste caso 0, 5 e 11 respectivamente para os grupos 1, 2 e 3.
Repare que cada grupo tem 5 objetos, como o grupo 2 foi criado imediatamente após o grupo 1, o índice de seu Frame é o 5. (os objetos do grupo 1 tem os índices: 0, 1, 2, 3 e 4)
A diferença do índice do grupo 3 ser 11 e não 10, é que o Label3 foi inserido no formulário antes desse grupo, portanto, o Label3 obteve o índice 10.
IMPORTANTE!
Para que este código funcione adequadamente, ao criar seu grupo de objetos insira cada objeto do grupo na sequência que pretende trabalhar, e não insira nenhum outro objeto que não seja deste grupo até terminá-lo.
Agrupe-o, coloque na caixa de ferramentas e pronto, basta tratar o índice de cada novo objeto que colocar no formulário (neste caso, iniciando de 1).
Este é o resultado dos testes:

Observe que são quatro testes, mas não apresentei a caixa de diálogo gerada pelo erro proposital do teste #4 (ela foi fechada antes do PrintScreen), para ficar fácil identificar na imagem acima o ocorrido:
1. Todos os dados do grupo 1 foram alterados, incluindo a imagem da bandeira
2. O grupo 2 ficou invisível
3. O grupo 3 ficou desabilitado, porém, apesar da imagem também estar desabilitada, ela não fica "esmaecida" (não fiz este efeito no exemplo)
4. A mensagem de erro causada por se chamar um quarto grupo que não existe no formulário gerou a mensagem de erro apropriada (não apresentei)
COMPLEMENTO
Caso o Label3 seja deletado do formulário, o índice do terceiro objeto mudará, para resolver isso pode-se criar uma rotina para buscar o índice do primeiro objeto do grupo ao se inicializar o formulário, por exemplo.
Sugestão simples de chamada da rotina:
    Dim Indice1, Indice2, Indice3 as Integer

    Indice1 = IndiceDoObjeto(UserForm1, "Frame1")
    Indice2 = IndiceDoObjeto(UserForm1, "Frame2")
    Indice3 = IndiceDoObjeto(UserForm1, "Frame3")

Caso o objeto não seja localizado no formulário eu indicaria informar por meio de uma mensagem e sair do programa imediatamente após a mensagem, pois não faz sentido prosseguir havendo este tipo de erro.
Desta forma não ocorrerá erros ao manipular objetos entre os grupos.
ORGANIZAÇÃO NA ORDEM DOS ÍNDICES DOS OBJETOS NO GRUPO
Ao trabalhar com grupos deste tipo (bem mais extensos), me deparei com um problema que pode ocorrer de duas formas:

*

*Se os objetos de um grupo não foram criados na ordem desejada ou intuitiva (a partir do primeiro de cima à esquerda até o último de baixo à direita), o índice de cada objeto no grupo evidentemente não acompanhará esta ordem, o que dificulta - pelo menos - o tratamento inicial dos mesmos no código.

*Se for alterada a posição ou ordem de exposição do objeto no formulário, com o "Trazer para frente" ou "Enviar para trás", por exemplo, os índices dos objetos no formulário são alterados, então pode ocorrer de um objeto do grupo ser "substituído" por outro no tratamento aos objetos do grupo ou mesmo todos os objetos terem seus índices alterados (caso de trazer para frente um objeto que foi criado antes do grupo).
Como solução, fiz um teste, passei a ordenar os objetos conforme o desejado, de forma que seus índices ficassem na ordem "intuitiva". Para tanto, fiz isso em um novo formulário, para não haver problema com outros objetos que poderiam interferir neste processo.
Então, sem precisar "reagrupar", pois permaneceram "agrupados" mesmo com os recursos do tipo "Avançar" e "Recuar", por exemplo, ao final o coloquei na caixa de ferramentas.
Neste momento, este novo grupo ficou ordenado como desejado, ou seja, ao inseri-lo em qualquer formulário, a ordem dos índices de seus objetos mantêm a ordem em que alterei no grupo.
SOLICITAÇÃO
Caso existam outras formas de se fazer isso, inclusive por meio de Classes de objetos com propriedades para passar estes dados, se puderem postar aqui um exemplo eu ficaria muito grato!


text:
Q: SQL, PHP, Prepared Statement I am trying to use a prepared statement to populate my table from PHP.
No errors are being thrown however, the data is not entering the table. Here is my code:
$stmt = $mysqli->prepare("INSERT INTO Parks VALUES (null,?,?,?,?,?,?,?,?,?,?,?,?,?,Now(),?,?,?, 0, 0, 0)");
    if ($stmt === FALSE) {
    die ("Mysql Error: " . $mysqli->error);
    }
    $stmt->bind_param('ssssssssssssssss', $name, $theme, $size, $mountains, $hills, $river, $lake, $island, $setofislands, $ocean, $waterfalls, $file, $image, $description, $author,$cs);

    $stmt->execute();
    $stmt->close();
    $mysqli->close();

Thanks in advance.
Data Types:

*

*ID (Int(autoincrement))

*Name (varchar(255))

*Theme (varchar(255))

*Size (varchar(255))

*Mountains (varchar(255))

*Hills (varchar(255))

*Rivers (varchar(255))

*Lake (varchar(255))

*Island (varchar(255))

*Setofislands (varchar(255))

*Ocean (varchar(255))

*Waterfall (varchar(255))

*File (varchar(255))

*Image (varchar(255))

*DateUploaded (date)

*Description(varchar(255))

*Author (varchar(255))

*CS(varchar(2000))

*Download(int(255))

*Rating(double)

*FileSize(BigInt(20)

(total 21)
Note: I have tried prepared statements on a test database, which just had one column and that worked...

A: After a series of trial and error I was able to resolve the issue.
It seemed that:
$stmt->bind_param('ssssssssssssssssi', etc
$stmt->exceute();

Was needed and that listing out the column names:
Insert into Parks (name, description) Values (?, ?)

were the changes needed to make it work.
To confirm, it now all works, thanks for everyones support on this! :)


text:
Q: mysql 5.6 replication log-slave-updates doesn't work We have a setup of master -> replication -> replication
the dbs are: mysql 5.7 -> 5.6 -> 5.7
on the replication 5.6 we have the following my.cnf:
[mysqld]
default-storage-engine=InnoDB
innodb_file_per_table=1
performance-schema=0

max_connections=4096
group_concat_max_len=8196
innodb_flush_log_at_trx_commit=0
query_cache_limit=128M
query_cache_size=128M
max_allowed_packet=268435456
open_files_limit=29000
#log_timestamps = SYSTEM

slow-query-log=1
#log = /var/log/mysql_query.log

server-id               = 2

log-bin

replicate-do-db = db_main
log-slave-updates

slave-skip-errors = all

however the bin-log on the server is not being updated. The relay-log IS being update. server-id on the master 5.7 is 1 and on the last 5.7 slave is 3.
all servers have log-slave-updates and upon checking with mysqladmin var|grep update we see log_slave_updates ON.
What are we missing?
Thanks!

A: First, you might want to explicitly set those options to on and restart the instance (enabling binary logging requires restart)
log_slave_updates=ON
log_bin=mysql-binlog
Second, you are not supposed to replicate from a master which is at a higher version to a slave at a lower version because of incompatible changes in binary log formats across versions: https://dev.mysql.com/doc/refman/5.7/en/replication-compatibility.html


text:
Q: List all recently changed files (recursive) So, I want to display (via ls for example) all files, which were changed in the last seven days. If I'm in my docroot-folder, it should be able to look "deeper".
For example:
File        Last changed
docroot
|- myfile1  30.11.2015
|- myfile2  10.11.2015
|- MySub
   |-sub1   30.11.2015
   |-sub2   10.11.2015

So, the ls (or whatever fits) should output myfile1 and (if possible)
MySub/sub1.
Is this doable with one command?

A: With zsh:
ls -l **/*(.m-7)

*

***/* will look for files recursively starting from current directory

*(.m-7) is glob qualifier where . indicates regular file, m-7 indicates files that were modified within last 7 days

A: Of course. From the directory you are in do:
find . -type f -mtime -7 -exec ls -l {} \;

Add a redirection to it (aka > results.txt to store them into that file).

*

*type f does only files and not directories

*mtime -7 does 7 days ago up to now (+7 would be 'older than 7 days')

*and it then feeds it to ls to show a long list

You can play with the ls -l part too:
find . -type f -mtime -7 -exec ls -Rl --time-style=long-iso {} \;
find . -type f -mtime -7 -exec ls -R  --time-style=long-iso {} \;

will show a tree like method with directories in between the files in long list (1) or short list (2).

A: The following command works a dream on Mac OSX - maybe also on ubuntu …
find . -type f -mtime -7 -exec stat -lt "%Y-%m-%d %H:%M:%S" {} \; | cut -d\  -f6- | sort -r

This finds files in the current directory tree which have been modified in the last 7 days, outputs the modification date + time and path, sorted newest first.
Example output:
2018-02-21 22:06:30 ./fmxmlsnippet.xml
2018-02-19 12:56:01 ./diff.html
2018-02-19 12:44:37 ./temp/iDDR/XMSC_fmxmlsnippet.xml
2018-02-18 22:04:05 ./temp/iDDR/XMFD_fmxmlsnippet.xml
2018-02-15 10:18:27 ./xml/iDDR/XML2_fmxmlsnippet.xml
2018-02-15 10:13:29 ./xsl/fmxmlsnippet/XML2_fmCM_AnalyseLayout.xsl
2018-02-15 10:11:36 ./xsl/.DS_Store
2018-02-15 10:10:51 ./xsl/_inc/inc.XML2_fmCM_ReportReferencesToExternalFiles.xsl
2018-02-15 10:10:09 ./xsl/_inc/.DS_Store
2018-02-15 10:07:35 ./xsl/fmxmlsnippet/XML2_fmCM_AnalyseLayout-NoAnchors.xsl
2018-02-15 10:07:35 ./xsl/_inc/inc.XML2_fmCM_AnalyseLayout.xsl

I'd be grateful of any feedback from ubuntu users.

A: Not exactly what was asked for... but much easier to remember...
ls -alRt docroot

or
ls -alRt /path/to/top/level/directory

A: 7 days that's 60 seconds*60minutes*24hours*7days
 = 604800 seconds
Find out current date in seconds (Unix epoch time):
$ date +%s
1448876323

Subtract the 7 days in seconds:
expr $(date +%s) - 604800
1448271548

Now take stat command and print stats for all files in format "name + time in seconds" and use awk to crop off those files whose modification time is greater that that date we calculated
$ stat --printf="%n %Y\n" $HOME/* | awk '$2 > 1448271265 {print $0}'
/home/xieerqi/1448428697574.png 1448429613
/home/xieerqi/1448763343273.png 1448763478
/home/xieerqi/1510DRIVE 1448352453
/home/xieerqi/addRemoveDistribution 1448666843
/home/xieerqi/add-update.awk 1448716356
/home/xieerqi/add-update.sh 1448625092

Particularly of interest are last 3 files, because I know I was working them on less that 7 days ago. Thus I know it works


text:
Q: MS SQL Update one table from another table with multiple masterid and different childid I am looking for a best approach to update 1 table from another table which has common multiple id's.
Below is the Scenario
Table1:
+----------+---------+
| masterid | childid |
+----------+---------+
| 1        | NULL    |
+----------+---------+
| 1        | NULL    |
+----------+---------+
| 1        | NULL    |
+----------+---------+
| 2        | NULL    |
+----------+---------+
| 2        | NULL    |
+----------+---------+
| 1        | NULL    |
+----------+---------+

Table2:
+----------+---------+
| masterid | childid |
+----------+---------+
| 1        | 2       |
+----------+---------+
| 1        | 3       |
+----------+---------+
| 1        | 4       |
+----------+---------+
| 2        | 9       |
+----------+---------+
| 2        | 8       |
+----------+---------+
| 1        | 5       |
+----------+---------+

I wish to update table1 comparing the masterid of table2 and corresponding childid should be be updated.
Solution1: Using ROW_NUMBER()
;
WITH cte
AS (SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) rn
FROM @t1),
cte1
AS (SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) rn
FROM @t2)

UPDATE t1
SET t1.childid = t2.childid
FROM cte AS t1
INNER JOIN cte1 AS t2
  ON t2.masterid = t1.masterid
  AND t2.rn = t1.rn

DEMO
How this can be achieved in different ways?

A: Sample Data
DECLARE @TAble1 AS TABLE (masterid INT , childid INT)
INSERT INTO @Table1
SELECT 1 , NULL UNION ALL
SELECT 1 , NULL UNION ALL
SELECT 1 , NULL UNION ALL
SELECT 2 , NULL UNION ALL
SELECT 2 , NULL UNION ALL
SELECT 1 , NULL

DECLARE @TAble2 AS TABLE (masterid INT , childid INT)
INSERT INTO @TAble2
SELECT  1, 2UNION ALL
SELECT  1, 3UNION ALL
SELECT  1, 4UNION ALL
SELECT  2, 9UNION ALL
SELECT  2, 8UNION ALL
SELECT  1, 5

This Update State is enough to update table Table1 No Need to use Any window function
SELECT * FROM @TAble1

UPDATE T1
SET T1.childid = T2.childid
FROM @TAble1 T1
INNER JOIN @TAble2 T2
ON T1.masterid = T2.masterid

SELECT * FROM @TAble1

Result Before Update
masterid    childid
1           NULL
1           NULL
1           NULL
2           NULL
2           NULL
1           NULL

Result After Update
masterid    childid
1            2
1            2
1            2
2            9
2            9
1            2


text:
Q: How to run the Metacircular Evaluator in DrRacket I'm trying to run the program described in SICP 4.1 (http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-26.html) but have run into some difficulty in redefining the function apply as the book suggests that you do.  The code is the following:
 #lang planet neil/sicp

;; -----------------------------------------------------------------------------
;; 4.1.1 The Core of the Evaluator
;; -----------------------------------------------------------------------------

;; Eval
(define apply-in-underlying-scheme apply)
(define (eval exp env)
  (display 'eval)
  (newline)
  (display exp)
  (newline)
  (cond ((self-evaluating? exp) exp)
        ((variable? exp) (let ((res (lookup-variable-value exp env)))
                           (display (list 'lookup exp))
                           (newline)
                           (display res)
                           (newline)
                           res))
        ((quoted? exp) (text-of-quotation exp))
        ((assignment? exp) (eval-assignment exp env))
        ((definition? exp) (eval-definition exp env))
        ((if? exp) (eval-if exp env))
        ((lambda? exp)
         (make-procedure (lambda-parameters exp)
                         (lambda-body exp)
                         env))
        ((begin? exp)
         (eval-sequence (begin-actions exp) env))
        ((cond? exp) (eval (cond->if exp) env))
        ((application? exp)
         (apply (eval (operator exp) env)
                (list-of-values (operands exp) env)))
        (else
         (error "Unknown expression" exp))))

;; Apply

(define (apply procedure arguments)
  (display 'apply)
  (newline)
  (display procedure)
  (newline)
  (cond ((primitive-procedure? procedure)
         (apply-primitive-procedure procedure arguments))
        ((compound-procedure? procedure)
         (eval-sequence
          (procedure-body procedure)
          (extend-environment
           (procedure-parameters procedure)
           arguments
           (procedure-environment procedure))))
         (else
          (error
           "Unknown procedure type -- " procedure))))

;; Application

(define (application? exp) (pair? exp))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))

;; Procedure arguments

(define (list-of-values exps env)
  (if (no-operands? exps)
      '()
      (cons (eval (first-operand exps) env)
            (list-of-values (rest-operands exps) env))))

(define (no-operands? ops) (null? ops))
(define (first-operand ops) (car ops))
(define (rest-operands ops) (cdr ops))

;; Conditionals

(define (eval-if exp env)
  (if (true? (eval (if-predicate exp) env))
      (eval (if-consequent exp) env)
      (eval (if-alternative exp) env)))

;; Sequences

(define (eval-sequence exps env)
  (cond ((last-exp? exps) (eval (first-exp exps) env))
        (else (eval (first-exp exps) env)
              (eval-sequence (rest-exps exps) env))))

;; Assignments and definitions

(define (eval-assignment exp env)
  (set-variable-value! (assignment-variable exp)
                       (eval (assignment-value exp) env)
                       env)
  'ok)

(define (eval-definition exp env)
  (define-variable! (definition-variable exp)
                    (eval (definition-value exp) env)
                    env)
  'ok)

;; Representing Expressions

;; self evaluating := items, numbers

(define (self-evaluating? exp)
  (cond ((number? exp) true)
        ((string? exp) true)
        (else false)))

;; variables = symbol

(define (variable? exp) (symbol? exp))

;; (quote <text-of-quotation>)

(define (quoted? exp) (tagged-list? exp 'quote))

(define (text-of-quotation exp) (cadr exp))

(define (tagged-list? exp tag)
  (if (pair? exp)
      (eq? (car exp) tag)
      false))

;; (set! <var> <value>)

(define (assignment? exp)
  (tagged-list? exp 'set!))

(define (assignment-variable exp) (cadr exp))
(define (assignment-value exp) (caddr exp))

;; (define <var> <value>)
;; or
;; (define <var>
;;   (lambda (<parameter-1> ... <parameter-n>)
;;      <body>))
;; or
;; (define (<var> <parameter-1> ... <parameter-n>)
;;    <body>)

(define (definition? exp)
  (tagged-list? exp 'define))

(define (definition-variable exp)
  (if (symbol? (cadr exp))
      (cadr exp)
      (caadr exp)))

(define (definition-value exp)
  (if (symbol? (cadr exp))
      (caddr exp)
      (make-lambda (cdadr exp)   ;; formal params
                   (cddr exp)))) ;; body

;; lambda

(define (lambda? exp) (tagged-list? exp 'lambda))

(define (lambda-parameters exp) (cadr exp))
(define (lambda-body exp) (cddr exp))

;; constructor for lambda expression

(define (make-lambda parameters body)
  (cons 'lambda (cons parameters body)))

;; if

(define (if? exp) (tagged-list? exp 'if))
(define (if-predicate exp) (cadr exp))
(define (if-consequent exp) (caddr exp))
(define (if-alternative exp)
  (if (not (null? (caddr exp)))
      (cadddr exp)
      'false))

;; constructor to transform cond expressions to if expressions

(define (make-if predicate consequent alternative)
  (list 'if predicate consequent alternative))

;; begin

(define (begin? exp) (tagged-list? exp 'begin))
(define (begin-actions exp) (cdr exp))
(define (last-exp? seq) (null? (cdr seq)))
(define (first-exp seq) (car seq))
(define (rest-exps seq) (cdr seq))

;; sequence->exp

(define (sequence->exp seq)
  (cond ((null? seq) seq)
        ((last-exp? seq) (first-exp seq))
        (else (make-begin seq))))

(define (make-begin seq) (cons 'begin seq))

;; derived expressions

(define (cond? exp) (tagged-list? exp 'cond))

(define (cond-clauses exp) (cdr exp))

(define (cond-else-clause? clause)
  (eq? (cond-predicate clause) 'else))

(define (cond-predicate clause) (car clause))
(define (cond-actions clause) (cdr clause))

(define (cond->if exp)
  (expand-clauses (cond-clauses exp)))

(define (expand-clauses clauses)
  (if (null? clauses)
      'false
      (let ((first (car clauses))
            (rest (cdr clauses)))
        (if (cond-else-clause? first)
            (if (null? rest)
                (sequence->exp (cond-actions first))
                (error "ELSE clause isn't last -- COND->IF"
                       clauses))
            (make-if (cond-predicate first)
                     (sequence->exp (cond-actions first))
                     (expand-clauses rest))))))

;; Representing procedures

;; (apply-primitive-procedure <proc> <args>)
;; (primitive-procedure? <proc>)

(define (make-procedure parameters body env)
  (list 'procedure parameters body env))

(define (compound-procedure? p)
  (tagged-list? p 'procedure))

(define (procedure-parameters p) (cadr p))
(define (procedure-body p) (caddr p))
(define (procedure-environment p) (cadddr p))

;; Operations on Environments

;; env is nothing but a list of frames.
(define the-empty-environment '())

(define (enclosing-environment env) (cdr env))
(define (first-frame env) (car env))

;; each frames contains variables and values
(define (make-frame variables values)
  (cons variables values))

(define (frame-variables frame) (car frame))
(define (frame-values frame) (cdr frame))

(define (add-binding-to-frame! var val frame)
  (set-car! frame (cons var (car frame)))
  (set-cdr! frame (cons val (cdr frame))))

;; (extend-environment <variables> <values> <base-env>)

(define (extend-environment vars vals base-env)
  (if (= (length vars) (length vals))
      (cons (make-frame vars vals) base-env)
      (if (< (length vars) (length vals))
          (error "Too many arguments supplied" vars vals)
          (error "Too few arguments supplied" vars vals))))

;; (lookup-variable-value <var> <env>)

(define (lookup-variable-value var env)
  (define (env-loop env)
    (define (scan vars vals)
      (cond ((null? vars)
             (env-loop (enclosing-environment env)))
            ((eq? var (car vars))
             (car vals))
            (else (scan (cdr vars) (cdr vals)))))
    (if (eq? env the-empty-environment)
        (error "Unbound variable" var)
        (let ((frame (first-frame env)))
          (scan (frame-variables frame)
                (frame-values frame)))))
    (env-loop env))

;; (set-variable-value! <var> <value> <env>)

(define (set-variable-value! var val env)
  (define (env-loop env)
    (define (scan vars vals)
      (cond ((null? vars)
             (env-loop (enclosing-environment env)))
            ((eq? var (car vars))
             (set-car! vals val))
            (else (scan (cdr vars) (cdr vals)))))
    (if (eq? env the-empty-environment)
        (error "Unbound variable -- SET!" var)
        (let ((frame (first-frame env)))
          (scan (frame-variables frame)
                (frame-values frame)))))
  (env-loop env))

;; (define-variable! <var> <value> <env>)

(define (define-variable! var val env)
  (let ((frame (first-frame env)))
    (define (scan vars vals)
      (cond ((null? vars)
             (add-binding-to-frame! var val frame))
            ((eq? var (car vars))
             (set-car! vals val))
            (else (scan (cdr vars) (cdr vals)))))
    (scan (frame-variables frame)
          (frame-values frame))))

(define (true? x)
  (not (eq? x false)))

(define (false? x)
  (eq? x false))

;; -----------------------------------------------------------------------------
;; 4.1.4 - Running the Evaluator as a Program
;; -----------------------------------------------------------------------------

(define (primitive-procedure? proc)
  (tagged-list? proc 'primitive))

(define (primitive-implementation proc) (cadr proc))

(define primitive-procedures
  (list (list 'car car)
        (list 'cdr cdr)
        (list 'cons cons)
        (list 'null? null?)
        ))

(define (primitive-procedure-names)
  (map car
       primitive-procedures))

(define (primitive-procedure-objects)
  (map (lambda (proc) (list 'primitive (cadr proc)))
       primitive-procedures))

(define (apply-primitive-procedure proc args)
  (apply-in-underlying-scheme
   (primitive-implementation proc) args))

(define (setup-environment)
  (let ((initial-env
         (extend-environment (primitive-procedure-names)
                             (primitive-procedure-objects)
                             the-empty-environment)))
    (define-variable! 'true true initial-env)
    (define-variable! 'false false initial-env)
    initial-env))

;; for scheme, uncomment for lisp
;;(define true #t)
;;(define false #f)

(define input-prompt " mscheme > ")
(define output-prompt " .. ")

(define (driver-loop)
  (prompt-for-input input-prompt)
  (let ((input (read)))
    (let ((output (eval input the-global-environment)))
      (announce-output output-prompt)
      (user-print output)))
  (driver-loop))

(define (prompt-for-input string)
  (newline) (newline) (display string) (newline))

(define (announce-output string)
  (newline) (display string) (newline))

(define (user-print object)
  (if (compound-procedure? object)
      (display (list 'compound-procedure
                     (procedure-parameters object)
                     (procedure-body object)
                     '<procedure-env>))
      (display object)))

;; start repl
(define the-global-environment (setup-environment))
(driver-loop)

The problem is the beginning, where I am trying to save the scheme builtin apply as "apply-in-underlying-scheme."  Since there is another function named "apply" written below, I get the error "reference to an identifier before its definition: apply."  How can I reference the builtin "apply" without causing an error here?

A: You could just rename the function that SICP calls apply to metacircular-apply or something like that. There's no need for it to be called apply other than aesthetics.

A: I use the following header, which renames apply to apply-in-underlying-scheme:
#!r6rs
(import (except (rnrs base) apply)
        (rnrs io simple)
        (rename (rnrs base) (apply apply-in-underlying-scheme))
        (rnrs mutable-pairs))

A: While you can't redefine a definition in the Racket language #lang racket or similar, you can use the require feature of Racket's module system.
(require (only-in racket [apply apply-in-underlying-scheme]))

Here only-in means that only the bindings we specify will be loaded, here being apply from the built-in module racket.
We could also use rename-in instead of only-in, but since the racket module is always loaded as part of the racket language, we don't need to re-import all of it and thus just use only-in.


text:
Q: Link two websites with the onclick property? I have a login page and a content page. Pressing the login button will open the content page in a new tab but I want it to open in the same tab. Tried window.location.href but it doesn't work for some reason.

function validate() {
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;
  if (username == "marin" && password == "12345678") {
    window.open("file:///C:/Users/lukam/OneDrive/Radna%20povr%C5%A1ina/stranica/stranica1_1.html")
    return false;
  } else {
    alert("login je pogresan")
  }
}

  Username
  <input type="text" name="Username" id="username">

  Password
  <input type="password" name="password" id="password">

<button type="submit" class="btn-submit" onclick="validate()">Login</button>


text:
Q: Select columns from nth row out all the rows which contains a value in a column in a SQL table Below is my table in a database.
What is the SQL query I should run to get 'name' & 'plot_summary' values from the 2nd row of all the rows which contain 'Drama' in 'movie_category' column?

Note - I have not populated the table completely yet and this is for reference. This table will contain many different rows having different 'movie_category' values and the 'n'th or'i'th row number required will be passed through a parameter in the query.

A: You can try this:
Select name,plot_summary from TableName where movie_category='Drama'
You just have to change TableName by your real table name and it will run.
I don't understand why you want the row number.
is it good?


text:
Q: MySQL fails to start with one config line change - innodb_buffer_pool_size = 1G My curent config works great but my innodb_buffer_pool_size is too small as the database is very large.
All I am changing in my MySQL.cnf is
innodb_buffer_pool_size = 1G

to
innodb_buffer_pool_size = 2G

I then try and restart MySQL and it errors with the following..
110715  8:44:48  InnoDB: Error: cannot allocate 2147500032 bytes of
InnoDB: memory with malloc! Total allocated memory
InnoDB: by InnoDB 25166072 bytes. Operating system errno: 12
InnoDB: Check if you should increase the swap file or
InnoDB: ulimits of your operating system.
InnoDB: On FreeBSD check you have compiled the OS with
InnoDB: a big enough maximum process size.
InnoDB: Note that in most 32-bit computers the process
InnoDB: memory space is limited to 2 GB or 4 GB.
InnoDB: We keep retrying the allocation for 60 seconds...

This is a 4GB x86 machine dedicated to MySQL!

A: I had the same problem with 32 bit version of MySQL on a windows server 2008 VM 64 bit with 4G Ram. I tried increasing system ram to 6G and still could not allocate over 1G for innoDB.
Since I was already on 64 bit OS, I tried the 64 bit installer for MySQL and had no issues at all allocating 2G on my 4G system.

A: I'm going with x86_32 (given the error message), and hence you're out of luck -- even with PAE, the maximum process size is still limited by the 4GB address space.  Get yourself a 64-bit system and be done with it.


text:
Q: Font awesome icons not showing in Wordpress after site address URL change This may be an obvious question for those of you more advanced in coding than myself...but I created a website in WordPress but their domain is hosted elsewhere.  They changed the A name and it now points to the site, but the font awesome icons are now square boxes.  How can I fix this? Is there a simple way?
Many thanks for any help/guidance.
Alison

A: Super late, but hopefully this saves someone a lot of time. After migrating an existing Wordpress site to a new domain, I too encountered icons missing (both on the front-end and the back-end administration). After a long search and applying different methods, I found the database still listed the original/old domain within the "option" table.
Using phpMyAdmin, select the "option" table. Within "option" you will see the "site" and "home" rows. If the value has the old domains, you will need to change it to match the sites URLs (Located on the Administration dashboard under Settings > WordPress Address (URL) & Site Address (URL). To change the value, click Edit > and update the URL.

A: Fix the problem in less then 2 mins. Simple replacement of /font-awesome/5.13.0/css/fontawesome.min.css with /font-awesome/5.13.0/css/all.min.css and also font-awesome/5.13.0/js/fontawesome.min.js with /font-awesome/5.13.0/js/all.min.js can fix this issue. https://youtu.be/_GV_pEmLCLU

A: I know this is 2 years old, but I just ran into a similar problem and the answer given by Owais did not feel right to me (getting CSS from another site).
This happened to me for the exact same reason as it did for OP. I migrated my website to another host and another domain-name. After doing that I ran a rename-script for the DB (thousants of hard-coded URLs were replaced).
However, as it turns out, my theme was also using hard-coded URLs in the CSS files and in some JS files, as they were generated (upload/fusion-scripts and upload/fusion-styles). After replacing the hardcoded URLs in these files (I used visual studio, but you can use any bulk-replace tool) everything worked fine again.

A: Just another idea to throw in here - after transferring the site to the new server, and running this handy script to replace all references of the old url with the new one, I was still having the same issue with font awesome.  The solution was to go to Settings / General and set the Endurance Cache to Off (0).  Refreshed the site and all was well.

A: In my case, I had that problem changing the url using the constants WP_HOME WP_SITEURL at wp-config.php
When I changed through the wp-admin using the RELOCATE flag, worked
As you may know, this is the official doc about it

A: I had this problem so many times but this time I found the full proof solution for this issue:
Open PhpMyAdmin and then click on wp_options table.
In this, you will see a table with a name(according to your theme name) something like "theme_options_css" edit it and change the URL from old to new.
The problem might occur due to Http to Https migration also. So for that also change Http to Https manually in the same table and the problem will be resolved the moment you save your table.