text:
Q: Required order for specifying restful routes in Laravel 4? I'm trying to understand routing in Laravel 4. I read a good post here on StackOverflow and a link to beware the route to evil, a post about manually specifying routes. I like the idea of specifying my routes manually and having the routes.php act as documentation. But it seems like I need to be cautious about the order of my Routes if I'm going to specify my own instead of using Route::resource() If I have the new or create route before the show then I won't be routed to the show because of the variable in URI? The order in which the routes are defined is important right?
// This will not work if I try and browse to dogs/new
Route::get('dogs', array('as' => 'dogs', 'uses' => 'DogsController@index'));
Route::get('dogs/{dogs}', array('as' => 'dog', 'uses' => 'DogsController@show'));
Route::get('dogs/new', array('as' => 'new_dog', 'uses' => 'DogsController@create'));

It seems I need to make sure that the dogs/new comes before the dogs/{dogs} for new to return correctly. I'm not clear on what {dogs} does or that's different from (:any) or {any} I've seen a few different uses in examples and pseudo code. I see that /new is the same as {...} when the route is before the more specific is the {} like a wildcard in Laravel 4? Is the (:...) the old way?
As an aside I've noticed a different naming convention from some of the examples I've seen when I run php artisan routes with a resource route like Route::resource('photos', 'PhotosController'); The method and named route for post to index to a create a new resource is named photos.store and @store. The method and named route for a link to a form to create a new resource is photos.create and @create. Is that Laravel 4 thing or conventions in other frameworks?

A: Route::get('dogs/{dogs}', array('as' => 'dog', 'uses' => 'DogsController@show'));

The above url expecting a parameter after dogs segment.
for example: http://laravel.com/dogs/xyz, http://laravel.com/dogs/new
after dogs url segment, Laravel will accept anything. So, your another routing will never executed for the route parameter.
Route::get('dogs/new', array('as' => 'new_dog', 'uses' => 'DogsController@create'));

More about route parameters:
http://laravel.com/docs/routing#route-parameters
Resource Controllers
Laravel and Ruby on rails support resource full routing. I think, Tailor borrow the resource full routing idea from Ruby on rails.
The following routes will generate if you use resource controller:
index
create
store
update
show
edit
destroy

http://guides.rubyonrails.org/routing.html
http://laravel.com/docs/controllers#resource-controllers


text:
Q: Android System Module does not generate output on build I am experiencing a problem while building android source code(Nougat). I have a system module named poweroffhandler, written in C++ and has Android.mk file as follow.
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)

LOCAL_SRC_FILES:= \
    #src_files

LOCAL_SHARED_LIBRARIES := \
    #libraries

LOCAL_MODULE:= poweroffhandler

include $(BUILD_EXECUTABLE)

When i add the file $(error error_message) it crashes(with error message "error_message") and stops the whole build.(So the module is included the building sequence) But it does not produce any output after build sequence.
I've tried creating a .rc file associated with it as follows.
Added Android.mk file ->
LOCAL_INIT_RC := PowerOffHandler.rc

Created a new file named PowerOffHandler.rc
service poweroffhandler /system/bin/poweroffhandler
    class core
    user graphics
    group graphics audio
    disabled
    oneshot

When i create an .rc file it does produce an output at intermediates folder but not in the system/bin folder.
And the weird part is i can build module with saying from project root: make poweroffhandler. Then i have no problem at all, problem is i can't use build all scripts for this module(so i can't proceed autonomous integration).
Any help will be appreciated, thank you

A: I found the answer, when you write a system module:

*

*You need to register your Android.mk (for example by saying include $(call all-subdir-makefiles) at top level folder)

*You need to register your module (specified by LOCAL_MODULE:= poweroffhandler) to {root}/build/target/product/embedded.mk by saying PRODUCT_PACKAGES += poweroffhandler

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass byte[] array from InputStrem to OutputStream? I have stored my image as mediumblob in database
In my Image bean class I have store photo property as byte[] like
private byte[] photo;

// getter and setter method for photo

I get image from database using to store in Image bean class
image.setPhoto(resultset.getBinaryStreams(1));

then i get the image in Servlet as:
InputStream input = null;
OutputStream output = null;
try {
    input = new ByteArrayInputStream(image.getPhoto());

    output = // What type of stream should I use here

    byte[] buffer = new byte[10240];
    int length;
    while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
} finally {
    output.flush();
    input.close();
}

Questions:

*

*WHat should I write at output line to show photo using response.getOutputStream or something else?

*Is this method correct or is there any better way?

A: Your output stream can be that stream returned by response.getOutputStream() directly. Just be sure to flush the stream after writing all the data to it.
If your servlet container isn't buffering output streams, you can consider wrapping the output in a BufferedOutputStream.


text:
Q: as3 - Error #1009, an object is null and bugged with timer When the player touches the door, the next level is supposed to be added and the previous level should be removed. However in the game, the next level does get added and everything works, but the output shows this issue.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.utils::Timer/tick()

This is the enterframe:
if (player.collisionArea.hitTestObject(door0))
        {
            var timer: Timer = new Timer(1000, 1);
            timer.addEventListener(TimerEvent.TIMER_COMPLETE, fade);
            timer.reset();
            timer.start();
        }

This is the timer:
function fade(event: TimerEvent)
    {
        removeEventListener(TimerEvent.TIMER_COMPLETE, fade);

        var pageTwo: PageTwo = new PageTwo;
        parent.addChild(pageTwo);
        this.parent.removeChild(this);

    }

This is in the "previous level" class. "this" is itself (previous level) and "pageTwo" is (next level).
So, the output indicates the error is at "parent.addChild(pageTwo);". However if I remove that, the output indicates the issue is from "this.parent.removeChild(this);
I assume it's because the child is removed that's why there is a null issue. But how do I solve this error coming from the output? Am I removing the movieclip the wrong way?

A: Your problem is coming from this line :
parent.addChild(pageTwo);

because in your code as this condition
if (player.collisionArea.hitTestObject(door0))

is true, you will create another Timer object which when its TimerEvent.TIMER_COMPLETE event is fired, it will try to add a new PageTwo instance to a null parent and that's why the error is fired.
So to avoid that, you can remove the Event.ENTER_FRAME event listener at the first time when that condition is true or if you still need it (the Event.ENTER_FRAME event listener) you have to verify your condition to avoid such behavior.
Also, your timer var should be declared as global to be accessible from the fade() function to be able to remove its TimerEvent.TIMER_COMPLETE event listener which you are trying to remove from your current object.
Hope that can help.


text:
Q: Nunit SetupUpFixture syntax What is the proper syntax to use when trying to implement the SetUpFixture ability in Nunit. This is what I have but I keep getting an error:
namespace Testing
{
    [SetUpFixture, RequiresSTA]
    public class SetupClass
    {
        public IE CASsite = new IE("awebsite");

        [SetUp]
        public void Setup()
        {

        }

        [TearDown]
        public void TearDown()
        {
            CASsite.Dispose();
        }

    }

    [TestFixture, RequiresSTA]
    public class Tests : SetupClass
    {
        [Test]
        public void DoSomething()
        {

         }
    }
}

The error I keep receiving is : Failure: TestFixtureSetUp failed in SetupClass

A: Do you have more than one SetUpFixture defined for your namespace Testing?
Per the docs,

Only one SetUpFixture should be created in a given namespace.

Your Tests class derives from your SetUpFixture class.  You don't need to do that.  The SetUpFixture class' SetUp and TearDown will run automatically for all classes in that namespace.

A: My guess would be that your IE class is failing to initialize.


text:
Q: Jquerymobile Slider range + In Jquerymobile range slider, I can set a value from 0 to 100 and it will show 0 to 100. In my case, I would like to set the range from 0 to 100, and 100+. If the user pushes to end, instead of showing the value of 100, how can I show it as 100+?

A: The inputs in the jQM rangeslider are type="range". This type only accepts numbers, so the text '100+' cannot be set as the value of the input.
One workaround could be to just position a '+' next to the 100:

Working DEMO

In the rangeslider markup, I have added a  with a class of labelPlus:

    Rangeslider:
    <input type="range" name="range-1a" id="range-1a" min="0" max="100" value="40" />
    Rangeslider:
    <input type="range" name="range-1b" id="range-1b" min="0" max="100" value="80" />
    +

The labelPlus class CSS initially hides the span but absolutely positions it in the correct spot:
.labelPlus{
    display: none;
    position: absolute;
    right: 0px;
    font-size: 14px;
    font-weight: bold;
    text-align: right;
    width: 48px;
    line-height: 30px;
    margin-right: 18px;
    margin-top: 8px;
}

Finally in javascript we handle the change event on the input and check to see if we are at 100. If so, show the span:
$("#range-1b").on("change", function(){
    var val = $(this).val();
    if (parseInt(val) >= 100) {
        $(".labelPlus").show();
    } else {
        $(".labelPlus").hide();
    }
});

A: I have created Fiddle.
 $(function() {
     $( "#slider" ).slider({
      range: true,
       min: 0,
       max: 110,
         slide: function( event, ui ) {
             if(ui.value>100)
             {
                 $("#ammount").text("100+")
             }
             else
             {
$( "#ammount" ).text(ui.value );
             }
         }
     });
});


text:
Q: PHP include() or require() I understand the functionality and differences of include(), require(), include_once(), require_once().
Please can someone tell me some real world practical usage of them in projects. I know that common functions can be stored in a separate file and can be imported to improve manageability.
What are other common usage of them, for example, when database accessing, etc? Can they be used to improve security, etc.?

A: It's mainly for code re-usability - this page sums it up rather well:

This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file.

It's used in many many PHP based platorms (Wordpress, Magento etc) and one of the common uses is for headers and footers.
UPDATE
Regarding Security
They can lower or higher security depending on how you use them. Remote file inclusion is an example of how it can lower page security. Something like:
<?php
$page = isset($_GET['page']) ? $_GET['page'] : 'home';
require $page . '.php';
?>

Imagine that at example.com/malice.php a file exists and our script is located at site.com/index.php. The attacker will do this request: site.com/index.php?page=www.example.com/malice. This file will get executed when it is included and it could write a new file to the disk.
An example where security could be improved:
<?php
// This script from your servers webroot
require '../public_index.php';
?>

This will access a file from outside you webroot. Default apache web users do not have premissions to view anything outside the webroot therefore they should never be able to access public_index.php (unless they obtained credentials of a user that was able to access - root for example).
A real world application of this kind of measure would be Wordpress' wp-config.php file which can be placed outside the servers webroot.
Source
A brief description outlining the difference between using require & require_once
require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page).
So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.
Source
I hope this helps.


text:
Q: How to declare symmetric self-referential many-to-many relationship in SQLAlchemy for storing directed graph from sqlalchemy import DateTime, Table, Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

__all__ = [ "GraphNode" ]

Base = declarative_base()

graph_edges = Table(
    'graph_edges', Base.metadata,
    Column('from_node_id', Integer, ForeignKey('graph_nodes.id'), primary_key=True),
    Column('to_node_id', Integer, ForeignKey('graph_nodes.id'), primary_key=True)
)

class GraphNode(Base):
    __tablename__ = 'graph_nodes'
    id = Column(Integer, primary_key=True, autoincrement=False)
    node_data = Column(String(50), nullable=False)

    from_me = relationship("GraphNode", secondary=graph_edges,
                           primaryjoin=id==graph_edges.c.from_node_id,
                           secondaryjoin=id==graph_edges.c.to_node_id)
    to_me = relationship("GraphNode", secondary=graph_edges,
                         primaryjoin=id==graph_edges.c.to_node_id,
                         secondaryjoin=id==graph_edges.c.from_node_id)

When I do this, I get this error from SQLAlchemy:
SAWarning: relationship 'GraphNode.to_me' will copy column graph_nodes.id to column graph_edges.from_node_id, which conflicts with relationship(s): 'GraphNode.from_me' (copies graph_nodes.id to graph_edges.from_node_id). If this is not the intention, consider if these relationships should be linked with back_populates, or if viewonly=True should be applied to one or more if they are read-only. For the less common case that foreign key constraints are partially overlapping, the orm.foreign() annotation can be used to isolate the columns that should be written towards.   To silence this warning, add the parameter 'overlaps="from_me"' to the 'GraphNode.to_me' relationship. (Background on this error at: https://sqlalche.me/e/14/qzyx)
It sounds like SQLAlchemy is noticing that putting something in one node's from_me list will result in a change to some other node's to_me list. This is the desired behavior. I want to be able to traverse the links backwards as well as forwards.
Is there any way to do this properly without SQLAlchemy complaining at me?

A: Here is what solved the problem. The solution was sort of in the error message, and I'm not completely sure why it worked. But, here it is:
from sqlalchemy import DateTime, Table, Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

__all__ = [ "GraphNode" ]

Base = declarative_base()

graph_edges = Table(
    'graph_edges', Base.metadata,
    Column('from_node_id', Integer, ForeignKey('graph_nodes.id'), primary_key=True),
    Column('to_node_id', Integer, ForeignKey('graph_nodes.id'), primary_key=True)
)

class GraphNode(Base):
    __tablename__ = 'graph_nodes'
    id = Column(Integer, primary_key=True, autoincrement=False)
    node_data = Column(String(50), nullable=False)

    from_me = relationship("GraphNode", secondary=graph_edges,
                           primaryjoin=id==graph_edges.c.from_node_id,
                           secondaryjoin=id==graph_edges.c.to_node_id,
                           back_populates="to_me")
    to_me = relationship("GraphNode", secondary=graph_edges,
                         primaryjoin=id==graph_edges.c.to_node_id,
                         secondaryjoin=id==graph_edges.c.from_node_id,
                         back_populates="from_me")

Basically, I added the back_populates parameter to each relationship. It had the effect I desired.
I really wish I understood what was going on better. I feel more like I'm following a cookbook than starting with ingredients and deciding what sort of meal I want to make with them. I always hate doing that when I'm programming because I'll not understand what's critical and what isn't and make a tiny change that turns out to be massively important.


text:
Q: Raphael JavaScript Library on iPhone I've included the Raphael JavaScript library into an iPhone project, however I'm not able to get it to work in a webview. I have a basic test where I should get a red circle. It works on Safari on the Mac but I can't get it to work on the iPhone simulator. I only get the "Hello This is a Raphael Test" text.
When I "Show Package Contents" on the app file in the Debug-iphonesimulator it shows that the JavaScript files are included.
I'm obviously not doing something right. Any ideas?
Below is the viewDidLoad content.
 - (void)viewDidLoad {
   [super viewDidLoad];

   NSString *htmlPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"TestRaphael.html"];
   NSString *htmlContent = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];

   [myWebView loadHTMLString:htmlContent baseURL:nil];
}

Below is the TestRaphael.html file.

<title>Raphael Test</title>

Hello

This is a Raphael Test

A: This seems to do with how xCode perceives the .js-file you added.
Did you get a warning like:
warning: no rule to process file '$(PROJECT_DIR)/raphael.js' of type sourcecode.javascript for architecture i386

Then read more about it over here


text:
Q: Command not found running in shell script I'm running git-bash on windows.  I feel the issue I'm facing is more of a NIX geared question than windows.  I have a shell script:
build.sh
myProject="../myProject/"
build="gulp build"

cd "${myProject}"
pwd
"${build}"

When I run this script I get error

gulp build: command not found

When I run "gulp build" directly in the shell, running these same commands by hand then everything works.  I tried executing the script via:
. build.sh and just build.sh
Same error either way.  How can I run a script that can access gulp/npm?  Why does this fail even when I am sourcing the script?

A: Do not quote "${build}". As it expects in such a case gulp build command (with a space inside) and reports rightfully such command does not exist.
Execute simply by ${build}. Then shell will treat it as a command and arguments.
myProject="../myProject/"
build="gulp build"

cd "${myProject}"
pwd
${build}

A: Quoting "${build}" prevents word splitting, so it has the same effect here as writing "gulp build" (with quotes), which would search for an executable called gulp build with a space inside the name; and not as writing gulp build, which executes gulp with a build argument.
Concluding, the last line of your script should be:
${build}


text:
Q: Grand Total in Google visualization dashboard table I have a simple Google visualization dashboard sample with one categorypicker control and a table. My code is given below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

I am stuck with a problem that I want the grand total of the values at the end. How can I add one more row at the end of table so that it shows the Grand total of all values in second column. i.e., initially it should show the total of all four rows and when filter is applied it should show the total of filtered row values.

A: You can just add a row before you "draw" the chart that shows the total:
For instance:
  var data = google.visualization.arrayToDataTable([
    ['Year', 'Austria', 'Belgium', 'Czech Republic', 'Finland', 'France', 'Germany'],
    ['2003',  1336060,   3817614,       974066,       1104797,   6651824,  15727003],
    ['2004',  1538156,   3968305,       928875,       1151983,   5940129,  17356071],
    ['2005',  1576579,   4063225,       1063414,      1156441,   5714009,  16716049],
    ['2006',  1600652,   4604684,       940478,       1167979,   6190532,  18542843],
    ['2007',  1968113,   4013653,       1037079,      1207029,   6420270,  19564053],
    ['2008',  1901067,   6792087,       1037327,      1284795,   6240921,  19830493]
  ]);

  function getSum(data, column) {
    var total = 0;
    for (i = 0; i < data.getNumberOfRows(); i++)
      total = total + data.getValue(i, column);
    return total;
  }

  alert(getSum(data, 1));

This will give you a nice alert box saying 9920627
1336060+1538156+1576579+1600652+1968113+1901067=9920627
You can just add a line to the end saying something like:
addRow('Total', getSum(data, 1));
If the question is on how to get the sum of a column that's been filtered by your sliders and the like, that's a different beast, and something that this jsfiddle by asgallant may be better for:

google.load('visualization', '1.1', {packages: ['controls']});
google.setOnLoadCallback(drawVisualization);

function drawVisualization() {
    // Prepare the data
    var data = google.visualization.arrayToDataTable([
        ['Name', 'RoolNumber', 'Gender', 'Age', 'Donuts eaten'],
        ['Michael', 1, 'Male', 12, 5],
        ['Elisa', 2, 'Female', 20, 7],
        ['Robert', 3, 'Male', 7, 3],
        ['John', 4, 'Male', 54, 2],
        ['Jessica', 5, 'Female', 22, 6],
        ['Aaron', 6, 'Male', 3, 1],
        ['Margareth', 7, 'Female', 42, 8],
        ['Miranda', 8, 'Female', 33, 6]
    ]);

    // Define a slider control for the Age column.
    var slider_rn = new google.visualization.ControlWrapper({
        controlType: 'NumberRangeFilter',
        containerId: 'control2',
        options: {
            filterColumnLabel: 'RoolNumber',
            ui: {
                labelStacking: 'vertical'
            }
        }
    });

    var slider = new google.visualization.ControlWrapper({
        controlType: 'NumberRangeFilter',
        containerId: 'control1',
        state: {
            lowValue: 10,
            highValue: 40,
            highThumbAtMax: true
        },
        options: {
            filterColumnLabel: 'Age',
            ui: {
                labelStacking: 'vertical'
            }
        }
    });

    // Define a category picker control for the Gender column
    var categoryPicker = new google.visualization.ControlWrapper({
        controlType: 'CategoryFilter',
        containerId: 'control3',
        options: {
            filterColumnLabel: 'Gender',
            ui: {
                labelStacking: 'vertical',
                allowTyping: false,
                allowMultiple: false
            }
        }
    });

    // Define a Pie chart
    var pie = new google.visualization.ChartWrapper({
        chartType: 'PieChart',
        containerId: 'chart1',
        options: {
            width: 300,
            height: 300,
            legend: 'none',
            title: 'Donuts eaten per person',
            chartArea: {
                left: 15,
                top: 15,
                right: 0,
                bottom: 0
            },
            pieSliceText: 'label'
        },
        // Instruct the piechart to use colums 0 (Name) and 3 (Donuts Eaten)
        // from the 'data' DataTable.
        view: {
            columns: [0, 4]
        }
    });

    // Define a table
    var table = new google.visualization.ChartWrapper({
        chartType: 'Table',
        containerId: 'chart2',
        options: {
            width: '500px'
        }
    });

    // get average and geometric mean values
    google.visualization.events.addListener(table, 'ready', function () {
        var group = google.visualization.data.group(table.getDataTable(), [{
            // we need a key column to group on, but since we want all rows grouped into 1,
            // then it needs a constant value
            column: 0,
            type: 'number',
            modifier: function () {
                return 1;
            }
        }], [{
            // get the average age
            column: 3,
            label: 'Average Age',
            type: 'number',
            aggregation: google.visualization.data.avg
        }, {
            // get the geometric mean of age
            column: 3,
            label: 'Geometric Mean of Age',
            type: 'number',
            aggregation: function (values) {
                var product = 1;
                var n = values.length;
                for (i = 0; i < n; i++) {
                    product = product * values[i];
                }
                return nthroot(product, n);
            }
        }]);
        document.getElementById('avg').innerHTML = group.getValue(0, 1);
        document.getElementById('geomean').innerHTML = group.getValue(0, 2);
    });

    // Create a dashboard
    new google.visualization.Dashboard(document.getElementById('dashboard')).
    // Establish bindings, declaring the both the slider and the category
    // picker will drive both charts.
    bind([slider, slider_rn, categoryPicker], [table, pie]).
    // Draw the entire dashboard.
    draw(data);
}

// nthroot function courtesy of http://gotochriswest.com
// see http://gotochriswest.com/blog/2011/05/06/cube-root-an-beyond/
// special function necessary because Math.pow(-8, 1/3) returns NaN instead of -2
function nthroot(x, n) {
    try {
        var negate = n % 2 == 1 && x < 0;
        if (negate) {
            x = -x;
        }
        var possible = Math.pow(x, 1 / n);
        n = Math.pow(possible, n);
        if (Math.abs(x - n) < 1 && (x > 0 == n > 0)) {
            return negate ? -possible : possible;
        }
    } catch(e){}
}


text:
Q: Form validation in multiple records in for loop I have here an php records, I have an edit page for multiple records and has form validation. My problems is in my for loop for calling multiple records.

Just like in the picture above,my PR# textbox had a message even the two PR# that has id of 000174 and 000176 have a correct input. How to make my validation works for only textbox that has an invalid inputs per ID.
Help please?
<form name="register_form" id="register_form" action="" method="post">

<?php
$id=$_POST['checkbox'];
$drop=$_POST['drop'];
$tier_two=$_POST['tier_two'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
    $result1 = $mysqli->query("
SELECT a.item_name, a.item_description, a.counter, b.counter, b.pr, b.total_quantity
FROM app a
LEFT OUTER JOIN purchase_request b
ON a.counter=b.counter
WHERE a.counter='$id[$i]'
    ");
    while ($row = $result1->fetch_assoc())
      { ?>

 ID <input name="counter[]"  type="text" value="<?php echo $row['counter'] ?>" readonly="readonly"/>

 Item <input name="item[]"  type="text" value="<?php echo $row['item_name'] ?>" readonly="readonly"/>

 Description <input name="desc[]"  type="text" value="<?php echo $row['item_description'] ?>" readonly="readonly"/>

 PR Quantity
            <input name="pr_qty[]" id="pr_qty[]"  class="textbox tb1" type="text" value="<?php echo $row['total_quantity']; ?>" />

 PR # <input name="pr[]"  type="text" value="<?php echo $row['pr'] ?>" />

      <?php
      }
}

?>

<input name="submit" type="submit" id="sbtBtn" value="Update">
</form>

And this is my Script

A: the id of span tag is same for every record,so if error is there in any record it will be reflected in the span tag of every record.Use different id for every record is the solution...

A: you have to loop every input like that
$("input:text[name=counter]").each(function(){
    alert($(this).val());
});


text:
Q: Can't include Spreadsheet Excel Writer I have a problem with Pear package Spreadsheet Excel Writer. I want to generate excle file from php and found this package on internet.
I copied smaple code from official page, but it doesn't work. Of course I have the pear installed on my server(Deb7, apache2, php5). I try to find where the app is not work and found that it doesn't include a file.
include_once 'Spreadsheet/Excel/Writer.php'

I installed the package by the command:
pear install -f OLE
pear install -f Spreadsheet_Excel_Writer

I don't have any idea why that package doesn't include. I try including other packages and it forks fine. I inspected files in that package and recognized that Spreadsheet/Excel/Writer/Worksheet.php  may cause the problem(I included each file in package and only this can't get included).
Please help me, maybe you now other way to generate excel from php.

A: You need to setup your include path correctly before you can use the pear-installed files.
Follow the instructions in http://pear.php.net/manual/en/installation.checking.php
Don't forget to restart the web server after modifying php.ini.


text:
Q: Xamarin.iOS 11 Resources are Not Loaded I recently updated my instance of Visual Studio 2017 to version 15.3.5 and in the process updated Xamarin.iOS to version 11.0.0.0.
Since updating, several of the resources in my project have stopped working. When deploying to a device, the app icon is not displayed (instead blank icon is shown), and Bundle Resources like a custom font file (.tff) is no longer loading. There has been no code changes to the stable branch of our build, but just updating appears to have broken multiple resources.
Has anyone else encountered this? Does the Xamarin team know about this (I'm looking at you Xamarin folks who said to post my questions in SO)?
EDIT:
Here is the guide for updating an app (doesn't appear to apply to the issue I'm seeing): Xamarin Update to iOS11.
Here's a specific example of code that has suddenly stopped working despite no code changes:
UIFont customFont = UIFont.FromName("streamline-24px", (float)this.IconButton.IconSize);

The .tff file is the same, but FromName() yields a null value now.

A: I figured it out, hopefully this helps anyone with the same configuration that upgrades their Xamarin.Forms or Xamarin.iOS project from Xamarin.iOS release 10 to 11. I was lucky to happen upon it after reading Kevin Mullins answer at Xamarin saying that you should:

*Ensure that all of you icon files are in place (either via the info.pst file or an Image asset).

My Info.plist > Visual Assets looked like this (which worked prior to the update)

Selecting Use Asset Catalog and selecting a value resolved the issue.


text:
Q: Google Sheets Chart Axis Title does not update when source cell is formula I want the Google Sheets chart x-axis title to change when the data in a chart changes. I've made a simple example to demonstrate the problem. In the following animated gif (click to see greater detail) the x-axis title does not update when the data in the scatter chart changes.

Apparently this happens because the source cell for that title (A1) is itself a formula (to give the average of the x-values -- in my real-world example, it's more complicated than that).
The only way I know to fix this is to delete the chart and make a new one, as shown in the last part of the animation. But with my real-world example, this is a lot more troublesome.
Thanks for any help.

A: I have been running a couple of tests and have some experience on how the charts are created under Sheets in comparison to the ones in Excel.
There have been multiple forums discussing this particular issue, the main issue with it is the fact that this portion of the Chart is only a title text and does not linked to any portion to the table or that you cannot select a custom formula to be used for updates. It is also mentioned over the official documentation that you can only manual edit this titles.

As an alternative, you could implement a script so it changes the chart title for the average.

function onOpen(){
  SpreadsheetApp.getUi().createMenu('Charts').addItem('Update title of the first chart from active cell', 'myFunction').addToUi();
}
function myFunction() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var chart = sheet.getCharts()[0];
  chart = chart.modify()
  .setOption('title', sheet.getActiveCell().getValue() || 'Empty')
  .build();
  sheet.updateChart(chart);
}

The portion of this code has been found and discussed over this thread.
I also believe that it should be a feature directly on Sheets and it should be implemented in the future, you can send feedback from the help option or go to the Feature ideas portal:

*

*https://www.googlecloudcommunity.com/gc/Feature-Ideas/cmp-p/grouphub:workspace-ideas-group


text:
Q: Sorting Gridview breaks ModalPopUp in GridView I have a gridview that has linkbuttons that call modalpopups and textboxes with values. I am trying to implement sorting for the gridview, but the if(!ispostback) statement I need for sorting prevents the modalpopup from appearing. It also does not sort the textboxes in the gridview. Is there a way to implement sorting without using ispostback in the page_load?
Here is the code for the modalpopup, gridview binding and sorting.
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["sortOrder"] = "";
            Bind_Gridview("", "");
            loadModals();
        }
    }
protected void viewModal(object sender, EventArgs e)
{
...
     mainPanel.Controls.Add(exstModal);
        mainPanel.Controls.Add(exstModalBox);
        exstModalBox.Show();
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        Bind_Gridview(e.SortExpression, sortOrder);
    }

public string sortOrder
    {
        get
        {
            if (ViewState["sortOrder"].ToString() == "desc")
            {
                ViewState["sortOrder"] = "asc";
            }
            else
            {
                ViewState["sortOrder"] = "desc";
            }

            return ViewState["sortOrder"].ToString();
        }
        set
        {
            ViewState["sortOrder"] = value;
        }
    }

protected void gv1_RowCommand(object sender, GridViewRowEventArgs e)
    {
...
CheckBox cb = new CheckBox();
        TextBox ca = new TextBox();
        ca.Width = 20;
        TextBox cga = new TextBox();
        cga.Width = 20;

if (e.Row.RowType == DataControlRowType.DataRow) //Foreach row in gridview
        {

    while (dr1.Read())
            {
                ca.Text = dr1["cyla"].ToString();
                cga.Text = dr1["cga"].ToString();
                checkText = dr1["completed"].ToString();
                if (checkText == "True")
                {
                    cb.Checked = true;
                }
                else
                {
                    cb.Checked = false;
                }
            }
...
            dr1.Close();
            conn1.Close();
            e.Row.Cells[6].Controls.Add(ca);
            e.Row.Cells[8].Controls.Add(cga);
            e.Row.Cells[9].Controls.Add(cb);
...
}

A: A GridView has built-in sorting capabilities. Depending on the dataset you are using to populate the data, you likely don't need to manually handle anything manually, let alone with the ViewState.
Check out the second example on this MSDN page and note that it never does anything manually with the ViewState... the OnSorting and OnSorted events are there just to display extra information or to impose requirements:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
If you post a bit more of your code (including your .aspx pages, the markup for the modal popups, and the code for the loadModals() function, we might be able to better help you.


text:
Q: How do you display tasks from a to-do list, in Rails? I'm trying to make the complete_task page display only tasks that have been completed. The schema uses a boolean value of true when the item is checked as complete. How do I setup a method in the task_controller.rb file, and reference in the task/complete_task view to accomplish this, while still paginating the results?
Right now my task_controller.rb file has this for the complete_task method:
def complete_task
    @tasks = current_user.tasks.paginate(page: params[:page], per_page: 10)
  end

This is just displaying all the user's tasks, like the index page. I'm guessing I should add a (params[:id]) to the .task part of the code? I don't know how to check the value of the task status boolean which is true or false.
The schema for tasks looks like this:
create_table "tasks", force: :cascade do |t|
    t.string   "name"
    t.boolean  "status"
    t.datetime "created_at",        null: false
    t.datetime "updated_at",        null: false
    t.integer  "user_id"
    t.date     "completition_date"
  end

My repo is Here.
Thank you.

A: You can use @tasks = current_user.tasks.where(status: true)
Which will return the current_user's tasks that are complete.


text:
Q: Why is only half of a collection view getting displayed? I have used MMPlayerView (GitHub link here) to add videos into a collection view, in the collection view the image gets replaced by a video in the code (from the demo). I took the MMPlayerView's demo project and changed stuff to fit my needs and then implemented it into my project to get something like this show in this video.
Now I'd like to obviously move the collection view up towards the buttons at the top of the screen, and later on I will use multiple collection views like that to get the style of the app store more like, just showing videos. Since I took the code from the demo I'm not too sure on some things, when I copied the project's demo the collection view was made for scrolling through it vertically, so it takes up the whole screen, so the collection view was constrained to the bottom of the view:

Which causes this to show in the app (I don't understand why it's so far away from the top when its constrained by 10 points):

Now I want to obviously want to remove the bottom constraint and constrain it by it's height instead so I can have multiple collection views, (probably through the use of table views), so I removed the constraint to the bottom of the view and added a height constraint for 250 points:

Which caused the app to look like this:

Why?? I'm guessing it has something to do with this part of the view controller code:
extension HomeViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let m = min(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
    return CGSize(width: m, height: m*0.75)
}

I want to keep the collection view's width the same width of the view, so the width is fine, it's just the height here. When I try and set the height to a constant value of 250 (the same as the height constraint) it does the same thing (only shows half of it) but shrinks the video a little bit. What can I change?

A: Taking a quick look at the Example app from MMPlayerView...
Change the height value in sizeForItemAt to the height of your collection view (250 per your question):
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let m = min(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
    return CGSize(width: m, height: 250.0)
    //return CGSize(width: m, height: m*0.75)
}

I'm assuming you were getting the same error messages in debug console as I got:

The behavior of the UICollectionViewFlowLayout is not defined because:
the item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values.

and it should also have printed the Collection View properties, including:

adjustedContentInset: {0, 0, 200, 0};

So the collection view has a Bottom inset of 200.
If you search that example project for contentInset you'll find this line in the view controller's viewDidLoad() function:
playerCollect.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 200, right:0)

If you comment-out / remove that line, you should now see the full cell.
Might be a good idea to get a handle on collection views to begin with and then review that example project for the video implementations in your app.


text:
Q: How to set Nginx for non root location properly? I would like to set up Nginx for Flask applications with uWSGI server. I have set the proxy over unix socket as the following.
The initial Nginx configuration:
    server {
        location / {
            include uwsgi_params;
            uwsgi_pass unix:/tmp/my_app.sock;
        }
    }

The uWSGI configuration:
    [uwsgi]
    socket = /tmp/my_app.sock
    virtualenv = /home/user/venv/my_app
    chdir = /home/user/apps/my_app
    wsgi-file = index.py
    callable = app
    processes = 4
    threads = 2

This works but when I change the location in the Nginx config I have get a 404 Not Found error.
    server {
        location /other_location/ {
            include uwsgi_params;
            uwsgi_pass unix:/tmp/my_app.sock;
        }
    }

The error possibly comes from the uWSGI server (because for other invalid URL the error page writes the Nginx version). I have checked the uWSGI log but it contains only the details about sending the error page with success.
     => generated 233 bytes in 15 msecs (HTTP/1.1 404) 2 headers in 72 bytes

How can I configure Nginx and uWSGI for working with non root locations?
Is it necessary to set the application route in the source code of the application?
I prefer solutions where I can use the unmodified application code. I like to separate the application development and deployment as possible.


text:
Q: JSON serialization of object with a base class list I am working on a Blazor app that uses the local storage. I want to JSON serialize this data-structure:

The XML serializer does this without a hitch, but de JSON serializer does not include any type-info, so my C's and D's are downgraded to the base class B (and only after making B's constructor public. I have following test code:
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestProject;

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        // setup
        var sut = new A();
        sut.Bs.Add(new C{Number = 9});
        sut.Bs.Add(new D{Text= "Bob"});
        Assert.AreEqual(2, sut.Bs.Count);

        var serialized = JsonSerializer.Serialize(sut);
        // serialized: {"Bs":[{"Key":"C"},{"Key":"D"}]}

        var deserialized  = JsonSerializer.Deserialize<A>(serialized);
        // excepiton:System.NotSupportedException:
        // 'Deserialization of types without a parameterless
        // constructor, a singular parameterized constructor, or a
        // parameterized constructor annotated with
        // 'JsonConstructorAttribute' is not supported.
    }

    public class A
    {
         public List<B> Bs { get; set; }

         public A()
         {
             Bs = new List<B>();
         }
    }

    public abstract class B
    {
        public string Key { get; init; }

        public B()
        {
            Key = GetType().Name;
        }
    }

    public class C : B
    {
        public int Number { get; set; }

        public C():base()
        {
        }
    }

    public class D : B
    {
        public string Text { get; set; } = null!;

        public D() : base()
        {
        }
    }
}

Is there a way to make this work (attributes and or options), or do I have to make shadow properties/fields for separate lists of C's and D's?


text:
Q: in array function php I use in_array() to check whether a value exists in an array like below,
But does not work as expected:
$projectId = $_GET['projectId'];
$userId = $_GET['userId'];

$qr2 = mysql_query("SELECT `userId`,`status` FROM `fndn_ProjectBacker` WHERE `projectId`='$projectId' && `status`='1'");

for($i = 1; $row2 = mysql_fetch_assoc($qr2); $i++) {
    $arr1[$i] = array($row2);
}

if (in_array($userId, $arr1)) {
    echo "True";
}

plz help me!

A: It doesn't work as you want it, because you create a two dimensional array with this:
$arr1[$i]=array($row2);
        //^^^^^^     ^ See here

Remove the array declaration here and you can also change out your for loop with a while loop, e.g.
while($row2 = mysql_fetch_assoc($qr2)){
    $arr1[] = $row2["userId"];
}

if (in_array($userId, $arr1)) {
    echo "True";
}

I also want to welcome you in 2015 and highly recommend to use mysqli_* prepared statements or PDO, they are much safer. (Also see: Why shouldn't I use mysql_* functions in PHP?)


text:
Q: How to add *.txt file package(together with other *.class files) in jar? I need to include *.txt file in package with *.class files after build task.
I know how to add resource in jar. But how to add text file together with *.class files in package?


text:
Q: Hexadecimal and words mixed in Python bytes I'm receiving frames from a websocket server and I'm not sure how to interpret some of the bytes object because they are mixed with actual words inside them.
I get something like this:
  b'\x00\x17\x04\x00\x00\x00\xc0\x05FOCUS\x01\x00\xff\xfc\x00\x05;\xea\x01\x03\xe8\x81'
This one has 'FOCUS' and a ';' in it. I am expecting 'FOCUS' to be part of the payload, but I don't know why it's showing up as is, and not in hex form. Can someone explain what's going on and how I can unpack the rest of the data?
Also, it seems I'm getting the data in reverse order. I think \x81 is supposed to be the first byte of the frame.
I'm using Python 3.6 and the websocket-client lib. Thank you.


text:
Q: Updating some rows dynamically in TableLayout I'm adding rows to my TableLayout dynamically and each row has more than one TextView.
I want to loop for each row in my TableLayout and I want to update some rows (not every row), for example the text of TextView in my rows. How can I manage this?

A: Loop through the children of the TableLayout, they should be TableRows (or another layout) - skip the ones you don't want to update. Loop through or findViewById the children of the TableRow (or whatever) which will be your TextViews
When you add the TextView / CheckBox to the TableRow, you can set the View's id with setId(R.id.id_of_the_view) (which you might want to add to the res/values/ids.xml file).
Then loop through like so:
TableLayout tableLayout = null;
for(int n = 0, s = tableLayout.getChildCount(); n < s; ++n) {
    TableRow row = (TableRow)tableLayout.getChildAt(n);
    TextView name = (TextView)row.findViewById(R.id.tv_name);
}

since you're using row.findViewById, you're looking for a specific id inside a specific row.

A: I recommend using the setTag method to quick reach specific rows, and Views within rows.
For example, lets say you have a CheckBox in a certain column, which represents "isSomethingEnabled". When creating the CheckBox, do setTag("foo").
Use setTag on the row as well, such as setTag("rowKey")
To quickly get to a specific row
TableRow tRow = (TableRow) tLayout.findViewWithTag("rowKey");
And to quickly get to a specific child
View v = tRow.findViewWithTag("foo");


text:
Q: How can I acces a method inside another method in the same class? In my code, is it possible to access method calculate() inside the method calculateSheet()? The 2 methods are in the same class.
Method calculate(), for example, calculates the sum of 2 doubles.
I want method calculateSheet(), to use this method to calculate this for every "cell" in the array sheet[] [].
//calculates every cell in the array.
public void calculateSheet() {
    for(int i = 0 ; i < rows ; i++) { //rows, amount of rows in the array>
        for (int j = 0 ; j < cols ; j++) { //cols, amount of colums in the array.
            sheet[i] [j].**calculate()** ; //method I want to use in the "calculateSheet" method.
        }
    }
}

A: First of all you need that calculations you want to do you have to put them in some variable.
Secondly I believe that you need that your calculate() method need return the result...
Assume that your method calculate is something like:
public double calculate(double a, double b){
    return a+b;
}

then you need to do something like:
public void calculateSheet() {
    double total = 0; //The variable when you going to put the result
    for(int i = 0 ; i < rows ; i++) { //rows, amount of rows in the array>
        for (int j = 0 ; j < cols ; j++) { //cols, amount of colums in the array.
            total += calculate(sheet[i], sheet[j]);
        }
    }
}

A: Lets make the complete code for you,
class{
public double calculate(double num1, double num2){
    return (num1+num2);
}

public void calculateSheet(int[][] sheet) {
    for(int i = 0 ; i < rows ; i++) {
        for (int j = 0 ; j < cols ; j++) {
            sheet[i] [j] = calculate(i, j);
        }
    }
}

}
Here each cell of a 2D array will store the sum of its both indices.


text:
Q: How provide default value in date in primeng I have calendar dropdown, it is working. However, I want to provide default date in it. How can it  do that.
Following is my component as follows:
import {HttpClient} from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { routerTransition } from '../../router.animations';
import { isNumber } from '@ng-bootstrap/ng-bootstrap/util/util';

@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.scss'],
    animations: [routerTransition()]
})
export class DashboardComponent implements OnInit {
   value= new Date();
   today_date: string;

   ngOnInit() {
      this.today_date = this.value.getFullYear() + '-' + this.value.getMonth() + '-' + this.value.getDate();
      console.log(this.today_date)
   }
}

HTML code is as follows:
<div>
     <p-calendar (ngModel)="today_date" [inputStyle]="{'width':'100%'}" dateFormat="yy-mm-dd"></p-calendar>
</div>

It is not picking date up. Console.log out is '2017/10/17'

A: To my understanding, value of p-calendar is of type Date. So a string wouldn't work. Here's what I have for mine and it works quite well:
TS
import * as moment from "moment"; //I use MomentJS and I recommend it also. The snippet is based on MomentJS as well.
calendarDate: Date;
ngOnInit() {
 this.calendarDate = moment().toDate();
}

HTML
<p-calendar [ngModel]="calendarDate"></p-calendar>

EDIT: You have a wrong syntax in your HTML template. (ngModel) does not make any sense. It should be [ngModel] for Property Binding, or (ngModelChange) for Event Binding, or [(ngModel)] for two-way binding.


text:
Q: Eloquent error using with and select together. Segmentation fault When performing select and with in one query builder there's no server error. I just get the following message: <domain> page isnt working. <domain> didn't send any data.
When I check in /var/log/apache2/error.log there is a log of:
child pid 1948 exit signal Segmentation fault (11), possible coredump in /etc/apache2
I've tried using query scopes as mentioned here eg
$posts = Post::with(['image' => function($query){
  $query->select('id');
}])->select('id')->get();

If I change get() to toSql() it only outputs select id from posts;
I've also tried removing the select and passing columns to get() with no luck.
Further investigation:
I've tried setting up GDP to debug apache core dumps, but no dumps seem to get created.
I've since setup xdebug and followed the function stack to it's death here at function loadRelation() inside Eloquent\Builder.php.
Prior to this it calls eagerLoadRelations(array $models) and gets all Post models correctly as a collection of posts with only id attributes, yet on the first iteration of of loading the image relation it dies on
call_user_func($constraints, $relation);
any help or advice would be appreciated.

A: Segmentation fault sounds a bit weird, but try adding user_id to the select so it can do the join e.g.:
$posts = Post::with(['image' => function($query){
  $query->select('id', 'user_id');
}])->select('id')->get();


text:
Q: No SMTP settings button in AWS ses
I am new to AWS and I am trying to configure SMTP but there is no SMTP settings menu in my AWS SES console. My IAM user is an admin user. I have gone through all the sub menus but still cannot find SMTP settings.


text:
Q: how to create a list of values from one key-value pair based on the value of another k-v pair from a list of dictionaries with two key-value pairs I am trying to iterate through a list of dictionaries with the goal of producing a list of lists of values from one k,v pair based on the value of the other k,v pair. Each dictionary contains two k,v pairs, the respective keys of which are the same.
For example, given this list:
dict_list =[{'basket': 1, 'fruit': 'apple'},
            {'basket': 1, 'fruit': 'orange'},
            {'basket': 1, 'fruit': 'peach'},
            {'basket': 2, 'fruit': 'kiwi'},
            {'basket': 2, 'fruit': 'lemon'},
            {'basket': 3, 'fruit': 'grape'}]

I would like to produce this list:
list_list = [['apple','orange','peach'],
             ['kiwi','lemon'],
             ['grape']]

I am having difficulty working through the iteration to achieve segregated lists. So far, I have only been able to get a list of all the fruit values together. Thank you for any suggestions.

A: You can use groupby from itertools.
import itertools

list_list = [[f['fruit'] for f in v] for k, v in itertools.groupby(dict_list, key=lambda x: x['basket'])]

This assumes that the basket entries in dict_list are sorted (or same baskets are next to each other in the list). If that's not the case, just sort before groupby.

A: Here is one way without using groupby:
from collections import defaultdict

dict_list = [
    {'basket': 1, 'fruit': 'apple'},
    {'basket': 1, 'fruit': 'orange'},
    {'basket': 1, 'fruit': 'peach'},
    {'basket': 2, 'fruit': 'kiwi'},
    {'basket': 2, 'fruit': 'lemon'},
    {'basket': 3, 'fruit': 'grape'},
]

def to_list(dlist):
    full_d = defaultdict(list)
    for d in dlist:
        basket = d['basket']
        fruit = d['fruit']
        full_d[basket].append(fruit)
    return list(full_d.values())

print(to_list(dict_list))

The output:
[['apple', 'orange', 'peach'], ['kiwi', 'lemon'], ['grape']]

Or simplifying a little more:
def to_list(dlist):
    full_d = defaultdict(list)
    for d in dlist:
        full_d[d['basket']].append(d['fruit'])
    return list(full_d.values())

A: I know this isn't exactly what you asked, but maybe you should reconsider the way you're structuring things. Consider maybe having a class that can maintain the state of your baskets and return their values like so:
class Basket:
    def __init__(self):
        self.basket = []

    def add_item(self, item):
        self.basket.append(item)

    def get_basket_items(self):
        return self.basket

This is how you could implement the above class into your workflow:
baskets = {}
baskets.update({1: Basket()})
baskets.update({2: Basket()})
baskets[1].add_item("orange")
baskets[1].add_item("apple")
baskets[2].add_item("kiwi")

all_items =[]
for basket in baskets.values():
    all_items.append(basket.get_basket_items())

print(all_items)

Classes are really useful when you want to start doing some funky things with the elements in your data structures. They are a little more flexible in that regard.
Hope that helps!


text:
Q: Paddle Payment - The checkout id must be a valid checkout id I try to integrate Paddle as a payment service in my Next.js App.
I keep getting this error on localhost:

The checkout id must be a valid checkout id

I tried both overlay and inline checkout following this tutorial.
For simplicity I created a minimal html file to test. I get the same error there:

    Buy Now!

I don't have a domain approved but the docs say that localhost should work without. Vendor ID and Product ID are correct of course.
I already contacted the support a few days ago but they barely respond and are not helpful yet. Maybe someone of you know how to fix the problem?


text:
Q: Modal for back button I was wondering..does anyone here knows how can I make a modal that will pop up once browser's back button is clicked just like in Facebook.
I'm using React version 16.9.0 and tried wrapping my component to withRouter and used the this.props.history.action === "pop" inside my componentDidMount() but none working.
I've seen questions the same as mine but it seems outdated with my current react version.
Thanks.

A: I had similar use case I did it the following way. The componentDidMount is from the component which is only rendered once(In my case it's header component - it only renders once in our use case) in the app.
browserBackHandler = (event) => {
    event.preventDefault();
    //do whatever is required here
};
componentDidMount() {
    window.onpopstate = this.browserBackHandler;
}


text:
Q: Ensure the done() callback is being called in this test (Mocha, Chai, Sinon) Looking at other questions, can't really find the cause of the problem. I am trying to import a module and test it using mocha.
import chai, {
    expect
}
from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import System from 'systemjs';
import '../public/config.js';

chai.use(sinonChai);

describe('helperModule', () => {
    let module;

    before(function () {
        return System.import('./public/js/helper.js')
            .then((mod) => module = mod);
    });

    describe('Module loading', function () {
        it('should load', function(){
            expect(module.default).to.not.be.undefined;
        });
    });
});

I get the following error when running the npm test command.
1) helperModule "before all" hook:
     Error: timeout of 2000ms exceeded. Ensure the done() callback is being
 called in this test.

Not really sure where to put the done callback. If you need any extra information about any packages I am using I will edit my question with them.

A: There's an expectation that a done() callback is called when your test is complete.  Some libraries do this implicitly for you, and you can also pass done to other functions that will call it on success. If you need to do it manually, done can be specified as a parameter of your test function to be called later.
describe('Module loading', function () {
    it('should load', function(done){
        expect(module.default).to.not.be.undefined;
        done();
    });
});


text:
Q: Does dynamic type choice break strict aliasing in C? Let's say that I have some code that looks like this:
void foo(void* obj, int type)
{
    TypeA* a = (TypeA*)obj;
    TypeB* b = (TypeB*)obj;
    TypeC* c = (TypeC*)obj;

    if( type == 1 ) {
        // code that uses "a"
    }
    else if( type == 2 ) {
        // code that uses "b"
    }
    else if( type == 3 ) {
        // code that uses "c"
    }
}

I'm curious to know whether or not this function breaks strict aliasing a
priori, or if the validity of the function depends on how it's actually used.
A certain part of me wants to hope that things will work out fine if I only
ever used the function as foo(&objectOfTypeA, 1), foo(&objectOfTypeB, 2),
or foo(&objectOfTypeC, 3). Yet I've only know about aliasing errors for a
few days, and so I worry that the function foo() is broken right from the
start simply because it casts the incoming void* to various different types to
begin with.

A: This does not break strict aliasing, because you only access *obj through the correct type.  Casting obj does not result in access to *obj.
The strict aliasing rule
Strict aliasing only applies to accessing an object, not to pointer manipulations.
You can manipulate the pointer all you want.
From n1570 §6.5 ¶7

An object shall have its stored value accessed only by an lvalue expression that has one of the following types...

Since you're not accessing *obj but just obj, the strict aliasing rule is not violated.
Conversions
The second question here is whether the conversions are permissible.  The answer is yes, because you can convert a void * to any other object pointer type.  The void type is special, it is the only type with this property.
int *i;
void *ptr = &i;
float *f = ptr; // Permissible

The standard is silent on what the value of f is.  In other words, while the conversion is permissible, there is nothing useful you can do with f.  You can't even convert it back to void *.
This is explained in n1570 §6.3.2.3 ¶1:

A pointer to void may be converted to or from a pointer to any object type.  A pointer to any object type may be converted to a pointer to void and back again, the result shall compare equal to the original pointer.

So, to repeat, the conversion is always permissible but not useful in any way.


text:
Q: Installing Jitsi from unstable error: The following packages have unmet dependencies Perhaps the cause of this problem is that jitsi Desktop (decidedly not jitsi-meet) has unmet dependencies which cannot be easily resolved:
nicholas $
nicholas $ cat /etc/apt/sources.list.d/jitsi-stable.list
#deb https://download.jitsi.org stable/
nicholas $
nicholas $ cat /etc/apt/sources.list.d/jitsi-unstable.list
deb https://download.jitsi.org unstable/
nicholas $
nicholas $ sudo apt update
Hit:1 https://download.jitsi.org unstable/ InRelease
Hit:2 http://archive.ubuntu.com/ubuntu focal InRelease
Hit:3 http://archive.canonical.com/ubuntu focal InRelease
Hit:4 http://archive.ubuntu.com/ubuntu focal-updates InRelease
Hit:5 http://archive.ubuntu.com/ubuntu focal-security InRelease
Hit:6 http://archive.ubuntu.com/ubuntu focal-backports InRelease
Reading package lists... Done
Building dependency tree
Reading state information... Done
210 packages can be upgraded. Run 'apt list --upgradable' to see them.
nicholas $
nicholas $ sudo apt -y install jitsi
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help resolve the situation:

The following packages have unmet dependencies:
 jitsi : Depends: libavformat57 but it is not installable or
                  libavformat-ffmpeg56 but it is not installable
         Depends: libavcodec57 but it is not installable or
                  libavcodec-extra57 but it is not installable or
                  libavcodec-ffmpeg56 but it is not installable or
                  libavcodec-ffmpeg-extra56 but it is not installable
         Depends: libavfilter6 but it is not installable or
                  libavfilter-extra6 but it is not installable or
                  libavfilter-ffmpeg5 but it is not installable
         Depends: libavutil55 but it is not installable or
                  libavutil-ffmpeg54 but it is not installable
         Depends: libswscale4 but it is not installable or
                  libswscale-ffmpeg3 but it is not installable
E: Unable to correct problems, you have held broken packages.
nicholas $

Again, not installing jitsi-meet but just jitsi for the SIP GUI.


text:
Q: Visual Studio Code formatting for "{ }" I'm on Ubuntu. C++ in Visual Studio Code automatically lints like
if (condition == true)
{
  DoStuff();
}

Instead I want to do :
if (condition == true) {
  DoStuff();
}

How do I do that?
I've already installed the C/C++ extension from the marketplace.

A: *

*Go File -> Preferences -> Settings

*Search for C_Cpp.clang_format_fallbackStyle

*Change from "Visual Studio" to "LLVM", "Google" or "WebKit"

A: base on @Chris Drew's answer

*

*Go Preferences -> Settings

*Search for C_Cpp.clang_format_fallbackStyle

*Click Edit, Copy to Settings

*Change from "Visual Studio" to "{ BasedOnStyle: Google, IndentWidth: 4 }"
e.g.

*

*"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 0}"

*btw ColumnLimit: 0 is helpful too, because google limit will break your code to next line when you do not need it.

If you want more:

*

*check https://clang.llvm.org/docs/ClangFormatStyleOptions.html

*customize your functionality to "C_Cpp.clang_format_fallbackStyle" for your loved favor.

More detail:
English: https://medium.com/@zamhuang/vscode-how-to-customize-c-s-coding-style-in-vscode-ad16d87e93bf
Taiwan: https://medium.com/@zamhuang/vscode-%E5%A6%82%E4%BD%95%E5%9C%A8-vscode-%E4%B8%8A%E8%87%AA%E5%AE%9A%E7%BE%A9-c-%E7%9A%84-coding-style-c8eb199c57ce

A: I generally have my own way of formatting almost everything :) so i prefer the most flexible way to achieve this. VS code is by far the most flexible editor as far as c++ formatting is concerned and also "easy".
This is what you should do to get custom formatting.

*

*create a file named .clang-format under the top folder of your work space.

*then start putting your configuration. you can refer page Clang format Style to know various options available.

*save the file and then either use Format Document (Ctrl+Shift+I) or Format Selection (Ctrl+K Ctrl+F)

Here is my file for your reference.
Standard: Cpp11
BasedOnStyle: LLVM
IndentWidth: 4
ColumnLimit: 0
AccessModifierOffset: -4
NamespaceIndentation: All
BreakBeforeBraces: Custom
BraceWrapping:
  AfterEnum: true
  AfterStruct: true
  AfterClass: true
  SplitEmptyFunction: true
  AfterControlStatement: false
  AfterNamespace: false
  AfterFunction: true
  AfterUnion: true
  AfterExternBlock: false
  BeforeCatch: false
  BeforeElse: false
  SplitEmptyRecord: true
  SplitEmptyNamespace: true

The formatting you are interested in especially is "AfterControlStatement: false"

A: Using MacOS for example, an ideal method of configuring clang-format for VS Code is to first install clang-format with Homebrew:
brew install clang-format

Then, use it to export the full style settings to ~/.clang-format:
clang-format -style=google -dump-config > ~/.clang-format

Then, perform the following in VS Code:

*

*Go to Code/File -> Preferences -> Settings and define the following parameters under User Settings:

*"C_Cpp.clang_format_path": "/usr/local/opt/llvm/bin/clang-format"

*"C_Cpp.clang_format_style": "Google"

*"C_Cpp.clang_format_fallbackStyle": "Google"

*"C_Cpp.intelliSenseEngine": "Tag Parser"
This sets the formatter to the clang-formatter installed with Homebrew, which will automatically pull your style settings from the ~/.clang-format file you just created. This way, you can change every parameter in the style as desired and not just a subset of these.
The last parameter, C_Cpp.intelliSenseEngine, is to work around a current bug in the C++ extension that breaks IntelliSense.

A: I haven't used Visual Studio in a while, but you should be able to open the Options menu through the Window tab.
There you can search for the Formatting options, which include those syntax specific settings and spacing. I think it's somewhere around the Text Editor options. The C/C++ extensions only installs the Visual C compiler and standard library, as well as the Windows SDK and a couple of other things.

A: Install C# FixFormat extension

*

*View > Extension

*Search "C# FixFormat"

*Install

Shift + Alt + F
If it complains about multiple formatters, then press the Configure button and select C# FixFormat.
It is possible to go back to having open braces on a new line by going to File > Preferences > Settings.  Then scroll down to Extensions, C# FixFormat configuration and uncheck Style > Braces: On Same Line


text:
Q: Script consuming extreme amounts of CPU I have a programme, which moves the mouse by certain coordinates when held down and it stops it when the mouse key is released. However the code below is taking up 90%+ of my CPU at time. How would I make the code below more efficient / take up less of my CPU's resources?
import pynput
import pyautogui

delta_x = [1,2,3]
delta_y = [3,2,1]
def on_press_start(*args):
    if args[-1]:
        return False

def on_press_loop(*args):
    if not args[-1]:
        return False

while True:
    i = 0
    with Listener(on_click=on_press_start) as listener:
        listener.join()

    with Listener(on_click=on_press_loop) as listener:
        for i in range(len(delta_x)):
            pyautogui.move(delta_x[i],delta_y[i])
            if not listener.running:
                break
            print(i)

A: According to https://pynput.readthedocs.io/en/latest/mouse.html,

A mouse listener is a threading.Thread, and all callbacks will be invoked from the thread.

which means that the more Listener you create the more CPU threads it creates, You've a while true loop which will create a ton of listener and a ton of threads due to which your progamme is taking too much CPU.

A: Even a simple
while True:
    pass

loop will use 100% of a CPU core. The efficiency of the code inside the loop will only effect the frequency. It won't effect the CPU usage unless you limit the frequency.
In your case, you don't need a while loop to monitor the mouse. The listener provided by the library does that for you but in a smarter way. From the docs:
# create a listener
listener = mouse.Listener(on_click=on_click)

...

# start listening to clicks
listener.start()

...

# stop listening to clicks
listener.stop()

When to start/stop listening to mouse events depends on your use case.
Example where the on_click and on_move events are used:
from pynput import mouse

if __name__ == "__main__":
    state = {
        "left_button_pressed": False
    }

    def on_click(x, y, button, pressed):
        if button == mouse.Button.left:
            state["left_button_pressed"] = pressed
            print("onclick", x, y, button, pressed)

    def on_move(*args):
        if state["left_button_pressed"]:
            print("on_move", *args)

    with mouse.Listener(on_click=on_click, on_move=on_move) as listener:
        listener.join()


text:
Q: How to check if a checkbox is ticked in PHP OK so basically I have a HTML checkbox:
<input type="checkbox" name="mailinglist" />

This checkbox is on a user sign up form and this determines if they want to subscribe to the mailing list. I just want this the return as a 1 or 0 (boolean) inside the PHP. As you can see I am using POST:
<form action="process-create.php" method="POST">

And in my PHP it is receiving that post like this:
$mailinglist = $_POST['mailinglist'];

This all looks fine up to here. Now I want to input it into a database (with a boolean value). This is the code that inputs it into the database:
$data = array('username'=>$username, 'firstname'=>$firstname, 'lastname' => $lastname, 'mailing_list'=>$mailinglist, 'email'=>$email );
mysql_insert('users', $data);

Even when I tick the box it still says 0 in the databse. As you can see:
USERNAME       FIRSTNAME       LASTNAME       MAILING LIST       EMAIL
odixon         Oliver          Dixon          0                  *********

Any suggestions? If you want more samples of code I would be happy to give them (if it would help).

A: Instead of
$mailinglist = $_POST['mailinglist'];

I believe you want to use:
$mailinglist = isset($_POST['mailinglist']);

The name associated with the checkbox is included only if the checkbox is checked.  Its value is the value of the checkbox (which you've omitted).

A: Can you try this,
 <input type="checkbox" name="mailinglist" value="yes"/>

 <?php  if(isset($_POST["mailinglist"]) && $_POST["mailinglist"]=="yes"){
             echo "checkbox ticked";
       }
 ?>

A: In your html page :
<input type="checkbox" name="mailinglist" value="1">

After submitting the form you can check it with:
isset($_POST['mailinglist'])
or
if ($_POST['mailinglist'] == '1')...


text:
Q: Opening a file for editing I want to create a method that will load a txt file and then change it but thats another method.
private void openFile() {
    fileChooser.getSelectedFile();
    JFileChooser openFile = new JFileChooser();
    openFile.showOpenDialog(frame);
}

What must go next in order to get data from the file after choosing it to manipulate its data?

A: The JFileChooser documentation has an example on how to continue your code, and get the name of the file chosen, which can then be turned into a File object. You should be able to modify that example to meet your needs:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
}

A: Here's an example that might help you. I would want to read up on and try some simple examples on different buffers that will read and write. In fact, i have worked with these a lot in the last few months and I still have to go and look.
public class ReadWriteTextFile {
      static public String getContents(File aFile) {
      StringBuilder contents = new StringBuilder();

    try {
         BufferedReader input =  new BufferedReader(new FileReader(aFile));
      try {
        String line = null; //not declared within while loop
        while (( line = input.readLine()) != null){
          contents.append(line);
          contents.append(System.getProperty("line.separator"));
        }
      }
      finally {
        input.close();
      }
    }
    catch (IOException ex){
      ex.printStackTrace();
    }
    return contents.toString();
  }

    static public void setContents(File aFile,
                                   String aContents)
                                      throws FileNotFoundException,
                                             IOException {
    if (aFile == null) {
      throw new IllegalArgumentException("File should not be null.");
    }
    if (!aFile.exists()) {
      throw new FileNotFoundException ("File does not exist: " + aFile);
    }
    if (!aFile.isFile()) {
      throw new IllegalArgumentException("Should not be a directory: " + aFile);
    }
    if (!aFile.canWrite()) {
      throw new IllegalArgumentException("File cannot be written: " + aFile);
    }

      Writer output = new BufferedWriter(new FileWriter(aFile));
    try {
      output.write( aContents );
    }
    finally {
      output.close();
    }
  }

  public static void main (String... aArguments) throws IOException {
    File testFile = new File("C:\\Temp\\test.txt");//this file might have to exist (I am not
                                                   //certain but you can trap the error with a
                                                   //TRY-CATCH Block.
    System.out.println("Original file contents: " + getContents(testFile));
    setContents(testFile, "The content of this file has been overwritten...");
    System.out.println("New file contents: " + getContents(testFile));
  }
}


text:
Q: R: calculating column sums & row sums as an aggregation from a dataframe I am trying to obtain column sums & row sums by aggregating with previous row sums & column sums.
For eg.
My initial data frame is:
      Flag1   Flag2  Flag3   Type1 Type2 Type3
1     Level1    A    FIRST     2     0    0
2     Level1    A    SECOND    1     9    0
3     Level1    A    THIRD     3     7    0
4     Level1    A    FOURTH    9    18    0
5     Level1    A    FIFTH     1    22    0
6     Level1    A    SIXTH     1    13    0
7     Level1    B    FIRST     0     0    0
8     Level1    B    SECOND    3     9    0
9     Level1    B    THIRD     5    85    0
10    Level1    B    FOURTH    4    96    0
11    Level1    B    FIFTH     3    40    0
12    Level1    B    SIXTH     0    17    0
22    Level2    A    FIRST     2     0    0
23    Level2    A    SECOND    1     9    0
24    Level2    A    THIRD     3     7    0
25    Level2    A    FOURTH    9    18    0
26    Level2    A    FIFTH     1    22    0
27    Level2    A    SIXTH     1    13    0
28    Level2    B    FIRST     0     0    0
29    Level2    B    SECOND    3     9    0
30    Level2    B    THIRD     5    85    0
31    Level2    B    FOURTH    4    96    0
32    Level2    B    FIFTH     3    40    0
33    Level2    B    SIXTH     0    17    0
34    Level3    A    FIRST     2     0    0
35    Level3    A    SECOND    1     9    0
36    Level3    A    THIRD     3     7    0
37    Level3    A    FOURTH    9    18    0
38    Level3    A    FIFTH     1    22    0
39    Level3    A    SIXTH     1    13    0
40    Level3    B    FIRST     0     0    0
41    Level3    B    SECOND    3     9    0
42    Level3    B    THIRD     5    85    0
43    Level3    B    FOURTH    4    96    0
44    Level3    B    FIFTH     3    40    0
45    Level3    B    SIXTH     0    17    0

My desired result is:
    Flag1   Flag2   Flag3   Type1   Type2   Type3   Sum
1   Level1  A   FIRST   2   0   0   2
2   Level1  A   SECOND  1   9   0   12
3   Level1  A   THIRD   3   7   0   22
4   Level1  A   FOURTH  9   18  0   49
5   Level1  A   FIFTH   1   22  0   72
6   Level1  A   SIXTH   1   13  0   86
7   Level1  B   FIRST   0   0   0   0
8   Level1  B   SECOND  3   9   0   12
9   Level1  B   THIRD   5   85  0   102
10  Level1  B   FOURTH  4   96  0   202
11  Level1  B   FIFTH   3   40  0   245
12  Level1  B   SIXTH   0   17  0   262
13  Level1  (all)   FIRST   2   0   0   2
14  Level1  (all)   SECOND  4   18  0   24
15  Level1  (all)   THIRD   8   92  0   124
16  Level1  (all)   FOURTH  13  114 0   251
17  Level1  (all)   FIFTH   4   62  0   317
18  Level1  (all)   SIXTH   1   30  0   348
19  Level1  A   (all)   17  68  0   85
20  Level1  B   (all)   15  247 0   262
21  Level1  (all)   (all)   32  315 0   347
22  Level2  A   FIRST   2   0   0   2
23  Level2  A   SECOND  1   9   0   12
24  Level2  A   THIRD   3   7   0   22
25  Level2  A   FOURTH  9   18  0   49
26  Level2  A   FIFTH   1   22  0   72
27  Level2  A   SIXTH   1   13  0   86
28  Level2  B   FIRST   0   0   0   0
29  Level2  B   SECOND  3   9   0   12
30  Level2  B   THIRD   5   85  0   102
31  Level2  B   FOURTH  4   96  0   202
32  Level2  B   FIFTH   3   40  0   245
33  Level2  B   SIXTH   0   17  0   262
34  Level2  (all)   FIRST   2   0   0   2
35  Level2  (all)   SECOND  4   18  0   24
36  Level2  (all)   THIRD   8   92  0   124
37  Level2  (all)   FOURTH  13  114 0   251
38  Level2  (all)   FIFTH   4   62  0   317
39  Level2  (all)   SIXTH   1   30  0   348
40  Level2  A   (all)   17  68  0   85
41  Level2  B   (all)   15  247 0   262
42  Level2  (all)   (all)   32  315 0   347
43  Level3  A   FIRST   2   0   0   2
44  Level3  A   SECOND  1   9   0   12
45  Level3  A   THIRD   3   7   0   22
46  Level3  A   FOURTH  9   18  0   49
47  Level3  A   FIFTH   1   22  0   72
48  Level3  A   SIXTH   1   13  0   86
49  Level3  B   FIRST   0   0   0   0
50  Level3  B   SECOND  3   9   0   12
51  Level3  B   THIRD   5   85  0   102
52  Level3  B   FOURTH  4   96  0   202
53  Level3  B   FIFTH   3   40  0   245
54  Level3  B   SIXTH   0   17  0   262
55  Level3  (all)   FIRST   2   0   0   2
56  Level3  (all)   SECOND  4   18  0   24
57  Level3  (all)   THIRD   8   92  0   124
58  Level3  (all)   FOURTH  13  114 0   251
59  Level3  (all)   FIFTH   4   62  0   317
60  Level3  (all)   SIXTH   1   30  0   348
61  Level3  A   (all)   17  68  0   85
62  Level3  B   (all)   15  247 0   262
63  Level3  (all)   (all)   32  315 0   347
64  (all)   A   FIRST   6   0   0   6
65  (all)   A   SECOND  9   27  0   42
66  (all)   A   THIRD   18  48  0   108
67  (all)   A   FOURTH  45  102 0   255
68  (all)   A   FIFTH   48  168 0   471
69  (all)   A   SIXTH   51  207 0   729
70  (all)   B   FIRST   0   0   0   0
71  (all)   B   SECOND  9   27  0   36
72  (all)   B   THIRD   24  282 0   342
73  (all)   B   FOURTH  36  570 0   948
74  (all)   B   FIFTH   45  690 0   1683
75  (all)   B   SIXTH   45  741 0   2469
76  (all)   A   (all)   51  552 0   1611
77  (all)   B   (all)   45  2310    0   5478
78  (all)   (all)   (all)   96  2862    0   7089

Thanks

A: It's not clear what you want here, since you mention "aggregating" and "previous" enitities, but if you want the rowsums followed by the colsums for a dataframe named dfrm, then this works:
dfrm$totals <- rowSums(dfrm[, 4:6])
dfrmT <- rbind(dfrm, data.frame(Flag1="all", Flag2="all", Flag3="all",
                                  t( colSums(dfrm[, 4:7]) )
                ) )
dfrmT

EDIT: So you did want the row sums and then within levels of Flag1 and Flag2 you wanted cumsums:
(And if you want the multiple subtotals, that was answered in your earlier question.)
R: calculating margins or row & col sums for a data frame
dfrmT$CS <- ave(   dfrmT$totals, list(dfrmT$Flag1, dfrmT$Flag2), FUN=cumsum)
dfrmT

     Flag1 Flag2  Flag3 Type1 Type2 Type3 totals  CS
1   Level1     A  FIRST     2     0     0      2   2
2   Level1     A SECOND     1     9     0     10  12
3   Level1     A  THIRD     3     7     0     10  22
4   Level1     A FOURTH     9    18     0     27  49
5   Level1     A  FIFTH     1    22     0     23  72
6   Level1     A  SIXTH     1    13     0     14  86
7   Level1     B  FIRST     0     0     0      0   0
8   Level1     B SECOND     3     9     0     12  12
9   Level1     B  THIRD     5    85     0     90 102
10  Level1     B FOURTH     4    96     0    100 202
11  Level1     B  FIFTH     3    40     0     43 245
12  Level1     B  SIXTH     0    17     0     17 262
22  Level2     A  FIRST     2     0     0      2   2
23  Level2     A SECOND     1     9     0     10  12
24  Level2     A  THIRD     3     7     0     10  22
25  Level2     A FOURTH     9    18     0     27  49
26  Level2     A  FIFTH     1    22     0     23  72
27  Level2     A  SIXTH     1    13     0     14  86
28  Level2     B  FIRST     0     0     0      0   0
29  Level2     B SECOND     3     9     0     12  12
30  Level2     B  THIRD     5    85     0     90 102
31  Level2     B FOURTH     4    96     0    100 202
32  Level2     B  FIFTH     3    40     0     43 245
33  Level2     B  SIXTH     0    17     0     17 262
34  Level3     A  FIRST     2     0     0      2   2
35  Level3     A SECOND     1     9     0     10  12
36  Level3     A  THIRD     3     7     0     10  22
37  Level3     A FOURTH     9    18     0     27  49
38  Level3     A  FIFTH     1    22     0     23  72
39  Level3     A  SIXTH     1    13     0     14  86
40  Level3     B  FIRST     0     0     0      0   0
41  Level3     B SECOND     3     9     0     12  12
42  Level3     B  THIRD     5    85     0     90 102
341    all   all    all    89   795     0    884 884

If on the other hand you want cumsums within each Type with initialization at new Flag1 and Flag2 divisions then:
ave( dfrm[ , grep("Type", names(dfrm))], list(dfrm$Flag1, dfrm$Flag2), FUN=cumsum)
   Type1 Type2 Type3
1      2     0     0
2      3     9     0
3      6    16     0
4     15    34     0
5     16    56     0
6     17    69     0
7      0     0     0
8      3     9     0
9      8    94     0
10    12   190     0
11    15   230     0
12    15   247     0
22     2     0     0
23     3     9     0
24     6    16     0
25    15    34     0
26    16    56     0
27    17    69     0
28     0     0     0
29     3     9     0
30     8    94     0
31    12   190     0
32    15   230     0
33    15   247     0
34     2     0     0
35     3     9     0
36     6    16     0
37    15    34     0
38    16    56     0
39    17    69     0
40     0     0     0
41     3     9     0
42     8    94     0

That is suitable for cbind()-ing to dfrm but needs work on the names():
dfrmCS <- cbind(dfrm, ave( dfrm[ , grep("Type", names(dfrm))],
                               list(dfrm$Flag1, dfrm$Flag2), FUN=cumsum) )
names(dfrmCS)[8:10] <- paste(names(dfrmCS)[8:10], "CS", sep="_")


text:
Q: How to convert values from two different lists into a single dictionary? I am scraping financial summary from https://www.investing.com/equities/nvidia-corp-financial-summary.
Code:
To get the ratio descriptions:
for element in soup.find_all('span', attrs={'class': 'float_lang_base_1'}):
    print(element)

The code will result in:
Gross margin
Operating margin
Net Profit margin
Return on Investment
Quick Ratio
Current Ratio
LT Debt to Equity
Total Debt to Equity
Cash Flow/Share
Revenue/Share
Operating Cash Flow

To get the values for each of ratio above:
for element in soup.find_all('span', attrs={'class': 'float_lang_base_2 text_align_lang_base_2 dirLtr bold'}):
    a = element.get_text()

results in:
 60.45%
 31.47%
 26.03%
 22.86%
 2.95
 3.62
 -
 49.02%
 -
 -
 16.77%

Now, I need to match the two, so that it will be a key value pair that can be transformed into a dataframe.
Gross margin : 60.45%
Operating margin: 31.47%
Net Profit margin: 26.03%
...

A: You can find main div tag which has both the values and iterate over that to identify other properties using class and append to dict1
dict1={}
for element in soup.find_all('div', attrs={'class': 'infoLine'}):
    name=element.find("span",class_="float_lang_base_1").get_text()
    value=element.find("span",class_="float_lang_base_2").get_text()
    dict1[name]=value

Here  you can use pandas to create df and transform dict1 to table form data
import pandas as pd
df=pd.DataFrame(dict1.items(),columns=['A','B'])
df

Output:
       A                  B
0   Gross margin        60.45%
1   Operating margin    31.47%
.....

A: You can Get values from two different lists into a single dictionary
Mykeys = ["a", "b", "c"]
Myvalues = [1, 3, 5]
print ("Mykey list: " + str(Mykeys))
print ("Myvalue list: " + str(Myvalues))
res = dict(zip(Mykeys, Myvalues))

print ("New dictionary will be : " +  str(res))

A: As mentioned in the answers you could zip() your lists and transform into dict().

Anyway there is an altrnative approach in selecting and extracting the information from the elements:
dict(list(row.stripped_strings)[::len(list(row.stripped_strings))-1] for row in soup.select('.infoLine'))

This one will select() or find_all() elements with class infoLine what is the container tag of the s. While .stripped_strings extract the texts as a ResultSet we only have to list slice the first and the last element and convert it in dict comprehension to the final result.
Be aware: Zipping lists or using lists at all you have to ensure, that they will have the same length, else you will get an error concerning this missmatch.
Example
import requests
from bs4 import BeautifulSoup

url='https://www.investing.com/equities/nvidia-corp-financial-summary'
soup = BeautifulSoup(requests.get(url, headers = {'User-Agent': 'Mozilla/5.0'}).text)
dict(list(row.stripped_strings)[::len(list(row.stripped_strings))-1] for row in soup.select('.infoLine'))

Output
{'Gross margin': '60.45%',
 'Operating margin': '31.47%',
 'Net Profit margin': '26.03%',
 'Return on Investment': '22.86%',
 'Quick Ratio': '2.95',
 'Current Ratio': '3.62',
 'LT Debt to Equity': '-',
 'Total Debt to Equity': '49.02%',
 'Cash Flow/Share': '-',
 'Revenue/Share': '-',
 'Operating Cash Flow': '16.77%'}


text:
Q: Using ViewModel constructor instead of ViewModelProvider to be able to get data from Room database based on parameters When using Room database with ViewModel and LiveDate based on this codelab in order to use queries with parameter I didn't find any solution so I tried to create another constructor for both view model class and repository class but I noticed that in CodeLab they don't use view model constructors at all and instead they use view model provider so I changed it and used
new StoryViewModel(getApplication(),"Fiction");
instead of
new ViewModelProvider(this).get(StoryViewModel.class);
I don't know if there's anything wrong with this or not. It works fine now, but if it's the way why don't we use this always? And why do we use view model provider?

If what I did is wrong then how can I retrieve data from db based on parameters?
Thank you.

A: you should not use directly viewModel constructor because the system creates the viewModel or gets it from cache. If you want to pass parameter to the viewModel constructor you should use a viewModel factory like this:
class ViewModelFactory(params) : ViewModelProviders.Factory {

     override fun <T : ViewModel> create(modelClass: Class<T>): T {
          return modelClass.getConstructor(params::class.java).newInstance(params);
     }

}

...

override fun onCreate(...) {

  viewModel = ViewModelProviders.of(this, ViewModelFactory(params)).get(MyViewModel::class.java)s
}

A: Here is a complete example, built with knowledge I gained from Pierluigi's answer:
class MyFragment: Fragment() {
    private lateinit var viewModel: ContactViewModel

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        activity?.let { activity ->
            viewModel = ViewModelProvider(
                activity,
                MyViewModelFactory(
                    "mode value",
                    "nickname value"
                )
            ).get(MyViewModel::class.java)
        } ?: throw AssertionError("Unable to get parent activity from fragment")
    }
}

class MyViewModelFactory(val mode: String, val nickname: String) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T =
        modelClass.getConstructor(String::class.java, String::class.java)
            .newInstance(mode, nickname)
}

class MyViewModel(val mode: String, val nickname: String) : ViewModel()


text:
Q: Broadcast an event to all consumers using an Azure event-hub I want to use the Azure service-bus event-hub to send a single message to many instances of an application but not with the goal of load-balancing.
What I want to do is broadcast a message to all application instances regardless of which partition it is.
I have heard that I can do it using consumer groups but I couldn't find any tutorials on it.

A: This scenario is relatively straight forward assuming you can consistently inject the same unique name into each application instance such as on the command line. If you want to use an EventProcessorHost just specify a different Consumer Group string for each application instance in the constructor. Then it will "load balance" to only one machine per group causing each instance to receive all the messages. There are fancier things you can do if you end up with more machines
I suggest looking at this for some additional discussion of Consumer Groups, or this which discusses using EventHubs as a backplane (basically what you're doing).


text:
Q: onClickListener on Whole Recylcerview doesn't work In xml,
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/itemRecyclerview"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:paddingTop="20dp"
            android:paddingBottom="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"/>

In onCreateView in Fragement,
    binding.apply {
        itemRecyclerview.setOnClickListener {
            NavigateWithItemname(itemname)
            Log.i("click","click") //doesn't work
        }
    }

setOnClickListener on whole RecylcerView doesn't work. ( I don't see click Log in logcat )
I don't know why...

A: Use onClickListener on ItemView this will help to navigate through position wise:
holder.itemView.setOnClickListener(v -> {
       if(position==0){
            openFragmentA();
       }else if(position == 1){
            openFragmentB();
    }else{
            openFragmentC();
    }

    });


text:
Q: Is there any way to detect if current tab URL hash is changed - Chrome Extension Development I am developing a chrome extension, Some of my function works when the page reloads, but in some website content is changed without reloading the page, only hash is changed. My functions are in content script. I need to reload them as URL changes.
I tried to use window.location.hash, I wrote this line in content script, but I see no result.
I am not sure is it because of content script or something else.
It would be very helpful if anyone tell me any way to reload my functions when URL changes. Thank you very much. Very much appreciate your help.


text:
Q: Same UIProgressView Over Multiple View Controllers PREAMBLE
I have an iOS application with a two page registration process.
I have installed a UIProgressView on each page to measure the cumulative progress of users within said registration process.
At present the registration process consists of six fields.
The existing UIProgressView takes a float input based on 1 / 6 updated when a text field finishes editing.
The first controller's UIProgressView launches with a float value of zero.
Once all fields are complete; the second view controller launches with a float value of 0.5.
PROBLEM
This solution is primitive and issues are abundant.
For starters you can see both UIProgressViews during unwind / segue.
QUESTION
Is it possible for me to use the same UIProgressView across the two view controllers ?
Thank you in advance for your help.
NB
The aforementioned registration process consists of two separate view controllers. Please advise if this is common practice / whether more suitable solutions exist.
MAIN ISSUE IMAGE

Solving the issue illustrated within the image above is my primary objective.

A: If you want the progress bar to stay fixed while the user completes your 2 registration VCs, then use view controller containment.
Create a parent view controller that contains the progress view and a container view to hold one of the 2 registration VCs. Use an embed segue to link that container view to a child view controller. You can make the child view controller a navigation controller if you like, or you can simply embed the first registration VC, then do the animation between the first and the second as desired.
Edit: There's a method called
transitionFromViewController:toViewController:duration:options:animations:completion: that lets you create transitions between child view controllers easily.
Second Edit: If you need to communicate between the parent view controller and the child view controller(s), you have to wire up a way to do that yourself. To communicate from the child back to the parent the usual way to do this is to set up a delegate property in the child and define a simple protocol to communicate back to the parent. In the parent's prepareForSegue method you set the child's delegate property to self. The child can then send messages to the parent as needed.
In your case you'd define a simple protocol that would let the child notify the parent about changes to the progress value, and then the parent would update the progress view. (It's a bad idea to have the child view controller manipulate the progress view directly.)
If you want the parent to communicate with the child then you need to save a pointer to the child view controller as you set it up, similar to setting up a delegate.
If you swap out the child view controller then you will need to set up the plumbing (child-to-parent delegate property and parent-to-child pointer) as part of the code that swaps child view controllers.
I have a project on gitHub with the truly dreadful name "test" (link) that sets up a parent and child view controller, plus communications from parent to child and from child to parent.

A: As per my opinion, create two separate UIProgressView for both controllers.
All you have to do is play with its value. Here the important thing is data not UI. I mean if you want to show like half of progress was completed. This can be achieved by creating a new UIProgressView control in next controller because ultimately data in control is change UI will be the same.
So when you finish process of completion on first view controller pass values of first progress control to second view controller and based on that value create second progress control.
If you don't know that how to pass data between two view controller than this answer will help you.
However if you not willing to create two separate progress on two different controllers than you can add progress control as a subview in root controller's window. So that it will share a common screen for all controllers and stay at top for whole application.
var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.window?.addSubview(progressView)

A: Adding another answer here for anyone else like me who thought there should be an even simpler solution, especially used in the Onboarding flow scenario.
For an example scenario including a five step Onboarding, my method is:

*

*Add a progress bar on every VC in the flow.

*For the first progress bar, you can simply set progress to 0.2 in Storyboard

*For the second, in the viewDidLoad, first set the progress of the bar to 0.2 with:yourProgressBar.progress = 0.2

*Then just below: let dispatchTime = DispatchTime.now() + 0.01 DispatchQueue.main.asyncAfter(deadline:dispatchTime, execute: { self.onboardingProgress.setProgress(0.4, animated: true)})

*Repeat in the 0.2 increments for each new step of Onboarding.

The Dispatch Queue allows the progress bar to set to the previous VC's progress, and then animate up to the new progress. Without the DispatchQueue, the whole Progress Bar would animate from the beginning when the VC is loaded, completely ruining the desired effect.
I hope this can be of help to someone!