text:
Q: Not getting didReceiveMemoryWarning when app is in the background I'm noticing that my view controllers aren't getting their didReceiveMemoryWarning methods called when my application is in the background state on the iPad simulator. More specifically, I see the call to applicationDidEnterBackground in my logs, then I hit the "Simulate Memory Warning" button, and then I notice a peculiar lack of any didReceiveMemoryWarning calls.
However, when I bring the application back to the foreground I suddenly get the didReceiveMemoryWarning call, as if it had been queued.
What I'm confused about here is if my application is really in the background, or if it's just flat out suspended. Is there any way to tell in the simulator?
Also, if it is not yet suspended, and really is just in the background, then I would find it silly that I'm unable to process didReceiveMemoryWarning. Because that would then mean that only the foreground application can process memory warnings to free up space, which is of course odd given that the foreground app could be only one of possibly dozens of running apps, and it would make so much more sense if they could all free up memory.
Anyway, the main questions are: why aren't I getting didReceiveMemoryWarning in the background state? And also, am I really suspended? And how do I tell?

A: If you did not start a background task, or do VOIP, location tracking or audio in the background, then your app is suspended after applicationDidEnterBackground. It will not get any notifications. Any notifications are kept around (even those that occur after the app was suspended) and sent to the app when the app goes to the foreground again.

A: I don't think that is the case. I am able to access didReceiveMemoryWarning code while in background. Once system generates low memory signal than as a good citizen we should release the memory. This  also helps our app from terminating by the system.


text:
Q: Equivalent of select query without passing primary key in DynamoDB? What will be the equivalent of below query in DynamoDB:
select field1,fields2 from table_name where filter1 == 'filter_value'

Please note that filter1 is not the primary key here, it can be any column in the table.
From what I have read, I understand that it can be achieved using scan() operation but it will return whole data not just fields we specify.
Also, I have read everywhere that we should avoid using scan() as it is heavy operation (scans whole table).

A: Using the AWS Command Line Interface, you would do it like this
aws dynamodb scan \
     --table-name table_name\
     --projection-expression "field1,fields2" \
     --filter-expression "filter1 = :filter_value"\

A scan always reads every row in the database. A filter expression simply limits what is returned to you. By default you get all attributes ('columns') back for each item but you can limit that using a projection expression.
Queries can be used when you are searching on an indexed attribute.
For information checkout the docs on scans and query

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bad JSON - Keys are not quoted I am scraping some JSONP dictionaries from AWS (from javascript files). After parsing the raw data for only the JSON-like data, in some cases I get a valid JSON and can successfully load this in Python (json_data = json.loads(json_like_data)). However, some of Amazon's JSONPs do not include quotes around their keys (see the following).
...
{type:"storageCurrentGen",sizes:
[{size:"i2.xlarge",vCPU:"4",ECU:"14",memoryGiB:"30.5",storageGB:"1 x 800 SSD",valueColumns:[{name:"linux",prices:{USD:"0.938"}}]},
{size:"i2.2xlarge",vCPU:"8",ECU:"27",memoryGiB:"61",storageGB:"2 x 800 SSD",valueColumns:[{name:"linux",prices:{USD:"1.876"}}]},
{size:"i2.4xlarge",vCPU:"16",ECU:"53",memoryGiB:"122",storageGB:"4 x 800 SSD",valueColumns:[{name:"linux",prices:{USD:"3.751"}}]},
...

For JSONP, this still works as it is valid JavaScript syntax. However, Python's json.loads(json_str) craps out as it is not valid JSON.
There is another Python module YAML which can handle unquoted keys, BUT there must be a space after the semicolons (:).
I figure that I have two options.

*

*Somehow replace character in between an open brace or comma ({ | ,) and a colon (:). Then use json.loads(...).

*Add a space after ever colon (:). Then parse with yaml.load(...).

My guess is that option 2 is better than 1. However, I am seeking suggestion of a better solution.
Has anyone encountered an ill-formatted JSON such as this before and used Python to parse it?

A: You can also do it (in this particular case) with simple Regex:
ll = '{type:"storageCurrentGen",sizes:\n[{size:"i2.xlarge",vCPU:"4",ECU:"14",memoryGiB:"30.5",storageGB:"1 x 800 SSD",valueColumns:[{name:"linux",prices:{USD:"0.938"}}]},\n{size:"i2.2xlarge",vCPU:"8",ECU:"27",memoryGiB:"61",storageGB:"2 x 800 SSD",valueColumns:[{name:"linux",prices:{USD:"1.876"}}]},\n{size:"i2.4xlarge",vCPU:"16",ECU:"53",memoryGiB:"122",storageGB:"4 x 800 SSD",valueColumns:[{name:"linux",prices:{USD:"3.751"}}]},'

ll_patched = re.sub('([{,:])(\w+)([},:])','\\1\"\\2\"\\3',ll)
>>> ll_patched
'{"type":"storageCurrentGen","sizes":\n[{"size":"i2.xlarge","vCPU":"4","ECU":"14","memoryGiB":"30.5","storageGB":"1 x 800 SSD","valueColumns":[{"name":"linux","prices":{"USD":"0.938"}}]},\n{"size":"i2.2xlarge","vCPU":"8","ECU":"27","memoryGiB":"61","storageGB":"2 x 800 SSD","valueColumns":[{"name":"linux","prices":{"USD":"1.876"}}]},\n{"size":"i2.4xlarge","vCPU":"16","ECU":"53","memoryGiB":"122","storageGB":"4 x 800 SSD","valueColumns":[{"name":"linux","prices":{"USD":"3.751"}}]},'

A: You have an HJSON document, at which point you can use the hjson project to parse it:
>>> import hjson
>>> hjson.loads('{javascript_style:"Look ma, no quotes!"}')
OrderedDict([('javascript_style', 'Look ma, no quotes!')])

HJSON is JSON without the requirement to quote object names and even for certain string values, with added comment support and multi-line strings, and with relaxed rules on where commas should be used (including not using commas at all).
Or you could install and use the demjson library; it supports parsing valid JavaScript (missing quotes):
import demjson

result = demjson.decode(jsonp_payload)

Only when you set the strict=True flag does demjson refuse to parse your input:
>>> import demjson
>>> demjson.decode('{javascript_style:"Look ma, no quotes!"}')
{u'javascript_style': u'Look ma, no quotes!'}
>>> demjson.decode('{javascript_style:"Look ma, no quotes!"}', strict=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mjpieters/Development/venvs/stackoverflow-2.7/lib/python2.7/site-packages/demjson.py", line 5701, in decode
    return_stats=(return_stats or write_stats) )
  File "/Users/mjpieters/Development/venvs/stackoverflow-2.7/lib/python2.7/site-packages/demjson.py", line 4917, in decode
    raise errors[0]
demjson.JSONDecodeError: ('JSON does not allow identifiers to be used as strings', u'javascript_style')

Using a regular expression you can try to regex your way to valid JSON; this can lead to false positives however. The pattern would be:
import re

valid_json = re.sub(r'(?<={|,)([a-zA-Z][a-zA-Z0-9]*)(?=:)', r'"\1"', jsonp_payload)

This matches a { or ,, followed by a JavaScript identifier (a character, followed by more characters or digits), and followed directly by a : colon. If your quoted values contain any such patterns, you'll get invalid JSON.


text:
Q: Package RQuantLib is not available for R 3.5.0 Has anyone else tried to load the RQuantLib package for R 3.5.0?
I tried (which has worked before):
install.packages("drat", dependencies = TRUE)
drat::addRepo("ghrr")
install.packages("RQuantLib", type = "binary")

but get the error message:
Warning: unable to access index for repository https://ghrr.github.io/drat/bin/windows/contrib/3.5:

cannot open URL 'https://ghrr.github.io/drat/bin/windows/contrib/3.5/PACKAGES'
Warning message:
package 'RQuantLib' is not available (for R version 3.5.0)

A: You can try this:
library(devtools)
install_github("eddelbuettel/rquantlib")

Or equivalently (based on comment by Dirk Eddelbuette)
install.packages("RQuantLib", type="source")


text:
Q: jmeter: how to fetch 6 requests in parallel in a transaction controller to simulate real browser When you record your website using the jmeter "Test Script Recorder", you can set each page to be a transaction.  Say you have 20 pages, each with 100 requests.  you will get 20 transaction controllers, each with 100 sub requests.  The transaction controller has "generate parent sample" which allows you to output the statistics per page, such as min and max times to load the page etc.  You can also add "think time" between transactions, just like a real user reading pages before clicking on next, which are not included in the page load times.
This is perfect except for one critical detail: browsers don't download a pages requests in series, they do 6 in parallel. Thus the times shown are wrong (far too large), and the server load pattern is different (although similar over time given we want to simulate 5k concurrent users)
There is a "parallel controller" plugin, but this is not suitable for two reasons:

*

*it does not work with transaction controller, according to the docs.

*you cant specify how many parallel downloads (e.g. 6) - it will try to download all 100 at the same time.  Manually dividing 100 requests into groups 6 would also not work correctly.

I tried adding a new thread group under the main threadgroup, thinking sub-thread groups could provide this, but it doesn't seem to let you.
Our load tests are predicated on acceptable page load times, which we cant find any way to  simulate.
Any suggestions for hacks/work arounds?

A: If these 100 requests are for images, scripts, styles, fonts, sounds, etc. - you should not be recording them at all and let JMeter download them on its own, the relevant setting lives under "Advanced" tab of the HTTP Requests Defaults configuration element:

See Web Testing with JMeter: How To Properly Handle Embedded Resources in HTML Responses article for more information


text:
Q: How can I allow precision loss over pyspark jdbc from oracle? I am attempting to move a very large Oracle table which contains 300+ columns and 10,000,000+ records using pyspark 3.0.1 over DataFrameReader.jdbc. I get the error message:
java.lang.ArithmeticException: Decimal precision 136 exceeds max precision 38

*

*I can't say which record, or even which column for that matter, is causing this error.

*Furthermore, I plan to repeat this process with many tables and need to automate handling this error.

*I do not have the permissions to change any data in the source database (read-only).

*Decimal precision of 136 is not necessary for my use cases.

*If there is a way to actually allow precision of 136, I would also be ok with that solution.
Everything I find online about this issue is regarding others wanting to preserve their decimal precision (not reduce it). I have tried adding the following to my SparkSession config:
spark.sql.decimalOperations.allowPrecisionLoss=true
But I still get the same error.
Update:
I was able to get the data to load, then I cast the decimal columns to float.
raw_data = self._get_spark().read.jdbc(self._url, self._table, **self._load_args)
decimal_cols = []
for column in raw_data.columns:
    if isinstance(raw_data.schema[column].dataType, DecimalType):
        decimal_cols.append(column)

    for col_name in decimal_cols:
        raw_data = raw_data.withColumn(col_name, col(col_name).cast('float'))

Next, I add a new column and make it a float as well. Printing data.schema shows that none of my datatypes in the dataframe is DecimalType. Finally, whenever I go to write back over jdbc I get the same error message.
data.write.jdbc(self._url, self._table, **self._save_args)

java.lang.ArithmeticException: Decimal precision 136 exceeds max precision 38


text:
Q: cannot get folder created by another apps script on google drive Using the following apps script function i can successfully create folders in google drive:
function uploadFileToGoogleDrive(data, file, name, email) {

    var parentFolderId = "FOLDER_ID";
    var parentFolder = DriveApp.getFolderById(parentFolderId);
    var subfolder;

        try {
    subfolder = parentFolder.getFoldersByName([name, email].join(" ")).next();
    }
    catch(e) {
    subfolder = parentFolder.createFolder([name, email].join(" "));
    }
      var contentType = data.substring(5,data.indexOf(';')),
        bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),
        blob = Utilities.newBlob(bytes, contentType, file),
        file = subfolder.createFile(blob);

          file = subfolder.createFile(file, data);
   Logger.log(subfolder);
      return "OK";
}

i want to access the folder using the following script:
function downloadFile(e) {
  var parentFolderId = "FOLDER_ID";
  var parentFolder = DriveApp.getFolderById(parentFolderId);

 var subfolderId;
 var subfolders = parentFolder.getFoldersByName([name, email].join(" "));

while (subfolders.hasNext()) {
  var folder = subfolders.next();
  Logger.log(folder.getId());
}
}

appsscript.json for uploadFileToGoogleDrive:
{
  "timeZone": "Europe/Bucharest",
  "dependencies": {
  },
  "webapp": {
    "access": "ANYONE_ANONYMOUS",
    "executeAs": "USER_DEPLOYING"
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}

appsscript.json for downloadFile :
{
  "timeZone": "Europe/Bucharest",
  "dependencies": {
  },
  "webapp": {
    "access": "ANYONE_ANONYMOUS",
    "executeAs": "USER_DEPLOYING"
  },
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes": ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.readonly"],
  "runtimeVersion": "V8"
}

The script can access ONLY the folders Created with google drive Web!
But cannot get the folders created with other apps script.
Note that the two functions (upload and download) are in separate google apps scripts.

A: Thanks @alberto vielma, As @TheMaster suggested, my problem was in name and email, a hidden "space" was by mistake in their string values which prevent them to match the folder name. Thanks all..


text:
Q: Magento Admin Custom Sales Report I have to develop a module to export collection of product,order,customer combined attributes. So i thought rather than modifying the core sales report for this purpose better to do a custom functionality. These are the steps that i did but i am not able to produce it. Used magento 1.4.1 version for this.
Under
/var/www/magento141/app/code/core/Mage/Reports/etc/adminhtml.xml
Added these lines for menus.
           <ereaders translate="title" module="reports">
                <title>Sales Report</title>
                 <children>
            <ereaders translate="title" module="reports">
                        <title>Sales Report</title>
                        <action>adminhtml/report_sales/ereaders</action>
                    </ereaders>
                </children>
            </ereaders>

Under
/var/www/magento141/app/design/adminhtml/default/default/layout/sales.xml
Added these lines for filter condition.
<adminhtml_report_sales_ereaders>
    <update handle="report_sales"/>
    <reference name="content">
        <block type="adminhtml/report_sales_sales" template="report/grid/container.phtml" name="sales.report.grid.container">
            <block type="adminhtml/store_switcher" template="report/store/switcher/enhanced.phtml" name="store.switcher">
                <action method="setStoreVarName"><var_name>store_ids</var_name></action>
            </block>
            <block type="sales/adminhtml_report_filter_form_order" name="grid.filter.form">
               ----
            </block>
        </block>
    </reference>
</adminhtml_report_sales_ereaders>

And then copied the needed block,model files from sales and renamed all of them into  ereaders under /var/www/magento141/app/code/core/Mage/Adminhtml/.
Then placed action for ereaders under /var/www/magento141/app/code/core/Mage/Adminhtml/controllers/Report/SalesController.php
public function ereadersAction()
{
$this->_title($this->__('Reports'))->_title($this->__('Sales'))->_title($this->__('EReaders Sales'));

    $this->_showLastExecutionTime(Mage_Reports_Model_Flag::REPORT_ORDER_FLAG_CODE, 'ereaders');

    $this->_initAction()
        ->_setActiveMenu('report/sales/ereaders')
        ->_addBreadcrumb(Mage::helper('adminhtml')->__('EReaders Sales Report'), Mage::helper('adminhtml')->__('EReaders Sales Report'));

    $gridBlock = $this->getLayout()->getBlock('report_sales_ereaders.grid');
    $filterFormBlock = $this->getLayout()->getBlock('grid.filter.form');

    $this->_initReportAction(array(
        $gridBlock,
        $filterFormBlock
    ));
    $this->renderLayout();
}

Here when i use var_dump ==> //var_dump($this->getLayout()->getBlock('report_sales_ereaders.grid')); am getting bool(false) only. It does not call the ereaders grid, instead of its still loading blocks and grids from Sales only.
I searched most of the files related to report, am not still able to find out the problem.
Hope many of you gone through these sort of issues, please can anyone tell me where am making mistake or missing something.

A: I don't see a block named "report_sales_ereaders.grid" in your layout file, if that's the name you want to use, you should change "sales.report.grid.container" to "report_sales_ereaders.grid" in your layout.  the getBlock method uses the name attribute in the layout file to load blocks from.
If you still have problems go into more detail about the blocks and models you copied in the background.  hope this helps.

A: You don't have the block named 'report_sales_ereaders.grid' because that block is created dynamically by Magento here:
// class Mage_Adminhtml_Block_Widget_Grid_Container
protected function _prepareLayout()
{
        $this->setChild( 'grid',
            $this->getLayout()->createBlock( $this->_blockGroup.'/' . $this->_controller . '_grid',
            $this->_controller . '.grid')->setSaveParametersInSession(true) );
        return parent::_prepareLayout();
}

$this->_controller is the key here.
And you define it inside your block, which, seeing your sales.xml is "adminhtml/report_sales_sales".
That Block should extends from Mage_Adminhtml_Block_Widget_Grid_Container, and you should define ::_controller inside the contrusctor of that block:
public function __construct()
{
        $this->_blockGroup = 'something';
        $this->_controller = 'report_sales_ereaders';  // THIS !!!
        parent::__construct();
            ... // see a similar block from magento
}

Also note from the first code above (_prepareLayout) that Mage_Adminhtml_Block_Widget_Grid_Container will try to use a Block called (uri):
'something/report_sales_ereaders_grid'
so you need that class too, and therefore you probably want to change "something" with the node used in yout config.xml under <blocks>
that block will have the name (inside your layout): "report_sales_ereaders.grid"
So, depending what you want to do, you have two options here:
1) Change the type of your block in your sales.xml layout, so it points to your own block (and you define there your "_controller" how I showed above, etc).
2) Change
 $gridBlock = $this->getLayout()->getBlock('report_sales_ereaders.grid');

to
 $gridBlock = $this->getLayout()->getBlock('report_sales_sales.grid');

because "report_sales_sales" is the value of "_controller" inside the block "adminhtml/report_sales_sales" (Mage_Adminhtml_Block_Report_Sales_Sales).


text:
Q: .htaccess RewriteRule issue I have a domain at OVH that links to my EC2 instance like this:
www.mysite.com --> 12.34.56.78/folder/
So everytime I type "www.mysite.com" in my address bar I end up on my website but the URL has been replaced to "12.34.56.78/folder/".
I'm currently trying to tweak a .htaccess file at the root of my server but it doesn't seem to work...
Here is the content of the file:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.mysite.com$
RewriteRule ^(.*)$ http://www.mysite.com/ [L]

Maybe I'm not looking at the right solution... Anyway if you can help me, I'll be grateful!
Cheers,

A: You are missing a couple of things that I added below
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.mysite\.com$
#$1 will include the original URI in the redirect, 301 for permanent
RewriteRule ^(.*)$ http://www.mysite.com/$1 [L,R=301]


text:
Q: Vulkan: one pipeline and multiple descriptor sets? I'm trying to create a single pipeline with a layout where it requires two bindings, a dynamic UBO and a image/sampler binding. I want each binding to come from a separate descriptor set, so I'd bind two descriptor sets per draw call. One descriptor set is for texture per object, the other is for the dynamic UBO(shared between objects). I want to be able to do something like this in the rendering portion:

commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);

for (int ii = 0; ii < mActiveQuads; ii++)
{
    uint32_t dynamicOffset = ii * static_cast<uint32_t>(dynamicAlignment);

    // bind texture for this quad
    commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, sharedPipelineLayout, 0, 1,
            &swapResources[current_buffer].textureDescriptors[ii], 1, &dynamicOffset);

    // draw the dynamic UBO with offset for this quad
    commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, sharedPipelineLayout, 0, 1,
                &swapResources[current_buffer].quadDescriptor, 1, &dynamicOffset);

    commandBuffer.draw(2 * 3, 1, 0, 0);
}

But this doesn't seem to work. First of all I'm not sure I have understood everything about descriptor sets and pipeline layouts to know if what I'm doing is allowed. Does this even make sense? That I can create a pipeline with a 2 binding layout, but create each descriptor to fill just one of those bindings each, then bind two descriptors per draw call for that pipeline?
If it is allowed. This is how I'm creating the pipeline and descriptors:
vk::DescriptorSetLayoutBinding const layout_bindings[2] = { vk::DescriptorSetLayoutBinding()
        .setBinding(0)
        .setDescriptorType(vk::DescriptorType::eUniformBufferDynamic)
        .setDescriptorCount(1)
        .setStageFlags(vk::ShaderStageFlagBits::eVertex)
        .setPImmutableSamplers(nullptr),
        vk::DescriptorSetLayoutBinding()
        .setBinding(1)
        .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
        .setDescriptorCount(1)//texture_count)
        .setStageFlags(vk::ShaderStageFlagBits::eFragment)
        .setPImmutableSamplers(nullptr) };

    // note binding count is 1 here
    auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(1).setPBindings(&layout_bindings[0]); // using the first part of the above layout
    device.createDescriptorSetLayout(&descriptor_layout, nullptr, &quadDescriptorLayout);

    // note binding count is 1 here
    auto const descriptor_layout2 = vk::DescriptorSetLayoutCreateInfo().setBindingCount(1).setPBindings(&layout_bindings[1]); // using the second part of the above layout
    device.createDescriptorSetLayout(&descriptor_layout2, nullptr, &textureDescriptorLayout);

    // Now create the pipeline, note we use both the bindings above with
    // layout count = 2
    auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(2).setPSetLayouts(desc_layout);
    device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &sharedPipelineLayout);

and the descriptors themselves:
    // alloc quad descriptor
    alloc_info =
        vk::DescriptorSetAllocateInfo()
            .setDescriptorPool(desc_pool)
            .setDescriptorSetCount(1)
            .setPSetLayouts(&quadDescriptorLayout);

     // texture descriptors(multiple descriptors, one per quad object)
    alloc_info =
        vk::DescriptorSetAllocateInfo()
            .setDescriptorPool(desc_pool)
            .setDescriptorSetCount(1)
            .setPSetLayouts(&textureDescriptorLayout);

Previously, with the texture and UBO in a single descriptor set it worked fine, I could see multiple quads but all sharing a single texture. When I split off the textures into a different descriptor set, that's when I get a hanging app. I get a 'device lost' error on trying to submit the graphics queue.
Any insight as to if this is possible to do or if I'm doing something wrong in my setup would be very appreciated. Thank you very much!
Below adding Shader code:
#version 450
#extension GL_ARB_separate_shader_objects : enable

layout(binding = 0) uniform UniformBufferObject {
    mat4 mvp;
    vec4 position[6];
    vec4 attr[6];
} ubo;

layout(location = 0) out vec2 fragTexCoord;

void main() {
    gl_Position = ubo.mvp *ubo.position[gl_VertexIndex];
    fragTexCoord = vec2(ubo.attr[gl_VertexIndex].x, ubo.attr[gl_VertexIndex].y);
}

Pixel shader:
#version 450
#extension GL_ARB_separate_shader_objects : enable

layout(set=0, binding = 1) uniform sampler2D texSampler;

layout(location = 0) in vec2 fragTexCoord;

layout(location = 0) out vec4 outColor;

void main() {
    outColor = texture(texSampler, fragTexCoord);
}

A: Yes, you can do this. Your pipeline layout has two descriptor sets. Each of the two descriptor set layouts has one descriptor: a dynamic UBO and a texture. At draw time, you bind one descriptor set of each descriptor set layout to the appropriate set number.
It looks like the firstSet parameter when binding the texture descriptor set is wrong: that's the second set in the pipeline layout, so it has index 1, but you're passing 0. The validation layers should have warned you that you're binding a descriptor set with a set layout that doesn't match what the pipeline layout expects for that set.
You don't show the shader code that accesses these, so you may have done this. But when going from a single descriptor set to two descriptor sets, you need to update the set index in the sampler binding.


text:
Q: help with this code <?php
      if(isset($_REQUEST['searchcat']))
  {
        $search_category = $_REQUEST['searchcat'];
        switch($search_category)
        {
            case 'Purchase':
                $city      = mysql_real_escape_string($_REQUEST['city']);
                $location  = mysql_real_escape_string($_REQUEST['location']);
                $bedrooms  = mysql_real_escape_string($_REQUEST['noofbedrooms']);
                $addeddate = mysql_real_escape_string($_REQUEST['addeddate']);
                $minprice  = mysql_real_escape_string($_REQUEST['pricefrom']);
                $maxprice  = mysql_real_escape_string($_REQUEST['priceto']);
                $minarea   = mysql_real_escape_string($_REQUEST['areafrom']);
                $maxarea   = mysql_real_escape_string($_REQUEST['areato']);
                $proptype   = mysql_real_escape_string($_REQUEST['proptype']);
                $addeddate = date($addeddate * 24 * 60 * 60);
                $query = 'SELECT image,propertytitle,propertypurpose,propertytype,city,id FROM properties WHERE 1 = 1 AND propertypurpose = "Purchase" ';
                $query .= strlen($city)     ? ' AND city = "'.$city.'"'         : '';
                $query .= strlen($location) ? ' AND location = "'.$location.'"' : '';
                $query .= strlen($bedrooms) ? ' AND bedrooms = "'.$bedrooms.'"' : '';
                if($addeddate!=0)
                    $query .= strlen($addeddate) ? ' AND dateadded >= "FROM_UNIXTIME('.$addeddate.')"' : '';
                $query .= strlen($minprice) ? ' AND price between "'.$minprice.'"' : '';
                $query .= strlen($maxprice) ? ' AND "'.$maxprice.'"' : '';
                $query .= strlen($minarea) ? ' AND landarea between "'.$minarea.'"' : '';
                $query .= strlen($maxarea) ? ' AND "'.$maxarea.'"' : '';
                $query .= strlen($proptype) ? ' AND propertytype = "'.$proptype.'"' : '';
                $getSearchRowsQuery = explode('properties',$query);
                $getSearchRowsQuery = 'SELECT COUNT(id) As numrows FROM properties' . $getSearchRowsQuery[1];
                break;
            case 'rentals':
                break;
            case 'agents':
                break;
            case 'developments':
                break;
            default:
        }
    }
    $classObject = new class_functions();
    $rowsPerPage = 2;
    // by default we show first page
    $pageNum = 1;
    // if $_GET['page'] defined, use it as page number
    if(isset($_GET['page']))
    {
        $pageNum = $_GET['page'];
    }
    // counting the offset
    $offset = ($pageNum - 1) * $rowsPerPage;
    if(!isset($_REQUEST['searchcat']))
    {
        if(!isset($_REQUEST['page']))
        {
            $query = '';
            session_destroy($_SESSION['searchquery']);
            session_destroy($_SESSION['searchcount']);
        }
        else
            $query = $_SESSION['searchquery'];
    }
else
{
    session_destroy($_SESSION['searchquery']);
    session_destroy($_SESSION['searchcount']);
}
if(isset($_SESSION['searchquery']))
    $query = $_SESSION['searchquery'];
$tmpquery = $query . ' LIMIT ' . $offset . ', ' .$rowsPerPage;
echo $tmpquery;
$listings[] = $classObject->getSearchListings($tmpquery,$offset,$rowsPerPage);
for($i=0;$i<sizeof($listings[0]);$i++) {
    if($i%2==0)
        echo '
';
    else
        echo '
';
?>

            <?php if($listings[0][$i][0]=="") {?>

                            <?php } else {?>
                                <img src="<?php echo $listings[0][$i][0]; ?>" alt="<?php echo $featured[0][$i][1]; ?>" /><?php }?>

                        <?php echo $listings[0][$i][1]; ?>
                        <?php echo $listings[0][$i][2]; ?>
                        <?php echo $listings[0][$i][3]; ?>
                        <?php echo $listings[0][$i][4]; ?>

                    <?php } ?>

                    <?php
                        //echo $getSearchRowsQuery;
                        if(!isset($_SESSION['searchcount']))
                            $numrows = $classObject->get_search_rows($getSearchRowsQuery);
                        else
                            $numrows = $_SESSION['searchcount'];
                        if($numrows==0)
                        {
                            echo 'No records found.';
                        }
                        else
                        {
                            // how many pages we have when using paging?
                            $maxPage = ceil($numrows/$rowsPerPage);

                            // print the link to access each page
                            $self = $_SERVER['PHP_SELF'];
                            $nav  = '';

                            for($page = 1; $page <= $maxPage; $page++)
                            {
                               if ($page == $pageNum)
                               {
                                  $nav .= " $page "; // no need to create a link to current page
                               }
                               else
                               {
                                  $nav .= " $page ";
                                  $_SESSION['searchquery'] = $query;
                                  $_SESSION['searchcount'] = $numrows;
                               }
                            }
                            if ($pageNum > 1)
                            {
                               $page  = $pageNum - 1;
                               $prev  = " [Prev] ";

                               $first = " [First Page] ";
                            }
                            else
                            {
                               $prev  = ' '; // we're on page one, don't print previous link
                               $first = ' '; // nor the first page link
                            }

                            if ($pageNum < $maxPage)
                            {
                               $page = $pageNum + 1;
                               $next = " [Next] ";

                               $last = " [Last Page] ";
                            }
                            else
                            {
                               $next = ' '; // we're on the last page, don't print next link
                               $last = ' '; // nor the last page link
                            }
                        }
                    ?>

My question is that how can i repeat the query on next pages using sessions. i.e i want to store the query if the pages exceeds results from 1 page. basically listing. I cant figure out the logic for storing the query and check for condition that the page is loaded first time or it is continuing search result.
sorry for improper formatting.

A: Well, ASP defines property IsPostBack for every page which answers your question whether page has been loaded before.  You can use same technique by creating custom bussiness class instance of which you store in $_SESSION['bl'] and check if $_SESSION['bl'] is null.  In that class you could define properties that store your query and other desired parameters.  Then you'll have all information you need and can go from there


text:
Q: Kendo numeric textbox in grid with Angular I'm trying to use the numeric textbox from kendo, in Angular, inside a kendo grid. Binding the data with my angular object doesn't work. I tried to put an "editor" field in the columns object, or even to do it with a jQuery command (which I know is bad)like this:
$('.editable').kendoNumericTextBox()

but it never works..

A: Instead of using the template in the columns object, use the editor attribute:
{
    field: "fieldName",
    title: "Field Title",
    width: "90px",
    editor: numberEditor
}

The numberEditor is a function which you can implement as following:
function numberEditor(container, options) {
  $('<input name="' + options.field + '"/>')
  .appendTo(container)
  .kendoNumericTextBox({
    decimals: 0,   // Settings for the editor, e.g. no decimals
    step    : 1,   // Defines how the up/down arrows change the value
    min     : 0    // You can also define min/max values
});

}


text:
Q: libcurl how to change encoding url behavior Problem: When I make a request which contains redirects, the last of the redirects returns 404 because a URL from the Location header contains a '#' character. libcurl encodes it to %23 and the request returns 404 (server's rules?) while some other requests with redirects to a URL containing a '#' work fine. For example the Opera browser also gets 404 with %23 and 200 with '#'. Does anyone knows how can I change such behavior and make libcurl not to encode the URL? So at this time I don't want to go to redirection URLs manually... This behavior is noted with and without a proxy.
Additional info
-------------------------------------
libcurl 7.27.0
Ubuntu 12.04
CURLOPT_FOLLOWLOCATION = true
CURLOPT_MAXREDIRS = -1
HTTP 1.1
CURLOPT_POSTREDIR = default

A: I do not know if you can control this directly in libcurl. But even if you cannot, not all hope is lost. Your code can hijack curl_easy_escape to get the behavior you want. This is a hack, but you could use it as a last resort, I guess.
The here is a simple example that highjacks the double sin(double) function from the math library. First the main file which uses sin:
sin_test.c:
#include <math.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char ** argv)
{
    double x = atof(argv[1]);
    printf("sin(%f) = %f\n", x, sin(x));
    return 0;
}

Compile this file: gcc -o sin_test sin_test.c -lm, and check that it works
./sin_test 1
sin(1.000000) = 0.841471

We will now take this as given, and try to override its behavior without changing its source code. To do this, we define a shared library sin_override.so as follows. Create the file sin_override.c with the contents:
#include <math.h>
#include <stdlib.h>
#define __USE_GNU
#include <dlfcn.h>

double sin(double x)
{
    double (*real_sin)(double) = NULL;
    if(!real_sin) real_sin = dlsym(RTLD_NEXT,"sin");
    return real_sin(x)/10;
}

And compile it with `gcc -fPIC -shared -o sin_override.so sin_override.c -ldl. Now tell the system to load this shared library before the program itself:
LD_PRELOAD=/full/path/to/sin_override.so ./sin_test 1
sin(1.000000) = 0.084147

The answer is now 10 times smaller than before, confirming that we have overridden the default sin.
In your case, you would be overriding curl_easy_escape instead, by first calling the real curl_easy_escape, and then running through the resulting string, replacing %23 with #, and then returning the modified string. I haven't tested this for libcurl, but something like this should work, though it is a bit cumbersome.


text:
Q: How can i apply upto three level of OrderbyChild in firebase Android I need three level orderbychild in firebase Android
I already apply two level of orderbychild
mFirebaseDatabase.getReference("childs").orderByChild("busNo").equalTo(no);

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("childs");
mDatabase.orderByChild("childPosition").addValueEventListener(new ValueEventListener() {  }

No such Error but finding the way to do it.

A: Firebase doesn't support ordering by multiple queries.

Queries can only order by one key at a time. Calling orderByChild()
  multiple times on the same query throws an error.

Try ordering by a simple query an then filter the data, sample:
Query searchAllQuery = usersRef
            .orderByChild("fullname")
            .startAt(searchBoxInput.toUpperCase())
            .endAt(searchBoxInput.toLowerCase() + "\uf8ff" )

searchAllQuery.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
        // filter your data here by username and country
        User user = dataSnapshot.getValue(User.class);
        if (user.getUsername().contains('wei')  || user.getCoutnry().contains('usa')) {
            // add the user to your list maybe?
        }
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});


text:
Q: isInfixOf and finding a string within a string The problem I have is that I am using isInfixOf on a string below to check whether the word I am looking for is within the string, the below works up to a certain point.
> "world" `isInfixOf` "hello world"
True

but what if it's part of another word it still returns TRUE as below:
> "wor" `isInfixOf` "hello world"
True

I am trying to find out whether the word passed in is in the string I am looking for but it is not part of another song.
I have tried a lot of methods but I am not sure how I could make sure the word is not part of a another word.
WORDS does not work because it doesn't strip the string of it's punc character.

A: You can use a different approach. The words function creates a list of strings that contains all of the words in a string. The elem function tells if something is part of a list. So, you could use elem "world" (words "hello world"). There are other solutions involving regular expressions, but this one is probably the simplest.

A: Some regular expression packages could be helpful here.
For example, using regex-prce-builtin.
> :m + Text.Regex.PCRE
> "Hello world" =~ "\\bworld\\b" :: Bool
True
it :: Bool
> "Hello world" =~ "\\bwor\\b" :: Bool
False

\\b stands for \b word boundary, which is used in Perl regular expressions.
So we can define new isInfixOf analogue using (=~).
> let s `isInfixOf_` l = l =~ ("\\b" ++ s ++ "\\b") :: Bool
isInfixOf_ :: RegexLike Regex source1 => [Char] -> source1 -> Bool
> "wor" `isInfixOf_` "Hello world"
False
it :: Bool
> "world" `isInfixOf_` "Hello world"
True
it :: Bool


text:
Q: How to add node at some specific index in a linked list? void insertLoc(int n, int i)
inserts a node with info n after the ith location in the list. If the ith location does not exist in the list then the program should exit with an error message.
Can anyone help me with the code please...
#include<iostream>
#include<process.h>
using namespace std;

struct node  {
    int info;
    node *nextptr;
};
class list {
    node *L,*tail;
    int count;
public:
    list() {
        L=tail=NULL;
        count=0;
    }
void size();
void InsertHead(int info);
int RemoveHead();
void Print();
void insertLoc(int n, int i);
};
void list::size() {
   cout<<"size is :"<<count<<endl;
}
void list::Print() {
    node *p;
    p=L;
    cout<<"\n\n";
    while(p!=NULL) {
        cout<<p->info<<"\t";
        p=p->nextptr;
    }
}
int list::RemoveHead() {
    int RemoveNode;
    if(L==NULL) {
        cout<<"\n\nSTACK EMPTY\n\n";
        exit(1);
    }
    node *temp;
    temp=L;
    RemoveNode=L->info;
    L=L->nextptr;
    delete temp;
    --count;
    return RemoveNode;
}
void list::InsertHead(int info) {
    node *n=new node;
    n->info=info;
    n->nextptr=L;
    L=n;
    ++count;
}
int main() {
    int choice,info;
    list L;
    while(1) {
        cout<<"\nENTER 1 FOR INSERT\n";
        cout<<"ENTER 2 FOR PRINT \n";
        cout<<"ENTER 3 FOR REMOVE\n";
        cout<<"ENTER 4 FOR SIZE\n";
        cout<<"ENTER 5 FOR SPECIFIC LOCATON\n";
        cout<<"ENTER 6 FOR EXIT\n\n";
        cin>>choice;

        if(choice==1) {
            cout<<"\n\nENTER VALUE FOR PUSH=\t";
            cin>>info;
            L.InsertHead(info);
        } else
            if(choice==2) {
                L.Print();
            } else
                if(choice==3) {
                    cout<<"REMOVE ITEM=\t"<<L.RemoveHead()<<endl;
                } else
                    if(choice==4)
                    {
                        L.size();
                    }
                    else
                        if(choice==5)
                        {
                            int infoo,pos;
                            cout<<"Enter info value nd pos=\t";
                            cin>>infoo;
                            cin>>pos;
                            L.insertLoc(infoo, pos);
                        }
                        else
                        {
                            exit();
                        }
    }
    return 0;
}

A: See insertLoc method below.  I changed the size method to return count instead of printing it on the screen.  A list class shouldn't print to the screen...just manage the list.  If something about the list needs to be printed on the screen, it would be better to have main (or some other code) call methods on the list class and print the results.  Instead of the print method being part of the list class, make it a standalone function that takes a const list& or const list* and iterates the list printing each node.
#include <iostream>
#include <process.h>

using namespace std;

struct node  {
   int info;
   node *nextptr;
};
class list {
   node *L,*tail;
   int count;
public:
   list() {
      L=tail=NULL;
      count=0;
   }
   int size();
   void InsertHead(int info);
   int RemoveHead();
   void Print();
   bool insertLoc(int n, int i);
};

bool list::insertLoc(int n, int i) {
   if (i > count)
      return false;  // error

   node *p = L;
   while (i) {
      p = p->nextptr;
      --i;
   }

   node *z = new node;
   z->info = n;
   z->nextptr = p->nextptr;
   p->nextptr = z;
   ++count;

   return true;
}

int list::size() {
   return count;
}
void list::Print() {
   node *p;
   p=L;
   cout<<"\n\n";
   while(p!=NULL) {
      cout<<p->info<<"\t";
      p=p->nextptr;
   }
}
int list::RemoveHead() {
   int RemoveNode;
   if(L==NULL) {
      cout<<"\n\nSTACK EMPTY\n\n";
      exit(1);
   }
   node *temp;
   temp=L;
   RemoveNode=L->info;
   L=L->nextptr;
   delete temp;
   --count;
   return RemoveNode;
}
void list::InsertHead(int info) {
   node *n=new node;
   n->info=info;
   n->nextptr=L;
   L=n;
   ++count;
}
int main() {
   int choice,info;
   list L;
   while(1) {
      cout<<"\nENTER 1 FOR INSERT\n";
      cout<<"ENTER 2 FOR PRINT \n";
      cout<<"ENTER 3 FOR REMOVE\n";
      cout<<"ENTER 4 FOR SIZE\n";
      cout<<"ENTER 5 FOR SPECIFIC LOCATON\n";
      cout<<"ENTER 6 FOR EXIT\n\n";
      cin>>choice;

      if(choice==1) {
         cout<<"\n\nENTER VALUE FOR PUSH=\t";
         cin>>info;
         L.InsertHead(info);
      } else
         if(choice==2) {
            L.Print();
         } else
            if(choice==3) {
               cout<<"REMOVE ITEM=\t"<<L.RemoveHead()<<endl;
            } else
               if(choice==4)
               {
                  cout << "size is :" << L.size() << endl;
               }
               else
                  if(choice==5)
                  {
                     int infoo,pos;
                     cout<<"Enter info value nd pos=\t";
                     cin>>infoo;
                     cin>>pos;
                     if (!L.insertLoc(infoo, pos)) {
                        cout << "insertLoc(" << infoo << ", " << pos
                           << ") failed. List size=" << L.size() << endl;
                        break;
                     }
                  }
                  else
                  {
                     exit(1);
                  }
   }

   return 0;
}


text:
Q: Perform code when frame is changed I have a custom class that's a subclass of UIView. In the storyboard I set a UIView's class to the custom class. The view in the storyboard has a height constraint so that I can change the height programmatically. (I know it's not the only way, but I think it's the easiest way.)
I want to perform some code in the custom class every time the view's height changes.
I tried the following:
- (void)setFrame:(CGRect)frame  {
    [super setFrame:frame};
    NSLog(@"Frame did change");
}

But this method only runs on startup, not when it's (self) height was changed. How can I perform code anytime it's frame is changed?

A: Just override layoutSubviews method in your custom view class
- (void)layoutSubviews
{
   [super layoutSubviews];
   NSLog(@"Frame did change");
}


text:
Q: Maven: build another POM as a part of build cycle Our web application uses a database and is currently configured as two unrelated Maven projects (kept in different git repositories):

*

*The application code (Java), let's call it app-pom.xml

*The database schema db-pom.xml - built upon Liquibase changelogs. Liquibase runs as a part of the deploy phase.

This worked just fine, but now we're setting up an end-2-end test, which requires a test DB. (Yes I know we could make DB changelogs a part of app-pom.xml, but we've chosen this design because there are more applications that use this DB schema).
Is it possible to download db-pom.xml and run its deploy target as a part of app-pom.xml's build cycle (e.g. during pre-integration-test)?


text:
Q: Staging test: Listener not resolving - TimeOut Error ( ChainLink Solidity Course)   Raffle Staging Tests
    fulfillRandomWords
Setting up test...
Setting up Listener...
Entering Raffle...
Ok, time to wait...
All Good here!!!
      1) works with live Chainlink Keepers and Chainlink VRF, we get a random winner

  0 passing (8m)
  1 failing

Problem:
Code runs properly until listener tries to listen to raffle.once("WinnerPicked", async () => { }

*

*It fails to resolve the try/catch block

*It fails to call upkeep but calls vrf succesfully (transactions for 0.1 ETH registered)

Error:
Error: Timeout of 500000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

================================================================
Code Block:
          describe("fulfillRandomWords", function () {
              it("works with live Chainlink Keepers and Chainlink VRF, we get a random winner", async function () {
                  // enter the raffle
                  console.log("Setting up test...")
                  const startingTimeStamp = await raffle.getLatestTimeStamp()
                  const accounts = await ethers.getSigners()

                  console.log("Setting up Listener...")
                  await new Promise(async (resolve, reject) => {
                      // setup listener before we enter the raffle
                      // Just in case the blockchain moves REALLY fast
                      raffle.once("WinnerPicked", async () => {
                          console.log("WinnerPicked event fired!")
                          try {
                              // add our asserts here
                              const recentWinner = await raffle.getRecentWinner()
                              const raffleState = await raffle.getRaffleState()
                              const winnerEndingBalance = await accounts[0].getBalance()
                              const endingTimeStamp = await raffle.getLatestTimeStamp()

                              await expect(raffle.getPlayer(0)).to.be.reverted
                              assert.equal(recentWinner.toString(), accounts[0].address)
                              assert.equal(raffleState, 0)
                              assert.equal(
                                  winnerEndingBalance.toString(),
                                  winnerStartingBalance.add(raffleEntranceFee).toString()
                              )
                              assert(endingTimeStamp > startingTimeStamp)
                              resolve()
                          } catch (error) {
                              console.log(error)
                              reject(e)
                          }
                      })

                      // Then entering the raffle
                      console.log("Entering Raffle...")
                      const tx = await raffle.enterRaffle({ value: raffleEntranceFee })
                      await tx.wait(1)
                      console.log("Ok, time to wait...")
                      const winnerStartingBalance = await accounts[0].getBalance()
                      console.log("All Good here!!!")
                      // and this code WONT complete until our listener has finished listening!
                  })
              })
          })
      })

================================================================
Solutions Attempted:

*

*GitHub conversation: https://github.com/smartcontractkit/full-blockchain-solidity-course-js/discussions/729
| When removed alters the code and functionality & does not fix the problem in my case
(bool upkeepNeeded, ) = checkUpkeep("");
      if (!upkeepNeeded) {
          revert Raffle__UpkeepNotNeeded(
              address(this).balance,
              s_players.length,
              uint256(s_raffleState)
          );
      }

*

*GitHub conversation: https://github.com/smartcontractkit/full-blockchain-solidity-course-js/discussions/967

*Google search + Forums

| 5 days spent researching a solution but still no success...
================================================================
Steps to reproduce:

*

*GitHub Repo:  https://github.com/DorianDaSilva/RaffleStagingDebug
================================================================
Repo:
Chainlink Solidity Course: https://github.com/PatrickAlphaC/hardhat-smartcontract-lottery-fcc

*

*../test/staging/Raffle.staging.test.js

================================================================
I would appreciate if someone could help me figure out how to fix the problem block or code so it runs as originally intended.
Thank you!


text:
Q: Оформление программы, свой дизайн Есть простая форма, мне нужно её украсить так, как я нарисовал макет в Adboe Photoshop. Как лучше будет реализовать картинку (макет) в живой интерфейс программы?

*

*Какие способы сейчас более актуальны?

*С помощью Canvas'a можно все это сделать или я ошибаюсь?

*Касательно картинок. Слышал, что некоторые умельцы делают весь дизайн с помощью нарезки картинок из Adobe Photoshop. Насколько это будет правильно?

P.S. Материала много в Интернете, но везде говорят по-разному и противоречат друг другу. Хотелось бы услышать мнение "в живую".
A: Модно и правильно делать так, чтобы программа выглядела естественно.
Не у всех хорошее зрение, не у всех выставлены стандартные настройки и много-много чего. Даже не у всех версий виндов одинаковое поведение.


text:
Q: Maven failsafe run Fitnesse tests I need to run some Fitnesse tests on the maven integration phase, when I do  mvn clean verify  the Fitnesse tests are executed but after the execution I get this:

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.723
  sec - in integration.runnerIT [INFO] --------------------- [INFO]
  BUILD SUCCESS [INFO] ---------------------

The thing is that the tests are executed and one of the test fail but maven says that no test was executed.
This is my pom file:
<plugins>
    <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.18.1</version>
        <executions>
            <execution>

            </execution>
        </executions>
        <configuration>
            <excludes>
                <!-- this test actually runs fitnesse tests
                     therefore it will only be executed for
                     integration-test goal
                -->
                <exclude>**/*IT.java</exclude>
            </excludes>
        </configuration>
    </plugin>

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-failsafe-plugin</artifactId>
        <version>2.18.1</version>

        <executions>
            <execution>
                <goals>
                    <goal>integration-test</goal>
                    <goal>verify</goal>
                </goals>
                <configuration>
                    <excludes>
                        <exclude>**/*Test.java</exclude>
                    </excludes>
                </configuration>
            </execution>
        </executions>
    </plugin>

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
            <source>1.7</source>
            <target>1.7</target>
            <encoding>UTF8</encoding>
            <optimize>true</optimize>
        </configuration>
    </plugin>
</plugins>

And this is my Test runner:
@RunWith(FitNesseRunner.class)
@FitNesseRunner.Suite("TimTests")
@FitNesseRunner.FitnesseDir("./src/test/resources")
@FitNesseRunner.OutputDir("./target/fitnesse-results")
public class runnerIT {
}

How maven can show the number of Fitness tests are executed and if they failed or not? is it possible?


text:
Q: Getting null values in a string Just started java.
The main code has no problem in it.
The hihestPage and lowestPages both show correct values
but im getting null on the bookmaxpage and bookminpage.
Trying to get the Title name on both max and min page.
    package Library;

import java.util.Scanner;
import java.util.Arrays;
public class Library {
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner scan = new Scanner(System.in);

    int i,j,number;
    int count=0;
    float highestPrice=0,total=0;
    String bookmaxpage=" ",bookminpage=" ";
    int highestPage=0;
    float averageCost=0;

    String Title[] = new String[20];
    String Author[] = new String[20];
    String Publisher[] = new String[20];
    float Price[] = new float[20];
    int Page[] = new int[20];
    int ISBN[] = new int[20];

    System.out.println("Enter the number of books that u want to enter : ");
    number = scan.nextInt();

    for(i=0;i<number;i++) {

        System.out.println("Enter Details of the book. ");

        System.out.println("Enter the title: ");
        Title[i]=scan.next();
            if(Title[i].equalsIgnoreCase("nomore")) {
                break;
            }
        System.out.println("Enter the author: ");
        Author[i]=scan.next();
        System.out.println("Enter the publisher: ");
        Publisher[i]=scan.next();
        System.out.println("Enter the price: ");
        Price[i]=scan.nextFloat();
        System.out.println("Enter the pages: ");
        Page[i]=scan.nextInt();
        System.out.println("Enter the ISBN: ");
        ISBN[i]=scan.nextInt();

        total=total+Price[i];
        count++;

    }

    for(i=0;i<Price.length;i++) {
        if(Price[i]>highestPrice)
            highestPrice = Price[i];
    }

    float lowestPrice= Price[0];
    for(i=0;i<Price.length;i++) {
        if(lowestPrice<Price[i])
            lowestPrice = Price[i];

    }

    for(i=0;i<Page.length;i++) {
        if(Page[i]>highestPage)
            highestPage = Page[i];
        bookmaxpage=Title[i];

    }

    int lowestPage= Page[0];
    for(i=0;i<Page.length;i++) {
        if(lowestPage<Page[i])
            lowestPage = Page[i];

        bookminpage=Title[i];
    }

    averageCost = total / number;

    System.out.println("Title \t\t Author \t\t Publisher \t\t Price \t Pages \t ISBN");
    System.out.println("======\t\t ====== \t\t ========= \t\t ===== \t ===== \t ====");
    for(i=0;i<number;i++) {

            System.out.println(Title[i] +" \t\t "+ Author[i] +" \t\t\t "+ Publisher[i] +" \t\t\t "+ Price[i] +" \t "+ Page[i] +" \t "+ ISBN[i]);
    }

    System.out.println("\n\n\n\nTotals ");
    System.out.println("------------------------------");
    System.out.println("Total number of books : " + count);
    System.out.println("Total cost of books : " + total);
    System.out.println("Maximum cost of a book : " + highestPrice);
    System.out.println("Minimum cost of a book : " + lowestPrice);
    System.out.println(bookmaxpage + " has the highest number of pages :" + highestPage);
    System.out.println(bookminpage + " has the lowest number of pages :" + lowestPage);
    System.out.println("Average Cost of books : " + averageCost);
}

}
Outcome : null has the maximum pages : 280.
Looking for : Example has the maximum pages : 280

A: There are a few issues with this code, but the one you've specifically pointed out is coming from the loops where you assign bookminpage and bookmaxpage.
Because you are initialising your arrays to have 20 elements, the loops are running all the way until i = 19, so unless you input exactly 20 books, you are setting bookminpage = Title[19] = null.
I would recommend initialising your arrays after you've asked how many books there are going to be.

I also think you are missing some braces on your if statements. If you have something like this
if(condition)
    statement1;
statement2;

then only statement1 is in the if block.

As a side note I would research into some Java naming conventions, variable names should almost always be in camelCase.


text:
Q: iads integration with cocos2d I am trying to integrate iads in my cocos2d application. In the ABCPopAppDelegate file implemnentation I have the following code:
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
    // wrapper controller class

    // CC_DIRECTOR_INIT()
    //
    // 1. Initializes an EAGLView with 0-bit depth format, and RGB565 render buffer
    // 2. EAGLView multiple touches: disabled
    // 3. creates a UIWindow, and assign it to the "window" var (it must already be declared)
    // 4. Parents EAGLView to the newly created window
    // 5. Creates Display Link Director
    // 5a. If it fails, it will use an NSTimer director
    // 6. It will try to run at 60 FPS
    // 7. Display FPS: NO
    // 8. Device orientation: Portrait
    // 9. Connects the director to the EAGLView
    CC_DIRECTOR_INIT();

    CCDirector *director = [CCDirector sharedDirector];
    CGSize winSize = [director winSize];
    MainViewController *controller = [[MainViewController alloc] init];
    controller.view.frame = CGRectMake(0,winSize.height-50 , 320, 50);
    controller.view.hidden = YES;

    controller.bannerView = [[ADBannerView alloc] initWithFrame:CGRectZero];

    //controller.bannerView.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifier320x50];
    //controller.bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;

    [controller.bannerView setDelegate:controller];

    [controller.view addSubview:controller.bannerView];

And I get the following error:
"_OBJC_CLASS_$_ADBannerView", referenced from:

what does that mean?

A: You are getting that error because you haven't add the iADFramework to your Target on XCode. Make sure you add it as a WEAK reference so that it doesn't break on devices running < 4.0 iOS. Don't forget to make the  RootViewController to comply with ADBannerViewDelegate.
As the above are suggesting, I would also recommend you to go through a nice tutorial. I like this one:
http://xcode4all.wordpress.com/2011/06/10/how-to-add-iad-banner-in-iphone-app/
and this other one:
http://useyourloaf.com/blog/2010/11/27/iad-framework-updates-for-ios-42.html


text:
Q: Replace text with CSS for woocommerce LOGIN page Im trying to replace a text with css, im using this code but not working...
https://monettia.com/mi-cuenta/
"Register" text
div.u-column2.col-2 h2{
 visibility:hidden;
}
div.u-column2.col-2 h2{
 content: 'new text';
}

Thanks

A: Please try with this, i hope it will work. It is only idea that the work can be done in this way
div.u-column2.col-2 h2{
 position: relative;
}
div.u-column2.col-2 h2:after{
    visibility: visible;
    content: 'new text';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background: gray;
}


text:
Q: Is there any risk in leaving a Li-ion connected to a solar panel with only step-down converter? I have a 18V solar panel which is connected to a step-down buck converter, which drops the voltage from 18V to 3.5V. When clouds block the sun, the voltage drops to less than 3.1V. I have added a diode on the positive terminal to make sure that the battery doesn't give back any current, but I was wondering if there is any risk in having such a fluctuation. Li-ion is sensible to trickle-voltage, and I am worried that this kind of of fluctuations will destroy the battery. Is this fear motivated by reality?
Right now, I'm only connecting the wires to the battery when it is full sun, because I have a constant voltage more or less. Can I keep this connection all the time or do I need other components to keep the battery safe?

A: Instead of what you are using just use a propper board. It will charge better and the risk is going to be smaller.
Search on eBay or Aliexpress for CN3791. The board is less than 4$ and does eveything properly.
If you are curious to learn about it, read it's datasheet.


text:
Q: Powershell hashtables as argument to custom cmdlet in C# Ive been using a custom class for some time like this in PS (2.0):
import-module .\MyClassLib.dll

$task = New-Object MyClassLib.OracleScript -Property @{
                                                            Files="MyScript.sql"
                                                            Database="TEST"
                                                            User="USER"
                                                            Password="PASSWORD"
                                                        }
$result = $task.Execute()

And this works just fine.
However i wanted to create a CmdLet in C# to do the work instead. So after creating the cmdlet i thought I could do one of the following:
Invoke-OracleScript @{
                            Files="Script.sql"
                            Database="db"
                            User="user"
                            Password="password"
                           }

Invoke-OracleScript @{
                            Files="Script.sql";
                            Database="db";
                            User="user";
                            Password="password";
                           }

Invoke-OracleScript -Property @{
                            Files="Script.sql"
                            Database="db"
                            User="user"
                            Password="password"
                           }

But no luck. :(.
I keep getting errors like:

*

*Cannot find the file System.Collections.Hashtable    ( it thinks the entire hashtable is the Files parameter)

*A parameter cannot be found that matches parameter name 'Property'

*And a couple more.

My Class:
[Cmdlet(VerbsLifecycle.Invoke, "OracleScript", ConfirmImpact = ConfirmImpact.High, SupportsShouldProcess = true, SupportsTransactions = false)]
public class Invoke_OracleScript : Cmdlet, IOracleScript
{
    [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
    public string Files { get; set; }

    [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
    public string Database { get; set; }
    ....

If I instead use parameters like this: -Files ""  -Database "",  it works just fine, but everything has to be on 1 line which is very bad for reading. So the hashtable is really my biggest wish :).
Can anyone explain to me what im missing here?
(ParameterSets?, a secret attribute i've been  unable to find in the docs, other)
Kind regards

A: You might want to take a look at a feature of PowerShell called Splatting. By default, a Cmdlet can take all its parameters and their values as a hashtable and you can pass that hash in as a param.
Function Add-ThreeNumbers {
param ($a,$b,$c)
$a + $b + $c
}

$params = @{a=10; b=15; c = 20}

Add-ThreeNumbers @params

A: If all you care is to make the cmdlet call to be in multiple lines, you can use backtick (`) to extend the command to the next line:
get-process -Name notepad `
            -Computername localhost `
            -Verbose

Or, you can create custom object:
$process = new-object psobject
$process | add-member -name name -value notepad -type noteproperty
$process | add-member -name computername -value localhost -type noteproperty
$process | get-process

Or, what you were doing:
$process = new-object psobject -property @{ name="notepad";
                                            computername = "localhost";}

$process | get-process

I think hashtable as objects was a feature that was added in v3.0 ( currently in CTP)


text:
Q: Iterating through DictReader I have read a csv file using,
with open('test.csv', newline='') as csv_file:
        #restval = blank columns = - /// restkey = extra columns +
        d = csv.DictReader(csv_file, fieldnames=None, restkey='+', restval='-', delimiter=',', quotechar='"')

I would like to iterate through the created dictionary to find blank values within the csv.
I have tried:
for k, v in d.items()
#Do stuff

However I get the error: AttributeError: 'DictReader' object has no attribute 'items'
Is it right in saying that the values stored in d is a dictionary of dictionaries?
Coming from C# I would have stored the csv in a multidimensional array with a nested for loop to iterate through the values. Unfortunately I'm still new to Python - any help + explanations will be appreciated!

A: You have to first iterate over the dict getting each row, and then iterate over the items in each row:
for row in d:
    for k, v in row.items():
        # Do stuff

A: DictReader() produces a sequence of dictionaries, not just one dictionary.
for row in d:
    for k, v in row.items():

A: We also can try:
with open('test.csv', newline='') as csv_file:
        #restval = blank columns = - /// restkey = extra columns +
        d = csv.DictReader(csv_file, fieldnames=None, restkey='+', restval='-', delimiter=',', quotechar='"')
        data = list(d)

for row in data:
        for key,val in row.items():
                print(key)
                print(val)


text:
Q: Simple PHP task of updating database with radio buttons Front-end designer here, not a PHP developer and I really need the help. Need to make a system that will allow the client to log into their own area to update a table. The table will have about 20 records and each row will be edited with radio buttons (4 choices). Only 2 columns, one for ID and one called status (the editable data).
The viewer will only see the changes made by the client and a background color change to that row depending on the status, which means the editable part will have to hold 2 pieces of data (integer value to change color and the name of the status, e.g. value of the radio button to change color, and label of button to echo the text into the cell). Will deal about login system later...
Database set-up:
Database: test
Table: fire_alert
Structure:
   id (INT, PRIMARY); color(INT); warning(VACHAR);

connect.php:
<?php
// Database Variables (edit with your own server information)
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'test';

// Connect to Database
$connection = mysql_connect($server, $user, $pass)
    or die("Could not connect to server ... \n" . mysql_error());
mysql_select_db($db)
    or die("Could not connect to database ... \n" . mysql_error());
?>

view.php:

<?php
// connect to the database
include('connect.php');
include("header.php");

// get results from database
$result = mysql_query("SELECT * FROM fire_alert")
    or die(mysql_error());
echo "Current date - " . date("Y/m/d") . "

";

// display data in table
echo "
";
echo "
 Area	 Status
";

// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array($result)) {
    // echo out the contents of each row into a table
    echo "
";
    echo '' . $row['id'] . '	';
    echo '' . $row['warning'] . '	';
    echo "
";
}

// close table>
echo "
";

echo 'Change Area Status	';
?>

edit.php (client access only) no dynamic data changes yet, hardcoded HTML so far:
<?php include("header.php"); ?>
<?php include("connect.php"); ?>

<?
$result = mysql_query("SELECT * FROM fire_alert")
    or die(mysql_error());
echo "Current date - " . date("Y/m/d") . "

";
?>

Area	Status

        1

            <form method="post" action="edit.php">
                <input type="radio" id="radio1" name="radio" value="1" />Safe
                <input type="radio" id="radio2" name="radio" value="2" />Caution L1
                <input type="radio" id="radio3" name="radio" value="3" />Caution L2
                <input type="radio" id="radio4" name="radio" value="4" />Closed
            </form>

<?php echo 'Update	'; ?>

A: The simplest way to run this update (or the way I use anyways) is by leveraging javascript.  Have each section of radio blocks in its own form that submits automatically onChange, and include a hidden variable to indicate page submission.  Then just write a function to update the database, based on the inputted user's id (or however you're validating) and their selection choice...
Something like:
if($_POST["submit"] == 1)
{
  $id = $_POST["id"];
  $radio = $_POST["radio"];
  $query = "UPDATE fire_alert SET warning = '$radio' WHERE id = '$id'";
  $result = mysql_query($query) or die(mysql_error());
}

You have a problem with how you formatted your view.php link, that line should be as follows:
'Update'; ?>'
Though the above won't quite work as you're intending since it's not submitting the form, so the radio button values won't be passed... instead you should do:
<form method="post" action="edit.php">
    <input type="radio" id="radio1" name="radio" value="1" onChange="this.submit()"/>Safe
    <input type="radio" id="radio2" name="radio" value="2" onChange="this.submit()"/>Caution L1
    <input type="radio" id="radio3" name="radio" value="3" onChange="this.submit()" />Caution L2
    <input type="radio" id="radio4" name="radio" value="4" onChange="this.submit()"/>Closed
    <input type="hidden" name="id" value="<?=$row["id"]?>" />
</form>

And you'll need to edit your php to reflect that difference as well


text:
Q: Does the union of all these neighborhood cover $[0,1]$ Consider the rationals in $[0,1]$. Around each I take a neighborhood (possibly of different radii). Is the union of all these neighborhood sure to cover $[0,1]$? What if I had used irrationals instead of rationals?

A: Hint: Take your least favourite irrational $\alpha$ in the interval $[0,1]$. For every rational $r$, you can construct an interval $I_r$ with centre $r$ that avoids $\alpha$.


text:
Q: Cannot Restore LAN Connection I have two servers, 198.162.0.4 and 198.162.0.10, that were connected across a LAN.  They are the components of a DMZ where 198.162.0.4 is the wen server and 198.162.0.10 the application server.  198.162.0.4 is running Ubuntu 11.04 while 198.162.0.10 is running Ubuntu 11.10.  I had to restart 198.162.0.10 because Unity froze up.  (I have since replaced it with Gnome.)  Ever since I started it up again, I cannot get connectivity with 198.162.0.4.  When I try
ping 192.162.0.4

I get
PING 192.162.0.4 (192.162.0.4) 56(84) bytes of data.

That is, it just hangs.  I get the same result if I try
ping 192.162.0.10

on 192.162.0.4.
I had been saving my iptables in iptables.save but now I see that that fie is of zero size for some reason although I had a lot of rules in the IPtable.  I tried to fix the problem with
sudo iptables -A OUTPUT -s 192.162.0.4 -j ACCEPT
sudo iptables -A OUTPUT -d 192.162.0.4 -j ACCEPT
sudo iptables -A INPUT -s 192.162.0.4 -j ACCEPT
sudo iptables -A INPUT -d 192.162.0.4 -j ACCEPT

but it has no effect. How do I fix it?

A: This might be an issue where the 198.162.0.4 is not responding to arps correctly.
One way to check this is to starting pinging 198.162.0.4 and then at the same to do an arp -an on the 198.162.0.10 and see if the other server is listed there properly.
Also, to check if it is a connectivity problem at all, try disabling your firewalls entirely until you can establish connectivity that way, at least then you can isolate the problem.
Finally, in this situation it is always good to run tcpdump in the background to save the packets. Remember to set the size to maximum to get the full packet!
(tcpdump -i <interface> -s 65535 -w <some-file>). That should provide you with some clues as to what is going on.

A: You are confusing your IP addresses.   Your hosts are almost certainly 192.168.x.x, but you called them 198.162.x.x in your question, and then used 192.162.x.x in your ping command.  Those are all different.


text:
Q: Continuity equation in QM I found this question in a quantum mechanics exam:
What is the physical interpretation of the continuity equation $\frac{\partial\rho}{\partial t}+\frac{\partial j}{\partial x}=0$? Here $\rho(x,t)$ is the probability density and $j(x,t)$ is the probability current.
I assume they want a one liner like "probability is conserved". But to be honest I do not understand this. Can any one help me here? What's the one liner they are looking for and why? Many thanks!

A: The continuity equation in 3-dimensions is
$$\frac{\partial \rho}{\partial t} + \vec{\nabla}·\vec{j}=0$$
where the second term is the divergence of $\vec{j}$. By integrating this equation within a fixed volume $V$ whose boundary is $\partial V$, and applying the divergence theorem, we get the integral form of the continuity equation:
$$\frac{d}{dt}\iiint\limits_{V}{\rho dV} + \iint\limits_{\partial V}{\vec{j}·\vec{dS}} =0$$
where the surface integral is over the closed surface $\partial V$ with $\vec{dS}$ defined as pointing normally outward. This equation states that the time rate of change of the probability within volume V is equal to the probability flux entering volume V across the boundary $\partial V$. This is a statement of conservation of probability.

A: You're actually right, it stems from the "conservation" of probability, or the fact that probability sums to 1. It is literally the equation that says if $\rho$ changes, then that must be due to $j$.
Consider the integral version of this equation. In 3D the space derivative is a divergence,
$$\int \left[\frac{\partial \rho}{\partial t} + \nabla\cdot j\right] dV$$
$$\frac{\partial P}{\partial t} = - \oint j \cdot dA$$
The time rate of change of probability in an area is equal to the amount of probability "leaving" the area in any direction (through the surface that defines the area).
In fact, this is the same as the differential form continuity equation in fluids, charge (electromagnetism), heat, etc.

A: This is a point that's not super subtle but is often only partially expressed in popular conversations in my experience. All the current answers are "correct but not complete", as Einstein liked to say. ;)
OK, so a continuity equation implies a conservation law, sure, but it implies something much stronger. It implies a local conservation law. The difference between the two is beautifully explained by Griffiths in their Electrodynamics book, in Chapter $8$, which I'll borrow. Suppose a quantity, say electric charge, is conserved. Given this much information, one can imagine that $5$ Coulomb of charge suddenly disappears in New York and $5$ Coulomb of charge suddenly appears in Vegas. This is perfectly consistent with the conservation of charge because the total amount of charge remains unchanged. But, Maxwell's equations imply a much stronger conservation law for charges, in particular, for a charge to disappear in New York and reappear in Vegas, it would have to travel in space from New York to Vegas. This is the local conservation of charge. A continuity equation implies local conservation of charge, not just a global one.
Now, let's get to the continuity equation for probability density in quantum mechanics. As with any continuity equation, it implies local conservation of probability. But it is important to ask as to why! The unitarity of quantum mechanics which is implied by the time translational symmetry of the universe (cf. Wigner's theorem) says that the probability in quantum mechanics is conserved. However, this only implies global conservation of probability. And since the Schrödinger equation is simply another way of saying that the evolution of a quantum state is unitary, it also shouldn't imply anything stronger. Then why do we get local conservation for probability using the Schrödinger equation? Well, it is because we smuggle in a specific form of the Hamiltonian. In particular, we usually consider a Hamiltonian of the form $\hat{H} = \hat{p}^2/2m + V(\hat{x})$. This kind of Hamiltonian represents interactions that are local in position basis. This is the key as to why we obtain a local conservation law for probability in the position basis. For example, you wouldn't get a continuity equation for the probability density in the momentum basis because interactions are not local in momentum.
So, to summarize, the continuity equation for probability density in position basis implies that the probability is locally conserved in the position basis, which is because the Hermitian Hamiltonian which governs the unitary time evolution of a state is taken to be local in position basis.

A: I would like to add a few more elaborations over the previous answer.
The Continuity Equation appears in many areas of Physics; for example, the same equation appears in Electrodynamics, Quantum Mechanics, Fluid Dynamics and Heat conduction but with different physical interpretations of $\rho$ and $\boldsymbol j$. It is indeed a mathematical form of conservation of charge, probability, mass or energy(respectively in the areas mentioned above). You have written it in one dimension but its most general form in three dimensions is $$\frac{\partial\rho}{\partial t}+\nabla\cdot\boldsymbol j=0\tag{1}$$
First let us see this equation in the light of Electrodynamics. Here, $\rho(\textbf r,t)$ is charge density, i.e., $\rho(\textbf r,t) dV$ denotes the amount of charge present in an infinitesimal volume $dV$ around the point $\textbf r$ at time $t$ . $\textbf j$ is the volume current density which is defined as 'charge flowing per unit time per unit area held perpendicular to the flow'; so if the velocity of the charge is $\textbf v$, then in unit time, the volume traversed is $v$ and so $\textbf j=\rho\textbf v$ . The equation $(1)$ can also be written as $$\nabla\cdot\textbf j=-\frac{\partial \rho}{\partial t}\Rightarrow \int_V \nabla\cdot\textbf j\,dV=-\frac{\partial}{\partial t}\int_V \rho \,dV\tag{2}$$
The physical interpretation of the divergence of a vector is that, its integral over a closed volume gives the net outward flux of the vector through the entire closed surface of the volume (in accordance with Gauss' Divergence Theorem). Now here, charge is conserved. So if charge flows out of a closed volume, then it must be at the expense of the charge inside it; in other words, the net outward flux of the volume current density throughout the surface of the volume is equal to the rate of decrease of charge density inside the volume. This is the physical interpretation of the Continuity Equation which is evidently a manifestation of conservation of charge.
There is a beautiful discussion regarding this in the book 'Introduction to Electrodynamics' (4th Edition, Chapter 8) by David J. Griffiths.
In Quantum Mechanics, we speak in terms of probabilities which according to me is not easy to 'feel' at first glance. Now that you have known the physical meaning of the Continuity Equation in the context of charges which is easy to imagine intuitively, you can understand the same equation in the light of Quantum Mechanics at ease. In Electrodynamics, charge flows but here what 'flows' is 'probability' (that's the weird nature of Quantum Mechanics!). $\rho(\textbf r,t)=\Psi^*\Psi$ is probability density which is interpreted as: the probability that a particle exists in an infinitesimal volume $dV$ around the point $\textbf r$ at time $t$ is given by $\rho dV=\Psi^*\Psi dV$ where $\Psi(\textbf r,t)$ is the wave-function of the particle. The probability current is given as $$\textbf j=\frac{\hbar}{2mi}(\Psi^*\nabla\Psi-\Psi\nabla\Psi^*)$$ which describes the flow of probability per unit time per unit area. Now, as the particle will always exist somewhere, so the total probability is conserved. So what does the Continuity Equation $(2)$ says now? That, the net outward flux of the probability current throughout the surface of a closed volume $V$ is equal to the rate of decrease of the probability density inside the volume $V$. It reflects that the more the outward flux, the less probable is the particle to be found inside the volume $V$.
Similarly, you can also find the meaning of $(1)$ in the light of diffusion in Fluid Dynamics or heat conduction. In the former, it means that the net outward flux of a fluid throughout a volume occurs at the expense of the mass of fluid inside the volume, thus reflecting the conservation of mass. In the latter, the quantity analogous to mass is energy.
You can read more about the Continuity Equation from various sources like : https://en.wikipedia.org/wiki/Continuity_equation#Energy_and_heat
Lastly, I would make a remark. When one becomes able to see how the same equation drops in so wonderfully in such a wide variety of areas, one realizes the underlying beauty of it explaining different natural phenomena in the same spirit. That is when, I think, the joy of Physics becomes utmost! Happy learning!


text:
Q: Problems in positioning div and image in Jquery UI Tabs Plugin I have downloaded Jquery UI Tabs Widget from

http://jqueryui.com/tabs/

And everything works perfect, when I use the next code:

Tab 1

Tab 2

Tab 3

Tab 4

    Image Test

        Tab 3

    Tab 4

CSS for red_div:
#red_div {
    width: 300px;
    height: 300px;
    background-color: red;
}

But when I add align attribute for the image, like

or when I add float attribute for div#red_div
#red_div {
    ...
    float: left;
}

I have problems with positioning. They are not in the place, they are supposed to be. They cross the bottom line. The pictures will describe this better.
http://i.stack.imgur.com/efFnK.jpg
http://i.stack.imgur.com/MLWJu.jpg

How can I get rid of this problem, if I really need to use float for div and align for image? Thanks.
UPDATE:
I have posted this problem on JSFiddle:
http://jsfiddle.net/q6F7r/

A: Try adding float (and width) to the "main div".
.ui-tabs {float:left; width:100%;}

http://jsfiddle.net/q6F7r/6/


text:
Q: formula for density of maximal Poisson disk sampling of radius 1? Maximal Poisson disk sampling of radius r, applied to a finite planar region, is defined by successively choosing sample points uniformly randomly from the part of the region that is not within distance r from any previously chosen sample point, until no more choices are possible.
As the size of the original region goes to infinity (keeping some constant not-too-weird shape, e.g. a square), the expected density (that is, number of sample points per unit area) produced by maximal Poisson disk sampling of radius 1 approaches a constant.  What is that constant?
Conversely, given a target density, what value of r will produce samplings whose expected density is equal to the target?
(As the region size approaches infinity, of course.)
I don't see any mention of this in the standard algorithmic references by Cook, Mitchell, Dunbar/Humphries, or Bridson.
UPDATE 2016/05/13:
@j.c. pointed out in comment that this is the same problem referred to in previous question
Packing density of randomly deposited circles on a plane, aka "Random Sequential Addition" or "Random Sequential Adsorption".  The reference given in j.c.'s accepted answer
gives an experimentally found estimate "fraction of space filled in the jammed state is around θJθJ=0.5472±0.002".  That says the constant I'm looking for is approximately 0.5472*4/$\pi$=0.6967, which is believable.
I can get a bit better estimate by implementing the state-of-the-art algorithm
described in Eurographics 2012, Ebeida/Mitchell/Patney/Davidson/Owens "A Simple Algorithm for Maximal Poisson-Disk Sampling in High Dimensions" and running it on a 10000x10000 square region, with toriodal boundaries to prevent edge artifacts. The number of points obtained on five different runs were:
69655186
69654635
69657327
69652623
69652892

which says the point density constant is roughly 0.6965[45] ± .00002.
I'm wondering if there is a formula, or at least an algorithm that converges faster than these experimental results, for computing this number.


text:
Q: Two notions of conditional expectation For a randomn variable $Y$ and an event $B$ we can define:
$$E(Y \mid B) = \frac{E(1_B\cdot Y)}{P(B)}$$ as the conditional expectation.
Now, for a sigma algebra $\mathcal{B}$ and sets $B$ in it you can also define:
$$\int_B E(X|\mathcal{B}) \, dP \; = \; \int_B X \, dP.$$
What I was wondering about is: Is the first definition somehow contained in the second one?
I mean,  we can treat $E(Y|B)$ as a (almost sure ) constant random variable. The problem is, $B$ is not a sigma algebra and therefore I don't see whether we can interpret $E(Y|B)$ in the sense of the second definition. Are there really two disjoint disjoint definitions for a conditional expectation available?

A: If you set $\mathcal{B} = \{ \emptyset, B, B', \Omega\}$ and define your random variable $E(X|\mathcal{B}) = E(X|B)$ on $B$ and $E(X|\mathcal{B}) = E(X|B')$ on $B'$.
then the two formulas are equivalent: $$\int_B E(X|\mathcal{B}) \, dP = E(X | B) P(B) $$
and $$ \int_B X \, dP = E(1_B X). $$


text:
Q: Ubuntu 16.04 VMware - Bluetooth unable to connect I've been using VMware which claims to have HID support, however I am unable to connect to my device as the connect switch is greyed out. (My host OS is macOS Sierra.) I tried using the command-line bluetoothctl, but it claims the device is unavailable.
drivers@ubuntu:~$ bluetoothctl
[NEW] Controller 78:4F:43:96:5D:53 ubuntu [default]
[NEW] Device 00:1E:35:77:43:03 Nintendo RVL-CNT-01
[bluetooth]# info 00:1E:35:77:43:03
Device 00:1E:35:77:43:03
    Name: Nintendo RVL-CNT-01
    Alias: Nintendo RVL-CNT-01
    Class: 0x002504
    Icon: input-gaming
    Paired: yes
    Trusted: yes
    Blocked: no
    Connected: no
    LegacyPairing: no
    UUID: Service Discovery Serve.. (00001000-0000-1000-8000-00805f9b34fb)
    UUID: PnP Information           (00001200-0000-1000-8000-00805f9b34fb)
    Modalias: usb:v057Ep0306d0600

[bluetooth]# connect 00:1E:35:77:43:03
Attempting to connect to 00:1E:35:77:43:03
[CHG] Device 00:1E:35:77:43:03 Connected: yes
Failed to connect: org.bluez.Error.NotAvailable
[CHG] Device 00:1E:35:77:43:03 Connected: no

[bluetooth]# quit
[DEL] Controller 78:4F:43:96:5D:53 ubuntu [default]

Many threads that I've found ask for the output to lsusb. Oddly enough, the lsusb output does not even mention bluetooth anywhere! According to this thread, the culprit is installing firmware for broadcom, but I have already done that.
drivers@ubuntu:~$ lsusb
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 005: ID 0e0f:0002 VMware, Inc. Virtual USB Hub
Bus 003 Device 004: ID 0e0f:0002 VMware, Inc. Virtual USB Hub
Bus 003 Device 003: ID 0e0f:0008 VMware, Inc.
Bus 003 Device 002: ID 0e0f:0003 VMware, Inc. Virtual Mouse
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 002: ID 0e0f:0002 VMware, Inc. Virtual USB Hub
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub


text:
Q: How to choose the best estimator? [Econometrics - panel data] I'm quite new to econometrics and Stata. I'm trying to learn it by my own but I'm having some problems. Here's my problem: I have a balanced panel data and I need to choose the best estimator for my regression model.
I have regressed my panel data in Stata using five different estimators and I don't know which one is the best. I need to choose one between these five.

*

*Pooled OLS estimator

*Between estimator

*Fixed Effects estimator

*First-differences estimator

*Random effects estimator

I also had calculated the Hausman test but it only tests the Fixed X Random Effects Model. The result of Hausman test was Prob>chi2 = 0.9699.
So I need to use the FE estimator. Is that? And about the others estimators?

A: Here are the steps that I use to estimate an panel data with Stata:
1, Peform an RE estimation with xtreg,re
2, Peform the Lagrange multiplier test for random effects with xttest0.The LM test helps you decide between a random effects regression and a simple OLS regression. The null hypothesis in the LM test is that variances across entities is zero. This is, no significant difference across units (i.e. no panel effect), and Pooled OLS is applied. If the null hypothesis is rejected, to step 3.
3, Perform an FE estimation with xtreg,fe, then perform an hausman test to compare with the RE estimation.
Differentiating POLS, FE, and RE is the first step to panel analysis for me.

A: Since you labeled this as econometrics, ostensibly you care about consistently estimating the coefficients. In that case, you should think about whether RE or Pooled OLS are justified on economic terms, meaning whether you have an identification problem in terms of omitted variation.
If the time-invariant heterogeneity is likely correlated with the error term, then RE and pooled OLS will be inconsistent and FE or D-D should be used.
While the tests that the other answer provides can help with determining whether you should not use RE or pooled OLS, if the tests fails to restrict your estimation method selection, you cannot have too much confidence that RE will be consistent as foolproof testing for endogeneity in this context cannot be done.

A: Model selection
Based on the information you provided, I assume that you have estimated all the models. If so, you are basically asking how to choose the best model. There are a couple of model selection criteria. The most usual methods are as follows:

*

*The $R^2$. A high $R^2$ indicates a good fit. If you use different independent variables in each model, it is better to use the $\bar{R}^2$ (adjusted $R^2$). Note: don't use this metric to pick the best model if you want to forecast, there is a lot of risk of overfitting.

*Information criteria such as the AIC and the BIC. These metrics are defined as a loss function plus a penalty term (AIC and BIC differ in the penalty term). A loss function should be minimized, so choose the model with the lowest AIC or BIC.

*These slides also mention a Mallows $C_p$, but I have never heard of it during my Bachelor nor during my Master in econometrics.
There are many more methods to decide the best model, but are probably too advanced for beginners in econometrics.
To (hopefully) give you more intuition about the different estimators I suggest you read this guide. It may be a bit technical, but it lists all the advantages and disadvantages of the different estimators.
The Hausman test
The high P-value indicates that you should reject the $H_0$. The $H_0$ in the Hausman test is that the RE is preferred over the FE due to higher efficiency. So yes, you should use the FE estimator.

A: "The high P-value indicates that you should reject the H0."
It should be otherwise; low p-values indicate that one should reject H0, so with a high p-Value should random effects.
A good introduction to the theory behind the different estimators and the Breusch-Pagan as well as Hausman test is provided here: https://sites.google.com/site/econometricsacademy/econometrics-models/panel-data-models


text:
Q: Send multiple variable with PHP AJAX GET onclick of a button I have two dynamically loaded dropdowns: one containing golf course holes information and another holding users- together the information will be used to generate a scorecard.
When the course is selected and a user is selected I want to click a button and then this will generate the scorecard.
Below is the code for the 'course' dropdown
<?php
    $db_host = 'localhost';
    $db_user = 'root';
    $db_pass = '';
    $db_name = '';

    $con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
    if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
    }

    $sql = "SELECT courseID, name FROM courses";

    $result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));

    while ($row = mysqli_fetch_array($result))
    {
        $courses[] = '<option       value="'.$row['courseID'].'">'.$row['name'].'</option>';
    }
     ?>

Below is the code for the 'user' dropdown
<?php

    $db_host = 'localhost';
    $db_user = 'root';
    $db_pass = '';
    $db_name = '';

    $con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
    if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
    }

    $sql = "SELECT userID, forename, surname FROM user";

    $result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));

    while ($row = mysqli_fetch_array($result))
    {
    $users[] = '<option value="'.$row['userID'].'">'.$row['forename'].' '.$row['surname'].'</option>';
    }

     ?>

Below is the HTML code for the dropdowns
<form>
<select id="selectCourse" onchange="showCourse(this.value)">
  <option value = "">Select Course</option>
  <?php foreach($courses as $c){
    echo $c;
}?>
</select>

<select id="selectUser" >
    <option value = "">Select User</option>
    <?php foreach($users as $u){
        echo $u;
    } ?>
    </select>

<button type="button" >Click me</button>
</form>

At the moment I have code that uses the 'onchange' to load the first part of the scorecard which contains the hole information about that course. I am having problems changing this to the click of the button and also consider another variable from the user dropdown.
The below code is taken from W3Schools which loaded the hole information correctly based on 'onchange'.

The below code shows the first half of the scorecard being generated from the selection of the first dropdown.
    <?php
$cValue = mysql_real_escape_string($_GET['cValue']);

$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';

$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

$sql="SELECT DISTINCT holeNumber, strokeIndex, par FROM holes WHERE courseID= '".$cValue."'";
$result = mysqli_query($con,$sql) or die("Error: ".mysqli_error($con));

echo '

HoleNumber
Par
Stroke Index
Score
Points

';
while($row = mysqli_fetch_array($result)) {
    echo "
";
    echo "" . $row['holeNumber'] . "	";
    echo "" . $row['par'] . "	";
    echo "" . $row['strokeIndex'] . "	";
    echo " <input required type=text />	";
    echo " 	";
    echo "
";
}
echo "
";
mysqli_close($con);
?>

What I am looking to know is can I pass two variables through at this point below:
xmlhttp.open("GET","generateSC.php?cValue="+str,true);

and if so how would I get the second variable.
EDIT

I've updated what I have above... the problem now is how do i get the button to work with the two variables?
                 <form>
<select id="selectCourse">
  <option value = "">Select Course</option>
  <?php foreach($courses as $c){
    echo $c;
}?>
</select>

<select id="selectUser" >
    <option value = "">Select User</option>
    <?php foreach($users as $u){
        echo $u;
    } ?>
    </select>

<button type="button" >Click me</button>
</form>

A: Just fetch the values from both dropdowns and concatinate the URL:
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
xmlhttp.open("GET","generateSC.php?cValue="+course+"&user="+user,true);

Then your generateSC php script will of course have to fetch the value from the user parameter and work with that as well.
$_GET['user'] will fetch the value from the user parameter.


text:
Q: Ошибка MySQL: Cannot send session cache limiter - headers already sent Подскажите, столкнулся с вот такой ошибкой

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at X:\home\localhost\www\My\profile.php:1) in X:\home\localhost\www\Myprogect\profile.php on line 2

Как ее можно решить? Вот то, что в profile.php. Заранее спасибо!
<?php
session_start();

include("bd.php");

if (!empty($_SESSION['email']) and !empty($_SESSION['password'])) {

    $email    = $_SESSION['email'];
    $password = $_SESSION['password'];
    $result2  = mysql_query("SELECT id FROM users WHERE email='$email' AND password='$password' ", $db);
    $myrow2   = mysql_fetch_array($result2);
    if (empty($myrow2['id'])) {

        exit("Register plz!");
    }
} else {
    $result = mysql_query("SELECT * FROM users WHERE id='$id'", $db);
    $myrow  = mysql_fetch_array($result);

    if (empty($myrow['email'])) {
        exit("no user");
    }
}
?>

A: Это ошибка PHP, а не Mysql. Функция session_start() посылает заголовок, но если до нее был какой-либо вывод (echo, какой-либо текст вне <? ?>, или, как уже сказали - BOM), то заголовки отсылаются до этого вывода и, наталкиваясь на session_start(), php выдает ошибку, что заголовки уже посланы и поезд ушел.
Нужно смотреть то, что описано в ошибке дальше: output started at... и искать вывод именно там.
A: Файл подключен в другой документ? И если да, проверьте, что подключен он первым, в самом начале документа. В файле profile.php, до <?php не дожно быть никакого другого кода, пробелов, пустых строк etc. Проверьте так же, чтоб документ, если он в кодировке UTF-8, был сохранен без BOM.