text:
Q: How do I print a list of strings contained within another list in iReport? I am creating a simple reporting program using java and iReport (from jasper), which is supposed to create a report in pdf showing PCs with their IP address, their location, whether it's idle or not at the moment (handled by another system), and a list of projects it is currently attached to (managed elsewhere, too).
I'm using iReport for this matter, and have created a dummy collection generating class as follows:
public class PCReports {

    public static java.util.Collection PC_collection;
    public static java.util.Collection generateCollection() {

        PC_collection = new ArrayList<PCLineDTO>();
        PCLineDTO line = new PCLineDTO();
        line.setIP("192.168.1.1");
        line.setLab("location");
        line.setActive(true);
        line.addProjectName("project1");
        line.addProjectName("project2");
        line.addProjectName("project3");
        PC_collection.add(line);

        line = new PCLineDTO();
        line.setIp("192.168.1.2");
        line.setLab("location2");
        line.setActive(false);
        line.addProjectName("project1");
        line.addProjectName("project2");
        PC_collection.add(line);

        return PC_collection;
    }
}

The entity class in this case being:
public class PCLineDTO {
    private String ip;
    private String lab;
    private Boolean active;
    private ArrayList<String> projects;
}

After some searching around the Internet, I found a way to do something similar, using subreports.
The thing is, I don't know how to print a collection of strings passed as a dataSource to this subreport.
In the examples I found on the Internet, for each item in the master collection, the subreports were passed a collection of objects -with their own getter methods for each attribute- instead of a collection of strings as is the case here. In those cases, they accessed the values they needed to use via the iReport syntax, which I was not able to use, for example:
$F{project}

Since iReport looks for a getProject method contained within the objects it receives, but in this case it's a simple String object (without a getProject method, as it were).

A: Interesting. I think you'd better use the List, and then define getName() on the Project class. Then in the subreport define a variable "name". It will work this way, and it will allow you to add easily additional information, like project duration, team-lead, etc.

A: Use a subreport or a subdataset.
Pass the subreport a collection datasource
JRBeanCollectionDataSource($F{Projects})

Then in the new subreport create a new field called "_THIS" exactly, this means the bean in the collection passed is the same as the value i want
For more info, check the source code of the class here: JRAbstractBeanDataSource
Note: this is available in JasperReport 3.0.0 im not sure if it exists in previous builds.
Hope this helps
Update: just checked the SVN, seems like this feature is implemented in JasperReports 2.0.0

A: As Bozho says, in case proyects was an array of complex object you should reference it as a field of type java.util.Collection an then pass it to the inner subreport the same way medopal indicates. And don´t put the _THIS field.

A: To elaborate on this without using _THIS: let's say a java bean has a list of subBeans and this subBean has a complex format and we want to print each subBean in a custom way. I quote an example where the subDataset element is on the report level and the componentElement is in the detail band:
<subDataset name="ListOfSubBeans" uuid="66c86e41-c565-4f18-bccf-1a1b2a567585">
    <field name="subBeanField_1" class="java.lang.String">
        <fieldDescription><![CDATA[subBeanField_1]]></fieldDescription>
    </field>
</subDataset>

...

        <componentElement>
            <reportElement x="780" y="0" width="100" height="30" uuid="f73864b9-46dd-4adb-8dad-a6bd8dfae64e">
                <property name="net.sf.jasperreports.export.headertoolbar.table.name" value=""/>
            </reportElement>
            <jr:list xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd" printOrder="Vertical">
                <datasetRun subDataset="ListOfSubBeans" uuid="a8dd1c2b-3ac0-4ffa-b9d0-08e4890e199a">
                    <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{listOfSubBeans})]]></dataSourceExpression>
                </datasetRun>
                <jr:listContents height="30" width="100">
                    <textField>
                        <reportElement x="0" y="0" width="100" height="30" uuid="61700c18-6bb9-45da-a235-b76b9f76a2ea"/>
                        <textFieldExpression><![CDATA[$F{subBeanField_1}]]></textFieldExpression>
                    </textField>
                </jr:listContents>
            </jr:list>
        </componentElement>

...

So, the master dataset has declared that the master bean has a member variable that is a list: listOfSubBeans. This java.util.List is used to feed the datasource of the jr:list, while the fields of the jr:list are declared using a subDataset called ListOfSubBeans (pay attention to case sensitivity).


text:
Q: Determining field lines of three-dimensional vector fields This has been a long time for me and my analysis reference is pretty abstract.

Could anybody show me again how to calculate the vector field lines
  for $F(x)=(y-z, z-x, x-y)$?

I know I have to make the differential equation and that the solution will be circles (when I plot it), but I forgot exactly which equation to make. I will be able to solve it of course, just reminding me the equation to solve is enough.

A: You want curves such that the vector field is tangent to the curve at any point. In other words, you want functions $\gamma:\Bbb R\to \Bbb R^3$ such that $\gamma'(t) = F(\gamma(t))$. Separating out the three component functions of $\gamma$, this is a system of homogenous, linear, first order differential equations with constant coefficients. Which is to say, we may write it using matrix multiplication in the following form:
$$
\gamma'(t) = \begin{bmatrix}0&1&-1\\-1&0&1\\1&-1&0\end{bmatrix}\gamma(t)
$$
Systems like this will have solutions of the form $e^{\lambda t}v$, where $\lambda$ is an eigenvalue of the above matrix, and $v$ is a corresponding eigenvector. And of course, any linear combination of such solutions is also a solution.
So we solve for the eigenvectors and eigenvalues of the above matrix. They turn out to be
$$
\begin{array}{|c|c|}
\hline\text{Eigenvalue}& \text{Eigenvector}\\
\hline 0 & (1, 1, 1)^T\\
i\sqrt3 & (1-i\sqrt3, 1+i\sqrt3, -2)^T\\
-i\sqrt3 & (1+i\sqrt3, 1-\sqrt3, -2)^T\\
\hline
\end{array}
$$
A keen eye will spot that an eigenvalue of $0$ means the corresponding eigenvector doesn't change as time goes by (in other words, that's the axis of rotation), while a conjugate pair of pure imaginary eigenvalues corresponds to pure rotation.
If you pick any vector $u\in \Bbb R^3$, and decompose it into a linear combination $a\cdot u_1 + b\cdot u_2 + c\cdot u_3$ of these three eigenvectors, then the field line that goes through $u$ will be given by
$$
a\cdot u_1 + b\cdot e^{i\sqrt3t}u_2 + c\cdot e^{-i\sqrt3t}u_3
$$
One can, of course, get rid of any and all mention of complex numbers here by replacing it with trigonometry, but I don't think that it makes the solution any nicer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why will numpy.round will not round my array? I am trying to round a numpy array that is outputted by the result of a Keras model prediction. However after executing numpy.round/numpy.around, there is no change.
The end goal here is for the array to get rounded down to 0 if below/equal 0.50 or rounded up if above 0.50.
The code is here:
from keras.models import load_model

import numpy

model = load_model('tried.h5')
data = numpy.loadtxt("AppData\Roaming\MetaQuotes\Terminal\94DDB309C90B408373EFC53AC730F336\MQL4\Files\indicatorout.csv", delimiter=",")
data = numpy.array([data])
print(data)
outdata = model.predict(data)
print(outdata)
numpy.around(outdata, 0)
print(outdata)
numpy.savetxt("AppData\Roaming\MetaQuotes\Terminal\94DDB309C90B408373EFC53AC730F336\MQL4\Files\modelout.txt", outdata)

The logs are also here:
Using TensorFlow backend.
[[1.19539070e+01 1.72686310e+01 2.24426384e+01 1.82771435e+01
  2.23788052e+01 1.62105408e+01 1.44595184e+01 1.90179043e+01
  1.71749554e+01 1.69194088e+01 1.89911938e+01 1.76701393e+01
  5.19613740e-01 5.38522415e+01 9.64037247e+01 1.73570000e-04
  4.35710000e-04 9.55710000e-04]]
[[0.4215713]]
[[0.4215713]]

Any help would be greatly appreciated, thank you.

A: I assume that you want the elements in the array to round to some n decimal places. Below is an illustration for doing so:
# sample array to work with
In [21]: arr = np.random.randn(4)

In [22]: arr
Out[22]: array([-0.94817409, -1.61453252,  0.16566428, -0.53507549])

# round to 3 decimal places; note that `arr` is still unaffected.
In [23]: arr.round(decimals=3)
Out[23]: array([-0.948, -1.615,  0.166, -0.535])

# if you want to round it to nearest integer
In [24]: arr_rint = np.rint(arr)

In [25]: arr_rint
Out[25]: array([-1., -2.,  0., -1.])

To make the decimal rounding to work in-place, specify the out= argument as in:
In [26]: arr.round(decimals=3, out=arr)
Out[26]: array([-0.948, -1.615,  0.166, -0.535])


text:
Q: Watson Conversation: Check and act on existence of context variable? I am using IBM Watson Conversation service and slots within a dialog node. In the response I want to return the value of a context variable that is gathered with a slot. However, I cannot be sure that the variable exists because the user could have cancelled the input process and because the variable is optional. How can I check the existence and act depending on that check?
Using this
<? $myVariable ?>

gives an error when the variable is not present.

A: The Conversation service uses Spring Expression Language (SpEL) to process variables and conditions in its responses. There is a special check that can be applied. I have taken the example from this useful collection of use cases:
"<? context.myVariable? 'Great. I have the following: '+context.myVariable+'.' :
'No information present' ?>"

You can access context variables via context followed by the variable name. The question mark (?) checks for existence. The first response is taken in the case the variable is present, else the second response. The colon (:) separates the two answer options.
In the above example is the answer is either "Great. I have the following: VALUE" or "No information present".


text:
Q: Submitting form gives MethodNotAllowedHttpException error I have a moderation queue as part of an application I'm building. Users can submit questionnaire's but they need to be moderated by an admin.
I've built the functionality for the queue and can load the answers they submit on to a page, but I'm having trouble implementing an approve/reject button.
I'm wanting the page to display their answers, which it does, and then down the bottom have a button to approve and then a button to reject (with a textbox for the reason).
When either button is clicked, I'm trying to update the table appropriately - however I'm just getting an error MethodNotAllowedHttpException in RouteCollection.php line 201:.
I don't understand why as I built the user administration function in a similar way without any trouble.
Can anyone help, or suggest a better way to do what I'm doing:
Routes
Route::resource('/questionnaire', 'QuestionnaireController');

Controller
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator;
use Input;
use Redirect;
use App\Questionnaire;
use App\User;
use DB;

class QuestionnaireController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        return view('questionnaire.index');
    }

    public function moderate()
    {
        $questionnaires = DB::table('users')
                        ->join('questionnaire', 'users.id', '=', 'questionnaire.memberid')
                        ->select('users.username', 'questionnaire.*')
                        ->get();
        return view('questionnaire.moderate', ['questionnaires' => $questionnaires]);
    }

    public function view($id)
    {
        $questionnaire = Questionnaire::find($id);

        return view('questionnaire.view', ['questionnaire' => $questionnaire]);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $questionnaire = new Questionnaire;

        $validator = Validator::make($request->all(), [
            'q1' => 'required|between:128,512',
            'q2' => 'required|between:128,512',
            'q3' => 'required|between:128,512',
            'q4' => 'required|between:128,512',
            'q5' => 'required|between:128,512',
        ], [
            'q1.required' => 'The first answer is empty!',
            'q2.required' => 'The second answer is empty!',
            'q3.required' => 'The third answer is empty!',
            'q4.required' => 'The fourth answer is empty!',
            'q5.required' => 'The fifth answer is empty!',
            'q1.between' => 'The first answer must be between :min - :max characters long.',
            'q2.between' => 'The second answer must be between :min - :max characters long.',
            'q3.between' => 'The third answer must be between :min - :max characters long.',
            'q4.between' => 'The fourth answer must be between :min - :max characters long.',
            'q5.between' => 'The fifth answer must be between :min - :max characters long.',
        ]);

        if ($validator->fails()) {
            return redirect('/questionnaire')
                ->withErrors($validator)
                ->withInput();
        }

        $questionnaire->memberid = $request->memberid;
        $questionnaire->q1 = $request->q1;
        $questionnaire->q2 = $request->q2;
        $questionnaire->q3 = $request->q3;
        $questionnaire->q4 = $request->q4;
        $questionnaire->q5 = $request->q5;

        $questionnaire->save();

        $id = $request->memberid;
        $user = User::find($id);
        $user->confirmed = 1;

        $user->save();

        return redirect('/');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $questionnaire = Questionnaire::find($id);
        return view('questionnaire.show', ['questionnaire' => $questionnaire]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $questionnaire = Questionnaire::find($id);
        return view('questionnaire.edit', ['questionnaire' => $questionnaire]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        $questionnaire = Questionnaire::find($id);
        $button = Input::get('buttonid');

        if ($button == "approve")
        {
            $questionnaire->status = 3;
            $questionnaire->save();
            return redirect('questionnaire/moderate');
        }

        if ($button == "reject")
        {
            $questionnaire->status = 2;
            $questionnaire->rejectreason = Input::get('rejectreason');
            $questionnaire->save();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}

View Which can be found at the URI /questionnaire/{membersid}/edit
@extends('app')

@section('content')

        @if (Auth::guest())
            You need to be logged in to use this page.
        @else

 Review Questionnaire

Question 1:

            {{$questionnaire->q1}}

Question 2:

            {{$questionnaire->q2}}

Question 3:

            {{$questionnaire->q3}}

Question 4:

            {{$questionnaire->q4}}

Question 5:

            {{$questionnaire->q5}}

            {!! Form::model($questionnaire, ['role' => 'form', 'url' => '/questionnaire/' . $questionnaire->memberid . '/edit', 'method' => 'PUT'])!!}
            {!! Form::hidden('memberid', $questionnaire->memberid) !!}
            {!! Form::submit('Approve', ['class' => 'btn btn-success', 'name' => 'buttonid', 'value' => 'approve']) !!}
            {!! Form::submit('Reject', ['class' => 'btn btn-danger', 'name' => 'buttonid', 'id' => 'buttonid', 'value' => 'reject']) !!}
            {!! Form::textarea('rejectreason', null, ['placeholder' => "Reason why you're rejecting... please be specific as the member will read this", 'class' => 'form-control']) !!}
            {!! Form::close() !!}

        @endif

@endsection

When I click either button though, I get the error below:
MethodNotAllowedHttpException in RouteCollection.php line 201:

in RouteCollection.php line 201
at RouteCollection->methodNotAllowed(array('GET', 'HEAD')) in RouteCollection.php line 188
at RouteCollection->getRouteForMethods(object(Request), array('GET', 'HEAD')) in RouteCollection.php line 140
at RouteCollection->match(object(Request)) in Router.php line 746
at Router->findRoute(object(Request)) in Router.php line 655
at Router->dispatchToRoute(object(Request)) in Router.php line 631
at Router->dispatch(object(Request)) in Kernel.php line 236
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 54
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 122
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
at Kernel->handle(object(Request)) in index.php line 54

I viewed other questions, but they seem specific to their set up. Can anyone help with this?

A: You should change your form opener to
{!! Form::model($questionnaire, ['role' => 'form', 'url' => '/questionnaire/' . $questionnaire->memberid, 'method' => 'PUT'])!!}

You are sending the request to /edit which is incorrect. Take a look at the table of routes for resource controllers in the documentation which shows the allowed methods.
Edit: You'll find you will avoid these type of errors if you use the route names for resources instead of manually building the URL.

A: If you are updating a questionnaire, it means it already exists. You don't have to save it but update. And, you have to pass the data, like so:
$questionnaire->update(Request::all());

P.S: that's on top of what Alex said, that was perfect too.


text:
Q: UITableView within a UITableViewCell events missing I've implemented a UITableView containing a custom UITableViewCell that has a UITableView inside, I'm able to bind all my data properly but what I'm missing are the events not being fired inside my inner UITableViews.
Basically:
outer UITableView
----custom cell
---- ---- ----inner UITableView #1
---- ---- ---- ----custom cell with two rows, row#1 with labels
---- ---- ---- ----custom cell with two rows, row#2 with swipe gesture
----custom cell
---- ---- ----inner UITableView #2
---- ---- ---- ----custom cell with two rows, row#1 with labels
---- ---- ---- ----custom cell with two rows, row#2 with swipe gesture
----custom cell
---- ---- ----inner UITableView #3
---- ---- ---- ----custom cell with two rows, row#1 with labels
---- ---- ---- ----custom cell with two rows, row#2 with swipe gesture

etc...
The swipe gesture inside the inner UITableView is not fired, no event is fired actually. I've tried overriding the touch events but they are not hit. I've tried numerous things to no avail including calling the NextResponder touch events.
The view containing the outer UITableView is scrollable, maybe that has something to do with it?
What I want to achieve is that only row #2 gets swiped and not the entire inner UITableView (it works when done from the outer UITableView but it is not the requirement since both rows #1 and #2 swipe) but since the events are not passed down, I can't get it to work.
What am I missing?
This is how I define the inner UITableView inside the outer UITableView custom cell:
public PlanningGwWrapperCell(IntPtr handle) : base(handle)
{
    _playersTable = new PlanningPlayersTableView();
    _playersTableSource = new MvxPlanningGwPlayersTableViewSource(_playersTable);

    _layout = CreateLayout();

    _playersTable.Source = _playersTableSource;
    _playersTable.Delegate = new PlanningGwPlayersTableDelegate();

    ContentView.AddSubview(new UILayoutHost(_layout));

    InitializeBindings();

    _playersTable.ReloadData();
}

The _layout is a LinearLayout (XibFree).
The UITableView is simply this:
class PlanningPlayersTableView : UITableView
{
    public PlanningPlayersTableView()
    {
        PrepareTable();
    }

    void PrepareTable()
    {
        SeparatorStyle = UITableViewCellSeparatorStyle.None;
        RowHeight = Dimens.TableRowHeight;
        ScrollEnabled = false;
        BackgroundColor = Colors.AppBackground;
    }
}

The table source is:
public class MvxPlanningGwPlayersTableViewSource : BaseMvxTableViewSource<PlanningGwPlayersCell>
{
    public MvxPlanningGwPlayersTableViewSource(UITableView tableView)
        : base(tableView)
    {
    }

    public override nint RowsInSection(UITableView tableview, nint section)
    {
        return 1;
    }

    public override nint NumberOfSections(UITableView tableView)
    {
        return 1;
    }

    public override bool CanEditRow(UITableView tableView, NSIndexPath indexPath)
    {
        var source = (MvxPlanningGwPlayersTableViewSource)tableView.Source;
        var itemsSource = (source).ItemsSource;

        if (itemsSource == null) return false;

        var row = ((ObservableCollection<PlanningGWItemsViewModel>)itemsSource)[indexPath.Row];

        return row.CanAdd || row.CanRemove;
    }

    public override void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
    {
        switch (editingStyle)
        {
            case UITableViewCellEditingStyle.None:
                break;
        }
    }

    public override UITableViewCellEditingStyle EditingStyleForRow(UITableView tableView, NSIndexPath indexPath)
    {
        return UITableViewCellEditingStyle.Delete;
    }

    protected override UITableViewCell GetOrCreateCellFor(UITableView tableView, NSIndexPath indexPath, object item)
    {
        return (PlanningGwPlayersCell)tableView.DequeueReusableCell(PlanningGwPlayersCell.Id);
    }
}

So any clues on how to pass down the events? Can the outer table respond only to the scroll event while all other events get handled by the inner table?
UPDATE
Turns out the problem has to do with the following line:
ContentView.AddSubview(new UILayoutHost(_layout));

The UILayoutHost is swallowing the events, if I place the table directly inside as a sub view, the events are kept.

A: Answer was indeed splitting the header row (first row) and swipe row (second row) from the UILayoutHost:
public PlanningGwWrapperCell(IntPtr handle)
        : base(handle)
    {
        ...

        ContentView.AddSubview(new UILayoutHost(_header));
        ContentView.AddSubview(_playersTable);

        InitializeBindings();

        _playersTable.ReloadData();
    }

    public override void LayoutSubviews()
    {
        base.LayoutSubviews();

        _playersTable.Frame = new CGRect(0, Dimens.TableRowHeight, ContentView.Bounds.Width, Dimens.TableRowHeight);
        _header.LayoutParameters = new LayoutParameters(ContentView.Bounds.Width, Dimens.TableRowHeight);
    }


text:
Q: Getting data from JSON Just wondering if anyone knew what I was doing wrong here?
I am trying to get data from an API for bitcoin via php. However, I am getting no results from my php page.
$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";
    $json = file_get_contents($url);
    $json_data = json_decode($json, true);
    echo "ID: ". $json_data["id"];

However I am getting nothing show at all on the php page. If I use the code below, It works and dumps out the entire information. But, I would prefer to obtain the information separately, instead of one big dump.
$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";

$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

var_dump(json_decode($result, true));

Anyone have any ideas why the first code block isn't working? Thanks! Very new to API and Json

A: Using cURL is much better
Updated code (needs error checking)
$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";

$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

$json_data = json_decode($result, true);

foreach ($json_data as $item)
    echo "ID: ". $item["id"];

A: I have printed the result it will produce following output
echo "<pre>";
print_r(json_decode($result, true));

Array
(
    [0] => Array
        (
            [id] => bitcoin
            [name] => Bitcoin
            [symbol] => BTC
            [rank] => 1
            [price_usd] => 3821.37
            [price_btc] => 1.0
            [24h_volume_usd] => 2089880000.0
            [market_cap_usd] => 63298556016.0
            [available_supply] => 16564362.0
            [total_supply] => 16564362.0
            [percent_change_1h] => -1.72
            [percent_change_24h] => -4.57
            [percent_change_7d] => -15.76
            [last_updated] => 1505359771
            [price_eur] => 3214.536444
            [24h_volume_eur] => 1758007056.0
            [market_cap_eur] => 53246745321.0
        )

)

so you can use foreach loop if your api contain multiple
$data=json_decode($result, true);
foreach($data as $key=>$val){
echo $val->id;

}

full code
    <?php
    $url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";

    $ch = curl_init();
    // Disable SSL verification
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // Will return the response, if false it print the response
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Set the url
    curl_setopt($ch, CURLOPT_URL,$url);
    // Execute
    $result=curl_exec($ch);
    // Closing
    curl_close($ch);
    $data=json_decode($result, true));

foreach($data as $key=>$val){
echo $val->id;

}

A: The setting you are looking for is allow_url_fopen.
You have two ways of getting around it without changing php.ini, one of them is to use fsockopen(), and the other is to use cURL.
I recommend using cURL over file_get_contents() anyways, since it was built for this.


text:
Q: Query to return highest value and name from two tables over two columns I'm trying to pull a one row result, (two or more if its a tie) from the following query.  The problem is, its returning three rows, and not just a single row containing the unit_name with the highest total HP, which is a combination of HP and Shields.
The query in english
   Which unit has the most total defense?
The query...
select unit_name, max(hp + shield) as totalHealth
from
(
select unit_name, hp, shield from units
where hp = (select max(hp) from units)
union
select unit_name, hp, shield from units
where shield =(select max(shield) from units)
) d
group by unit_name

the result...
unit_name       totalhealth
Archon          360
Battlecruiser   550
Mothership      700

I would hope the query would just return Mothership and 700,
something like this....
unit_name      totalHealth
Mothership     700

I'm using postgres

A: You need to add hp and shield together to get the total health.  You can then use a ranking function to get the rows with the highest value.  So, assuming that hp and shield are not NULL:
select u.*
from (select u.unit_name, sum(hp + shield) as totalhealth,
             rank() over (order by sum(hp + shield) desc) as seqnum
      from units u
      group by unit_name
     ) u
where seqnum = 1;


text:
Q: Show that $X - Y$ is not uniformly distributed on (a,b) for some aLet X and Y be independent and identically distributed.
Show that $X - Y$ is not uniformly distributed on (a,b) for some  $a<b$.
Let $Z = X - Y$. I know that in order for $Z$ to be uniformly distributed in some interval $(a,b)$ it will be when $a = -b$. And as  X and Y are identically distributed, then they will have the same characteristic function.
I don't really know how to keep going using characteristic functions. I'd appreciate any hint! Thanks.

A: The characteristic function of uniform distribution on $(-a,a)$ is $\frac  1 {2a}\int_{-a}^{a} e^{itx} dx=\frac {\sin (at)} {at}$. Note that this function takes both positive and negative values. However $Ee^{it(X-Y)}=|Ee^{itX}|^{2} \geq 0$. Hence $X-Y$ cannot be uniformly distributed . (I have used your observation the interval on which we have uniform distribution has to be symmetric).


text:
Q: find last index of a string in swift In swift 4 you can use the following method to extract a substring:
let str = "abcdefghci"
let index = str.index(of: "c") ?? str.endIndex
print(str[...index])

This will print abc
But how can I find the index of the last c, to extract a substring from that location ?
UPDATE
@vadian please see the attached image:

A: Use range(of which can search backwards and use lowerBound as end index.
let str = "abcdefghci"
if let range = str.range(of: "c", options: .backwards)  {
    print(str[...range.lowerBound])
}


text:
Q: NPC Follower - how to implement script my goal is to have an NPC follow ThePlayer. I had a functioning NPCFollower script attached to a character with two animations, Idle and Walk.
I'm wondering if anyone knows how I can implement the NPCFollower script with the'SimpleCharacterControl'script which is attached to a character with an animator with multiple animations. I would like to call on two of the animations, walk and idle. I highly appreciate the help!
NPCFollow' script
public class NPCFollow : MonoBehaviour {

public GameObject ThePlayer;
public float TargetDistance;
public float AllowedDistance = 5;
public GameObject TheNPC;
public float FollowSpeed;
public RaycastHit Shot;

void Update () {
    transform.LookAt(ThePlayer.transform);
    if (Physics.Raycast(transform.position,transform.TransformDirection(Vector3.forward),out Shot))
    {
        TargetDistance = Shot.distance;
        if(TargetDistance >= AllowedDistance)
        {
            FollowSpeed = 0.02f;
            TheNPC.GetComponent<Animation>().Play("Walk");
        }

        else
        {
            FollowSpeed = 0;
            TheNPC.GetComponent<Animation>().Play("Idle");
        }
    }
}

}
'SimpleCharacterControl'script
public class SimpleCharacterControl : MonoBehaviour {

private enum ControlMode
{
    Tank,
    Direct
}

[SerializeField] private float m_moveSpeed = 2;
[SerializeField] private float m_turnSpeed = 200;
[SerializeField] private float m_jumpForce = 4;
[SerializeField] private Animator m_animator;
[SerializeField] private Rigidbody m_rigidBody;

[SerializeField] private ControlMode m_controlMode = ControlMode.Direct;

private float m_currentV = 0;
private float m_currentH = 0;

private readonly float m_interpolation = 10;
private readonly float m_walkScale = 0.33f;
private readonly float m_backwardsWalkScale = 0.16f;
private readonly float m_backwardRunScale = 0.66f;

private bool m_wasGrounded;
private Vector3 m_currentDirection = Vector3.zero;

private float m_jumpTimeStamp = 0;
private float m_minJumpInterval = 0.25f;

private bool m_isGrounded;
private List<Collider> m_collisions = new List<Collider>();

private void OnCollisionEnter(Collision collision)
{
    ContactPoint[] contactPoints = collision.contacts;
    for(int i = 0; i < contactPoints.Length; i++)
    {
        if (Vector3.Dot(contactPoints[i].normal, Vector3.up) > 0.5f)
        {
            if (!m_collisions.Contains(collision.collider)) {
                m_collisions.Add(collision.collider);
            }
            m_isGrounded = true;
        }
    }
}

private void OnCollisionStay(Collision collision)
{
    ContactPoint[] contactPoints = collision.contacts;
    bool validSurfaceNormal = false;
    for (int i = 0; i < contactPoints.Length; i++)
    {
        if (Vector3.Dot(contactPoints[i].normal, Vector3.up) > 0.5f)
        {
            validSurfaceNormal = true; break;
        }
    }

    if(validSurfaceNormal)
    {
        m_isGrounded = true;
        if (!m_collisions.Contains(collision.collider))
        {
            m_collisions.Add(collision.collider);
        }
    } else
    {
        if (m_collisions.Contains(collision.collider))
        {
            m_collisions.Remove(collision.collider);
        }
        if (m_collisions.Count == 0) { m_isGrounded = false; }
    }
}

private void OnCollisionExit(Collision collision)
{
    if(m_collisions.Contains(collision.collider))
    {
        m_collisions.Remove(collision.collider);
    }
    if (m_collisions.Count == 0) { m_isGrounded = false; }
}

void Update () {
    m_animator.SetBool("Grounded", m_isGrounded);

    switch(m_controlMode)
    {
        case ControlMode.Direct:
            DirectUpdate();
            break;

        case ControlMode.Tank:
            TankUpdate();
            break;

        default:
            Debug.LogError("Unsupported state");
            break;
    }

    m_wasGrounded = m_isGrounded;
}

private void TankUpdate()
{
    float v = Input.GetAxis("Vertical");
    float h = Input.GetAxis("Horizontal");

    bool walk = Input.GetKey(KeyCode.LeftShift);

    if (v < 0) {
        if (walk) { v *= m_backwardsWalkScale; }
        else { v *= m_backwardRunScale; }
    } else if(walk)
    {
        v *= m_walkScale;
    }

    m_currentV = Mathf.Lerp(m_currentV, v, Time.deltaTime * m_interpolation);
    m_currentH = Mathf.Lerp(m_currentH, h, Time.deltaTime * m_interpolation);

    transform.position += transform.forward * m_currentV * m_moveSpeed * Time.deltaTime;
    transform.Rotate(0, m_currentH * m_turnSpeed * Time.deltaTime, 0);

    m_animator.SetFloat("MoveSpeed", m_currentV);

    JumpingAndLanding();
}

private void DirectUpdate()
{
    float v = Input.GetAxis("Vertical");
    float h = Input.GetAxis("Horizontal");

    Transform camera = Camera.main.transform;

    if (Input.GetKey(KeyCode.LeftShift))
    {
        v *= m_walkScale;
        h *= m_walkScale;
    }

    m_currentV = Mathf.Lerp(m_currentV, v, Time.deltaTime * m_interpolation);
    m_currentH = Mathf.Lerp(m_currentH, h, Time.deltaTime * m_interpolation);

    Vector3 direction = camera.forward * m_currentV + camera.right * m_currentH;

    float directionLength = direction.magnitude;
    direction.y = 0;
    direction = direction.normalized * directionLength;

    if(direction != Vector3.zero)
    {
        m_currentDirection = Vector3.Slerp(m_currentDirection, direction, Time.deltaTime * m_interpolation);

        transform.rotation = Quaternion.LookRotation(m_currentDirection);
        transform.position += m_currentDirection * m_moveSpeed * Time.deltaTime;

        m_animator.SetFloat("MoveSpeed", direction.magnitude);
    }

    JumpingAndLanding();
}

private void JumpingAndLanding()
{
    bool jumpCooldownOver = (Time.time - m_jumpTimeStamp) >= m_minJumpInterval;

    if (jumpCooldownOver && m_isGrounded && Input.GetKey(KeyCode.Space))
    {
        m_jumpTimeStamp = Time.time;
        m_rigidBody.AddForce(Vector3.up * m_jumpForce, ForceMode.Impulse);
    }

    if (!m_wasGrounded && m_isGrounded)
    {
        m_animator.SetTrigger("Land");
    }

    if (!m_isGrounded && m_wasGrounded)
    {
        m_animator.SetTrigger("Jump");
    }
}

}

A: 1) Get a reference to ThePlayer(Any object you want other objects to follow).
2) Find direction of ThePlayer.
3) In update check for DistanceFromTarget
if (DistanceFromTarget <= distanceUwant)
{
  setMovingSpeed=0;
  playIdelAnimation();
}
else
{
  setMovingSpeed= asmuchyouwant;
  playWalkAnimation();
}


text:
Q: Difference between values and how the code reads the values in CS50 Here's my main code:
// Update vote totals given a new vote
bool vote(string name, int candidatecount, candidate candidates1[MAX])
{
    // TODO
    for (int a = 0; a < candidatecount; a++)
    {
        if (candidatecount == a)
        {
            printf("a\n");
            return false;
        }
        if (name == candidates1[a].names)
        {
            printf("b\n");
            candidates[a].votes = candidates[a].votes + 1;
        }
        printf("%s, %s\n", candidates1[a].names, name);
    }
    printf("1\n");
    return(name);
}

This was my command line:
    ./plurality R D

The output (with my responses) was this:
    Number of voters: 3
    Vote: R
    R, R
    D, R
    1
    Vote: D
    R, D
    D, D
    1
    Vote: R
    R, R
    D, R
    1
    vote candidate 0 go around 0
    b 0 e (null)
    vote candidate 0 go around 1
    b 0 e (null)
    (null) won with 0 votes.

It makes it seem like this:
    if (name == candidates1[a].names)

should work, but it doesn't, because the printf I have after it doesn't work.
Does anyone know why?

A: Review the Week 3 video, starting around the 40 minute mark. The prof says

It turns out that in C, you can't use equals equals to compare two strings.

He introduces strcmp at that time, and will give further explanation about why in the next lesson. The simple explanation is that strings are pointers and == will compare the addresses of the operands, not the values.


text:
Q: Opening submenu in action bar on Hardware menu button click Title explains everything. I want to open a submenu in actionbar when clicking Hardware menu button
This is the code and it works fine first time i click menu. Every other time it just flashes(opens and the instantly closes it)
private Menu mainMenu;
public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
mainMenu = menu;

return true;
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
    switch(keyCode) {
    case KeyEvent.KEYCODE_MENU:

        mainMenu.performIdentifierAction(R.id.more, 0);

        return true;
    }
}
return super.onKeyDown(keyCode, event);
}

and here is options.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:id="@+id/settings"
    android:icon="@drawable/ic_menu_preferences"
    android:showAsAction="ifRoom|withText"
    android:title="Settings"/>

<item
    android:id="@+id/about"
    android:icon="@drawable/ic_menu_info_details"
    android:showAsAction="ifRoom|withText"
    android:title="About"/>

<item
    android:id="@+id/more"
    android:icon="@drawable/ic_menu_moreoverflow_normal_holo_dark"
    android:showAsAction="always|withText"
    android:title="More">
    <menu>
        <item
    android:id="@+id/changelog"
    android:icon="@drawable/ic_menu_recent_history"
    android:showAsAction="ifRoom|withText"
    android:title="Changelog"/>
        <item
    android:id="@+id/update"
    android:icon="@drawable/ic_menu_refresh"
    android:showAsAction="ifRoom|withText"
    android:title="Update Check"/>
<item
    android:id="@+id/check"
    android:icon="@drawable/ic_menu_help"
    android:showAsAction="ifRoom|withText"
    android:title="Compatibility Check"/>
        </menu>
        </item>

</menu>

UPDATE:(Solution)
Just changed onKeyDown() method to onKeyUp() and now it sticks

A: Try this:
public boolean onCreateOptionsMenu(Menu menu)
{
    super.onCreateOptionsMenu(menu);// <--- add this

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options, menu);
    mainMenu = menu;
    return true;
}

//override this method instead of onKeyDown()....
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    super.onOptionsItemSelected(item);

    int menuId = item.getItemId();
    if(menuId == R.id.settings)
    {
        //do settings
    }
    //else if(menuId = ...) {....}

    return true;
}


text:
Q: OpenGL point light moving when camera rotates I have a point light in my scene. I thought it worked correctly until I tested it with the camera looking at the lit object from different angles and found that the light area moves on the mesh (in my case simple plane). I'm using a typical ADS Phong lighting approach. I transform light position into camera space on the client side and then transform the interpolated vertex in the vertex shader with model view matrix.
My vertex shader looks like this:
#version 420

layout(location = 0)  in vec4 position;
layout(location = 1)  in vec2 uvs;
layout(location = 2)  in vec3 normal;

uniform mat4 MVP_MATRIX;
uniform mat4 MODEL_VIEW_MATRIX;
uniform mat4 VIEW_MATRIX;
uniform mat3 NORMAL_MATRIX;

uniform vec4 DIFFUSE_COLOR;

//=======  OUTS  ============//
out smooth  vec2 uvsOut;
out flat  vec4 diffuseOut;

out  vec3 Position;
out smooth vec3 Normal;

out gl_PerVertex
{
   vec4 gl_Position;
};

void main()
{
    uvsOut = uvs;
    diffuseOut  =  DIFFUSE_COLOR;
    Normal = normal;
    Position = vec3(MODEL_VIEW_MATRIX * position);

    gl_Position = MVP_MATRIX * position;
}

The fragment shader :
//====================  Uniforms  ===============================
struct LightInfo{

 vec4 Lp;///light position
 vec3 Li;///light intensity
 vec3 Lc;///light color
 int  Lt;///light type

};

const int MAX_LIGHTS=5;

uniform LightInfo lights[1];

// material props:
uniform vec3 KD;
uniform vec3 KA;
uniform vec3 KS;
uniform float SHININESS;
uniform int num_lights;

////ADS lighting method :

vec3 pointlightType( int lightIndex,vec3 position , vec3 normal) {

    vec3 n = normalize(normal);
    vec4 lMVPos = lights[0].Lp ;  //
    vec3 s = normalize(vec3(lMVPos.xyz) - position); //surf to light
    vec3 v = normalize(vec3(-position)); //
    vec3 r = normalize(- reflect(s , n));
    vec3 h = normalize(v+s);

    float sDotN = max( 0.0 , dot(s, n) );

    vec3 diff = KD *  lights[0].Lc * sDotN ;
    diff = clamp(diff ,0.0 ,1.0);

    vec3 spec = vec3(0,0,0);

    if (sDotN > 0.0) {
        spec = KS * pow( max( 0.0 ,dot(n,h) ) ,  SHININESS);
        spec = clamp(spec ,0.0 ,1.0);
    }

    return lights[0].Li *  ( spec+diff);
}

I have studied a lot of tutorials but none of those gives thorough explanation on the whole process when it comes to transform spaces.I suspect it has something to do with camera space I transform light and vertex position into.In my case the view matrix is created with
  glm::lookAt()

which always negates "eye" vector so it comes that the view matrix in my shaders has negated translation part.Is is supposed to be like that? Can someone give a detailed explanation how it is done the right way in programmable pipeline? My shaders are implemented based on the book "OpenGL 4.0 Shading language cookbook" .The author seems to use also the camera space.But it doesn't work right unless that is the way it should work ...
I just moved the calculations into the world space.Now the point light stays on the spot.But how do I achieve the same using camera space?

A: I nailed down the bug and it was pretty stupid one.But it maybe helpful to others who are too much "math friendly" .My light position in the shaders is defined with vec3 .Now , on the client side it is represented with vec4.I was effectively setting .w component of the vec4 to be equal zero each time before transforming it with view matrix.Doing so ,I believe , the light position vector wasn't getting transformed correctly and from this all the light position problems stems in the shader.The solution is to keep w component of light position vector to be always equal 1.


text:
Q: Responsive Design - Images not fitting viewport size height wise Hello I am new to responsive design and I have been recently working on a portfolio website where I have been trying to make it responsive at all the given sizes presented in the Mozilla responsive design developer view tool.
As I shrink the view port to go down to the smaller sizes the height of my images no longer fit the height of the view port, this can be especially seen at view port size 320px. Is this an issue with my media queries or a general flaw with my HTML structure? or CSS? Could this be an issue with the size of my images? This has derailed my progress with the other aspects of my website any help with this would be greatly appreciated.
HTML
<!DOCTYPE html>

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

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

CSS
html, body {
    height: 100%;
    margin: 0;
    background-color: #2576bc;
}
#wrapper {
    width: 100%;
    min-height: 100%;
    margin: 0 auto -81px;
}
header {
    width: 800px;
    height: 244px;
    border: solid 4px black;
    margin: 0px auto;
}
#main-content {
    width: 800px;
    height: 500px;
    border: solid 4px black;
    margin: 0px auto;
}
/*#about-me {
    position: absolute;
    width: 436px;
    height: 200px;
    background-color: #2576bc;
    border: solid 3px black;
    margin: -450px 180px;
}*/
footer, .push {
    height: 81px;
}
footer {
    width: 800px;
    border: solid 4px black;
    margin: 0px auto;
}
header img {
    width:100%;
    height:auto;
}
footer img {
    width:100%;
    height: auto;
}
#main-content img {
    width:100%;
    height:auto;
}

Media Queries
/*Responsive CSS*/
 @media screen and (max-width:959px) {
    #wrapper {
        width: 100%;
    }
    header {
        width: 100%;
    }
    #main-content {
        width: 100%;
    }
    footer {
        width: 100%;
    }
    .push {
        width: 100%;
    }
}
@media screen and (max-width:640px) {
    #wrapper {
        width: 100%;
    }
    header {
        width: 100%;
    }
    #main-content {
        width: 100%;
    }
    footer {
        width: 100%;
    }
    .push {
        width: 100%;
    }
}
@media screen and (max-width:320px) {
    #wrapper {
        width: 320px;
    }
    footer {
        width: 320px;
    }
}

A: The images are behaving like this, because the DIVs (and other elements—header, footer) they're enclosed in have a set height. Since the images are set to width: 100%, they will always fill the enclosing DIV in their width entirely. However, their height is set to auto, which means they will keep the original aspect ratio.
If you want the images to fill the DIV both height- and width-wise, don't set the height of the enclosing elements (that way the DIV will stretch around the images as needed).

A: Try this. You should use max-width on your #wrapper, and don't set manual heights on your div's. You don't need the media queries for this unless you want special styles for certain screen sizes.

html, body {
    height: 100%;
    margin: 0;
    background-color: #2576bc;
}
#wrapper {
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
}
header {
    border: solid 4px black;
    margin: 0;
}
#main-content {
    border: solid 4px black;
    margin: 0;
}
/*#about-me {
    position: absolute;
    width: 436px;
    height: 200px;
    background-color: #2576bc;
    border: solid 3px black;
    margin: -450px 180px;
}*/
footer {
    border: solid 4px black;
    margin: 0;
}
header img {
    width:100%;
}
footer img {
    width:100%;
}
#main-content img {
    width:100%;
}
<!DOCTYPE html>

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

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

A: Your images are responsive.  If you try IE, Moz and Chrome you will see that they all perform a little differently as you shrink your window.  That difference is hard coded and nothing that I'm aware of can change that.
However, you might see if placing this first, in your CSS, doesn't help:
*, *:before, *:after {
        box-sizing: border-box;
 }


text:
Q: Error Passing Relation to Python UDF in Pig I am trying to pass relation to Python UDF in Pig. But it's throwing me an error. Following are my Pig Latin Script, Python Script, and error log,
REGISTER '/home/cloudera/jython-installer-2.7.0.jar';
REGISTER '/home/cloudera/Code.py' USING jython as myfunc;
A = LOAD '/home/cloudera/Link.txt' as (line:chararray);
B = FOREACH A GENERATE myfunc.codefunc(line);

//Python Script
import pandas as pd
def count(A,  crime):
    with open(A, 'r', encoding='UTF8') as fileA:
        data = fileA.read().lower()
        count = data.count(crime.lower())
        return count
def codefunc(A):
    crime = ['Rape', 'Murder', 'Extortion', 'Felony', 'Burglary', 'Property Damage', 'Arrest', 'Political Unrest', 'Civil Unrest', 'Solitication', 'Larceny', 'Abettor', 'Trafficking', 'Tresspasser', 'Robbery']
    crimecount = {}
    for i in range(len(crime)):
            crimecount[crime[i]] = count(A, crime[i])
    final_count = pd.DataFrame(list(crimecount.items()), columns = ['Crime', 'Value'])
    final_count['Percentage'] = 0
    total_count = final_count['Values'].sum()
    for i in range(0, final_count.last_valid_index()+1):
            final_count['Percentage'][i] = float((final_count['Values'][i]/total_count)*100.0)
    final_count.sort_values(by=['Percentage'], ascending=False)
    final_count.to_csv('/home/cloudera/solution.csv', header=0)

//Error Log
 Link of Error Log
I have placed the link where dataset resides, and I have passed the link from Pig to Python. Python should go to that link and read the dataset and execute the code written. Python Code is absolutely fine. I am confident on that. But Pig is throwing me an error at relation, 'B'. I tried placing the error code here, but Stack Overflow isn't letting me do it, so I have placed the link. Regret the inconvenience. Can anyone please help me. Thanks in advance.

A: Your code is absolutely fine. Problem is with Jython. Jython doesn't support Pandas dataframe because it was written in C/C++. So cheer up!
Hope you like my answer! Yippee!!


text:
Q: Pivot in sql server while using functions I have a stored procedure like this:
ALTER procedure [dbo].[performance]
@startdate nvarchar(100),
@enddate nvarchar(100) as begin declare @date1 nvarchar(100)=convert(varchar, @startdate+'00:00:00.000',120)  declare @date2 nvarchar(100)= convert(varchar, @enddate+'23:59:59.000',120)   set NOCOUNT on;
select l.LocName,v.Vtype,
 SUM(convert(numeric(18, 2), DATEDIFF(MI,t.DelDate,t.Paydate))) as TotalDiff,[dbo].[testfunctionstacknew](
   CONVERT(decimal(10,1), AVG( CONVERT(NUMERIC(18,2), DATEDIFF(SS,t.Paydate,t.DelDate) ) )))  as Average
from Transaction_tbl t left join VType_tbl v on t.vtid=v.vtid left join Location_tbl l on t.Locid=l.Locid
where t.Locid in(select t1.Locid  from Transaction_tbl t1) and dtime between @date1 and @date2 and Status =5 group by v.Vtype,l.LocName,l.Locid order by l.Locid
end

I am getting out put like this:
LocName   Vtype    TotalDiff   Average
Address   Normal     15         00:10:01
Adress    vip        18         00:08:01
Address   VVIP        9         00:04:00
Address   Pass       20         00:15:00
Goldsouk  normal     45         00:18:08
Goldsouk   vip       17         00:11:36
Fashion    vip       78         00:35:25
Fashion    VVip      2          00:01:00

but i need output in different model as
LocName     Normal      Vip      VVip        Pass        Staff
Address     00:10:01    00:08:01  00:04:00    0           0
GoldSouck    00:18:08   00:11:36   0          0           0
Fashion      0          00:35:25   00:01:00   0           0

For getting out put like i know i have to use pivot..but i dont know how to use this? if any one know please help me to find out..i cant hardcord my vtype..actulay vtype is dynamic.that is coming from Vtype Table..if any one know how to resolve this issue..please help me to find out

A: you can pivot manually:
ALTER procedure [dbo].[performance]
(
    @startdate nvarchar(100),
    @enddate nvarchar(100)
)
as
begin
    set nocount on

    declare
        @date1 nvarchar(100)=convert(varchar, @startdate+'00:00:00.000',120)
        @date2 nvarchar(100)= convert(varchar, @enddate+'23:59:59.000',120)

    ;with cte as (
        select
            l.LocName, v.Vtype,
            sum(datediff(mi, t.DelDate, t.Paydate)) as TotalDiff,
            dbo.testfunctionstacknew(
                convert(decimal(10,1),
                    avg(convert(numeric(18,2), datediff(ss, t.Paydate, t.DelDate))
                )
            ) as Average
        from Transaction_tbl as t
            left join VType_tbl as v on t.vtid = v.vtid
            left join Location_tbl as l on t.Locid = l.Locid
        where
            t.Locid in(select t1.Locid from Transaction_tbl as t1) and
            t.dtime between @date1 and @date2 and
            t.Status = 5
        group by v.Vtype, l.LocName, l.Locid
    )
    select
        c.LocName,
        max(case when c.Vtype = 'Normal' then Average end) as Normal,
        max(case when c.Vtype = 'Vip' then Average end) as Vip,
        max(case when c.Vtype = 'VVip' then Average end) as VVip,
        max(case when c.Vtype = 'Pass' then Average end) as Pass,
        max(case when c.Vtype = 'Staff' then Average end) as Staff
    from cte as c
    group by c.LocName
    order by c.LocName
end


text:
Q: Completion block for nested requests I am trying to build methods with completion blocks for nested requests. The issue is that a completion block catches to early for parent requests (meaning that the child requests haven't actually completed yet). So far I haven't found a way for a child request to communicate back to the parent request other than what I've done in my example below (which is to count the amount of child requests have completed and compare it against the expected amount of requests).
The example below is working against a Firestore database. Imagine a user has multiple card games (decks) with each multiple cards. I'm grateful for any help how to build better completion blocks for cases like these:
func fetchCardsCount(uid: String, completion: @escaping (Int) -> ()) {
    let db = Firestore.firestore()

    var decksCount = Int()
    var cardsCount = Int()

    db.collection("users").document(uid).collection("decks").getDocuments { (deckSnapshot, err) in
        if let err = err {
            print("Error fetching decks for user: ", err)
        } else {
            guard let deckSnapshot = deckSnapshot else { return }

            deckSnapshot.documents.forEach({ (deck) in
                let dictionary = deck.data() as [String: Any]
                let deck = FSDeck(dictionary: dictionary)
                db.collection("users").document(uid).collection("decks").document(deck.deckId).collection("cards").getDocuments(completion: { (cardSnapshot, err) in
                    if let err = err {
                        print("Error fetching cards for deck: ", err)
                    } else {
                        guard let cardSnapshot = cardSnapshot else { return }
                        decksCount += 1
                        cardsCount += cardSnapshot.count

                        if decksCount == deckSnapshot.count {
                            completion(cardsCount)
                        }
                    }
                })
            })
        }
    }
}

A: Here is the solution, using DispatchGroup, found with @meggar's help in the comments:
func fetchCardsCount(uid: String, completion: @escaping (Int) -> ()) {
    let db = Firestore.firestore()

    var cardsCount = Int()
    let group = DispatchGroup()

    group.enter()
    db.collection("users").document(uid).collection("decks").getDocuments { (deckSnapshot, err) in
        if let err = err {
            print("Error fetching decks for user: ", err)
        } else {
            guard let deckSnapshot = deckSnapshot else { return }

            deckSnapshot.documents.forEach({ (deck) in
                let dictionary = deck.data() as [String: Any]
                let deck = FSDeck(dictionary: dictionary)

                group.enter()
                db.collection("users").document(uid).collection("decks").document(deck.deckId).collection("cards").getDocuments(completion: { (cardSnapshot, err) in
                    if let err = err {
                        print("Error fetching cards for deck: ", err)
                    } else {
                        guard let cardSnapshot = cardSnapshot else { return }
                        cardsCount += cardSnapshot.count
                    }
                    group.leave()
                })
            })
        }
        group.leave()
    }

    group.notify(queue: .main) {
        completion(cardsCount)
    }
}


text:
Q: (sqlite3.OperationalError) unable to open database file when using absolute file path in sqlite3 connection string in sqlalchemy on windows I'm trying to create a database engine from a connection string using sqlite3 and sqlalchemy but am running into issues.
My particular details are that I want to use an absolute filepath from the os module in the connection string (this makes it easier when I deploy it only python anywhere) and am currently working on windows.
The most viewed answer to this question can be found here:  OperationalError: (sqlite3.OperationalError) unable to open database file but its answers did not work for me.
Here is my current directory structure:
 /db
   -- assets.db
 /app
   -- load_engine.py
   -- models.py

The idea is that I want to initialize my sqlalchemy connection from a function in the load_engine file, but reference the file path to /db/assets.db into it.
This is the function inside load_engine:
def load_engine():

    db_file = os.environ.get('database_file')

    script_path = os.path.realpath('__file__')
    parent_path = os.path.dirname(script_path)
    db_path = os.path.join(os.path.sep,parent_path, "db", db_file)

    engine = create_engine(fr"sqlite:///{db_path}")
    return engine

I'm trying to invoke this function in the models.py file in the following way:
Base = declarative_base()

class Assets(Base):
    """Main table that will hold the list of ticker names"""
    __tablename__ = 'assets'

    id     = Column(Integer, primary_key = True)
    ticker = Column(String(250), nullable = False, unique = True)
    type   = Column(String(100), nullable = False)

class BarData(Base):
    """Will hold daily bar data from yahoo finance"""
    __tablename__ = 'bardata'

    id        = Column(Integer, primary_key = True)
    ticker    = Column(String(250), ForeignKey("assets.ticker"), nullable = False)
    open      = Column(Float, nullable = False)
    high      = Column(Float, nullable = False)
    low       = Column(Float, nullable = False)
    close     = Column(Float, nullable = False)
    volume    = Column(Float, nullable = False)
    dividends = Column(Float, nullable = False)
    splits    = Column(Float, nullable = True)

if __name__ == '__main__':
    engine = load_engine()
    Base.metadata.create_all(engine)

And when I run this I get the error, presumably because my filepath is wrong.  I've tried deleting the assets.db file to see if that changed, but it didn't work.  I also tried using 4 forward slashes vs. 3, but also got the same message.
If I reference a file that's in the same directory it works fine, so I would assume the issue is the filepath.
EDIT:
Per comments, output of engine is the following:
Engine(sqlite:////C:\Users\Jonat\trading\app\db\assets.db)


text:
Q: Scanning and storing a simple image in a complex matrix I have been playing with linear algebra transformations in R, moving around a bunch of points plotted in the complex plane. I have posted the results here - the code is linked on the first sentence.
I would like to do the same operations on a real image. Evidently I don't want to get into Fourier transforming the image, or dealing with color or grayscale. I would like to get any old jpeg, turn it into a summarized plot of black and white dots, locate each dot in terms of its position in the complex plane, and then apply the linear algebra operations as I did to my drawing of a house.
The questions are, 1. What is the name for the type of stripped-down, basic black and white image that I am describing? 2. How can I turn a regular jpeg (or other file) into that type of image? How can then store every dot of the thousands of dots the image will contain into a matrix of complex numbers?
Is there software to do this? Is there code in R or python to do it?

A: It's not clear what you're trying to do with those complex vectors, that wouldn't be more easily obtained using standard x,y coordinates, but here goes a possible starting point
library(jpeg)

im <- readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"))
gr <- apply(im, 1:2, mean)
bw <- which(gr < 0.5, arr.ind = TRUE)

conjure_matrix_of_darkness <- function(bw, xlim=c(-2, 2), ylim=c(-2,2)){

  x <- (bw[,1] - min(bw[,1]))/diff(range(bw[,1])) * diff(xlim) + min(xlim)
  y <- (bw[,2] - min(bw[,2]))/diff(range(bw[,2])) * diff(ylim) + min(ylim)
  x+1i*y
}

test <- conjure_matrix_of_darkness(bw)
par(mfrow=c(2,1), mar=c(0,0,0,0))
plot(test, pch=19, xaxt="n", yaxt="n")
plot(test*exp(1i*pi), pch=19, xaxt="n", yaxt="n")


text:
Q: Black Screen when using -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath I'm so frustrated because I've done this a million times before, but now I can't get a tableviewcontroller to push my detailsviewcontroller. I'm using the didSelectRowAtIndexPath method and my code is below:
 HistoryDetailsViewController *HDV = [[HistoryDetailsViewController alloc] init];
[self.navigationController pushViewController:HDV animated:YES];

All I get in return is a black screen. I just want to be able to go from a table view cell to this view controller. What am I doing wrong?

A: If your HistoryDetailsViewController has its layout defined in a storyboard, you need to instantiate the view controller from the storyboard:
HistoryDetailsViewController *HDV = [self.storyboard instantiateViewControllerWithIdentifier: @"yourstoryboardidentifierhere"];

A: Ah, I'm such an idiot. The following solution is below:
 HistoryDetailsViewController *HDV = [self.storyboard instantiateViewControllerWithIdentifier:@"HistoryDetails"];
[self.navigationController pushViewController:HDV animated:YES];

This worked perfectly


text:
Q: How can I type Horizontal line in console in JavaScript? I want to type Horizontal line like '-' 'ㅡ' ..
'-' this is dash(is underbar with shift.. _ ). it is too short
'ㅡ' this is korean. it is fine but still short
Is there any other way??
I am drawing a coordinate system on the console.
I want horizontal and vertical lines of the same length

A: I can't directly answer your question but maybe an ASCII art npm package can help you? It supports drawing graphs with ASCII characters which can then be printed onto the console.


text:
Q: Wireless XP users don't get their home folder mapped We're using Windows XP and Active Directory, we have a number of laptops that have a excellent connection to the wireless network, the logon script runs and maps the required drives etc, all appears fine apart from the Home Folder isn't mapped, we rely on the home folder mapping to be done by AD when the user logs on we don't map this with the logon script.
The problem is the home folder doesn't get mapped when using wireless, plug an ethernet cable in and the home folder is mapped. What could be causing this? Anyone and ideas?
Thanks

A: It sounds like you don't have Wireless Zero Config setup to be able to authenticate before the user is completely logged in.  You need to have the machine able to connect to wireless without user interaction in order to authenticate against AD and now cached credentials as squillman said.
How to enable computer-only authentication for a 802.1X-based network in Windows Vista, in Windows Server 2008, and in Windows XP Service Pack 3

A: When is it that the wireless connection is established, before or after login?  It sounds like the machine is logging in (with cached credentials) prior to the network connection being established.  This being the case, there would be no network connection for use to map the drive.

A: Perhaps it would help to put a sleep-statement at the beginning of you the logon scripts. Or a more elegant way would be to check (via ping) the connectivity to your fileserver and retry as long as it is NOT reachable ...


text:
Q: PHP - Delete XML tag Elements based on selected Checkbox Array values I have an XML file of songs and I'm using PHP to build a form (with checkboxes) to delete 1 or more songs from that file. The problem I'm running into is that I can't quite figure out how to iterate through the list of IDs from the form and delete the songs with those IDs.
Here's my XML:
<?xml version="1.0" encoding="utf-8"?>
<songs>
    <song id="1380682359">
        <artist>Artist</artist>
        <title>Title</title>
    </song>
    <song id="1380682374">
        <artist>Artist</artist>
        <title>Title</title>
    </song>
    <song id="1380828782">
        <artist>Artist</artist>
        <title>Title</title>
    </song>
</songs>

This builds the form:
<?
echo "<form action='removesong.php' method='post'>\n";
$doc = new DOMDocument();
$doc->load('songlist.xml');
$songlist = $doc->getElementsByTagName("song");
foreach($songlist as $song) {
    $id = $song->getAttribute("id");
    $artists = $song->getElementsByTagName("artist");
    $artist = $artists->item(0)->nodeValue;
    $titles = $song->getElementsByTagName("title");
    $title = $titles->item(0)->nodeValue;
    echo "<input type='checkbox' name='SongsToRemove[]' value='" . $id . "'> $artist, "$title"
\n";
}
echo "
<input type='submit' value='Delete Song' />\n</form>\n";
?>

And "removesong.php" is going to be something close to this (I think):
<?
$doc = new DOMDocument();
$doc->load("songlist.xml");
$songs = $doc->getElementsByTagName("song");
foreach($songs as $song) {
    if($song['id'] == $_POST["SongsToRemove"]) {
        unset($song); // or $song->removeChild($song);
    }
}
$doc->save("songlist.xml");
?>

I can't quite figure out how to use $_POST["SongsToRemove"] to delete those songs.

A: --edit-- just saw you are already using a $_POST array, so modified the example:
try this:
<?
// post variable is string with comma seperators
//$_POST['SongsToRemove'] = '1380682359,1380828782';
//$songs_to_remove = explode( ',', $_POST['SongsToRemove'] );

// songs to remove is already post array:
$songs_to_remove = $_POST['SongsToRemove'];

$doc = new DOMDocument();
$doc->load("songlist.xml");
$songs = $doc->getElementsByTagName("song");
foreach($songs as $song) {
    if( in_array( $song['id'], $songs_to_remove ) {
        unset($song); // or $song->removeChild($song);
    }
}
$doc->save("songlist.xml");
?>

Other things you could try are setting the songs to remove to an array (you can do that with HTML too): this would eliminate the need for the explode etc...
<input type="text" name="SongsToRemove[]" />
<input type="text" name="SongsToRemove[]" />
<input type="text" name="SongsToRemove[]" />


text:
Q: Why in C++ do I need to pass a pointer by reference to change the pointed content? I am writing a function to load text from shader code file. I have stumbled upon something strange regarding pointers and I cannot figure out why.
I have a function named Load. In this function I copy text, taken from a file stream, in the output variable.
static void Load(const GLchar* source_path,  GLchar* output,GLint& count )
{
    string code;

    // loading logic here
    code= vShaderStream.str(); // copying the string from the stream
    count = code.length();
    output = new GLchar[count];
    std::size_t length = code.copy(output, count, 0);
    output[length]= '\0';
}

Load is called in this way:
for (size_t i = 0; i < d_n_fragment; i++)
{
    Load(d_fragment_source_path, d_fragment_code[i], d_fragment_string_count[i]);
}

where d_fragment_code is a double pointer of Glchar** which is already initialized. After Load function is called the pointer d_fragment_code[i] contains no text. I tried to change the signature of the Load function to:
static void Load(const GLchar* source_path,  GLchar*& output,GLint& count )

and thus passing the pointer by reference. It works, after the function is called d_fragment_code holds correctly the text loaded from the file but I don't understand why a pointer it is to be passed by reference.
I thought that passing a pointer only would suffice to change its content. I am confused, could you shed some light on it?

A: You should pass pointers by reference if you have to modify the pointer rather than the object that the pointer is pointing to.
Using double pointers is also a similar case.
Here is a more detailed article:
http://www.codeproject.com/Articles/4894/Pointer-to-Pointer-and-Reference-to-Pointer

A:
output = new GLchar[count];

This changes what output points to. If you are sure that output already points to a buffer of sufficient size, remove this line.

A:
I thought that passing a pointer only would suffice to change its content.

Passing a pointer suffices to change the content of the pointee (the thing pointed to). That's great, and it has essentially the same effect as passing a reference.
But you're not doing that. You want to change the pointer itself.
Consider, if you wanted to pass an object into a function such that the function altered the original object. Let's call the object's type T, and let's pretend that it has a member function mutate that changes it somehow (so that we don't have to give a real-world example of this as T changes):
void foo(T& handle)
{
   handle.mutate();
}

void bar(T* handle)
{
   handle->mutate();
}

int main()
{
   T obj;
   foo(obj);
   bar(&obj);
}

Both foo and bar accomplish the same thing, using a reference and a pointer respectively.
Now we can apply this logic to anything, by exchanging various types for T. The scenario that you're thinking of, is passing some non-pointer object, by pointer, to mutate it:
void bar(int* handle)
{
   handle->mutate();
}

int main()
{
   int obj;
   bar(&obj);
}

But the situation you're actually in calls for T itself to be a pointer, and to use foo rather than bar. It's understandable that this is confusing!
void foo(GLint*& handle)
{
   handle.mutate();
}

int main()
{
   GLint* obj;
   foo(obj);
}

If it helps, you could also have written:
void bar(GLint** handle)
{
   handle->mutate();
}

int main()
{
   GLint* obj;
   bar(&obj);
}

which is effectively equivalent.
(disclaimer: I didn't initialise obj in any of those examples. You'll want to.)


text:
Q: bower install package with custom directory structure how to install js-package using bower with following directories structure:
package-name
----version
--------files

by default directories structure is:
bower_components
----package-name
--------files

after modifying .bowerrc
{
    "directory": ""
}

directories looks like:
----package-name
--------files

A: As far as I know there is no way of achieving this directory layout out of the box.
You might be able to achieve this by post processing the downloaded components.
One option is using a Bower postinstall hook which will rearrange the directory layout. The hook can get a list of all components downloaded by Bower. You will need to figure out which component  version was downloaded. You can get this information from the .bower.json which is created by Bower at resolution time (do not confuse with bower.json). Notice that this file is used internally by Bower and may be subject to change.
You can achieve the same results with various available grunt tasks, for example the grunt-bower-task. Again the challenge would be getting the resolved version of the components.


text:
Q: Resizing UITableView as seen in Rdio iOS app Im attempting to replicate the resizing behaviour of a screen seen in the iOS app Rdio. The screen in question provides an overview of a selected album and contains a UIView on the top half and a UITableView on the bottom half. When the tableView is scrolled, it first resizes upwards to fill the screen, then begins to scroll through its content normally once the maximum height is reached.
After some searching I found this question: Dragging UITableView which is basically asking for the same thing, however its accepted method is the same as my initial thoughts & trial, which was to use a UIPanGestureRecognizer and resize the tableviews height according to the translation of the pan.
This does not provide the behaviour i'm looking for. Using this method only allows you to statically drag the tableviews height up or down and it has the added issue of the panGesture overriding that of the tableViews which then prevents scrolling through the content.
The resizing behaviour of the Rdio app functions and feels exactly like a UIScrollView, it has inertia. You can drag it all the way, flick it up or down, and it smoothly resizes. When the tableView has reached its full-size or original half-size, the remaining inertia is seemingly passed on the tableview causing the cells to scroll as they normally would for that amount. I know they must be manipulating UIScrollViews, I just can't figure out how.
As a final note, eventually I will be using AutoLayout on this screen so i'm wondering how that will potentially hinder or help this situation as well.
Update
This approach has gotten me closest to the behaviour i'm looking for so far.
Flicking the tableView upwards behaves exactly like I wanted it to (resize with inertia & continue scrolling when max height is reached), although with less sensitivity than i'd like. Flicking downwards however, provides no inertia and instantly stops.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGRect scrollViewFrame = scrollView.frame;
    CGFloat scrollViewYOffset = scrollView.contentOffset.y;

    if (scrollViewFrame.origin.y <= kTableViewMaxYOrigin || scrollViewFrame.origin.y <= _originalTableViewFrame.origin.y)
    {
        scrollViewFrame.origin.y -= scrollViewYOffset;

        if(scrollViewFrame.origin.y >= kTableViewMaxYOrigin && scrollViewFrame.origin.y <= _originalTableViewFrame.origin.y)
        {
            scrollViewFrame.size.height += scrollViewYOffset;
            scrollView.frame = scrollViewFrame;
            scrollView.contentOffset = CGPointZero;
        }
    }
}

A: I made a version that uses autolayout instead.
It took me a while of trial and error to get this one right!
Please use the comments and ask me if the answer is unclear.
In viewDidLoad save the initial height of your layout constraint determining the lowest down you want the scrollview to be.
- (void)viewDidLoad
{
    ...
    _initialTopLayoutConstraintHeight = self.topLayoutConstraint.constant;
    ...
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    BOOL leaveScrollAlone = self.topLayoutConstraint.constant == _initialTopLayoutConstraintHeight && scrollView.contentOffset.y <= 0;
    if (leaveScrollAlone)
    {
        // This allows for bounce when swiping your finger downwards and reaching the stopping point
        return;
    }

    // Do some capping of that layout constraint to keep it from going past the range you want it to be.
    // In this case, I use self.topLayoutGuide.length so that my UICollectionView scales all the way until
    // it hits the bottom of the navigation bar
    CGFloat topLayoutConstraintLength =   _initialTopLayoutConstraintHeight - scrollView.contentInset.top;
    topLayoutConstraintLength           = MAX(topLayoutConstraintLength, self.topLayoutGuide.length);
    topLayoutConstraintLength           = MIN(topLayoutConstraintLength, _initialTopLayoutConstraintHeight);
    self.topLayoutConstraint.constant   = topLayoutConstraintLength;

    // Keep content seemingly still while the UICollectionView resizes
    if (topLayoutConstraintLength > self.topLayoutGuide.length)
    {
        scrollView.contentInset = UIEdgeInsetsMake(scrollView.contentInset.top + scrollView.contentOffset.y,
                                                   scrollView.contentInset.left,
                                                   scrollView.contentInset.bottom,
                                                   scrollView.contentInset.right);

        scrollView.contentOffset = CGPointZero;
    }

    // This helps get rid of the extraneous contentInset.top we accumulated for keeping
    // the content static while the UICollectionView resizes
    if (scrollView.contentOffset.y < 0)
    {
        self.topLayoutConstraint.constant -= scrollView.contentOffset.y;

        scrollView.contentInset = UIEdgeInsetsMake(scrollView.contentInset.top + scrollView.contentOffset.y,
                                                   scrollView.contentInset.left,
                                                   scrollView.contentInset.bottom,
                                                   scrollView.contentInset.right);
    }

    // Prevents strange jittery artifacts
    [self.view layoutIfNeeded];
}

A: It turns out the key component to getting the smooth inertial resizing in both directions was to update the scrollViews contentInset.top by its contentOffset.y.
I believe this makes sense in retrospect as if the content within is already at the top it cannot scroll anymore, hence the sudden stop rather than smooth scroll. At least thats my understanding.
Another key point was to make sure the cells only started scrolling once maximum or original height was achieved. This was done simply by setting the scrollViews contentOffset to CGPointZero each time the view resized until maximum or original height was reached.
Here is the - (void)scrollViewDidScroll:(UIScrollView *)scrollView method demonstrating how to achieve this effect.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGRect scrollViewFrame = scrollView.frame;
    CGFloat scrollViewTopContentInset = scrollView.contentInset.top;
    CGFloat scrollViewYOffset = scrollView.contentOffset.y;

    if (scrollViewFrame.origin.y <= kTableViewMaxYOrigin || scrollViewFrame.origin.y <= _originalTableViewFrame.origin.y)
    {
        scrollViewFrame.origin.y -= scrollViewYOffset;

        if(scrollViewFrame.origin.y >= kTableViewMaxYOrigin && scrollViewFrame.origin.y <= _originalTableViewFrame.origin.y)
        {
            scrollViewFrame.size.height += scrollViewYOffset;
            scrollViewTopContentInset += scrollViewYOffset;
            scrollView.frame = scrollViewFrame;
            scrollView.contentInset = UIEdgeInsetsMake(scrollViewTopContentInset, 0, 0, 0);
            scrollView.contentOffset = CGPointZero;
        }
    }
}

A: I haven't seen the app in question, but from your description... in your tableView's delegate method -scrollViewDidScroll:, set tableView.frame.origin.y to albumView.frame.height - tableView.contentOffset.y and change its height accordingly.
(If you're using autolayout, you'll have to change the constraints pertaining to the tableView's frame rather than the frame itself.)


text:
Q: Counting sheeps So i'm trying to use the push method to solve the couting sheeps problem. Basically in this problem i need to count how many "true" there is in a given array. The array itself is
[true,  true,  true,  false,
  true,  true,  true,  true ,
  true,  false, true,  false,
  true,  false, false, true ,
  true,  true,  true,  true ,
  false, false, true,  true]

And i want to understand why the push method, that seem to REMOVE the last index of the array and RETURN it does not work.
function countSheeps(arrayOfSheep) {

  let a = arrayOfSheep;
  let b = 0;
  let answer = 0;

    for(let i = 0; i < a.length; i++){
      b = a.push();
        if(b === true){
          answer += 1;
}
}
  return answer;
}

In my thinking, each time the for loop goes, the length of array a are reduced by one. So in the final loop the array a is [0] and the if makes the answer variable to be equal to 17, but it always return 0.

A: I think your approach is overly complex. If I wanted to count how many items in a list match some criteria, I would just look at each item and increment a counter if it matches until I was done with the entire array.
function countTrue(arr) {
  // accumulator variable, at the end of each iteration
  // of the loop, `result` will be gauranteed to have the
  // total number of `true` elements seen so far
  let result = 0;
  // iterate over the entire array
  for (const item of arr) {
    if (item === true) {
      // this item is true, increment our accumulator
      result++;
    }
  }
  // return our accumulated result, zero or otherwise.
  return result;
}

A: You could just add the boolean values.

const
    array = [true, true, true, false, true, true, true, true, true, false, true, false, true, false, false, true, true, true, true, true, false, false, true, true],
    result = array.reduce((a, b) => a + b, 0);

console.log(result);

A: You don't need to push any new value to simply count unique items in an array.

var array = [true,  true,  true,  false,
  true,  true,  true,  true ,
  true,  false, true,  false,
  true,  false, false, true ,
  true,  true,  true,  true ,
  false, false, true,  true];

var total = 0;
array.forEach(function (item){
  if(item){
    total++;
  }
});
console.log(total);

A: Quite likely, you meant to use the .pop() method which removes an element from the end of the array - changing the array. You also could have used the .unshift() method which removes an element from the beginning of the array. Each of these methods destroy the original array.
You can use Array#filter() method and length property and still leave the original array intact.

const
      input = [true,true,true,false,true,true,true,true,true,false,true,false,true,false,false,true,true,true,true,true,false,false,true,true],
      output = input.filter(sheep => sheep).length;

console.log( output );

NOTE

*

*If you must use a loop, see below.

*If you must use Array#pop, not while looping through the same array.

for loop:

const
      input = [true,true,true,false,true,true,true,true,true,false,true,false,true,false,false,true,true,true,true,true,false,false,true,true],

      countSheep = a => {
          let count = 0;
          for(let i = 0; i < a.length; i++) {
              !a[i] || count++;
          }
          return count;
      },

      output = countSheep( input );

console.log( output );

for-of loop:

const
      input = [true,true,true,false,true,true,true,true,true,false,true,false,true,false,false,true,true,true,true,true,false,false,true,true],

      countSheep = a => {
          let count = 0;
          for(const element of a) {
              !element || count++;
          }
          return count;
      },

      output = countSheep( input );

console.log( output );


text:
Q: Change focus among figure canvas in TkInter I'm plotting 2 different figures within a TkInter window. I'm using TkInter because I'll add some buttons later on. Just FYI, the two figures have different sizes, because I will interact with only the big one, leaving the small one for other uses. When the window opens, the focus is always set on the small one, so I need to use the TAB to switch it to the big figure. I tried many combinations of focus() or focus_set() but no metter what I tried it always opened the window with the focus on the small figure.
What can I do?
I attach here a simple code showing my problem.
import matplotlib
matplotlib.use('TkAgg')

from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import sys
import Tkinter as tk

root = tk.Tk()
root.wm_title("Embedding in TK")

f1 = Figure(figsize=(7.5,10), dpi=100)
a1 = f1.add_subplot(111)
f2 = Figure(figsize=(7.5,5), dpi=100)
a2 = f2.add_subplot(111)

t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)

a1.plot(t,s)
a2.plot(t,s)

canvas1 = FigureCanvasTkAgg(f1, master=root)
canvas2 = FigureCanvasTkAgg(f2, master=root)
canvas1.show()
canvas2.show()
canvas1.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
canvas2.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH)

def print_key(event):
    print 'you pressed '+event.key

cid = f1.canvas.mpl_connect('key_press_event', print_key)

#SOMETHIN MISSING HERE IN ORDER TO SET THE FOCUS ON THE BIGGER WINDOW

tk.mainloop()

A: you could try changine the settings of the small figure to prevent it being allowed focus:
canvas2.get_tk_widget().configure(takefocus=False)


text:
Q: SAX Parser: Specify DTD location in applet I have an applet that works fine in the applet viewer but once deplayed to the server it can't parse the XML files
the reason is simple: the SAX parser is trying to open the dtd on the hard disk and not in the JAR.
I was told to do this:

URLs to resources can easily be formed
  using the URL(baseURL, pathString)
  constructor where the base URL is
  obtained from Applet.getDocumentBase()
  or Applet.getCodeBase().

but I don't know how to apply this in my case:
heres a XML sample :
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "leveldtd.dtd">
<level>
...
</level>

and here is the init of my parser
public static void parseThis(InputSource is) throws Exception{
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLHandlerLevel myExampleHandler = new XMLHandlerLevel();
        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(myExampleHandler);
        /* Begin parsing */
        xr.parse(is);
    }

any ideas ?
Jason

A: If validation is not required you could just turn it of in the SAXParserFactory.setValidating() so the parser won't try to read the DTDs.
If you however do need validation you can redirect any DTD/XSD requests by setting your own EntityResolver on the sax parser.


text:
Q: Why noscript and skel are not working in wordpress? I'm using Miniport Template.
 A demo can be found here.
The head section looks like as below:
<!DOCTYPE HTML>
<!--
    Miniport 2.5 by HTML5 UP
    html5up.net | @n33co
    Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
    <head>
        <title>Miniport by HTML5 UP</title>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <meta name="description" content="" />
        <meta name="keywords" content="" />
        <link href="http://fonts.googleapis.com/css?family=Open+Sans:300,600,700"       rel="stylesheet" />
        <script src="js/jquery.min.js"></script>
        <script src="js/config.js"></script>
        <script src="js/skel.min.js"></script>
        <noscript>
            <link rel="stylesheet" href="css/skel-noscript.css" />
            <link rel="stylesheet" href="css/style.css" />
            <link rel="stylesheet" href="css/style-desktop.css" />
        </noscript>
        <!--[if lte IE 9]><link rel="stylesheet" href="css/ie9.css" /><![endif]-->
        <!--[if lte IE 8]><script src="js/html5shiv.js"></script><link rel="stylesheet" href="css/ie8.css" /><![endif]-->
        <!--[if lte IE 7]><link rel="stylesheet" href="css/ie7.css" /><![endif]-->
    </head>

There is nothing changed but added <?php wp_head(); ?> when converting it into wordpress theme.
But css is broken, It looks like the page is not getting the css when <noscript> is there.
Also responsiveness is broken when converting the original theme into wordpress.
How to fix 1.noscript issue 2. responsiveness issue ?

A: you're calling stylesshets in a wrong way. change the css calls to:
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/skel-noscript.css" />
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/style.css" />
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/style-desktop.css" />

But I recommend you to create a style.css in your index folder, then use @import to other sheets. for this, change the calling to:
<link rel="stylesheet" type="text/css" media="screen" href="<?php bloginfo('stylesheet_url'); ?>" />

Notice: do the same with js files.
<script src="<?php bloginfo('template_url'); ?>/js/jquery.min.js"></script>
<script src="<?php bloginfo('template_url'); ?>/js/config.js"></script>
<script src="<?php bloginfo('template_url'); ?>/js/skel.min.js"></script>


text:
Q: PHP CURL error 18 on Chunked Requests (Hidden Timeout Variable) I've been going crazy because of a timeout that is occurring on chunked requests with PHP version 5.5 and curl version 7.51.0. PHP is requesting a set of data from a Scala Play Framework service, which is returning a chunked response.
What's happening: As soon as the PHP request waits 60 seconds for the next chunk, it terminates with a CURL error 18. This same endpoint works with requests of smaller sizes, so I know that it's not a general connection issue.
Testing the endpoint from the PHP box via command line using a request of this format works without issue:
curl -i -X POST -H 'Content-Type: application/json' -d '<Request Params>' <URL>

My PHP Request (using guzzle shown here, but I've also tried raw curl exec) looks like this:
$client->request('POST', $route, [
            // I thought this would work first
            'timeout' => 120,
            // Maybe some of these other timeouts will help...
            'connect_timeout' => 120,
            'read_timeout' => 120,
            'json' => $body,
            'headers' => [
                // I found some random SOs that suggest setting headers..
                'Connection' => 'close',
                'Expect' => '',
                'Transfer-Encoding' => 'chunked'
                ],
            'stream' => true,
                'curl' => [
                        // Beginning the descent into insanity
                        CURLOPT_CONNECTTIMEOUT => 120,
                        // I don't have a low speed limit set but maybe?
                        CURLOPT_LOW_SPEED_TIME => 120,
                        // Perhaps there's a guzzle bug that doesn't set timeout.. NOPE
                        CURLOPT_TIMEOUT => 120,
                        // Hey, this one works! We'll see in the curlinfo below
                        CURLINFO_HEADER_OUT => true,
                        CURLOPT_VERBOSE => true,
                        CURLOPT_STDERR => '<logloc>',
                        // alright this isn't even a socket connection but sure
                        CURLOPT_FORBID_REUSE => true,
                        // SET ALL OF THE TIMEOUTS!!
                        CURLOPT_TCP_KEEPALIVE => 120,
                        CURLOPT_TCP_KEEPIDLE => 120,
                        CURLOPT_TCP_KEEPINTVL => 120
                ]
        ]);

None of the above worked. Some suggestions recommend that I set HTTP version to 1.0. That is an unnacceptable solution, as the data returned from this endpoint needs to be streamed directly in the response (hence stream => true). The same problem occurs with raw curl (without Guzzle).
In addition to the above request settings, I've set the following PHP settings:
set_time_limit(0); // also have set this to large numbers
ini_set("default_socket_timeout", 270); // Have also set this in the PHP.ini

The curl stats of the failed response are
{
    "url": "<URL>",
    "content_type": "text/plain; charset=utf-8",
    "http_code": 200,
    "header_size": 144,
    "request_size": 207,
    "filetime": -1,
    "ssl_verify_result": 0,
    "redirect_count": 0,
    "total_time": 60.20854, // WHY CRUEL WORLD??
    "namelookup_time": 0.124769,
    "connect_time": 0.125011,
    "pretransfer_time": 0.132244,
    "size_upload": 116,
    "size_download": 51,
    "speed_download": 0,
    "speed_upload": 1,
    "download_content_length": -1,
    "upload_content_length": -1,
    "starttransfer_time": 0.132248,
    "redirect_time": 0,
    "redirect_url": "",
    "primary_ip": "<>",
    "certinfo": [],
    "primary_port": 443,
    "local_ip": "<>",
    "local_port": 39562,
    "request_header": "POST <URL> HTTP/1.1 Host: <HOST> User-Agent: GuzzleHttp/6.2.1 curl/7.51.0 PHP/5.5.38 Content-Type: application/json Connection: close Transfer-Encoding: chunked "
}

Then it throws:
cURL error 18: transfer closed with outstanding read data remaining (see http://curl.haxx.se/libcurl/c/libcurl-errors.html

To sum up..
I've set a number of timeout variables, but none that I've set have been able to rid me of this insanity. Can anyone show me the light?


text:
Q: How can I access this value in an object inside an object from this Api response? So I'm trying to get the value of faceit_elo that is inside the csgo object
I've tried doing data.games.csgo.faceit_elo but it doesn't work.
Does anyone have an idea how to get this value?
Thank you!

Edit: Whenever I try to get the faceit_elo value, or just try to console.log(data.games.csgo), it just says process isn't defined. But when I try to get the value of avatar (data.avatar) there isn't any issue with that. I don't think there is an issue with the code, I just don't know how to access the faceit_elo
Edit:
I've figured out the error, it was on the setData(response), I had to change it to setData(response.games.csgo) so I could access the faceit_elo value.
This is for react-native.
As for a normal javascript app, you just get the value the same as javascript opjects.

A: It seems like you're getting the response as a JSON format.
Try this:
JSON.parse(data).games.csgo.faceit_elo


text:
Q: Setting default schema hibernate In eclipse I configured a database connection and I set up my JPA project to use it.
In my entity classes, I get the following error:
Schema "ROOT" cannot be resolved for table "XXX"
In the project's JPA settings, there is a check box to "Override default schema from connection" with the schema set to "ROOT" by default.
I can not change that because when I check the checkbox, the schema dropdown is empty.
How do I force eclipse to use the correct schema? What is the correct schema name anyway? I only know the database / catalog name.

A: You can set the default schema in the JPA properties for hibernate
<prop key="hibernate.default_schema">application_schema</prop>


text:
Q: How to use ROW_NUMBER() function mysql after the ORDER BY? SELECT user.id
      ,user.emp_id
      ,user.name,COUNT(transfer.record_name) AS current_rank
      ,ROW_NUMBER() OVER () AS count
FROM transfer AS transfer
LEFT JOIN users AS user ON user.emp_id= transfer.user_id
WHERE transfer.lobs= 0
AND transfer.shift_date = '2020-03-27'
GROUP BY user.emp_id
ORDER BY current_rank DESC

This query will give me a result of like this:
user.id|   user.emp_id|   user.name|   current_rank|   count
25           1234          test1           4             4
30           4321          test2           2             2
18           5678          test3           1             1
12           8765          test4           1             3

My goal is to use ORDER BY DESC first so that I can order the current_rank and the count column should have the count of:
user.id|   user.emp_id|   user.name|   current_rank|   count
25           1234          test1           4             1
30           4321          test2           2             2
18           5678          test3           1             3
12           8765          test4           1             4

How can I use the ROW_NUMBER() function after I ORDER BY my current_rank column?
Thank you any help. I will appreciate it.

A: The result of ROW_NUMBER() is not affected by the sort in the query.
Instead, it accepts an ORDER BY option within its OVER clause: without it, the ordering of ROW_NUMBER() is undefined, meaning that the database is free to order the rows as it likes. You may observe that the same ordering is used over consecutive executions, but the database does not guarantee it.
So, do add an ORDER BY to the window function:
ROW_NUMBER() OVER (ORDER BY COUNT(transfer.record_name) DESC) AS count