text:
Q: django Admin list object print My user model is as follows.
**model.py**
class User(models.Model):
    #user_idx = models.AutoField('user-num', primary_key=True)
    user_idx = models.OneToOneField(Counsel, primary_key=True, db_column="user_idx", related_name="useridx" , on_delete="models.DO_NOTHING")
    district_id = models.IntegerField(blank=True, null=True)
    user_email = models.CharField(unique=True, max_length=200)
    user_password = models.CharField(max_length=200)
    user_name = models.CharField(max_length=100)

    class Meta:
        managed = False
        db_table = 'user'

           verbose_name_plural = "USER"

class Counsel(models.Model):
    counsel_idx = models.AutoField(primary_key=True)
    category_sub_idx = models.IntegerField(blank=True, null=True)
    user_idx = models.IntegerField()
    counsel_title = models.CharField(max_length=255)
    counsel_contents = models.TextField()
    counsel_status = models.CharField(max_length=1, choices=COUNSEL_STATUS)
    answer_count = models.IntegerField()
    hit = models.IntegerField()
    user_ip = models.CharField(max_length=20, blank=True, null=True)
    register_date = models.DateTimeField()
    update_date = models.DateTimeField()
    deleted = models.CharField(max_length=1, choices=DELETE_STATUS)

The django Admin then created the source as follows:
class UserAdmin(admin.ModelAdmin):
    list_display = ('user_idx', 'show_firm_url', 'user_name',)

    def show_firm_url(self, obj):
        return format_html("{1}", obj.user_idx, obj.user_email)

    show_firm_url.short_description = 'E-mail'

The results are like images.

Counsel object (1494)
Please tell me how to get this number out.
Counsel object (1494) -----> 1494

A: override __unicode__ to change what django renders for your model object => this method works for python2 not python3
override __str__ to change what django renders for your model object
class User(models.Model):

    user_idx = models.OneToOneField(Counsel, primary_key=True,
    db_column="user_idx", related_name="useridx" , on_delete="models.DO_NOTHING")
    district_id = models.IntegerField(blank=True, null=True)
    user_email = models.CharField(unique=True, max_length=200)
    user_password = models.CharField(max_length=200)
    user_name = models.CharField(max_length=100)

    def __str__(self):
        return "%d" % self.user_idx.id  # id is field of Counsel object you want to show

In your case if you want to change what Counsel object represents you have to change that model to this one:
class Counsel(models.Model):
    counsel_idx = models.AutoField(primary_key=True)
    category_sub_idx = models.IntegerField(blank=True, null=True)
    user_idx = models.IntegerField()
    counsel_title = models.CharField(max_length=255)
    counsel_contents = models.TextField()
    counsel_status = models.CharField(max_length=1, choices=COUNSEL_STATUS)
    answer_count = models.IntegerField()
    hit = models.IntegerField()
    user_ip = models.CharField(max_length=20, blank=True, null=True)
    register_date = models.DateTimeField()
    update_date = models.DateTimeField()
    deleted = models.CharField(max_length=1, choices=DELETE_STATUS)

    def __str__(self):
        return "%d" % self.user_idx

A: Django uses the __str__() method defined on a model instance whenever it needs to represent the model instance as a string:
class User(models.Model):
    # ... your fields

    def __str__(self):
        return "%d" % self.user_idx.pk

__unicode__() only works if your are not running Django on Python3.


text:
Q: Comparing elements of two lists in jython I am EXTREMELY new to coding and have no idea how to efficiently compare the elements in two lists/arrays in jython.  I have one list of length 5 and another of length 0 to infinity.  Elements are not in any kind of order. I want to find the difference between each element of the two lists.  So if list1 = [30, 20, 50, 66, 2] and list2 = [6, 50, 90], I should have 15 outputs (len(list1)*len(list2)).  I know how to go through and compare each element one by one, but I need an efficient way to compare all elements at once.  I think I need some kind of iterator function, but have no idea how to implement it.

A: This tutorial on control flows might be helpful.
list1 = [30, 20, 50, 66, 2]
list2 = [6, 50, 90]

result = []

for item1 in list1:
    for item2 in list2:
        result.append( item1 - item2 )

print result
#[24, -20, -60, 14, -30, -70, 44, 0, -40, 60, 16, -24, -4, -48, -88]

A: I guess this should do:
list_a=[30,20,50,66,2]
list_b=[6,50,90]

for i in list_a:
    for j in list_b:
        #compare here, i am assuming a differnce is the comparision you want to do
        print i-j

A: I find list comprehensions easier to read:
from pprint import pprint
list1 = [30, 20, 50, 66, 2]
list2 = [6, 50, 90]

result = [[ one * two for one in list1] for two in list2]
pprint(result)

A: Another option here with list comprehensions:
compare one by one if they are equal
print [x==y for x in list2 for y in list1 ]
output:
[False, False, False, False, False, False, False, True, False, False, False, False, False, False, False]

and print matching:
print [ x for x in list2 for y in list1 if x==y ]
output:
[50]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display Text Based On Dropdown Selection I'm trying to write some fairly basic code, but not having touched JavaScript in many years, I'm really not sure about the best way to go about it.
The goal: Have a dropdown of 42 arena section numbers that when selected, will display either "Red" or "Black" based on that number. For the sake of being overly informative, the section numbers are:
Black: 103, 105, 107, 111, 113, 115, 119, 121, 123, 127, 129, 131, 201, 203, 205, 207, 209, 217, 219, 221, 223, 225
Red: 104, 106, 110, 112, 114, 116, 120, 122, 126, 128, 130, 132, 202, 204, 206, 218, 220, 222, 224
Does anyone know the best method for going about this? I appreciate the help!

A: Use the value attributes of options to contain red or black. The display text will be the number, but the select element val() comes from the value of the selected option.
HTML (shortened for the example):
<select>
    <option value="black">103</option>
    <option value="black">105</option>
    <option value="black">107</option>
    <option value="black">111</option>
    <option value="black">113</option>
    <option value="black">115</option>
    <option value="red">104</option>
    <option value="red">106</option>
</select>

http://jsfiddle.net/25mneof2/1/
$('select').change(function(){
    $('#output').val($(this).val());
});


text:
Q: Request For Help In using POST in postman and Angular Controller I am using Postman for the first time to POST to a server. I get an error a non-descript body is required.
What should I put in the body? I selected JSON and raw.

This is the Angular controller code:
namespace backend.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class QuestionsController : ControllerBase
{
    // POST api/values
    [HttpPost]
    public void Post([FromBody] string value)
    {
    }
}

}

A: A POST request contains a payload (data which we want to be saved via this POST request). In postman, we need to send that through the request body. Add the JSON/data (in the acceptable signature) to be saved through the request in the request body.

A: I found the answer here
The body is :
"{  \"key1\": \"value1\" }"


text:
Q: Insert int variable into the class using LLVM PASS or Clang I want to insert integer variable into all classes using LLVM PASS or Clang.
How to do this ?
For example..
class foo {
     int a;
}

I want to insert new value as below.
class foo {
     int a;
     unsigned int b; // I want to insert this.
}

How can I do this using LLVM PASS or Clang ?
 - I much prefer LLVM PASS.
Thank you very much :)

A: My recommendation would be to use Clang for this, as LLVM operates on bitcode (IR) and the operation you want is very much C++ related, so why not exploit Clang's knowledge about the AST?
With LibTooling you can write stand-alone tool to do exactly what you want. More specifically, use an AST Matcher to find all C++ class declarations (cxxRecordDecl). You can then insert a new FieldDecl in your callback.
More info: LibTooling and LibASTMatchers Tutorial


text:
Q: Does a subclass need to override the clone() method explicitly if the superclass has already done it? If class A extends class B and class B has already implemented the Cloneable interface, then is it necessary for class A to declare 'clone() throws CloneNotSupportedException'?
I guess it should not be mandatory, as the property to clone objects of class A would automatically be inherited from class B.

A: It is necessary to override clone() if class B defines non-primitve mutable member fields. These need to be deep copied explicitly within B.clone(). If B only contains primitive and/or immutable data members, A.clone() will do the job.
For a more detailed explanation, see this earlier answer of mine to a similar question.

A: If the parent class, and all ancestors, implements its Clone method by calling its parent class' Clone method, all the way up to Object.clone, and if none of the fields added by the subclass hold references to things which should be changeable on one object without affecting the other, then one can simply inherit clone without overriding it.  If the parent class implements the clone method as described above but the subclass adds fields that themselves need to be cloned, the best pattern is for the subclass to call base.Clone and then clone the appropriate fields.
If the parent class or any ancestor does not implement its Clone method as described above but instead uses a copy constructor, then the derived class, and all base classes derived from it) must override Clone to do likewise, regardless of whether the base class adds any new fields.
Unfortunately, I know of no nice way to ascertain which category a parent class belongs to.  If a parent class supports Clone by calling base.Clone, it would be unfortunate for a derived class to needlessly break the chain by implementing a copy constructor.  On the other hand, if the parent class implements Clone as a copy constructor, a base class which does not do so will have broken semantics.


text:
Q: XSD Enumeration used in a XSLT File I have this XSD Enumeration :
<xs:element name="NeedEnum" type="my:Enum" />

<xs:simpleType name="Enum">
  <xs:restriction base="xs:string">
    <xs:enumeration value="Enumeration 1" id="E_1" />
    <xs:enumeration value="Enumeration 2" id="E_2" />
    <xs:enumeration value="Enumeration 3" id="E_3" />
    <xs:enumeration value="Enumeration 4" id="E_4" />
  </xs:restriction>
</xs:simpleType>

I want to be able to use this simple type/enumeration into a XSLT File to be able to have an HTML select populated with those values.
This is my XSLT File so far (just the table part, not all the namespaces) :
    <div>
     <select title="Enum" class="">
      <xsl:for-each select="Enum">
       <option>
        <xsl:value-of select="./@value"/>
       </option>
      </xsl:for-each>
      <option>
       <xsl:value-of select="NeedEnum"/>
      </option>
     </select>
    </div>

I know that my XSLT file is way off, but I would like to have a select with the value of the options being the enumeration id and the "caption" being the value of the enumeration. I mean I've been reading for a couple of hours and I didn't find anything that could've helped me.
I want to have something like this linked to my NeedEnum :
<select title="Enum" >
 <option value="E_1" >Enumeration 1</option>
 <option value="E_2" >Enumeration 2</option>
 <option value="E_3" >Enumeration 3</option>
 <option value="E_4" >Enumeration 4</option>
</select>

Can you help me?

A: You haven't said anything about your processing environment, but if this is a schema-aware transformation using Saxon-EE, then when $e is bound to the (schema-validated) NeedEnum element:
let $t := saxon:type($e)

returns (a representation of) the simple type Enum
let $f := $t('facets')[.('class')='enumeration']

returns its enumeration facet
let $v := $f('values')

returns the enumeration values as a sequence of strings.
So you can write:
<xsl:for-each select="saxon:type($e)('facets')[.('class')='enumeration']('values')">
   <option value="E_{position()}"><xsl:value-of select="."/></option>
</xsl:for-each>

The id attributes in the schema, unfortunately, are not available.
(Not tested.)


text:
Q: How to solve "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in 'where clause'" I am trying to extend the sales order grind in Magento in order to show Product Name, SKU, And Billing email. I've had to use an Observer since there is a module currently rewriting the Grid. I have the columns I need but I am unable to search them without getting this error.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in 'where clause'

Here is my Observer
public function salesOrderGridCollectionLoadBefore($observer)
    {
        $collection = $observer->getOrderGridCollection();

        $select = $collection->getSelect();

        if(Mage::getStoreConfig('sales/ordergrid/postcode'))
        {
            $select->joinLeft(array(
                    'sfoa'=>'sales_flat_order_address'),
                    'main_table.entity_id = sfoa.parent_id AND sfoa.address_type="billing"',
                    array(
                        'sfoa.postcode',
                        'sfoa.email',

                    )
                );
        }

        if(Mage::getStoreConfig('sales/ordergrid/skus')||(Mage::getStoreConfig('sales/ordergrid/items')))
        {

            $select->join(array(
                        'item'=>$collection->getTable('sales/order_item')),
                    'item.order_id=`main_table`.entity_id AND item.product_type="simple"',
                    array(
                        'skus' => new Zend_Db_Expr('group_concat(item.sku SEPARATOR ", ")'),
                        'name' => new Zend_Db_Expr('group_concat(item.name SEPARATOR ", ")')
                         )
                     );
        }

        if(Mage::getStoreConfig('sales/ordergrid/payment'))
        {
            $select->joinLeft(array(
                        'payment' => $collection->getTable('sales/order_payment')),
                    'payment.parent_id=main_table.entity_id',
                    array(
                        'payment_method' => 'method'
                         )
                    );
        }

        if(Mage::getStoreConfig('sales/ordergrid/coupon'))
        {
            $select->joinLeft('sales_flat_order',
                    'main_table.entity_id = sales_flat_order.entity_id',
                    array(
                        'coupon_code'
                         )
                    );
        }

        $select->group('main_table.entity_id');

        // Fix for ambiguous 'created at' columns. With extended/rewrite approach we can use:
        //      $collection->addFilterToMap('created_at', 'main_table.created_at');
        // However, with event observer something more creative has to be used to fix the query:

        if ($where = $select->getPart('where')) {
            foreach ($where as $key=> $condition) {
                if (strpos($condition, 'created_at')) {
                    $new_condition = str_replace("created_at", "main_table.created_at", $condition);
                    $where[$key] = $new_condition;
                }
            }
            $select->setPart('where', $where);
        }

        //Mage::log($select->__toString());

    }

    // This adds the mass action button

    public function beforeBlockToHtml(Varien_Event_Observer $observer)
    {
        $block = $observer->getEvent()->getBlock();
        if ($block instanceof Mage_Adminhtml_Block_Sales_Order_Grid) {
            $this->_modifySalesOrderGrid($block);
            $block->getMassactionBlock()->addItem('export', array(
                        'label' => 'Download CSV',
                        'url' => $block->getUrl('*/*/massExportAction'),
                ));
        }
    }

    protected function _removeColumn(Mage_Adminhtml_Block_Sales_Order_Grid $block, $columnName)
    {
        $columns = $block->getColumns();
        unset($columns[$columnName]);
        $this->_mutateProtectedProperty($block, '_columns', $columns);
    }

    protected function _mutateProtectedProperty($object, $propertyName, $value)
    {
        $reflection = new ReflectionClass($object);
        $property = $reflection->getProperty($propertyName);
        $property->setAccessible(true);
        $property->setValue($object, $value);
    }

    protected function _callProtectedMethod($object, $methodName)
    {
        $reflection = new ReflectionClass($object);
        $method = $reflection->getMethod($methodName);
        $method->setAccessible(true);
        return $method->invoke($object);
    }

    protected function _modifySalesOrderGrid(Mage_Adminhtml_Block_Sales_Order_Grid $grid)
    {

        $this->_removeColumn($grid, 'shipping_name');
        $this->_removeColumn($grid, 'base_grand_total');
        $this->_removeColumn($grid, 'grand_total');

        $grid->sortColumnsByOrder();
        $this->_callProtectedMethod($grid, '_prepareCollection');

    }

A: Solved it...
Needed to add this to the layout.xml in order to filter
    <action method="addColumnAfter" ifconfig="sales/ordergrid/email">
        <columnId>email</columnId>
        <arguments>
            <header>Email</header>
            <index>email</index>
            <type>text</type>
            **<filter_index>sfoa.email</filter_index>**
            <width>80px</width>
        </arguments>
        <after>created_at</after>
    </action>


text:
Q: When is a child class too different to be inherited? I have a set of closely linked data structures that feel like they ought to be inherited. However, they are different in that children have some extra variables. I can achieve this via:
struct A {
int a;
int b;
virtual int kind()=0;
A(int a_, int b_) : a{a_}, b{b_} {};
}

struct B: A {
int c;
int kind() {return 1;};
B(int a_, int b_, int c_) : A(a_, b_), c{c_} {};
}

struct C : A {
int d;
int kind() {return 2;};
C(int a_, int b_, int d_) : A(a_, b_), d{d_} {};
}

But if I want to iterate through a vector of these and access variables of a derived class it starts to become a bit messy:
std::vector<A*> v;
v.push_back(new B(1,1,1));
v.push_back(new C(1,1,2));

for (A* bar : v) {
    if (bar->kind() == 1) {
        auto *bar_ = dynamic_cast<B*>(A);
        std::cout << bar_->c << std::endl;
    } else if (bar->kind() == 2) {
        auto *bar_ = dynamic_cast<C*>(A);
        std::cout << bar_->d << std::endl;
    }
}

Is this sort of thing normal, or am I missing something and breaking some important rule? Most examples I find for inheritance don't have different important member variables or methods, just the same ones implemented differently.

A: You've already done the work of creating the virtual base class. Instead of returning the kind as a value you can just overload the functions where you want to do separate things.
struct A {
  virtual ~A() = default;
  int a;
  int b;
  virtual int get_value() const = 0;
  A(int a_, int b_) : a{a_}, b{b_} {};
}

struct B: A {
  int c;
  int get_value() const override {return c;};
  B(int a_, int b_, int c_) : A(a_, b_), c{c_} {};
}

struct C : A {
  int d;
  int get_value() const override {return d;};
  C(int a_, int b_, int d_) : A(a_, b_), d{d_} {};
}

Note that I have used the override specifier here. This is a good practice in modern c++ for readability and also for code safety.
Now, we can use the virtual function to simplify the main code
std::vector<A*> v;
v.push_back(new B(1,1,1));
v.push_back(new C(1,1,2));

for (auto* bar : v) {
  std::cout << bar->get_value() << std::endl;
}

// ... do something else with v

// clean up the memory

for (auto *bar : v) {
  delete bar;
}

Remember to define a virtual destructor in the base class. This ensures that when we delete the A* in the vector v the destructor of the inherited class is also called and we don't get a memory leak.


text:
Q: Text editor with coloring to highlight "non-parameters" in conf files? Some .conf files have a lot of comments and parameters in them like so,
# WINS Server - Tells the NMBD components of Samba to be a WINS Client
# Note: Samba can be either a WINS Server, or a WINS Client, but NOT both
; wins server = w.x.y.z

# This will prevent nmbd to search for NetBIOS names through DNS.
dns proxy = no
.....

It gets difficult to look for only the parameters among the plethora of comments, so is there some text editor that can highlight the comments in dark grey so that the real parameters stand out?

A: Emacs does automatic syntax highlighting for .conf files. It's possible you won't like (I don't!) its colors for .conf files, so check https://stackoverflow.com/questions/1076503/change-emacs-syntax-highlighting-colors and you'll be able to change it to your tastes. And it can do it the same way with a GUI or in console mode.
GEdit also does it, but not automatically. Manually set the highlighter (click on "Plain Text" on the status bar, or through View > Highlighter) to awk or sh, and you'll have a similar effect.
I'm just suggesting these two. There are many other editors that will do what you want.


text:
Q: Unexpect token '(' on multiple expression statement Was trying to do a mutliple expression if statement as shown on W3Schools but my browser seems to throw a error Uncaught SyntaxError: Unexpected token ( The second if statement is the one in question: if ( newbalance > 0 || newincome > 0 ) || ( newbalance > 0 && newincome > 0 ) {
Full function
    // Start inverval
    function ticker(p) {

        var newbalance = 0;
        var newincome = 0;

        if ( p == true ) {

            if ( newbalance > 0 || newincome > 0 ) || ( newbalance > 0 && newincome > 0 ) {
                newbalance = ( newbalance + 1 );
            } else {
                newbalance = ( rmoney.balance + 1 );
            }

            $('.balancec').html('$' + formatMoney(newbalance, 2));

        } else {

            if ( btrigger.taxhike ) {
                var ticker = setTimeout(function(){
                    if ( newbalance > 0 && newincome > 0 ) {
                        newbalance = ( newbalance + boosts.taxhike ),
                        newincome = ( newincome + boosts.taxhike );
                    } else {
                        newbalance = ( newbalance + boosts.taxhike ),
                        newincome = ( newincome + boosts.taxhike );
                    }
                    $('.balancec').html('$' + formatMoney(newbalance, 2));
                    $('.incomec').html('+$' + formatMoney(newincome, 2) + '/ps');

                });
            }
            if ( btrigger.raisepay ) {
                var ticker = setTimeout(function(){
                    if ( newbalance > 0 && newincome > 0 ) {
                        newbalance = ( newbalance + boosts.raisepay ),
                        newincome = ( newincome + boosts.raisepay );
                    } else {
                        newbalance = ( newbalance + boosts.raisepay ),
                        newincome = ( newincome + boosts.raisepay );
                    }
                    $('.balancec').html('$' + formatMoney(newbalance, 2));
                    $('.incomec').html('+$' + formatMoney(newincome, 2) + '/ps');
                });
            }

        }

    }

A: You are missing parenthesis here,
if (( newbalance > 0 || newincome > 0 ) || ( newbalance > 0 && newincome > 0 )){
---^  ------------------------------------------------------------------------^

The basic syntax for the if statement is,
if(condition){
  code block
}

But you have used a syntax which is some thing like
if condition {
  code block
}

A: You do not have opening ( and closing ) parenthesis for if statement, You have if()() instead of if(()()) the outer set is missing.
Change
if ( newbalance > 0 || newincome > 0 ) || ( newbalance > 0 && newincome > 0 ) {

To
if (( newbalance > 0 || newincome > 0 ) || ( newbalance > 0 && newincome > 0 ) ){

A: You are missing open and closed parenthesis
if ( (newbalance > 0 || newincome > 0 ) || ( newbalance > 0 && newincome > 0 )) {

A: // Start inverval
function ticker(p) {

  var newbalance = 0;
  var newincome = 0;

  if ( p == true ) {

    if (( newbalance > 0 || newincome > 0 ) || ( newbalance > 0 && newincome > 0 ) {
      newbalance = ( newbalance + 1 );
    } else {
      newbalance = ( rmoney.balance + 1 );
    }

    $('.balancec').html('$' + formatMoney(newbalance, 2));

  } else {

    if ( btrigger.taxhike ) {
      var ticker = setTimeout(function(){
        if ( newbalance > 0 && newincome > 0 ) {
          newbalance = ( newbalance + boosts.taxhike ),
            newincome = ( newincome + boosts.taxhike );
        } else {
          newbalance = ( newbalance + boosts.taxhike ),
            newincome = ( newincome + boosts.taxhike );
        }
        $('.balancec').html('$' + formatMoney(newbalance, 2));
        $('.incomec').html('+$' + formatMoney(newincome, 2) + '/ps');

      });
    }
    if ( btrigger.raisepay ) {
      var ticker = setTimeout(function(){
        if ( newbalance > 0 && newincome > 0 ) {
          newbalance = ( newbalance + boosts.raisepay ),
            newincome = ( newincome + boosts.raisepay );
        } else {
          newbalance = ( newbalance + boosts.raisepay ),
            newincome = ( newincome + boosts.raisepay );
        }
        $('.balancec').html('$' + formatMoney(newbalance, 2));
        $('.incomec').html('+$' + formatMoney(newincome, 2) + '/ps');
      });
    }

  }

}

use this you miss "(" in your code

A: it seems your function is correct but you ended if condition
       if ( newbalance > 0 || newincome > 0 ) || ( newbalance > 0 && newincome > 0 ) {

}

you need change your  if condition to ..
    if (( newbalance > 0 || newincome > 0 ) || ( newbalance > 0 && newincome > 0 )){
}

How to use logical oprator
for e.g
Given that x=6 and y=3, the table below explains the logical operators:
Operator      Description                                Example
&&                and                         (x < 10 && y > 1) is true
||                or                          (x==5 || y==5) is false
!                 not                         !(x==y) is true


text:
Q: EMR run out of memory after many iterations and not clear the cache even I terminate my process I'm running a spark job on my EMR on AWS
Master:m3.xlarge
Core:r3.xlarge * 4

It is a long running process which will loop the same job in each hour. In each iteration, it will load about 600M data from S3, doing some basic operations like map, groupby, reduce, collect, and finally write data to RDS. I use dataframe and dataset to do all my jobs, and use ganglia to watch the memory usage.
And at the start of each iteration, I will call spark.catalog.clearCache() to make sure that all my cached datasets are unpersisted. I check out the value of spark.sparkContext.getPersistentRDDs.keys.size and get 0 in each start of my iteration.
However, my memory usage is still growing slowly, below is the memory usage screenshot after running my process two days

Some weird thing is that after the memory usage touch the upper limit, my "use" memory start to go down and my "cached" memory keep going larger, like below:

And finally it run out of memory after about 3-4 days
OpenJDK 64-Bit Server VM warning: INFO: os::commit_memory(0x00007f91f9d03000, 12288, 0) failed; error='Cannot allocate memory' (errno=12)
#
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (mmap) failed to map 12288 bytes for committing reserved memory.

Moreover, after the process is terminated, the "cached" memory is still persisted like below:
Since what I do is the same in each iteration and it can start from zero without any data comes from the pervious iterations. How can I really "clean" my memory usage on my machines in each iteration? Thanks!


text:
Q: Approximation of a sum within an exponential There is a well-known equation in international economics, called
the gravity equation. This equation expresses imports from a country
as a function of importer size, exporter size, and distance. In particular,
$$
X_{ij}=\frac{Y_{i}Y_{j}}{\tau_{ij}}
$$
Here, the LHS measures the value of imports by $i$ from~$,$$\tau_{ij}$
represents distance between $i$ and $j,$$Y_{i}$ represents $i's$
size and~$Y_{j}$ represents $j's$ size., Now, in a regression framework,
one estimates this equation in additive form:
$$
lnX_{ij}=lnY_{i}+lnY_{j}-ln\tau_{ij}+\epsilon_{ij}
$$
where $\epsilon_{ij}$ is a random measurement regression error term.
The OLS predicted values one obtains are defined as $\widehat{lnX_{ij}}$.
As always, the hats denote the orthogonal projection of $X_{ij}$
onto the space spanned by $Y_{i},Y_{j}$ and $\tau_{ij}.$Without
getting into the details of the procedure, one wishes to add over
all the trading partners for a country $i,$ after exponentiating
this expression. In other words, total\emph{ predicted} imports by
$i$ are
$$
\sum_{j\neq i}exp\left(\hat{\beta}_{1}lnY_{i}+\hat{\beta}_{2}lnY_{j}+ln\tau_{ij}\right)
$$
 The expression above is quite complicated. If there were no exponential,
this would be easily simplified. Can this be approximated by a linear
function, or any function that allows me to say collect terms that
don't involve $j$ , and just make this expression more tractable?
I feel that this question is not apt for the economics forum, as the
question is not about the economics.


text:
Q: 'NoneType' object is not subscriptable error I'm having trouble getting training and test data. I classified the data into seven types. Then we created a function that combines the data again. However, when I run it, the training data is None and I get the following error message:
'NoneType' object is not subscriptable
Please tell me what to do (variable data's shape is (len(data),2))
    def get_train_And_test(self, data, percent = 80):
        if percent > 100 :
            print('파라미터를 확인해주세요')
            return
        target1=[]
        trainx=[]
        testx=[]
        criteria1=0
        for i in range(7):
          target1.append([])
        for i in range(len(data)):
            if data[i, 0] < 0.5 and data[i, 1] < 0.5 :
                target1[0].append(data[i])
            elif data[i, 0] >= 0.5 and data[i, 1] < 0.5 :
                target1[1].append(data[i])
            elif data[i, 0] < 0.5 and data[i, 1] >= 0.5 :
                target1[2].append(data[i])
            elif data[i, 0] >= 0.5 and data[i, 0] < 0.75 and data[i,1]>=0.5 and data[i,1]<0.75:
                target1[3].append(data[i])
            elif data[i, 0] >= 0.5 and data[i, 0] < 0.75 and data[i,1] >= 0.75:
                target1[4].append(data[i])
            elif data[i, 1] >= 0.5 and data[i, 0] >= 0.75 and data[i,1] < 0.75:
                target1[5].append(data[i])
            elif data[i, 0] >= 0.75 and data[i, 1] >= 0.75:
                target1[6].append(data[i])
        for i in range(7):
          criteria = int(len(target1[i]) * percent / 100)
          trainx.extend(target1[i][0 : criteria])
          testx.extend(target1[i][criteria: ])
          criteria1+=criteria
        np.random.shuffle(trainx);np.random.shuffle(testx);
        print('기준 ', criteria1)
        return (trainx,testx)

    (x_train, x_test) = analysis.get_train_And_test(data, 80)
    print(x_train[0:4])

Result:

TypeError                                 Traceback (most recent call last)
<ipython-input-77-cbab7c630a54> in <module>()
      1 (x_train, x_test) = analysis.get_train_And_test(data, 80)
----> 2 print(x_train[0:4])
      3 (t_train, t_test) = analysis.get_train_And_test(encoded_target, 80)
      4 print(t_train[0:4])
      5 (x_train2, x_test2) = analysi2.get_train_And_test(data2, 80)

TypeError: 'NoneType' object is not subscriptable


text:
Q: Any way to know if a cluster exists in orientdb? Is there a command/query to know if a cluster exist in the DB? or to know the list of clusters in the DB?
Thanks.

A: Using Document API:
// if you know the name of the cluster
db.existsCluster("V");
// if you only know the id of the cluster
db.existsCluster(db.getClusterNameById(9));

Using Graph API:
graph.getRawGraph().existsCluster("V");
graph.getRawGraph().existsCluster(graph.getRawGraph().getClusterNameById(9));

A: From the API docs:
  To view all clusters, from the console run the CLUSTERS command:

  CLUSTERS:
  -------------+------+-----------+-----------+
  NAME        | ID   | TYPE      | RECORDS   |
  -------------+------+-----------+-----------+
  account     | 11   | PHYSICAL  |      1107 |
  actor       | 91   | PHYSICAL  |         3 |
  address     | 19   | PHYSICAL  |       166 |
  animal      | 17   | PHYSICAL  |         0 |
  animalrace  | 16   | PHYSICAL  |         2 |
  ....        | .... | ....      |      .... |
  -------------+------+-----------+-----------+
  TOTAL                                23481 |
  --------------------------------------------+


text:
Q: Oracle: Insert constant numbers for a set of records and reiterate with incremented value The requirement is to insert a constant number (say 1) in column A for 6 incrementing values in column B in a cycle. This set of 6 values will repeat as designed in the sequence and trigger, once maximum value of 6 is reached. However, the column A should consist of another incremented constant number (say 2) for next set of column B values and so on.
I am new to Oracle PL/SQL and triggers. I searched for a solution but couldn't get what is required. Can anyone please suggest some keywords based upon which I can find relevant information in web or share some ideas about how to resolve this?

A:
"Column A is present as primary key in another table and is present as
  foreign key in the table"

There is no easy way to count the number of instances of COL_B for each value in COL_A in the child table, because of the mutating trigger error: we cannot select rows from table T1 in a trigger built on T1.
This means storing the current values of COL_A and COL_B in another table, which it turns out you have. Effectively the referenced table is a code control table.  This is a valid design providing you accept that inserting into the child table is a serialized process because you need a lock on the parent table.
Here is a worked example: T23 is the child table, T23_CTRL stores the current values.
create table t23 (id number, col_a number, col_b number);

create table t23_ctrl (col_a number, col_b number);

insert into t23_ctrl values (1, 0);

This trigger maintains the columns in both tables.
create or replace trigger t23_trg
    before insert or update  on t23
    for each row
declare
    ctrl t23_ctrl%rowtype;
begin
    select * into ctrl
    from t23_ctrl
    for update;
    if 6 * ctrl.col_a = ctrl.col_b
    then
       ctrl.col_a := ctrl.col_a +1;
       ctrl.col_b := 0;
    end if;
    ctrl.col_b := ctrl.col_b + ctrl.col_a;

    update t23_ctrl t
    set t.col_a = ctrl.col_a
       , t.col_b = ctrl.col_b;

    :new.col_a := ctrl.col_a;
    :new.col_b := ctrl.col_b;

end;
/

Here is a test:
SQL> insert into t23 (id)
  2  select level
  3  from dual
  4  connect by level <= 14
  5  /

14 rows created.

SQL> select * from t23
  2  /

        ID      COL_A      COL_B
---------- ---------- ----------
         1          1          1
         2          1          2
         3          1          3
         4          1          4
         5          1          5
         6          1          6
         7          2          2
         8          2          4
         9          2          6
        10          2          8
        11          2         10
        12          2         12
        13          3          3
        14          3          6

14 rows selected.

SQL> select * from t23_ctrl
  2  /

      COL_A      COL_B
 ---------- ----------
          3          6

SQL>

Maybe this is not what you're expecting.  If so, please expand your answer (use the Edit feature) to include sample output.


text:
Q: How find this value if such $f[f(x,y),z]=f(z,xy)+z,x,y,z\in R$ Question:

let function $f(x,y)$ such
  $$f(x,0)=1,x\in R$$
  (2):$$f[f(x,y),z]=f(z,xy)+z,x,y,z\in R$$

Find the value
$$f(2014,6)+f(2016,6)=$$
My idea: let $y=0$, then
$$f(1,z)=f(z,0)+z=1+z$$
I think follow we can let $z=6$,But I can't solve it.
Thank you

A: $f(y,z)=f(f(1,y-1),z)=f(z,y-1)+z$, so you have a reduction formula.  Repeat until you get to $f(k,0)$ for some $k$


text:
Q: Outer bound type declarations without ScopedTypeVariables I have a following working definition:
{-# LANGUAGE ScopedTypeVariables #-}
module Control.Retry where

import Prelude hiding (catch)
import Control.Exception
import Control.Concurrent

retrying [] action = action
retrying (i:is) action = catch action processError
  where
    processError (e :: IOException) = threadDelay i >> retrying is action

Just out of curiosity I am wondering how I could reimplement this without utilizing the ScopedTypeVariables pragma, or whether I could at all, and what the inferred type declaration of processError actually is, because specifying processError :: IOException -> IO a makes it uncompilable.

A: Another option, maybe a little cleaner than asTypeOf:
retrying [] action = action
retrying (i:is) action = catch action processError
  where
    processError e = threadDelay i >> retrying is action
      where
        _ = e :: IOException

Not sure if this is idiomatic; I just made it up and it worked.

A: If you want to avoid ScopedTypeVariables, you can most of the time use asTypeOf.
retrying [] action = action
retrying (i:is) action = catch action processError
  where
    processError e = snd (e `asTypeOf` (undefined :: IOException), threadDelay i >> retrying is action)

The undefined :: IOException is an expression type signature, and that is allowed by the standard. The asTypeOf requires the exception e to be an IOException.
I would prefer ScopedTypeVariables here, though.
With
retrying :: [Int] -> IO a -> IO a

the type of processError is inferred as
processError :: IOException -> IO a

with the a here being the same type variable as in the signature of retrying. That type can, however, not be specified in Haskell without the ScopedTypeVariables extension, since type variables in written-down signatures are by default universally quantified.

A: How about this:
retrying [] action = action
retrying (i:is) action = catch action $ processError $
                         threadDelay i >> retrying is action
  where
    processError :: IO a -> IOException -> IO a
    processError foo e = foo

Basically, this takes care of the problem of doing processError :: IOException -> IO a, where the a is generic and not the same a as in the enclosing function, by taking in an argument with the type a in it in order to tie it to the type in the enclosing function.


text:
Q: Couldn't debug android app in Xiomi redmi4? I am trying to debug my android app on my xiomi redmi4 phone.
I am getting this error while running app.
What am I doing wrong? Please suggest me.
Thanks

A: If you had tried all above options(USB debugging should be ON,
Install via USB should be ON) then, Go to the developer setting, then find the option Trun on MIUI optimization,

trun it off then restart the device, hope it will work!!

A: turn off MIUI Optimization inside Developer Options. Reboot it and run android app

A: You have to uninstall the app from your phone, Before debugging and when you click Run in android studio should click allow your phone to install the app.
it happen when there is changes in build gradle
I had same issue with Mi note 2

A: I have also faced that kind of problems.
just follow the steps
Goto your mobile setting menu ---> Additional settings ---> Developer options --->

*

*Developer mode should be ON

*USB debugging should be ON

*Install via USB should be ON

After done this steps, You can able to run your app via USB.
Hope this will help you :)

A: Your device is attached to debugger and there is already app installed so you need to remove existing application using adb command in CMD so follow these steps:

*

*go to SDK and sdk\platform-tools in cmd

*adb uninstall com.app.package (package of your application)

*Now redeploy the app, your app will be installed and you will be able to debug app.


text:
Q: What is the best degradation for CSS :before, :after pseudos in older IE's CSS2.1 :before, :after pseudo-elements are a really useful for inserting static content. But  what is the best way to degrade it gracefully for older browsers that do not support such feature?
Is creating an element instead so far the best option?

A: IE8 (mostly) supports pseudo elements. There are some issues with opacity and z-index (http://css-tricks.com/browser-support-pseudo-elements/).
IE7 is <1% world wide; supporting IE7 isn't doing anyone any favors (the user needs to be forced to upgrade). However, if you must support IE7, than I can see two workarounds:

*

*As you suggested, simply create the extra HTML element. Not necessarily semantic, but if you are support IE7...you gotta do what you gotta do.

*You can use Javascript to inject the element so search engines won't see the extra element (if that is a concern).


text:
Q: Python not modifying global variable I have the below code:
failure = ""
def walk(dictItems):
    returnVal = ""
    for key, item in dictItems.items():
        if isinstance(item,dict):
            walk(item)
        else:
            returnVal = returnVal +"
"+key+" : "+ item + "
"
        global failure
        failure = returnVal
dictItems={"personal_details":{"phone*":"","nationality*":"MW","id_number*":"","gender*":"MALE","title*":"MR","surname":"","marital_status*":"MARRIED","first_name*":"","dob*":"","id_type*":"BUSINESS.REG"},"residential_details":{"city":"","location":"","residence_physical_address":""}}
walk(dictItems)
print(failure)

failure variable is always null despite having values on returningVal any help?

A: Oh I see, you reset every time returnVal therefore when you assign it to failure is empty. Change your code to this:
failure = ""
def walk(dictItems):
    for key, item in dictItems.items():
        if isinstance(item,dict):
            walk(item)
        else:
            global failure
            failure += "
"+key+" : "+ item + "
"
dictItems={"personal_details":{"phone*":"","nationality*":"MW","id_number*":"","gender*":"MALE","title*":"MR","surname":"","marital_status*":"MARRIED","first_name*":"","dob*":"","id_type*":"BUSINESS.REG"},"residential_details":{"city":"","location":"","residence_physical_address":""}}
walk(dictItems)
print(failure)

A: I guess you you are iterating over a dictionary with sub-dictionarys so calling walk wen you hit a sub-dictionary sets the failure value to only the keys and items of the sub-dictionary. You should add, not set to failure. Or walk() should return like this:
    dictItems = {
        "key1":"item1",
        "key2":"item2",
        "key3":{
            "subkey1":"subitem1",
            "subkey2":"subitem2"
        },
        "key4":"item4"
    }

    def walk(dictItems):
        returnVal = ""
        for key, item in dictItems.items():
            if isinstance(item, dict):
                returnVal += walk(item)
            else:
                returnVal += "
"+key+" : "+ item + "
"
        return returnVal
    print(walk(dictItems))


text:
Q: Module installed but can't find a shared library installed by Brew I need to install a module pyzbar which depends on another called zbar. According to the pypi link I first need to install zbar via
brew install zbar

then install the pyzbar
pip install pyzbar

Having done of that when trying to run a code based on importing specific part of the module, it gives an error.
from pyzbar.pyzbar import decode

The error is
ImportError: Unable to find zbar shared library
How to check where exactly is the issue coming from and how to resolve it?
Here are steps I took after checking comments:
1- Tried finding libzbar file and some how link that to the path so that the pyzbar file zbar_library.py can find that. The libzbar files were in this location /opt/homebrew/Cellar/zbar/0.23.90 installed by homebrew and not in usr/local/lib (which surprisingly no such directory exists on my mac). The way I added the location of zbar lib file to path was by
export DYLD_LIBRARY_PATH=/opt/homebrew/lib

in the terminal while I'm in the conda environment on which my python is running. Now when trying to run python while importing pyzbar it finds something and no longer give the "no shared lib found" error, but gives the following errors:
  File "/Users/username/miniconda3/envs/my_env/lib/python3.7/site-packages/pyzbar/zbar_library.py", line 66, in load
    libzbar = cdll.LoadLibrary(path)
  File "/Users/username/miniconda3/envs/my_env/lib/python3.7/ctypes/__init__.py", line 442, in LoadLibrary
    return self._dlltype(name)
  File "/Users/username/miniconda3/envs/my_env/lib/python3.7/ctypes/__init__.py", line 364, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: dlopen(/opt/homebrew/lib/libzbar.dylib, 6): no suitable image found.  Did find:
    /opt/homebrew/lib/libzbar.dylib: mach-o, but wrong architecture
    /opt/homebrew/Cellar/zbar/0.23.90/lib/libzbar.0.dylib: mach-o, but wrong architecture
    /opt/homebrew/lib/libzbar.dylib: mach-o, but wrong architecture
    /opt/homebrew/Cellar/zbar/0.23.90/lib/libzbar.0.dylib: mach-o, but wrong architecture

A: You may have multiple python/pip versions that caused such issue. To be sure about this, you can try
python3.9 -m pip install pyzbar

python3.9
from pyzbar.pyzbar import decode

If there are still any errors on import, please include a list of all installed pip packages by doing
pip freeze --all

A: Probably your operating system has two versions of python even if you have configured the path correctly your system installs the library in the default python and not in the version you want.
The default directory after installing python depends on your system.
You can install directly specifying which version will receive the library:
python3.9 -m pip install "package"
python3.7 -m pip install "package"
python2.7 -m pip install "package"
It is always recommended to use a version manager , virtual environment that separates the versions and can be used individually
reference install package


text:
Q: Retrieve just the month and year from database date column I stored the date (October 18, 2013 1:38am) with the following code to my database, now I just want to retrieve the month (eg. October, 2013) from the date in my database. please help.
$date = date("F j, Y g:i a");

    //insert into SQL code here
    $insert_sql = "INSERT INTO walls(upload_date) VALUES ('{$date}');";

insert into database
mysql_query($insert_sql)
        or die(mysql_error());

A: I think this will do it:
SELECT CONCAT(LEFT(upload_date, LOCATE(" ", upload_date)-1), ", ",
              SUBSTR(upload_date, LOCATE(", ", upload_date)+2,
                                  LOCATE(" ", SUBSTR(upload_date, LOCATE(", ", upload_date)+2)))) month_year
FROM walls

If you instead stored it as a DATETIME, it would be:
SELECT DATE_FORMAT(upload_date, "%M, %Y") month_year
FROM walls


text:
Q: Ошибка при чтении большого файла в память У меня файл больше 10 гиг. Хочу залить содержимое в память. Сделал проект 64х битным. Озу 256 гиг
В какой то момент времени выдаёт ошибку OutOfMemoryException. Что может быть не так? Объем используемого озу максиму гиг 15
var lst = new List<string>();
using (StreamReader sr = new StreamReader(filename))
{
    string line = string.Empty;
    while ((line = sr.ReadLine()) != null)
    {
       lst.Add(line);
    }
}

PS После долгих тестов увидел что список вмещает в себя максимум 134217728 строк. Какое-то системное ограничение. Как его обойти?

A: В App.config добавил следующий код и все заработало
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <runtime>
        <gcAllowVeryLargeObjects enabled="true" />
    </runtime>
</configuration>


text:
Q: How to close any window using OS library in python I coded my own virtual assistant in python. I know how to start apps through my voice via os.system or os.startfile, but I don't know how to close the current window ?

A: os.system('taskkill /F /IM processname')
e.g:  os.system('taskkill /F /IM chrome.exe')


text:
Q: Why do I not see instance variable after creation? (attr reader) I have following code, which creates instance variables dynamically. If the instance variable does not exist, I use the no method error to create the attr_reader and attr_writer methods dynamically. All works fine, but I don't understand why I don't see the @anything instance variable after having created the first attr_reader.
require "pry-byebug"

class UberHash
  attr_accessor :color
  def initialize
    @color = nil
  end

  def method_missing(m, *args, &block)
    if m.match(/=/)
      puts "create attr writer"
      self.instance_variable_set("@#{m[0..-2]}", args[0])
    else
      puts "create attr reader"
      self.instance_variable_get("@#{m}")
    end
  end
end

uber_hash = UberHash.new
puts "call 1 .................."
p "uber_hash.anything: #{uber_hash.anything}"
p "uber_hash.inspect: #{uber_hash.inspect}"
p uber_hash.anything = "hola"
p uber_hash.inspect

With following results:
call 1 ..................
create attr reader
"uber_hash.anything: "
"uber_hash.inspect: #<UberHash:0x00007f851b1e41a8 @color=nil>"
"#<UberHash:0x00007f851b1e41a8 @color=nil>"
create attr writer
"hola"
"#<UberHash:0x00007f851b1e41a8 @color=nil, @anything=\"hola\">"

After creating the first instance variable anything, with the method instnace_variable_set, I understand that I create an attr_reader right?
Why do I not see the @anything instance variable if I inspect the instance?

A: You don't see the instance variable in the first inspect. You expect it the be there because in previous line you call uber_hash.anything, right?
Well, the uber_hash.anything call evaluates the else in the #method_missing conditional: self.instance_variable_get("@#{m}") - that's why no instance variable is set.
Also, in #method_missing conditional you print two messages: puts "create attr writer" and puts "create attr reader" - they are wrong. It should be: puts "create instance variable" and puts "read instance variable"

A:
After creating the first instance variable anything, with the method instnace_variable_set, I understand that I create an attr_reader right?

No, that is not correct.  Your class never creates (or runs) attr_reader.  Try this (after running your example commands)
p( uber_hash.methods - Object.new.methods )

and you see only the methods additionally defined in your class be [:color, :color=, :method_missing] in your class.
The method :color is defined because of attr_accessor :color.  Remember attr_accessor etc is just a shortcut to define methods.
By contrast, the method :anything is not defined because your class has never defined the method.
Instead, in your class, every time a method uber_hash.anything is called, uber_hash.method_missing is run and does the job, that is, manipulation or viewing of the instance variable @anything.
Secondly, while instance_variable_set does set a value to an instance variable (and creates it if it does not exists), instance_variable_get refers to it only if it exists, else returns nil and does not create an instance variable. That is why @anything is created after instance_variable_set, but not just after instance_variable_get.  Try this to see the point (after your definition of the class).
class UberHash
  def test_pr
    print 'color='; p instance_variable_get("@color")
    print 'other='; p instance_variable_get("@other")
    p instance_variables  # => @other is not defined
    print 'other='; p instance_variable_set("@other", 99)
    p instance_variables  # => @other is NOW defined
  end
end

uber_hash.test_pr

Consequently, the behaviour you see is perfectly legitimate.
Note: this past answer explains it.


text:
Q: Is it possible to get different equation numbers when utilizing different label prefixes? I am writing a document in latex and I utilize \begin{equation} to write mathematical expressions, but also to draw some circuits (Quantum Computing stuff). For the circuits I utilize a specific label prefix circuit:somelabel, while for the mathematical equation I am using the standard eq:somelabel prefix.
Is it possible to generate separate numbers for separate prefixes? For example, I want the first equation in the second section to be labeled (2.1) while for the first circuit I want [2.1], for example. Now I get (2.1) for both when referencing.


text:
Q: Resample 15 min data month profile into an average day profile I have a dataframe that consists of 15 min data of each day for an entire month. Where DateTime column is a timestamp data type and the dataframe looks like this:
DateTime, Temperature, Moisture, Accumulated precipitation

1/01/2022 00:00, 23, 50, 2,
1/01/2022 00:15, 22, 45, 1,
1/01/2022 00:30, 20, 39, 0,
1/01/2022 01:00, 25, 34, 0,
1/01/2022 01:15, 23, 50, 0,
.
.
.
31/01/2022 00:00, 23, 45, 0,
31/01/2022 00:15, 22, 45, 1,
31/01/2022 00:30, 20, 39, 0,
31/01/2022 01:00, 25, 34, 0,

Therefore, how could I resample the dataframe in order to get an average value of each 15 min data for the entire month?. The expected result for December should be:
DateTime Temperature
00.00 18.4
00:15 15.4
00:30 16.5
.
.
.
23:45 15.0

A: You can create a new column called 'time' by separating the time from the 'DateTime' column, then perform a mean groupby on the 'time' column. For example:
import numpy as np
import pandas as pd

np.random.seed(42)
df = pd.DataFrame({
    'DateTime':pd.date_range('1/1/2000', periods=4*24*30, freq='15min'),
    'Temperature':np.random.uniform(low=0.0, high=100.0, size=4*24*30),
    'Moisture':np.random.uniform(low=0.0, high=100.0, size=4*24*30)
})
df['Time'] = df['DateTime'].dt.time
result = df.groupby('Time').mean().reset_index()

Output:
>>> result
        Time  Temperature   Moisture
0   00:00:00    53.906354  49.702393
1   00:15:00    58.617754  46.533957
2   00:30:00    42.697347  47.283152
3   00:45:00    48.215645  46.413589
4   01:00:00    51.422462  51.100578
..       ...          ...        ...
91  22:45:00    42.881353  43.369940
92  23:00:00    48.179361  54.289938
93  23:15:00    46.109330  48.163814
94  23:30:00    53.840951  62.281667
95  23:45:00    58.671288  43.572069


text:
Q: Получение данных из iframe Есть iframe, который я формирую, в нем input'ы [type='radio']. Мне нужно узнать какой radiobutton выбран

  Ваш браузер не поддерживает плавающие фреймы!

<?php

$i=1;
$files = scandir('/images/'.$_GET['fon']);

foreach (array_slice($files,2) as $file) {
?>

        <label for="<?php echo $file; ?>"><img src="/images/<?php echo $_GET['fon'].'/'.$file; ?>" width="100"/>
        <input type="radio" id="<?php echo $file; ?>" name="<?php echo $_GET['fon'].'[]'; ?>" value="<?php echo $file; ?>" >

    <?php if($i%4==0):?>
<?php endif; ?>
<?
    $i++;
}
?>

A: Ваши радиобаттоны должен быть такими:
<input type="radio" onclick="window.parent.myButtonSelected(1);"/>
<input type="radio" onclick="window.parent.myButtonSelected(2);"/>
<input type="radio" onclick="window.parent.myButtonSelected(3);"/>

А в родительском окне, которое содержит iframe, соответственно, нужна такая функция:
function myButtonSelected(num) {
   alert("Выбрана кнопка номер "+num)
}

A: у инфрейма свой контекст. туда даже яваскриптом не залезть.
сделан специально. чтобы например в формы логинов социалок не лазили.


text:
Q: Re-defne a Paragraph Range to Include a Subset of Words in the Paragraph I'm using Microsoft.Interop.Word / C# to programmatically create a Word document. In a given paragraph, I need to change the color of words that occur between brackets "[" and "]"
The words are variable.
As I understand it, I need a Range object in order to set colors. I'm using the following code, which does not work:
// Add the paragraph.
Microsoft.Office.Interop.Word.Paragraph pgf = document.Paragraphs.Add();

// Insert text into the paragraph.
pgf.Range.InsertBefore("JIRA Issue: " + jiraIssueId + " [" + statusName + "]");

//Get start and end locations of the brackets.
//These will define the location of the words to which I will apply colors.
int startPos = pgf.Range.Text.IndexOf("[") + 1;
int endPos = pgf.Range.Text.IndexOf("]") - 1;

/* Attempt to change range start and end positions,
 so the range contains just the words between brackets.
 I've tried two methods.
*/
// The following line does not work.
pgf.Range.SetRange(startPos, endPos);

// And the following lines do not work either
pgf.Range.Start = startPos;
pgf.Range.End = endPos;

// Attempt to Change color. The following line changes the color of entire paragraph:
pgf.Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;

/* The following always prints the entire contents of the paragraph,
  and not just the words between the brackets. So my attempts at narrowing
  the range were not successful.
*/
Console.WriteLine(pgf.Range.Text);

A: The SetRange doesn't work because you can't change beginning or ending of a paragraph. It just begins where it begins. You need an "own" range that you can modify. What a luck there exists the property Duplicate of a Range. As MSDN says: By duplicating a Range object, you can change the starting or ending character position of the duplicate range without changing the original range.
First I assume that the MS Word namspace is included:
using Microsoft.Office.Interop.Word;

So after calculating startPos and endPos you should change your code to (UPDATED):
Microsoft.Office.Interop.Word.Range rng = pgf.Range.Duplicate;
rng.MoveEnd(WdUnits.wdCharacter, endPos - rng.Characters.Count);
rng.MoveStart(WdUnits.wdCharacter, startPos);
rng.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;

and it should work. (Just don't decrement the endPos some lines above; but you will realize it)


text:
Q: How can I differentiate Safari and Chrome in CSS? I know I can use conditional CSS to differentiate webkit browsers from others, but it is my understanding that both chrome and safari are webkit browsers. How would I differentiate between the two? There is a safari specific fix that makes chrome pixelate the Nivo Slider when it gets small, and I need to get this working for both browsers.
The Safari fix is:
img{
    -webkit-transform: translate3d(0, 0, 0);
}

My Conditional Code is:
[if Webkit] img {
     -webkit-transform: translate3d(0, 0, 0);
}

Thanks!

A: If you are using JavaScript, this code fragment will distinguish Safari from Chrome:
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
    $('html').addClass('safari-only');
}

For a CSS-only hack, try this (don't know if it works):
/* Safari only */
.myClass:not(:root:root) {
}

For your specific case, with JavaScript:
JS:
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
    $('img').addClass('safari-only');
}

CSS:
img.safari-only {
     -webkit-transform: translate3d(0, 0, 0);
}

CSS only:
img:not(:root:root) {
     -webkit-transform: translate3d(0, 0, 0);
}


text:
Q: Selective reading in of JSON objects Let's assume that I have this JSON string (copied from digitalocean.com)
{
  "sammy" : {
    "username"  : "SammyShark",
    "location"  : "Indian Ocean",
    "online"    : true,
    "followers" : 987
  },
  "jesse" : {
    "username"  : "JesseOctopus",
    "location"  : "Pacific Ocean",
    "online"    : false,
    "followers" : 432
  },
  "drew" : {
    "username"  : "DrewSquid",
    "location"  : "Atlantic Ocean",
    "online"    : false,
    "followers" : 321
  },
  "jamie" : {
    "username"  : "JamieMantisShrimp",
    "location"  : "Pacific Ocean",
    "online"    : true,
    "followers" : 654
  }
}

I need to selectively read in only objects/records that contain, say, Pacific in the key named location. How can I NOT read in other records, such as the ones with "Indian Ocean" and "Atlantic Ocean" as values for location? So far, all examples I can find read in the entire file.
Thank you very much for help, even the answer is "you just have to read in the whole thing"!

A: If you really can't read the file in and slice, you can do it by loop
selective_data = ['Pacific Ocean']
batch = []

for k, v in data.items():
    for ii, jj in v.items():
        if jj in selective_data:
            batch.append(v)

df = pd.DataFrame(batch)
            username       location  online  followers
0       JesseOctopus  Pacific Ocean   False        432
1  JamieMantisShrimp  Pacific Ocean    True        654


text:
Q: Prove that a non-zero, non-unit element $a \in R$ is irreducible Prove that a non-zero, non-unit element $a \in R$ is irreducible iff its only divisors are units of $R$ and elements of $R$ which are associates of $a$
I have a proof below but i'm not sure if it is correct. I think I need to use $c$ in the second part but I'm not sure how.
Here is my proof
$\Rightarrow$
Assume $a\ne 0$, $a$ is not a unit $\in R$ is irreducible
Then $a=bc$ where at least one of $b$ or $c$ is a unit
Therefore if $b$ is a unit then $c$ is an associate of a and if $c$ is a unit then $b$ is an associate of a
As $a=bc$ then $b|a$ and $c|a$
$b$ and $c$ are either units or associates of $a$ therefore the only divisors of $a$ are units of $R$ or associates of $a\in R$
$\Leftarrow$ Assume $a\in R$ can only be divided by units or associates
Let $b,c\in R$ divide $a$, by assumption $b$ must either be a unit or an associate
If $b$ is a unit then $a$ is irreducible
else $b$ is an associate
This means there exists a unit $u\in R$ where $a=ub$
Therefore $u|a$ so once again a is divided by a unit and is therefor irreducible

A: $\Rightarrow$
Assume $a\ne 0$, $a$ is not a unit $\in R$ is irreducible
Then $a=bc$ where at least one of $b$ or $c$ is a unit
Therefore if $b$ is a unit then $c$ is an associate of a and if $c$ is a unit then $b$ is an associate of a
As $a=bc$ then $b|a$ and $c|a$
$b$ and $c$ are either units or associates of $a$ therefore the only divisors of $a$ are units of $R$ or associates of $a\in R$
$\Leftarrow$ Assume $a\in R$ can only be divided by units or associates
Let $b,c\in R$ divide $a$, by assumption $b$ must either be a unit or an associate
If $b$ is a unit then $a$ is irreducible
else $b$ is an associate
This means there exists a unit $u\in R$ where $a=ub$
Therefore $u|a$ so once again a is divided by a unit and is therefor irreducible


text:
Q: Clarification / Examples on ServiceStack Authentication I'm trying to get to grips with ServiceStack to build a new mobile product with it.  It's slowly coming together but the documentation, although good, is a little brief in parts with no facility for comments & questions.
This question is about the built-in authentication.
I have been working from the SocialBootstrap, which is a great example, though my lack of experience with backbone is a bit of a hindrance. I'd like to learn it at the same time but don't have the time to do that so want to continue with traditional views.
Based on this there are some samples or documentation extensions that would be really useful.
1. Why are all the properties on AuthUserSession strings?
I have seen via the CustomUserSession class that you can create a CustomId though shouldn't a default property map to the AutoIncrement property of a database table?  Having to parse to an integer is not really ideal. I suppose it's only done once but still seemed odd.
var user = session.TranslateTo<User>();
user.Id = int.Parse(session.UserAuthId);

2. Retrieving the session
My controllers derive from ControllerBase  which implements ServiceStackController<CustomUserSession>, so getting to the session from controllers is easy with base.UserSession. If I need to access the session in the View then I simply stuff the session in a ViewBag property.
My services extend AppServiceBase, at the moment the only way I've been able to access the session is by injecting the ClientCache:
public ICacheClient CacheClient { get; set; }

And then calling:
var userSession = SessionFeature.GetOrCreateSession<AuthUserSession>(CacheClient);

This doesn't seem the most elegant of solutions so I hope there is a better way that I don't know of.  Which leads onto..
3. IClientCache
From reading this question it sounds like I need to implement a more persistent session cache. It's quite annoying having to authenticate every time I recompile, save _layout, or any other app resetting action.
Would the recommended solution for more persistent caching be to use Memcached? Unfortunately in the past I have only worked with FormsAuthentication so this again is new territory.
container.Register<ICacheClient>(new MemcachedClientCache("127.0.0.0[:11211]");

4. Manual Registration
This is a weird one.  I was trying to code without an internet connection so I implemented manual registration to avoid having to comment out all the [Authenticate] attributes on my controllers (the views also have some logged in logic).
It worked, or I recall it working as I could continue debugging. However now back in the connected world it doesn't.  And the API endpoint seems to not exist.  If I browse to /api/register then I receive a NotImplementedException. Again, as I'm not using backbone I have a javascript function to perform the work:
var gateway = new servicestack.ClientGateway(location.protocol + "//" + location.host + '/api/');

function intiRegisterUser() {
    $('#signup-button').click(function () {
        gateway.postFormDataToService({
                Register: {
                    userName: $('#Username').val(),
                    displayName: $('#Username').val(),
                    firstName: $('#FirstName').val(),
                    lastName: $('#LastName').val(),
                    email: $('#Email').val(),
                    password: $('#Password').val()
                }
            },
            function(e) {
                document.location = "/";
            },
            function(ex) {
                handleError(ex);
            });
    });
}

This also returns a NotImplementedException.
This documentation page is great btw, but could be extended a bit to include some of this.
https://github.com/ServiceStack/ServiceStack/wiki/Sessions

A: 1. Why are all the properties on AuthUserSession strings?
ServiceStack's built-in Authentication was designed to support multiple Auth Repository and Session provider back-ends. To be able to support multiple providers and to reduce the friction required in creating new providers many metadata properties remain as strings which can hold any data type (as opposed to int's which can only hold 32bit integers).
2. Retrieving the session
When using ServiceStack's New API you can inherit from the convenient Service base class which lets you access the typed UserAuthSession with:
base.SessionAs<AuthUserSession>();

It also provides access to the dynamic Session bag with:
base.Session["dynamicProperty"]

3. IClientCache
If you want a permanent cache, use any of ServiceStack's distributed cache providers. I recommend Redis which holds many advantages over Memcached and is easy to get running in Windows with Vagrant:
4. Manual Registration
The /api/register service only implements HTTP POST. Whilst the custom route for the Registration Service is /register the pre-defined route for the RegistrationService (which your example is using) is inferred by the Registration Request DTO which is:
/api/json/syncreply/Registration

or as of v3.9.35 release, the shorter alias:
/api/json/reply/Registration

So your javascript example needs to use the Registration property, e.g:
 gateway.postFormDataToService({
    Registration: { .. }
 });


text:
Q: Get the exact contents of a textarea using javascript I have a text area that looks like this:
<textarea id="txtBody" name="txtBody">q231231231231321321321231321231231 < &lt;</textarea>

When I do this in javascript:
var t = document.getElementById('txtBody').value;

I get this back:

q231231231231321321321231321231231 < <

Seems like it should just give me the exact characters as they are... am I missing something? Is there a way to get the exact characters out of a text area?

A:
am I missing something?

& is HTML for "Start an entity".
When you put the text into the HTML document (between the start and end tags for the textarea), you are failing to represent that text as HTML.
As a result, the browser performs error recovery and treats  as "A less than character, the word strong, then a greater than character" (because tags are not allowed inside a textarea element, but treats < as "A less than character" because there isn't a machine detectable error here.

Is there a way to get the exact characters out of a text area?

You need to write the HTML correctly in the first place.
<textarea id="txtBody" name="txtBody">q2312312312<strong>313213213</strong>21231321231231 &lt; &amp;lt;</textarea>

A: I get the right contents, I guess your (X)HTML is not valid...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>untitled</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />

    <textarea id="txtBody" name="txtBody">q231231231231321321321231321231231& < &lt;</textarea>


text:
Q: OSM xml broken? I have downloaded the OSM world-map.
While parsing I get an Exception:
osm
bound
changeset
(...)
changeset
Exception in thread "main" org.xml.sax.SAXParseException; lineNumber: 3682; columnNumber: 140; XML-Dokumentstrukturen müssen innerhalb derselben Entity beginnen und enden.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:400)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
    at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1472)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.endEntity(XMLDocumentFragmentScannerImpl.java:899)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.endEntity(XMLDocumentScannerImpl.java:559)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.endEntity(XMLEntityManager.java:1398)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1916)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.scanLiteral(XMLEntityScanner.java:1187)
    at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanAttributeValue(XMLScanner.java:987)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanAttribute(XMLDocumentFragmentScannerImpl.java:1548)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1315)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2784)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:842)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:327)
    at javax.xml.parsers.SAXParser.parse(SAXParser.java:195)
    at xxxx.web.OSMReader.main(OSMReader.java:20)

My code is:
public class OSMReader {
    public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
        BZip2CompressorInputStream bic = new BZip2CompressorInputStream(new FileInputStream(new File("X:\\Medien\\Karten\\planet-200309.osm.bz2")));
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.newSAXParser().parse(bic, new DefaultHandler() {
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                System.out.println(qName);
            }
        });
        bic.close();
    }
}

I am pretty sure that OSM is able to produce capable XML files.
The XML-File itself is much too large to confirm the problem.
Any idea how to parse the XML successfully?
EDIT
I tried to read the lines in the xml:
public class OSMReader {
    public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
        BZip2CompressorInputStream bic = new BZip2CompressorInputStream(new FileInputStream(new File("X:\\Medien\\Karten\\planet-200309.osm.bz2")));
        BufferedReader br = new BufferedReader(new InputStreamReader(bic));
        int i = 0;
        while (i++ < 3685) {
            String line = br.readLine();
            if (i > 3680) {
                System.out.println(line);
            }
        }
        bic.close();
    }
}

What gives me this output:
 <changeset id="3678" created_at="2008-06-01T01:18:46Z" closed_at="2008-06-01T02:47:15Z" open="false" user="mawis" uid="37850" min_lat="49.1950155" min_lon="9.2284944" max_lat="49.2049970" max_lon="9.2458586" num_changes="154" comments_count="0"/>
 <changeset id="3679" created_at="2007-04-01T11:30:20Z" closed_at="2007-04-01T12:30:24Z" open="false" user="B10xxx" uid="6454" min_lat="52.
null
null
null

I checked the MD5 hashes and they match:
X:\Medien\Karten>fciv -md5 planet-200309.osm.bz2
//
// File Checksum Integrity Verifier version 2.05.
//
4da6b47311c1b05f603542a55df2d69b planet-200309.osm.bz2

X:\Medien\Karten>

With the contents of https://planet.openstreetmap.org/planet/2020/planet-200309.osm.bz2.md5

A: I had to add a , true to the constructor of the BZip2CompressorInputStream.


text:
Q: Does $\lim_{x\to 0} \frac{\sin(x^2\sin \frac{1}{x})}{x^2\sin \frac{1}{x}}$ exist? There are two definitions on the limit of a function:
Definition 1: Let $f(x)$ be a function defined on a neighbourhood of $x_0$,  $\lim_{x\to x_0} f(x)=A $ if only if for every real  $\varepsilon>0$,   there exists a real  $ \delta>0$  such that for all  $\mathrm{x}, 0<|x-x_0|<\delta$  implies that  $|f(x)-A|<\varepsilon$.
Definition 2:
Apart from open intervals, limits can be defined for functions on arbitrary subsets of $\mathbf{R}_{\text {, }}$ as follows (Bartle & Sherbert 2000): let $f$ be a real-valued function defined on a subset $S$ of the real line. Let $p$ be a limit point of $S$-that is, $p$ is the limit of some sequence of elements of $S$ distinct from $p$. The limit of $f_{t}$ as $x$ approaches $p$ from values in $S_{t}$ is $L$, if for every $\varepsilon>0$, there exists a $\delta>0$ such that $0<|x-p|<\delta$ and $x \in S$ implies that $|f(x)-L|<\varepsilon$.
Let $f(x)=\frac{\sin(x^2\sin \frac{1}{x})}{x^2\sin \frac{1}{x}}$, Obviously, $f(x)$ is not defined on $x=\frac{1}{n\pi}, n\in Z$ and $x=0$.
I am wondering whether  $\displaystyle\lim_{x\to 0} \frac{\sin(x^2\sin \frac{1}{x})}{x^2\sin \frac{1}{x}}$ exists.
I think the above limit exists (equals to 1) according to definition 2 but not according to definition 1. Any help would be appreciated!


text:
Q: Can losetup be made efficient with sparse files? So my setup is like this.
$ truncate -s 1T volume
$ losetup -f --show volume
/dev/loop0
$ mkfs.ext4 /dev/loop0
$ ls -sh volume
1.1G volume
$ mount /dev/loop0 /mnt/loop

Now I have a 1.1TB volume, as expected. The overhead of ext4 expanded the sparse file to 1.1G, but that's fine. Now to add a file.
$ dd if=/dev/urandom of=/mnt/loop/file bs=1M count=10240
$ ls -sh volume
12G volume

Cool, now I don't want the file.
$ rm /mnt/loop/file
$ ls -sh volume
12G volume

The free space is still taking up space, as expected, and $ fallocate -d volume frees up 1gb.
My question is, how can I zero out the free space here without expanding the volume to the full size? $ dd if=/dev/zero will expand it to full size, and with conv=sparse makes it create a useless sparse file inside the volume.
TL;DR: Is there a way to make losetup ignore writes of null blocks to null sectors, while allowing everything else?

A: To automatically discard data blocks when they are no longer used, use mount -o discard ....  Or you can manually run fstrim.
This feature was apparently added to the loop device in Linux 3.2.  https://outflux.net/blog/archives/2012/02/15/discard-hole-punching-and-trim/

In the general case, mount -o discard is not guaranteed to be effective, because some types of device are allowed to ignore discard requests when they are busy.  This would not be a concern for the size of your sparse file though.
In this general case - e.g. if you also wanted to send discard requests to an underlying physical device - the most robust method is to run fstrim at regular intervals.

A: Not a solution using built in tools, but I whipped up a python script to do what I want. Here it is if it helps anyone. Still looking for a built in solution, if there is one.
#!/usr/bin/python3.6
import os
import time
import sys

if len(sys.argv) != 2:
    print('''Usage: {} <file>

Fills a file/device with zeros, with efficiencies for sparse files.'''.format(sys.argv[0]))
    exit(1)

f = open(sys.argv[1], 'rb+', 0)

bs = 1024*1024 # block size
zb = b'\0'*bs  # a full block of zeros

lasttime = round(time.time())
block = f.read(bs)
while len(block) == bs:

    # IFF a block contains non-zero characters, zero it
    if block != zb:
        f.seek(-bs, os.SEEK_CUR)
        f.write(zb)
    block = f.read(bs)

    # Print the processed bytes every second
    # Could add a MB/s or % completed, but too lazy
    if round(time.time()) != lasttime:
        print(f.tell())
        lasttime = round(time.time())

# Hit EOF, might have missed bytes at the end
# Zero last block unconditionally, too lazy to check if its required
f.seek(-bs, os.SEEK_CUR)
f.write(zb)
f.close()


text:
Q: Dynamically adding values in activiti enum form type Can we dynamically add enum values to activiti enum form property type?
I am aware we can statically add form properties as :
<activiti:formProperty id="vacationApproved" name="Do you approve this vacation" type="enum" required="true">
  <activiti:value id="true" name="Approve" />
  <activiti:value id="false" name="Reject" />
</activiti:formProperty>

Instead of statically supplying values using activiti:value tag, i would like to achieve the same using expressions. I supplied an expression thinking it would resolve. HOwever, When the form is retrieved, there were no values in the form property. Thanks.

A: the OOTB forms aren't much flexible, they are for simple use cases. for more complex forms try extending the forms framework or simply use form-key that can be later on used to search for your custom form definitions (in form of json, xml, etc.). once you have your definition, you can work on UI based on it.


text:
Q: How to replicate np.random result directly? import numpy as np
np.seed(1)
a=np.random.randint(10)
b=np.random.randint(10)

I know that after setting the random seed, every time I run this code, a and b will always be initialized to some fixed value, respectively.
My question is: In a new run, how can I directly generate b's value without generating a's value first?
In my mind, I need something like:
import numpy as np
np.seed(1)
a = np.random.randint(10)
# DO SOMETHING to get some situation-specific information, something like a new seed

So that in the new run, I can do like:
# DO SOMETHING to load or set that situation-specific information
b = np.random.randint(10)

Is there any way to do this?

A: IIUC, use numpy.random.get_state and set_state:
import numpy as np

a = np.random.randint(10)
a
# 5

# Now get the current state
after_a = np.random.get_state()

b = np.random.randint(10)
b
# 8

# After some work...

np.random.set_state(after_a)

b = np.random.randint(10)
b
# 8

A: you can just run random function and do not need to set it for a.
first time
np.random.randint(10)
# DO SOMETHING to load or set that situation-specific information
b = np.random.randint(10)


text:
Q: struts2 jquery auto complete load all results on focus I am using the struts2 jquery plugin. I need to implement the auto complete functionality in such a way that when the user focuses on the auto complete element, it should display all the possible options. Also if the user enters some text, sutocomplete should be triggered.
Currently, the autocomplete gets triggerred only when text is typed . Is there any way to trigger it on focus of the element?

A: *

*try use loadMinimumCount = 0, it could help.

*if (1) is not working, try:
<sj:autocompleter id="test" name="test" list="list" onFocusTopics="showList"/>

<script>
    $(function(){
      $.subscribe('showList', function(event, data){
      $('select#testjson').show();
      // or $('select[name="test"]').show();
      // try one of both.
      }
    });
</script>


text:
Q: Javascript HTTP POST input JSON error I am trying to add JSON request into a HTTP POST javascript code like below. Please see the code below.
My problem is, I need to input following format JSON and send it. But, I am getting Uncaught SyntaxError: Unexpected token : Could you please advise, What is wrong formatting JSON in my code below?
Sample JSON format to be sent=> {"records":[{"value":{"foo":"bar"}}]}

Code:
function savedata() {

    var membernameStr = parseInt(document.getElementById("MemberID").value).toString();
    var data = JSON.stringify({

        "records": [["value":{"MemberID":membernameStr,"MemberName":"Anna", "AccountNo":"7623", "Address":"Peter", "AccountType":"Peter"}]]

    });
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("readystatechange", function () {
        if (this.status == 200) {
            console.log(this.responseText);

            // Based on successful response, call next POST API.
            var xhr1 = new XMLHttpRequest();
            xhr1.open("POST", "http://localhost:3500");
            xhr1.send(data);

        }
    });
    xhr.open("POST", "http://localhost:8082/topics/topictest");
    xhr.setRequestHeader("Content-Type", "application/vnd.kafka.json.v2+json; charset=utf-8");
    xhr.setRequestHeader("Accept", "application/vnd.kafka.v2+json; charset=utf-8");
    xhr.send(data);
}

A: Your JSON was incorrect in the syntax, please have a look at below JSON:
{
  "records": [
    [
      {
        "value": {
          "MemberID": membernameStr ,
          "MemberName": "Anna",
          "AccountNo": "7623",
          "Address": "Peter",
          "AccountType": "Peter"
        }
      }
    ]
  ]
}

A:
why did you use array within array ? you can also use as below ..

{
  "records": [
      {
        "value": {
          "MemberID": membernameStr ,
          "MemberName": "Anna",
          "AccountNo": "7623",
          "Address": "Peter",
          "AccountType": "Peter"
        }
      }
  ]
}


text:
Q: unable to update or upgrade using apt-get When I run sudo apt-get upgrade, I get the following error,
Extracting templates from packages: 100%
Preconfiguring packages ...
(Reading database ... 331810 files and directories currently installed.)
Removing python-jasmin (0.9.27) ...
jasmind.service is not a native service, redirecting to systemd-sysv-install
Executing /lib/systemd/systemd-sysv-install disable jasmind
insserv: warning: script 'S02jasmind' missing LSB tags and overrides
insserv: warning: script 'jasmind' missing LSB tags and overrides
insserv: warning: current stop runlevel(s) (empty) of script `jasmind' overrides LSB defaults (0 1 6).
update-rc.d: error: cannot find a LSB script for jasmind
dpkg: error processing package python-jasmin (--remove):
 subprocess installed post-removal script returned error exit status 1
Errors were encountered while processing:
 python-jasmin

How do I fix this?
Edit:
adding the output of apt-cache policy python-jasmin
python-jasmin:
  Installed: 0.9.27
  Candidate: 0.9.27
  Version table:
 *** 0.9.27 500
        500 https://packagecloud.io/jookies/python-jasmin/ubuntu xenial/main amd64 Packages
        500 https://packagecloud.io/jookies/python-jasmin/ubuntu xenial/main i386 Packages
        100 /var/lib/dpkg/status
     0.9.26 500
        500 https://packagecloud.io/jookies/python-jasmin/ubuntu xenial/main amd64 Packages
        500 https://packagecloud.io/jookies/python-jasmin/ubuntu xenial/main i386 Packages

the file /etc/init.d/jasmind is empty.


text:
Q: Async Action Method with ActionController / AsyncActionController I can write an Action Method in MVC using Async and Await keywords in my controller class inheriting Controller, then why/what is the purpose of AsyncController base class?
In code what is the difference between the following two approach
    public class FileUploadController : Controller
    {
        public async Task<ActionResult> Index()
        {...}
    }

vs
 public class FileUploadController : AsyncController
{
    public async Task<ActionResult> Index()
    {...}
}

A: As we know async tasks helps to optimise pool http rquests,

Most web developers know about ASP.NET's request processing pipeline. An HTTP request is synchronously processed on a Thread which is grabbed from the ThreadPool. The Thread on which this request is processed is blocked from doing anything else like handling another incoming reques

Here is interesing article about it,
Maybe it will be helpfull.


text:
Q: Getting Error with an API data when connecting to JAVASCRIPT I've been trying to connect to An API using JavaScript for an assignment I've been given but couldn't get it through. Every time I'm trying to run a file it's showing blank HTML page, but on using different API link my code is working fine.
The errors it's showing:
Access to XMLHttpRequest at 'http://qa.parentlane.com/api/content-feed/' from origin 'null' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://www.parentlane.com' that is not equal to the supplied origin.
scripts.js:37
Cross-Origin Read Blocking (CORB) blocked cross-origin response http://qa.parentlane.com/api/content-feed/ with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
const app = document.getElementById('root');

const container = document.createElement('div');
container.setAttribute('class', 'container');

app.appendChild(container);

var request = new XMLHttpRequest();
request.open('GET', 'http://qa.parentlane.com/api/content-feed/', true);
request.onload = function () {

  var data = JSON.parse(this.response);
  if (request.status >= 200 && request.status < 400) {
    data.forEach(feed => {
      const card = document.createElement('div');
      card.setAttribute('class', 'card');

     const h1 = document.createElement('h1');
      h1.textContent = feed.title;

      const p = document.createElement('p');
      feed.text = movie.text.substring(0, 50);
      p.textContent = `${feed.text}...`;

      container.appendChild(card);
      card.appendChild(h1);
      card.appendChild(p);
    });
  } else {
    const errorMessage = document.createElement('marquee');
    errorMessage.textContent = `Gah, it's not working!`;
    app.appendChild(errorMessage);
 }
 }

request.send();

The result should pop-up a grid-like interface with the data in the JSON file.

A: I'm afraid that's because the target host you're trying to query doesn't allow access
apart from itself. If I take a look at it's response header, it says:
access-control-allow-origin : https://www.parentlane.com

This means the script trying to query the api and the api would need to be on the same host.
Here's an in-depth article:
https://developer.mozilla.org/de/docs/Web/HTTP/CORS


text:
Q: "Nowhere near ready/finished" vs "Nowhere near being ready/finished" I have a quick question.
Which is correct? Are they both correct?

*

*I am nowhere near ready.

*I am nowhere near being ready.

Is "ready" being modified by an adverb in #1?
Please help!
THANKS!

A: You have two questions here.
First: Yes, both sentences are grammatically correct. But to me, the word "being," in the second sentence, sounds redundant. WIthout the "nowhere near" adverbial phrase, you would say "I am ready."
Second: In both sentences, "nowhere near" is an adverbial phrase.


text:
Q: ; expected but everything is correct i,m working on my first delphi script and when i want to run it there is an '; expected' error but i dont know why. When i click on the error the cursor jumps to the location where the error appears but that's two lines below the end of the code
What's wrong?
var
   stringName : String;
   stringBase : String;

procedure setPicturePath();
var
    qryPicEncode : TOraQuery;
    qryPicDecode : TOraQuery;
begin
    qryPicEncode := TOraQuery.Create(nil);
    qryPicEncode.SQL.Text := 'select ''utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw("werner weilenmann"))) from dual';
    qryPicDecode := TOraQuery.Create(nil);
    qryPicDecode.SQL.Text := 'select ''utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw("d2VybmVyIHdlaWxlbm1hbm4="))) from dual';

    qryPicEncode.open;
    qryPicEncode.first;
    if not(qryPicEncode.eof) then begin
        stringName := qryPicEncode.fieldByName('pic4Path').AsString;
    end;
    qryPicDecode.open;
    qryPicDecode.first;
    if not(qryPicDecode.eof) then begin
       stringBase := qryPicDecode.fieldByName('ODACQuery1').AsString;
    end;
    qryPicEncode:=nil;
    qryPicDecode:=nil;
end;

begin
    //Picture2.LoadFromFile('U:\Documents\logos\logo1.png');
    setPicturePath();
    showmessage(stringName);
    showmessage(stringBase);
end.

A: Seems you have some errors with begin/end's.
Here:
begin
    setPicturePath();
    showmessage(qryPicEncode);
    showmessage(qryPicDecode);
end;

you refer to variable qryPicEncode local to setPicturePath(); procedure - but this code chunk is outside of it...
Format source to reveal mistakes


text:
Q: Where to put a counter variable? I'm reading a file where each line gives some information for some certain instance in time. I want to assign each person an ID in the order in which they're read beginning at 0 and so on. Each person will be stored in a person_info object. The way I'm thinking of numbering the ids is to have a static global_id variable inside the person_info class that increments every time the constructor is called as shown below.
However, when I think about this, I feel this design is not very good because I could accidentally create a copy somewhere, and that would end up calling the constructor and subsequently increasing the global_id and then I would have a situation where the series of IDs are not contiguous (though that really doesn't break down any part of my code because it does not rely on contiguity). Aside from that are there other issues with this approach that you can think of?
The other idea is I'll just keep a global_id variable outside of the person_info class, and perhaps put it in my parsing function, and then when I construct the person_info object, I'll pass it into the constructor and then increment global_id before getting to the next person's information. That'll take care of the non-contiguity "issue," but I don't like the idea of having the global_id sitting outside of the only place it's going to be used in (i.e., the person_info struct). Ideally, I want to encapsulate it within where its actually used.
struct person_info
{
  person_info() : id{global_id} {++global_id;}
  inline static int global_id = 0;
  // there's a bunch more variables not shown here
};

A:
I could accidentally create a copy somewhere, and that would end up calling the constructor and subsequently increasing the global_id

You could create a copy constructor.
class person_info {
  person_info(const person_info& other)
    : id(other.id)
  {}
};

Or delete the copy constructor so you are not allowed to do so.
class person_info {
  person_info(const person_info&) = delete;
  person_info& operator=(const person_info&) = delete;
};


text:
Q: WUBI error after installation on Windows 8 laptop I try to install Ubuntu on a Laptop which actually runs with Windows 8.
After the Installation and restart, it´s this Error:
\ubuntu\wubildr.mbr

staus: 0x0000076


text:
Q: Vue.js Error "missing param for named route "editarProductos": Expected "id_producto" to be defined" While configuring HTML buttons in vue.js, I got a warning in console: missing param for named route "editarProductos": Expected "id_producto" to be defined Checking my code, I could infer that I got an issue with slot and slot-scope. Right now I'm working with @vue/cli 5.0.8
Also, in the line "data.item.id" from code down below, "data" reflects a error: "Property 'data' may not exist on type 'Vue3Instance<{ fields: { key: string; label: string; }[]; productos: never[]; },"
I hope u guys could help me, THANKS...
//C O D E//
 <template slot="action" slot-scope="data">
   <b-button
     size="sm"
     variant="primary"
     :to="{ name:'editarProductos', params: { id_producto: data.item.id } }"
   >
     Editar
   </b-button>
   <b-button size="sm" variant="danger">
     Eliminar
   </b-button>
</template>

<script>
import axios from 'axios';
export default {
 data() {
   return {
     fields: [
       { key: 'nombreProd', label: 'Nombre' },
       { key: 'precioProd', label: 'Precio' },
       { key: 'contenido', label: 'Contenido neto' },
       { key: 'descripcionProd', label:'Descripción' },
       { key: 'action', label:'' }
     ],
     productos: []
    };
  },
},
</script>

A: there is a problem in your code (maybe you are new to vue, it's ok keep it up and you can make it)
For your problem: You don't need data prefix just item.id is enough, see this example: https://vuejs.org/guide/introduction.html#api-styles
And if this still not work then make sure that your params(id_producto) is not required, see this: https://router.vuejs.org/guide/essentials/route-matching-syntax.html#optional-parameters


text:
Q: Adding more than 3 options in C# MessageDialog I want to add 4 options in a MessageDialog in C# Windows Store App. I can add 3 options like this example:
http://msdn.microsoft.com/en-us/library/windows/apps/dn308255.aspx
But when I am going to app 4th option it throws exception
"The operation attempted to access data outside the valid range (Exception from HRESULT: 0x8000000B)"

Is it not possible to add more than 3 options?

A: The message dialog has a command bar that can support up to three commands.
If you don't specify any commands, then a default command is added to close the dialog.
if you want to add more option try to override MessageDialog class.