text:
Q: Extension of copulas Let $(X,Y)$ be a random vector. Suppose that the marginal distribution functions of $X$ and $Y$ are known (say $F_1$ and $F_2$). Then the joint law of $(X,Y)$ is given by the following formula:
$$F_{X,Y}(x,y)=C(F_1(x),F_2(y)),$$
where C is some copula function. It means, that if the distributions of $X$ and $Y$ are given, we can construct (at least one) joint distribution of $(X,Y)$ conforming with given distributions (e.g. one can set $F_{X,Y}(x,y)=F_1(x)F_2(y)$.
I wonder whether is it possible to extent this property to the case when the distribution of $X+Y$ is known as well (say $F_3$).
My question is: if the distributions of $X$, $Y$ and $X+Y$ are given how can I construct (at least one) joint distribution of $(X,Y)$, conforming with univariate distributions?
Is there any closed-form solution like we have in case when only the marginals are given?
Thank you for the answers!

A: You can not prescribe the distribution of the sum.
Counterexample: Let X and Y be uniform on [0,1]. Now choose the distribution for X+Y so that P(X+Y < 0.5) = 1. This means P(X > 0.5) = 0 a contradiction to uniform.
A way to visualize this might be looking at mass distributions on the square [0,1]x[0,1]. Prescribing the margins (here uniform) is a restriction on the projections to the axes (i.e. 0x[0,1] and [0,1]x0) and the remaining freedom is distributing the mass in the square.

A: OK then another answer to another problem:
An easy and practical way might be discretizing all functions. Then your conditions are linear constraints which can be solved for $C$.
Since one can always transform with the inverse cdf we can assume without loss of generality that both marginal distributions are uniform [0,1]. Let $F$ be the distribution of the sum of the marginals.
Now partition the interval [0,1] into n intervals [k-1/n, k/n]. By taking products you arrive at a partition of the square $[0,1]x [0,1]$ into $n^2$ squares.
Let $C_{i,j}$ be the mass of $C$ on each of the squares of the grid. You arrive at 3 different types of constraints for $C_{i,j}$:
(1) $\sum_{i,j} C_{i,j} = 1$ this is the condition that the copula is a probability distribution
(2) $\sum_{i} C_{i,j} = 1/n$,  $\sum_{j} C_{i,j} = 1/n$ this is the condition that the marginals are uniform
(3) With $I_d = \{(i,j)| i+j = d\}$ the d-th diagonal with d = 2,...,2n the condition on the distribution of the sum is $\sum_{I_d} C_{i,j} = \sum_{I_d} F(1/i + 1/j)$.
These are 1 + n + n + (2n - 1) linear equations for the $n^2$ unknowns.
I guess this will give a numeric solution, a continous solution could be derived by a proper limit argument.
This should work not only for sums but also other functions of X and Y as well.
I hope this helps


text:
Q: ORA-00933: SQL command not properly ended ORACLE select
  (
    (select Count(country_isoname) from games.country where country_olympic_code is null)
    /
    (select Count(*) from games.country)
  ) * 100 as 'Percentage'
from
  games.country;

I am currently trying to get the percentage but getting an error, syntax looks correct i think?
PLease help!

A: 'Percentage' is a string literal. Object (column) names have be enclosed with double quotes.
So you need to use "Percentage" not 'Percentage'

A: Try using this
select (t1.specific_count/t2.all_count)*100 from
(select count(country_isoname) as specific_count from country
where country_olympic_code is null) t1,
(select count(*) as all_count from country) t2;

redpajama_set_name: RedPajamaStackExchange


text:
Q: JSoup not printing all elements in HTML table row I am trying to get all the elements in a HTML table row using JSoup. However, it seems to consistently omit columns and print only about half of the columns in the table. For instance, if I have an HTML table like so:

            1
            4

NAME

Country

Club

SR

56.00 (5)

51.62 (3)

1:47.62

And I try printing the cells like so:
Document doc = Jsoup.parse(html);  //html is a string containing the full HTML page
Elements tableRows = doc.select("tr.table");

for (Element tableRow : tableRows) {

    System.out.println(tableRow.text());

}

For some reason, the only cells that are ever printed are the 1st, 3rd and 9th cell.
You  can find the full HTML here. (It's a website used for displaying live timing of alpine ski races). For the sake of brevity I only included one
 tag, but the website contains hundreds of them. Also, I don't know if it matters, but every
 calls a Javascript function onmouseover and onmouseout.
Is the problem a bad HTML? I thought JSoup took care or cleaning bad HTML. Or am I not using JSoup properly?
Thanks for the help.
EDIT: Fixed it. As I was using and Android WebView, I had not realized I was loading the mobile site instead of the desktop version.

A: Firstly make sure which the html is: the source downloaded from the url or the full html copied from browser.If the source, you will get nothing due to the page is dynamic and the table load by http://live-timing.com/includes/aj_race.php?r=163390&&m=1&&u=5(maybe you can try to get result directly from this url).If the full html, your selector syntax has no problem, you can try in https://try.jsoup.org/, the result is correct.


text:
Q: Programmatically breaking search distance into two parts in PostgreSQL/PostGIS I have a query which for each address location (ad), searches the nearest streets (st) in a radius of 50 meters and return (260 rows) selected streets with respective address locations. Table 'ad' contains 87 rows, while 'st' contains 16,060 rows. The execution time is 61 milli-seconds. The code is below:
SELECT
      ad.gid As address_id,
      ST_AsText(ad.geom) As address_locations,
      ST_AsText(st.geom) As selected_streets
FROM ad
Left JOIN st ON ST_DWithin(ad.geom, st.geom, 50)
ORDER BY  ad.gid, St_Distance(ad.geom, st.geom);

Now, I would like to programmatically break this query such that: for each address location the search is first performed in a radius of 30 meters, if streets are found select them and then expand the search distance up to 50 meters for those not in 30 meters radius. How to do that?


text:
Q: Retrieve customer password in magento from database I have migrated my project site from magento to django, it is a site with millions of users. I have successfully imported all the data from the site but the main problem I am having, is to migrate customer database especially with password, because obviously I can't give new passwords to each customer on django site because it will be so time consuming. And for the customers to reset the password, will be very irritating and many customers will be lost from the site.
Please give me some ideas how can I retrieve customer password in magento from database?

A: You can not restore passwords. Magento uses hashes with salt for storing passwords (md5 and sha1 according to the edition).
Only things you can do - reset passwords or implement in your site the same function for checking passwords as it's done in magento.

A: At a glance it looks like django stores it's passwords using md5${salt}${hashed_password} and they prepend the salt. This being the case you should be able to take the Magento passwords and reformat the string so that it passes django password checks.
$hashArr = explode(':', $hash);
$newPasswordString = 'md5$'.$hashArr[1].'$'.$hashArr[0];

The viability / accuracy of this answer will depend on whether you are using Community / Professional or Enterprise. The code is based on the Community code as I can share this more freely, depending on the implementation the same may or may not be possible with Enterprise, you'd need to check Mage_Core_Model_Encryption:validateHash.

A: If you keep old and weak hashes from legacy systems, you are endangering your users.
If some attacker (or some evil admin) gets access to the hashes and user data, he can easily crack them (see e.g. http://hashcat.net/oclhashcat-plus/ ) and use them globally against any service your users are using (of course users are advised to not reuse passwords, have strong passwords, etc., but many will not know or ignore this).
Weak hashes are about anything except bcrypt, pbkdf2, shaXXX_crypt. Even something like randomly salted sha256 has to be considered as weak.
So, a sane procedure could be:

*

*Do NOT just support weak hashes directly

*Import the weak hashes, but hash them again using strong algo: strong(weak(cleartext))

*At login time, upgrade the double-hashed stuff to just strong(cleartext)

*Run the system in this mode for a while, your frequent users will have strong(cleartext) hashes at some time.

*To get rid of the inner weak() hash, invalidate all such hashes (this will only affect your infrequent users), send users a password-reset link and some contact info for cases of trouble. In the E-Mail you can point out that you care very much about security and that the reset is necessary to improve it. If the infrequent user is still interested in your service, he will just reset his password. If he is not interested any more, he will ignore the email. In any case, you won't have a double-hashed pw in your password storage any more, but just an invalid one.

*Disable support for the inner weak() hash, for double-hashing in the site configuration.

*Deprecate support for the inner hash / double hashing in the software.

*Later, remove support for the inner hash / double hashing in the software, to simplify it.

Note: if the legacy system had security breaches, taking the old hashes is no option as you have to consider the passwords to be exposed.

A: This could be a guide in you quest:
How to decrypt magento enterprise edition password?

A: The answer by Cags works for me.  I'm moving from Magento community edition 1.7 to Django-Oscar.
I only have a few hundred users to move, but resetting their passwords wasn't an option.
For convenience...
The python version of his code:
hash = xxxxxxxxxxxxxxxxx:xx  # The hash from Magento DB table customer_entity_varchar
splithash = hash.split(':')
djangopass = 'md5$' + splithash[1] + '$' + splithash[0]


text:
Q: Display custom select form in "Quick View" window in WooCommerce I use the code, that on the product editing page shows the checkbox "Roast Level". When the manager clicks on this checkbox, a select box appears on the page of a single product, allowing the customer to select "Roast Level".
When selecting and adding a product to the cart, the selected value appears in the cart itself. This value is also shown on the checkout page, on the "Thank You" page, in the order, on the email notification, and on the order editing page in the admin panel.
Here is the code:
// Display Checkbox Field
add_action('woocommerce_product_options_general_product_data', 'roast_custom_field_add');

function roast_custom_field_add() {
    global $post;

    // Checkbox
    woocommerce_wp_checkbox(
            array(
                    'id' => '_roast_checkbox',
                    'label' => __('Roast Level', 'woocommerce'),
                    'description' => __('Enable roast level', 'woocommerce')
            )
    );
}

// Save Checkbox Field
add_action('woocommerce_process_product_meta', 'roast_custom_field_save');

function roast_custom_field_save($post_id) {
    // Custom Product Checkbox Field
    $roast_checkbox = isset($_POST['_roast_checkbox']) ? 'yes' : 'no';
    update_post_meta($post_id, '_roast_checkbox', esc_attr($roast_checkbox));
}

/*---------------------------------------------------------------
*Display Select Box
---------------------------------------------------------------*/
add_action( 'woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0 );
function add_roast_custom_field() {
    global $product;

    // If is single product page and have the "roast_checkbox" enabled we display the field
    if ( is_product() && $product->get_meta( '_roast_checkbox' ) === 'yes' ) {

        echo '
';

        $select = woocommerce_form_field( 'roast_custom_options', array(
            'type'          => 'select',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Roast Level'),
            'required'      => false,
            'return'       => false,
            'options'   => array(
                ''      => 'Please select',
                'Blue'  => 'Blue',
                'Rare'  => 'Rare',
                'Medium Rare'   => 'Medium Rare',
                'Medium'    => 'Medium',
                'Medium Well'   => 'Medium Well',
                'Well Done' => 'Well Done'
            )
        ), '' );
        echo $select;
        echo '
';
    }
}
/*---------------------------------------------------------------
* Add as custom cart item data
---------------------------------------------------------------*/
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 21 );
function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id ){

    if( isset( $_POST['roast_custom_options'] ) ) {
        $cart_item_data['roast_option'] = wc_clean( $_POST['roast_custom_options'] );
    }
    return $cart_item_data;
}
/*---------------------------------------------------------------
* Add custom fields values under cart item name in cart
---------------------------------------------------------------*/

add_filter( 'woocommerce_cart_item_name', 'roast_custom_field', 10, 21 );
function roast_custom_field( $item_name, $cart_item, $cart_item_key ) {
    if( ! is_cart() )
        return $item_name;

    if( isset($cart_item['roast_option']) ) {
        $item_name .= '

' . __("Roast Level", "woocommerce") . ': ' . $cart_item['roast_option'] . '
';
    }
    return $item_name;
}

/*---------------------------------------------------------------
* Display roast custom fields values under item name in checkout
---------------------------------------------------------------*/

add_filter( 'woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 21 );
function roast_custom_checkout_cart_item_name( $item_qty, $cart_item, $cart_item_key ) {
    if( isset($cart_item['roast_option']) ) {
        $item_qty .= '

' . __("Roast Level", "woocommerce") . ': ' . $cart_item['roast_option'] . 'гр.
';
    }
    return $item_qty;
}

/*---------------------------------------------------------------
* Save chosen slelect field value to each order item as custom meta data and display it everywhere
---------------------------------------------------------------*/
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 21 );
function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order ) {
    if( isset($values['roast_option']) ) {
        $key = __('Roast Level', 'woocommerce');
        $value = $values['roast_option'];
        $item->update_meta_data( $key, $value ,$item->get_id());
    }
}

add_action('wp_footer','add_footer_script');
function add_footer_script(){
    ?>

    <?php
}

I need to add the "Roast Level" selection form to the quick view window, to the
 content-product-quick-view.php file.
When adding code, errors appeared. The form does not show, or the "Add to Cart" button disappears.
global $product;

// If is single product page and have the "roast_checkbox" enabled we display the field
if ( $product->get_meta( '_roast_checkbox' ) === 'yes' ) {

    echo '
';

    $select = woocommerce_form_field( 'roast_custom_options', array(
        'type'          => 'select',
        'class'         => array('my-field-class form-row-wide'),
        'label'         => __('Roast Level'),
        'required'      => false,
        'return'       => false,
        'options'   => array(
            ''      => 'Please select',
            'Blue'  => 'Blue',
            'Rare'  => 'Rare',
            'Medium Rare'   => 'Medium Rare',
            'Medium'    => 'Medium',
            'Medium Well'   => 'Medium Well',
            'Well Done' => 'Well Done'
        )
    ), '' );
    echo $select;
    echo '
';
}

As a result, I could not put this code in the php file. Perhaps here need to add additional code. And I ask for your help.

A: Change your script in add_footer_script with this:
( function( $ ) {
   $( document ).ready( function() {
       $(document).on('change', '#roast_custom_options' ,function() {
           $('.add_to_cart_button').data('roast_custom_options', this.value)
       });
   });
 }( jQuery ) );

if you are using ajax, you must subscribe via the parent container or document. To pass custom field using data attribute.

A: That template already has the variable product and and you're redeclaring it.   Remove global $product from it the code you added to content-product-quick-view.php file and you should be good to go.


text:
Q: Find & Replace in bulk, but the phrases have commas I tried a bulk find & replace, but my phrases have commas in them.
I used a few snippets I found online, such as the two examples below.
I tinkered with them a bit.
I regularly have documents where there are stutters and the speaker says "the, the" or "and, and" etc.
I've a list of about 15 of these repeat phrases. I'd like to replace them in bulk rather than one at a time in the normal find/replace option in Word.
Sub MultiReplace()
Dim StrOld As String, StrNew As String
Dim RngFind As Range, RngTxt As Range, i As Long
StrOld = "the,quick,brown,fox"
StrNew = "The,Quick,Brown,Fox"
Set RngTxt = Selection.Range
For i = 0 To UBound(Split(StrOld, ",";))
    Set RngFind = RngTxt.Duplicate
    With RngFind.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = Split(StrOld, ",")(i)
        .Replacement.Text = Split(StrNew, ",")(i)
        .Format = False
        .MatchWholeWord = True
        .MatchAllWordForms = False
        .MatchWildcards = False
        .Execute Replace:=wdReplaceAll
    End With
Next
End Sub

AND.... VERSION 2:
Sub FindAndReplaceMultiItems()
'Update by ExtendOffice 2018/10/25
    Dim xFind As String
    Dim xReplace As String
    Dim xFindArr, xReplaceArr
    Dim I As Long
    Application.ScreenUpdating = False
    xFind = InputBox("Enter items to be found here,seperated by comma: ", "Kutools for Word")
    xReplace = InputBox("Enter new items here, seperated by comma: ", "Kutools for Word")
    xFindArr = Split(xFind, ",")
    xReplaceArr = Split(xReplace, ",")
    If UBound(xFindArr) <> UBound(xReplaceArr) Then
        MsgBox "Find and replace characters must be equal.", vbInformation, "Kutools for Word"
        Exit Sub
    End If
    For I = 0 To UBound(xFindArr)
        Selection.HomeKey Unit:=wdStory
        With Selection.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = xFindArr(I)
            .Replacement.Text = xReplaceArr(I)
            .Format = False
            .MatchWholeWord = False
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
    Next
    Application.ScreenUpdating = True
End Sub

A: You could simply change the delimiter. For example:
Sub MultiReplace()
Application.ScreenUpdating = False
Dim StrOld As String, StrNew As String, i As Long
StrOld = "the|quick|brown|fox"
StrNew = "The|Quick|Brown|Fox"
With Selection.Range
  .ClearFormatting
  .Format = False
  .MatchWholeWord = True
  .MatchAllWordForms = False
  .MatchWildcards = False
  .Wrap = wdFindStop
  For i = 0 To UBound(Split(StrOld, "|";))
    .Replacement.ClearFormatt"|")(i)
    .Replacement.Text = Split(StrNew, "|")(i)
    .Execute Replace:=wdReplaceAll
  Next
End With
Application.ScreenUpdating = False
End Sub


text:
Q: Disable touchscreen before login (in the greeter) Recently I broke the screen of my Asus x200e and the tactile does random thing. I manually disable the touchscreen with
xinput disable ID

I need to do that everytime I restart. It's not a big issue because i just alt ctrl t - f11 and I can write my command without the mouse unfocusing the terminal and it just take a few secondes.
But my prob is that I have no option to disable the touchscreen during the ubuntu install (xubuntu ou ubuntu) and i can't disable the touchscreen before the login (greeter).
Do you have an idea ?
Thank's a lot, sorry for my English, I'm a baguette ... I mean, I'm french.
PS : Do you know if I can remove the touch glass on my screen ? Is the screen under the "touch" glass a normal screen ? Thank's
CONFIG : xubuntu 16.04 dual boot win10 - x200e 11.6" i3-3217u 4go

A: I would add xinput disable "whatever is the name of your touch screen" to your start up. To find the name of your device, run xinput.
For example, here is my start up:
xinput disable "ELAN Touchscreen"


text:
Q: Custom three level expandable list Android(each row different) I need to create custom expandable list inside navigation view. At the beggining i needed only two level list, but now i must add new row with third level.
Does anyone know how to create something like this:
- clickable element without child
-group
 -clickable element without child
 -clickable element without child
-group
 -group2
  -clickable element without child
 -group2
  -clickable element without child

each clickable element does same action and same view.


text:
Q: How to pass data from parent to child in loop and child is bootstrap modal in ReactJS? Unable to pass props from parent to child component if parent is looping to render child, and child component is modal, it doesn't update the value with every different component(only the first value is showing)
arr.map((data)=>{ return (<component1 data={data}/>)};

Component1
  import MainbodyComp2 from "./mainbodyComp2";
  export default function MainbodyComp1({ data }) {

   const [data1] = useState(data);

return (

{data.location}

${data.rent}k

         {
            alert("Sorry this functionality is not available yet");
          }}
        >
          Rent it Now

      <MainbodyComp2 data={data1} />

);
}
BootStrap Component
import React, { useState } from "react";

   export default function MainbodyComp2(props) {
   const [data] = useState(props);
   return (

            {data.data.propertyType}
      //this remains same for every component

          <button
            type="button"
            className="btn-close"
            data-bs-dismiss="modal"
            aria-label="Close"
          ></button>

            <ImLocation />
              {data.data.location}

          {data.data.description}

          {data.data.moveInDate}

only for ${data.data.rent}k

   {
      console.log("this is console check event", e.target);
    }}
  >
    <BsInfoCircleFill />

);
}
Whenever I try to open modal the above content remains the same for every element
One possible solution that I found is to hide the bootstrap component and show when it is toggled, but why doesn't the above method work?
Is there any solution to the problem? Any help will be highly appreciated

A: You have to destructure the data before using it in your component..
import Bootstrap from "abc/csf.js"
export default Component1=({data})=>{
 return(

     // or use it as props.data.val
      {data.val}
      <Bootstrap data={data}/>

)
 }


text:
Q: iOS - How to draw a YUV image using openGL Currently, I am trying to draw an image using openGL (the image updates very often, and thus must be redrawn).  Previously, I was converting my image from YUV to RGB, and then using this new image to draw with openGL.  All worked fine, but the conversion process was not particularly fast.
I am now attempting to change the code so that the conversion is taken care of in the openGL shaders.  After looking around, I've found a couple code snippets (particularly the shaders and the bulk of my renderImage function) that have helped me get a baseline, but I can't seem to actually get the image to draw properly - all I ever see is a black image.
It's quite likely that I'm missing something extremely simple and important - My experience with openGL is rather limited.  If anyone can take a look and see if they recognize anything wrong, please let me know.
I should point out, I'm trying to support iOS 4.x, so CVOpenGLESTextureCacheCreateTextureFromImage  shouldn't be usable (and I'm not really positive how to setup to use it even if I wanted to).
Any help would be appreciated.  Code below -
My Vertex shader:
attribute vec4 position;
attribute vec4 inputTextureCoordinate;

varying vec2 textureCoordinate;

void main()
{
    gl_Position = position;
    textureCoordinate = inputTextureCoordinate.xy;
}

Fragment Shader:
#ifdef GL_ES
precision mediump float;
#endif

varying vec2 textureCoordinate;

uniform sampler2D videoFrame;
uniform sampler2D videoFrameUV;

const mat3 yuv2rgb = mat3(
                          1, 0, 1.2802,
                          1, -0.214821, -0.380589,
                          1, 2.127982, 0
                          );

void main() {
    vec3 yuv = vec3(
                    1.1643 * (texture2D(videoFrame, textureCoordinate).r - 0.0625),
                    texture2D(videoFrameUV, textureCoordinate).r - 0.5,
                    texture2D(videoFrameUV, textureCoordinate).a - 0.5
                    );
    vec3 rgb = yuv * yuv2rgb;

    gl_FragColor = vec4(rgb, 1.0);
}

The renderImage function:
-(void)renderImage:(ImageBuffer *)image
{
    if (image)
    {
        int bufferHeight = image->GetHeight();
        int bufferWidth = image->GetWidth();

        if(!imageTexture){
            // Dealing with the Y portion of the YCbCr
            glActiveTexture(GL_TEXTURE0);
            glGenTextures(1, &imageTexture);
            //Bind Y texture
            glBindTexture(GL_TEXTURE_2D, imageTexture);
            glUniform1i(uniforms[UNIFORM_VIDEOFRAME], 0);
            // For fitting
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            // This is necessary for non-power-of-two textures
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

            glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, bufferWidth, bufferHeight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image->GetPlanePointer(0));

            // Dealing with the CbCr potion of the YCbCr
            glActiveTexture(GL_TEXTURE1);
            glGenTextures(1, &imageTextureUV);
            //Bind CbCr texture
            glBindTexture(GL_TEXTURE_2D, imageTextureUV);
            glUniform1i(uniforms[UNIFORM_VIDEOFRAMEUV], 1);
            // For fitting
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            // This is necessary for non-power-of-two textures
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

            glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, bufferWidth/2, bufferHeight/2, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, image->GetPlanePointer(1));

        }

        [self drawFrame];
    }
}

And finally, the drawFrame function:
- (void)drawFrame
{
    [self setFramebuffer];

    // Replace the implementation of this method to do your own custom drawing.
    static const GLfloat squareVertices[] = {
        -1.0f, -1.0f,
        1.0f, -1.0f,
        -1.0f, 1.0f,
        1.0f, 1.0f
    };

    static const GLfloat textureVertices[] = {
//        1.0f, 1.0f,
//        1.0f, 0.0f,
//        0.0f,  1.0f,
//        0.0f,  0.0f,
        0.0f, 1.0f,
        1.0f, 1.0f,
        0.0f, 0.0f,
        1.0f, 0.0f
//        0.0f, 0.8f,
//        1.0f, 0.8f,
//        0.0f, 0.2f,
//        1.0f, 0.2f
    };

    static float transY = 0.0f;

    if ([context API] == kEAGLRenderingAPIOpenGLES2) {
        // Use shader program.
        glUseProgram(program);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, imageTexture);

        // Update attribute values.
        glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, 0, 0, squareVertices);
        glEnableVertexAttribArray(ATTRIB_VERTEX);
        glVertexAttribPointer(ATTRIB_TEXTUREPOSITON, 2, GL_FLOAT, 0, 0, textureVertices);
        glEnableVertexAttribArray(ATTRIB_TEXTUREPOSITON);

        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, imageTextureUV);

        // Update attribute values.
        glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, 0, 0, squareVertices);
        glEnableVertexAttribArray(ATTRIB_VERTEX);
        glVertexAttribPointer(ATTRIB_TEXTUREPOSITON, 2, GL_FLOAT, 0, 0, textureVertices);
        glEnableVertexAttribArray(ATTRIB_TEXTUREPOSITON);

        // Validate program before drawing. This is a good check, but only really necessary in a debug build.
        // DEBUG macro must be defined in your debug configurations if that's not already the case.
#if defined(DEBUG)
        if (![self validateProgram:program]) {
            NSLog(@"Failed to validate program: %d", program);
            return;
        }
#endif
    } else {
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glTranslatef(0.0f, (GLfloat)(sinf(transY)/2.0f), 0.0f);
        transY += 0.075f;

        glVertexPointer(2, GL_FLOAT, 0, squareVertices);
        glEnableClientState(GL_VERTEX_ARRAY);
    }

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    [self presentFramebuffer];
}

A: Here is some snippets of code from my project 'movie player for iOS'.
1. fragment shader
varying highp vec2 v_texcoord;
uniform sampler2D s_texture_y;
uniform sampler2D s_texture_u;
uniform sampler2D s_texture_v;
void main() {
    highp float y = texture2D(s_texture_y, v_texcoord).r;
    highp float u = texture2D(s_texture_u, v_texcoord).r - 0.5;
    highp float v = texture2D(s_texture_v, v_texcoord).r - 0.5;
    highp float r = y +             1.402 * v;
    highp float g = y - 0.344 * u - 0.714 * v;
    highp float b = y + 1.772 * u;
    gl_FragColor = vec4(r,g,b,1.0);
}

2. create textures from YUV420p frame
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(3, _textures);
const UInt8 *pixels[3] = { yuvFrame.luma.bytes, yuvFrame.chromaB.bytes, yuvFrame.chromaR.bytes };
const NSUInteger widths[3]  = { frameWidth, frameWidth / 2, frameWidth / 2 };
const NSUInteger heights[3] = { frameHeight, frameHeight / 2, frameHeight / 2 };
for (int i = 0; i < 3; ++i) {
    glBindTexture(GL_TEXTURE_2D, _textures[i]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, widths[i],heights[i],0,GL_LUMINANCE,GL_UNSIGNED_BYTE,pixels[i]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}

3. init vertices and texture coords
static const GLfloat texCoords[] = { 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f };
static const GLfloat vertices[]= {-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f };

4. render frame
[EAGLContext setCurrentContext:_context];
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
glViewport(0, 0, _backingWidth, _backingHeight);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(_program);
for (int i = 0; i < 3; ++i) {
    glActiveTexture(GL_TEXTURE0 + i);
    glBindTexture(GL_TEXTURE_2D, _textures[i]);
    glUniform1i(_uniformSamplers[i], i);
}
glVertexAttribPointer(ATTRIBUTE_VERTEX, 2, GL_FLOAT, 0, 0, vertices);
glEnableVertexAttribArray(ATTRIBUTE_VERTEX);
glVertexAttribPointer(ATTRIBUTE_TEXCOORD, 2, GL_FLOAT, 0, 0, texCoords);
glEnableVertexAttribArray(ATTRIBUTE_TEXCOORD);
glBindRenderbuffer(GL_RENDERBUFFER, _renderbuffer);
[_context presentRenderbuffer:GL_RENDERBUFFER];

The link to project on github.


text:
Q: Linq query across all sites and subsites on a sharepoint server? I'm working on a webpart for a sharepoint 2010 installation. This has multiple sites, and each site has pages, and may have subsites, themselves with more pages and sites. I want to get a list of all pages in the entire installation that match a certain criteria (eg title == "Test").
I can do this using a CAML SPSiteDataQuery object and setting the 'Webs' property to <Webs Scope="Recursive" />. Obviously this makes the query consider the current site and all subsites.
On the other hand I want to use linq2sp if possible as it will present an easier learning curve for other developers. Using SPMetal I can generate a DataContext for my site, and then can query it with linq, however this will only access pages in the root site.
Is there some way to control the scope of a Linq query so that it works across all pages in all of the sites?
thanks,
  S

A: Upon ... reflection ... it would appear that you (and all of us) are out of luck. LINQ to Sharepoint converts queries to SPQuery objects, which can only be used to query specific lists. SPSiteDataQuery is not used anywhere in the Microsoft.SharePoint.Linq assembly.
I guess you could iterate over all Lists executing the same query but that would be awfully inefficient.
You can only scope specific lists to folders using the EntityList< TEntity>.ScopeToFolder method.
A possible workaround is to use a custom Sharepoint LINQ provider that supports cross-site queries like this one . I haven't used it so I can't vouch for it.


text:
Q: ¿Cómo puedo ejecutar un código al mover un objeto en Blender por medio de python bpy? Lo que busco un es que se detecte cuando el objeto se traslada de posición y a partir de ahí me ejecute una acción.
Un ejemplo de lo que busco:
bpy.data.objects["miObjeto"].location.onChange(myFunction)

def myFunction():
    #do stuff every time location is changed...


text:
Q: How to implement actionbar activities in android <3 I'm trying to implement an actionbar in the API 10. I've created the layout file as 'actionbar.xml' which is included as a layout on every screen. I have a clickable image view on the actionbar layout. How do I write an 'onClick()' method for this. Meaning, do I have to write this method in every activity? Is there anyway I can create a separate activity as 'ActiobarActivity.java' which will have 'onClick()'? If so, then how do I link it to the flow of the application as it is there on every screen?
Basically, can anyone suggest an approach to implement a clickable widget on actionbar in API < 11.

A: That is what Actionbar Sherlock is for:
http://actionbarsherlock.com/

A: ActionBarSherlock at http://actionbarsherlock.com is an Android library for implementing the action bar design pattern using the native ActionBar on 3.0+ and a third-party library on pre-3.0.
Other ActionBar implementations for pre-3.0 devices:
GreenDroid at https://github.com/cyrilmottier/GreenDroid
or android-actionbar at https://github.com/johannilsson/android-actionbar


text:
Q: How to get all the cache names in an Infinispan cache cluster I am using Infinispan with jgroups in java.
I want to get all the cache names in an infinispan cache cluster.
I have tried using
DefaultCacheManager.getCacheNames();
but it gives only caches which are accessed on that the jvm from which it is called from and not all the caches in that cluster.
Once i access a cache on that jvm, it becomes available and the it starts coming in the cachelist which i get from
DefaultCacheManager.getCacheNames();
I am using the same config file for infinispan and jgroups(using tcp).
Please suggest a way by which I can get all the cache names in a cluster.
Thanks,
Ankur

A: Hmmm, normally you'll have all caches defined cluster wide, so getting the cache names in a node is good enough to know the caches that are available cluster wide.
This doesn't seem to be your case though, so the easiest thing I can think of is to do a Map/Reduce functionality in Infinispan to retrieve the cache names from individual nodes in the cluster and then collate them.
For more info, see https://docs.jboss.org/author/display/ISPN/Infinispan+Distributed+Execution+Framework and https://www.jboss.org/dms/judcon/presentations/Boston2011/JUDConBoston2011_day2track2session2.pdf


text:
Q: Getting nosuchelement Exception public class Vowcon {
    public static void main(String[] args) throws Exception {
        try {
        int vcount1=0 , ccount1=0;
        int vcount2=0 , ccount2=0;
        Scanner sc = new Scanner(System.in);
        int t_case = sc.nextInt();
        for (int i=0; i<t_case+1; i++) {
            String str1 = sc.next();
            String str2 = sc.next();

            for(int j=0;j<str1.length();j++) {
                if(str1.charAt(j)=='a'||str1.charAt(j)=='e'||str1.charAt(j)=='i'||str1.charAt(j)=='o'||str1.charAt(j)=='u') {
                    vcount1++;
                }else if(str1.charAt(j)>='a'||str1.charAt(j)<='z') {
                    ccount1++;
                }
            }

            for (int k=0; k<str2.length(); k++) {
                if(str2.charAt(k)=='a'||str2.charAt(k)=='e'||str2.charAt(k)=='i'||str2.charAt(k)=='o'||str2.charAt(k)=='u') {
                    vcount2++;
                }else if(str2.charAt(k)>='a'||str2.charAt(k)<='z') {
                    ccount2++;
                }
            }
            System.out.println(vcount1 + " " + ccount1 + " " + vcount1*ccount1);
            System.out.println(vcount2 + " " + ccount2 + " " + vcount2*ccount2);
        }
        sc.close();
    } catch(Exception e) {
        System.out.println(e.toString());
    }

    }
}

It is my code and I wanted to know why I am getting this exception . and can anybody help to resolve this exception. Please help me to resolve this problem

A: Most likely you are attempting to access the index of the string that is not reachable. Try str2.length() - 1 ;


text:
Q: SSMS shows up in taskbar but is invisible I came across this very weird issue today. When I open SQL server management studio it shows up in the task bar but somehow it never appears on my screen, even when I do alt+tab to switch to SQL server window, it still shows up in the list of applications but does not appear when I select this application. It even shows up in Task Manager and I can close it from there. I have also restarted my system but without any success.

A: I did further research and it turned out to be the issue of window being hidden somewhere else. I had attached another monitor with my laptop and SQL window was appearing in the external monitor and unfortunately that monitor was switched off. I haven't been so foolish in my life before.

A: I had this issue and resolved by
in the application on taskbar
1 --> Shift + Right Click
2 --> Press Maximize

A: my problem soleved by: Shift + Right Click in profiler on taskbar and Press Maximize


text:
Q: Stuck in programming this Console application for Solid Edge I'm trying to make a visual basic console application for a 3D CAD program Solid Edge, in this console application I want visual basic to make curves in it. I want to make these curves with an 4th degree equation.The data used for the equation is stored in a space dilimited text file. In the text file there are several rows with different data, every row is used to make the 4th degree equation. Now, I tried to make the program but it got stuck at making the curve lines, the console just stays black and doesn't close. The program does make a connection to the program and opens up a 3d modeling environment.
Does anyone knows what I'm doing wrong in my code, or what I should do instead? I'm using visual basic 2003 standart.
I'm not a programmer, but I try this to automate things in the 3D CAD program.
Heres my code:
Imports System.IO
Imports System.Runtime.InteropServices
Module Module1
    Sub Main()

        Dim strFileName As String = "U:\pompen.prn"
        Dim objFS As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
        Dim objSR As New StreamReader(objFS)

        Dim objApp As SolidEdgeFramework.Application = Nothing
        Dim objDocuments As SolidEdgeFramework.Documents = Nothing
        Dim objPart As SolidEdgePart.PartDocument = Nothing
        Dim objProfileSets As SolidEdgePart.ProfileSets = Nothing
        Dim objProfileSet As SolidEdgePart.ProfileSet = Nothing
        Dim objProfiles As SolidEdgePart.Profiles = Nothing
        Dim objProfile As SolidEdgePart.Profile = Nothing
        Dim objRefplanes As SolidEdgePart.RefPlanes = Nothing
        Dim objdraft2d As SolidEdgeDraft.CoordinateSystem2d = Nothing
        Dim objBSpline As SolidEdgeFrameworkSupport.BSplineCurve2d = Nothing
        Dim objBSplines As SolidEdgeFrameworkSupport.BSplineCurves2d = Nothing
        Dim objLines2d As SolidEdgeFrameworkSupport.Lines2d = Nothing
        Dim objLine2d As SolidEdgeFrameworkSupport.Line2d = Nothing
        Dim objsketch As SolidEdgePart.Sketch = Nothing

        Dim strEmpRecord As String
        Dim type As String
        Dim N1 As Double
        Dim QT As Double
        Dim DW1 As Decimal
        Dim EQ As Decimal
        Dim EH As Decimal
        Dim DWL As Decimal
        Dim DHL As Decimal
        Dim C1 As Decimal
        Dim C2 As Decimal
        Dim C3 As Decimal
        Dim C4 As Decimal
        Dim C5 As Decimal
        Dim QFACTOR As Decimal

        Do While objSR.Peek <> -1
            ' read the current record (line) into the variable strEmpRecord
            strEmpRecord = objSR.ReadLine
            Try
                ' break up the record into separate variables
                type = strEmpRecord.Substring(0, 20)
                N1 = CDbl(strEmpRecord.Substring(20, 10))
                QT = CDbl(strEmpRecord.Substring(30, 10))
                DW1 = CDec(strEmpRecord.Substring(40, 10))
                EQ = CDec(strEmpRecord.Substring(50, 10))
                EH = CDec(strEmpRecord.Substring(60, 10))
                DHL = CDec(strEmpRecord.Substring(70, 10))
                DWL = CDec(strEmpRecord.Substring(80, 10))
                C1 = CDec(strEmpRecord.Substring(90, 20))
                C2 = CDec(strEmpRecord.Substring(110, 20))
                C3 = CDec(strEmpRecord.Substring(130, 20))
                C4 = CDec(strEmpRecord.Substring(150, 20))
                C5 = CDec(strEmpRecord.Substring(170, 20))
                QFACTOR = CDec(strEmpRecord.Substring(190, 10))
            Catch ex As System.InvalidCastException
            End Try

            'connect to a Solid Edge file.
            ' Connect to a running instance of Solid Edge
            objApp = Marshal.GetActiveObject("SolidEdge.Application")
            ' Get a reference to the documents collection
            objDocuments = objApp.Documents
            ' Create a new part document
            objPart = objDocuments.Add("SolidEdge.PartDocument")
            ' Get a reference to the profile sets collection
            objProfileSets = objPart.ProfileSets
            ' Add a new profile set
            objProfileSet = objProfileSets.Add()
            ' Get a reference to the profiles collection
            objProfiles = objProfileSet.Profiles
            ' Get a reference to the ref planes collection
            objRefplanes = objPart.RefPlanes
            'open a new sketch
            objsketch = objPart.Sketches.Add
            ' Add a new profile
            objProfile = objProfiles.Add(objRefplanes.Item(3))
            'Gat a reference to spline curve collection
            objBSplines = objProfile.BSplineCurves2d
            ' Get a reference to the lines2d collection
            objLines2d = objProfile.Lines2d

            Try
                'Draw the curves with 4th degree equation, DMax
                Dim q As Decimal = (QT * 0.2)
                Dim h As Decimal = (((q ^ 4) * C1) + ((q ^ 3) * C2) + ((q ^ 2) * C3) + (q * C4) + C5)
                Do
                    q = (q + 0.5)
                Loop Until q <= (QT * QFACTOR)
                objBSpline = objBSplines.objsr.AddByPoints(q, h)

                'Draw the curves with 4th degree equation, DMin
                Dim qx As Decimal = ((DWL / DW1) ^ EQ)
                Dim hx As Decimal = ((DWL / DW1) ^ EH)
                Dim qa As Decimal = (qx * q)
                Dim ha As Decimal = (hx * (((q ^ 4) * C1) + ((q ^ 3) * C2) + ((q ^ 2) * C3) + (q * C4) + C5))
                Do
                    qa = (qa + 0.5)
                Loop Until qa = (qx * (QT * QFACTOR))
                objBSpline = objBSplines.objsr.addbypoints(qa, ha)

                'make connection lines
                objLine2d = objLines2d.AddBy2Points((qx * (QT * QFACTOR)), (QFACTOR * (hx * (((q ^ 4) * C1) + ((q ^ 3) * C2) + ((q ^ 2) * C3) + (q * C4) + C5))), (QT * QFACTOR), (QFACTOR * (((q ^ 4) * C1) + ((q ^ 3) * C2) + ((q ^ 2) * C3) + (q * C4) + C5)))

                ' Close the profile
                objProfile.End( _
                    SolidEdgePart.ProfileValidationType.igProfileClosed)

            Catch ex As Exception

            Finally
                If Not (objLine2d Is Nothing) Then
                    Marshal.ReleaseComObject(objLine2d)
                    objLine2d = Nothing
                End If
                If Not (objLines2d Is Nothing) Then
                    Marshal.ReleaseComObject(objLines2d)
                    objLines2d = Nothing
                End If
                If Not (objBSpline Is Nothing) Then
                    Marshal.ReleaseComObject(objBSpline)
                    objBSpline = Nothing
                End If
                If Not (objRefplanes Is Nothing) Then
                    Marshal.ReleaseComObject(objRefplanes)
                    objRefplanes = Nothing
                End If
                If Not (objProfile Is Nothing) Then
                    Marshal.ReleaseComObject(objProfile)
                    objProfile = Nothing
                End If
                If Not (objProfiles Is Nothing) Then
                    Marshal.ReleaseComObject(objProfiles)
                    objProfiles = Nothing
                End If
                If Not (objProfileSet Is Nothing) Then
                    Marshal.ReleaseComObject(objProfileSet)
                    objProfileSet = Nothing
                End If
                If Not (objProfileSets Is Nothing) Then
                    Marshal.ReleaseComObject(objProfileSets)
                    objProfileSets = Nothing
                End If
                If Not (objPart Is Nothing) Then
                    Marshal.ReleaseComObject(objPart)
                    objPart = Nothing
                End If
                If Not (objDocuments Is Nothing) Then
                    Marshal.ReleaseComObject(objDocuments)
                    objDocuments = Nothing
                End If
                If Not (objsketch Is Nothing) Then
                    Marshal.ReleaseComObject(objsketch)
                    objsketch = Nothing
                End If
                If Not (objApp Is Nothing) Then
                    Marshal.ReleaseComObject(objApp)
                    objApp = Nothing
                End If
            End Try
        Loop

        objSR.Close()
        Console.WriteLine("")
        Console.WriteLine("Press Enter to close this window.")
        Console.ReadLine()

    End Sub
End Module

A: I'm going to guess that you should move this block of code to be outside your loop, ie. before the Do While objSR.Peek <> -1. In the loop it will do all these things for each line in your file. I would think you would only want to do this stuff once.
      'connect to a Solid Edge file.
        ' Connect to a running instance of Solid Edge
        objApp = Marshal.GetActiveObject("SolidEdge.Application")
        ' Get a reference to the documents collection
        objDocuments = objApp.Documents
        ' Create a new part document
        objPart = objDocuments.Add("SolidEdge.PartDocument")
        ' Get a reference to the profile sets collection
        objProfileSets = objPart.ProfileSets
        ' Add a new profile set
        objProfileSet = objProfileSets.Add()
        ' Get a reference to the profiles collection
        objProfiles = objProfileSet.Profiles
        ' Get a reference to the ref planes collection
        objRefplanes = objPart.RefPlanes
        'open a new sketch
        objsketch = objPart.Sketches.Add
        ' Add a new profile
        objProfile = objProfiles.Add(objRefplanes.Item(3))
        'Gat a reference to spline curve collection
        objBSplines = objProfile.BSplineCurves2d
        ' Get a reference to the lines2d collection
        objLines2d = objProfile.Lines2d

Then you would probably have to move this to after your loop,
            ' Close the profile
            objProfile.End( _
                SolidEdgePart.ProfileValidationType.igProfileClosed)

Just a tip, you should remove this line
  Catch ex As Exception

If you have an empty catch block, you will just hide any errors from yourself.


text:
Q: Magento2 price filter with configurable products I created a custom price filter (without layered navigation). This function works great on simple products, but configurable products are filtered (maybe because they don't have a price?).
This is my function:
<?php namespace Silvan\Sidebar\Model\Plugin;

use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;

class SidebarFilter
{
    public function aroundAddFieldToFilter(ProductCollection $collection, \Closure $proceed, $fields, $condition = null)
    {
        if ($fields === 'category_ids') {

            $price  = isset($_GET[ 'price' ]) ? $_GET[ 'price' ] : false;

            if ($price && strpos($price, '-') !== false) {
                $price = explode('-', $price);
                $min   = isset($price[ 0 ]) ? $price[ 0 ] : 0;
                $max   = isset($price[ 1 ]) ? $price[ 1 ] : 9999999;

                $collection->addAttributeToFilter('price', ['gt' => $min]);
                $collection->addAttributeToFilter('price', ['lt' => $max]);
            }
        }

        return $fields ? $proceed($fields, $condition) : $collection;
    }
}

I tried using min_price and max_price, but these attributes are ignored in the filter.

A: Your code did not for simple products too (because it not include data from special price, tear price, required options, catalog price rules).
Magento using price index mechanism to pre-calculate price for a product. See catalog_product_index_price table. The field min_price contains the minimal possible price for product and layered navigation use this field for filtering.
So, try replace in your code
$collection->addAttributeToFilter('price', ['gt' => $min]);
$collection->addAttributeToFilter('price', ['lt' => $max]);

on
$collection->addFieldToFilter('price', ['from' => $min, 'to' => $max]);

A: Try this code, it filters on min_price range used by configurable products:
class Related extends \Magento\Framework\View\Element\Template
{
  public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
    \Magento\Catalog\Model\Product\Visibility $productVisibility,
    \Magento\Framework\Registry $registry,
    array $data = []
  )
  {
    $this->_productCollectionFactory = $productCollectionFactory;
    $this->productStatus = $productStatus;
    $this->productVisibility = $productVisibility;
    $this->_registry = $registry;
    parent::__construct($context, $data);
  }

  public function getProductCollection()
  {
    try {

      $product = $this->_registry->registry('current_product');

      $range_percentage = 35;
      $price_temp = round($product->getFinalPrice() / 100 * $range_percentage);
      $price_from = $product->getFinalPrice() - $price_temp;
      $price_to = $product->getFinalPrice() + $price_temp;

      $categories = $product->getCategoryIds();

      $collection = $this->_productCollectionFactory->create();
      $collection->addAttributeToSelect('*')
        ->addCategoriesFilter(['in' => $categories])
        ->addPriceDataFieldFilter('%s >= %s', ['min_price', $price_from])
        ->addPriceDataFieldFilter('%s <= %s', ['min_price', $price_to])
        ->addMinimalPrice()
        ->addAttributeToFilter('entity_id', ['neq' => $product->getId()])
        ->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
        ->setVisibility($this->productVisibility->getVisibleInSiteIds())
        ->setPageSize(5);

      return $collection;

    } catch (\Exception $e) {

      var_dump($e->getMessage());
    }
  }
}

A: Configurable products are filtered (maybe because they don't have a price?). > You're right.
I have exactly the same issue when filtering quantity (qty).
Configurable products quantity is 0.
I don't think the team who designed Magento 2 handled this feature to be able to filter by configurable products children attributes.
We will have to analyze the vendor source code to figure out if they did it somewhere somehow.
Another possible fix would be to set price/quantity of configurable products manually by fetching its children attributes.
Maybe a custom script/command we could then put into a cron after each stock update/import.


text:
Q: jquery does not display content I this simple bit of test code to loop through and display content from an array. When I run it in my browser, it doesn't display or run any errors.

    <title>jquery each test</title>

A: Change your ready function code with following line
 $(document).ready(function(){
          $.each(arr, function(index, value) {
            task += value + "
";
            $('div.content').html(task);
          })});

A: As described in document-ready documentation:
$( document ).ready(function() {
    YOUR CODE HERE
});

So your code should be:

var arr = ["One", "Two", "Three", "Four", "Five"];
var task = "";
$(document).ready(function () {
  $.each(arr, function (index, value) {
    task += value + "
";
    $('div.content').html(task);
  });
});

A shorter form is:
    $(function () {
        $.each(arr, function (index, value) {
            task += value + "
";
            $('div.content').html(task);
        });
    });


text:
Q: Make a scrollable ColumnControl popup JXTable Good aftermoon. I am having a interesting issue with the propeties of a JXtable.
The thing is that I have created the JXTable with too many columns, so I decided to let the user choose which column to display using the ColumnControlButton that comes by default with the JXTable in the SwingX library.
As I have too many columns, when I press the ColumnControl button, it doesn't show me all the columns that can be hided/displayed. The default ColumnControl doesn't comes with a scrollable property to manage this cases. I need some kind of code like the one is used with the JXTable.. I don't know, maybe something like .setHorizontalScrollEnabled(true), so I can see all the columns in the ColumnControl.
I appreciate in advance your answer guys...
By the way, heres the code that loads the table:
public static void load_resg() throws Exception{

     String[] titles = new String[80];

     for(int i=0; i<80; i++){
         titles[i]=NbP[i];
     }

      modelResg=new DefaultTableModel(null, titles){

          @Override
             public boolean isCellEditable(int i, int i1) {
               return false; //To change body of generated methods, choose Tools | Templates.
             }
        };

      BufferedReader bw = new BufferedReader(new FileReader("Out\\Depth.txt"));
      String line;

      while((line=bw.readLine())!=null){
          modelResg.addRow(line.split(";"));
      }

    bw.close();
    resg.setIntercellSpacing(new Dimension(5, 5));
    resg.setHighlighters(HighlighterFactory.createSimpleStriping());
    resg.setHorizontalScrollEnabled(true);
    resg.packSelected();
    resg.setSortable(true);
    resg.getColumnControl();
    resg.setColumnControlVisible(true);
    resg.setModel(modelResg);

}

A: You should be able to use the Table Column Manager which was designed to be used with a JTable. It will display a menu of all the columns with a JCheckBoxMenuItem so you can choose which columns to display.

but it doesn't add a vertical scroll bar to the pop up, so it doesn't let me see all the columns

When you have that many menu items you might then want to use the Menu Scroller. This will allow you control how many menu items are displayed at one time and will then add up/down buttons to scroll through the remaining menu items.
In the showPopup(...) method from the TableColumnManager class I added the following line of code:
MenuScroller.setScrollerFor(popup, 10);
popup.show(header, r.x, r.height);

to display 10 menu items at one time. Hoevering the mouse over the arrows will cause the menu to scroll.


text:
Q: JSON parse error: Cannot construct instance of `` no String-argument constructor/factory method to deserialize from String value I'm having trouble to find out what I'm doing wrong in my below code to make the client consume the rest service.
I want to send json instead of person object and return the response the same way.
My caller service is as follow:
@Component
public class CallRestService implements CommandLineRunner {

@Autowired
private RestTemplate restTemplate;

private void callRestService() {

    // create a request body
    String requestBody = "{\"id\":\"1\",\"firstName\":\"replacedFirstName\",\"lastName\":\"replacedLastName\", \"age\":30}";

    // set headers
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON   );
    HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);

    //send the request
    Object response1 = restTemplate.postForObject("http://localhost:8080/person/1", entity, Object.class);
    System.out.println("Person's details are: " + response1);

}

@Override
public void run(String... args) throws Exception {
    callRestService();

}
}

My consumed rest service controller is as follow:
@RestController
@RequestMapping("/person")
public class PersonController {

@Autowired
PersonService personService;

@GetMapping("/all")
public Hashtable<String, Person> getAll(){
    return personService.getAll();
}

@GetMapping("/{id}")
public Person getPerson(@PathVariable("id") String id) {
    return personService.getPerson(id);
}

@PostMapping("/{id}")
public Person setPerson(@PathVariable("id") String id, @RequestBody Person person) {

    Person updatedPerson = personService.getPerson(id);
    updatedPerson.setFirstName(person.getFirstName());
    updatedPerson.setLastName(person.getLastName());

    return updatedPerson;
}

}
My person class in my service is as follow:
public class Person {

String id;
String firstName;
String lastName;
int age;

...// getters and setters
}

Can anyone tell me what's the mistake I'm doing to get this message error?
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.rest.model.Person` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"id":"1","firstName":"replacedFirstName","lastName":"replacedLastName", "age":30}'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.rest.model.Person` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"id":"1","firstName":"replacedFirstName","lastName":"replacedLastName", "age":30}') at [Source: (PushbackInputStream); line: 1, column: 1]

EDITED
Here's my restTemplate configuration with the mapper:
@Configuration
public class RestConfiguration {

@Autowired
private ObjectMapper objectMapper;

@Bean
public RestTemplate createRestTemplate() {
 objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
    jsonMessageConverter.setObjectMapper(objectMapper);
    messageConverters.add(jsonMessageConverter);
    restTemplate.setMessageConverters(messageConverters);
    return restTemplate;
}
}


text:
Q: What is the expected directory structure for submodule stubs to be understood by mypy? I have a package backed by an .so file for which I have generated stubs using stubgen, I renamed the original __init__.pyi to impl.pyi and added a py.typed and __init__.pyi.
the resulting structure looks like
site-packages/
├── __init__.pyi
├── impl.pyi
├── impl.so
├── sub_impl
│   ├── __init__.pyi
│   └── something.pyi
└── py.typed

here
impl.so is a module with a sub_impl "submodule" with entries created via pybind11's def_submodule
in another directory I have a test_import.py and a mypy.ini with the absolute path
[mypy]
mypy_path=/something/site-packages/
[head]

As expected
import impl as foo
print(foo)

gives
Success: no issues found in 1 source file

also
from impl import SomeObject
print(SomeObject)

gives
Success: no issues found in 1 source file

but
import impl.sub_impl as foo
print(foo)

gives
test_import.py:1: error: Cannot find implementation or library stub for module named "impl.sub_impl"
test_import.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
Found 1 error in 1 file (checked 1 source file)

all 3 cases run fine under the python interpreter.
Whats wrong with the directory structure and what does mypy need to detect the submodule?

A: The structure for stubs depends on the runtime appearance of the code, not its implementation:

*

*a module foo corresponds to a file:
foo.pyi

*a package foo corresponds to a folder and file:
foo/__init__.pyi

*a sub-module or sub-package is placed in its respective parent package.

This is the same structure as for regular Python code. Similarly, py.typed must be placed in the top-level package – no matter whether it is a stub or real package.
site-packages/
├── impl.so                # the implementation
└── impl/                  # the stubs for...
    ├── __init__.pyi       # import impl
    ├── sub_impl/
    │   ├── __init__.pyi   # import impl.sub_impl
    │   └── something.pyi  # import impl.sub_impl.something
    └── py.typed


text:
Q: Get HTML Code after logging into Website via Powershell I'm trying to get the HTML code of a website after I log in. The website is only accessible from a local network.
The code I get is from the login-site.
My script looks like this:
$ie = new-object -com "InternetExplorer.Application"
$ie.Navigate("http://192.168.135.189/mysite/check_mk/login.py")
$ie.visible = $true

while($ie.busy) {start-sleep 1}

#login
$ie.Document.getElementById("input_user").Value = "cmkadmin"
$ie.Document.getElementById("input_pass").Value="xxxx"

while($IE.busy) {Start-Sleep 1}
#Click-Button
$ie.document.getElementByID('_login').Click()

while($IE.busy) {Start-Sleep 1}
$IE.navigate("http://192.168.135.189/mysite/check_mk/index.py?start_url=%2Fmysite%2Fcheck_mk%2Fview.py%3Fhost%3D192.168.135.189%26site%3Dmysite%26view_name%3Dhost")

while($IE.busy) {Start-Sleep 1}

#Fetch Site
$WebFetch = Invoke-WebRequest -Uri "http://192.168.135.189/mysite/check_mk/index.py?start_url=%2Fmysite%2Fcheck_mk%2Fview.py%3Fhost%3D192.168.135.189%26site%3Dmysite%26view_name%3Dhost"

#Typename
$WebFetch | Get-Member

#RawContent
$WebFetch.RawContent

$WebFetch.AllElements | where tagname -EQ "Memory"

A: Seth comment has a good point. Are you passing login page with ie com object?
If the answer is yes, you can simply do:
$ie.Document.documentElement.outerHTML > "C:\some\path\to\save.html"

You can also use variable:
$sourceHTML = $ie.Document.documentElement.outerHTML


text:
Q: Registros por día de la semanal php mysql Necesito crear un código php que me traiga los registros por día de la semana. Osea cuantos usuarios se registraron el Lunes, el Martes, El miércoles... y así hasta el domingo.. que se calcule por el numero de semana actual.
Se puede hacer algo así? lo he echo por rango de fechas o por una fecha determinada.
Pero quisiera hacerlo por día de la semana. osea semanalmente.
EJEMPLO:
Lunes: 85
Martes: 32
Miércoles: 65
Jueves: 18
Viernes: 3 (Día actual)
Sábado: 0
Domingo: 0

<?php
include("conexion.php");

$semana_actual = date('W');
$dif = $semana_actual - $semana_actual;

$actual = date('W');
$calculo1 = date('W')+1;
$calculo2 = $actual - $calculo1;

$fecha_lunes = date("Y-m-d", strtotime("Monday $calculo2 week"));
$fecha_martes = date("Y-m-d", strtotime("Tuesday $calculo2 week"));
$fecha_miercoles = date("Y-m-d", strtotime("Wednesday $dif week"));
$fecha_jueves = date("Y-m-d", strtotime("Thursday $dif week"));
$fecha_viernes = date("Y-m-d", strtotime("Friday $dif week"));
$fecha_sabado = date("Y-m-d", strtotime("Saturday $dif week"));
$fecha_domingo = date("Y-m-d", strtotime("Sunday $dif week"));

$sql_lunes=mysqli_query($conexion,"select count(*) cuenta1 from persona where fecha_inscripcion like '%".$fecha_lunes."%'")or die("error consulta1");
IF($row_lunes=mysqli_fetch_array($sql_lunes)){
$lunes=$row_lunes["cuenta1"];
}

$sql_martes=mysqli_query($conexion,"select count(*) cuenta2 from persona where fecha_inscripcion like '%".$fecha_martes."%'")or die("error consulta2");
IF($row_martes=mysqli_fetch_array($sql_martes)){
$martes=$row_martes["cuenta2"];
}

$sql_miercoles=mysqli_query($conexion,"select count(*) cuenta3 from persona where fecha_inscripcion like '%".$fecha_miercoles."%'")or die("error consulta3");
IF($row_miercoles=mysqli_fetch_array($sql_miercoles)){
$miercoles=$row_miercoles["cuenta3"];
}

$sql_jueves=mysqli_query($conexion,"select count(*) cuenta4 from persona where fecha_inscripcion like '%".$fecha_jueves."%'")or die("error consulta4");
IF($row_jueves=mysqli_fetch_array($sql_jueves)){
$jueves=$row_jueves["cuenta4"];
}

$sql_viernes=mysqli_query($conexion,"select count(*) cuenta5 from persona where fecha_inscripcion like '%".$fecha_viernes."%'")or die("error consulta5");
IF($row_viernes=mysqli_fetch_array($sql_viernes)){
$viernes=$row_viernes["cuenta5"];
}

$sql_sabado=mysqli_query($conexion,"select count(*) cuenta6 from persona where fecha_inscripcion like '%".$fecha_sabado."%'")or die("error consulta6");
IF($row_sabado=mysqli_fetch_array($sql_sabado)){
$sabado=$row_sabado["cuenta6"];
}

$sql_domingo=mysqli_query($conexion,"select count(*) cuenta7 from persona where fecha_inscripcion like '%".$fecha_domingo."%'")or die("error consulta7");
IF($row_domingo=mysqli_fetch_array($sql_domingo)){
$domingo=$row_domingo["cuenta7"];
}

echo $lunes; echo "
";
echo $martes; echo "
";
echo $miercoles; echo "
";
echo $jueves; echo "
";
echo $viernes; echo "
";
echo $sabado; echo "
";
echo $domingo; echo "
";

A: Pues lo primero, lo que deseas hacer se puede hacer desde la DB, utilizando las funciones de MySQL WEEK para obtener el número de semana del año y DAYNAME para obtener el nombre del dia de la semana según la fecha (en mi ejemplo añadí SET @@lc_time_names = 'es_SV'; para cambiar el lenguaje, en mi caso a español de El Salvador), luego utilizar PHP para mostrar el resultado, algo así:
<?php
include("conexion.php");

$sql = "SET @@lc_time_names = 'es_SV';

sELECT
FECHA,
CASE
    WHEN DAYNAME(FECHA) = 'lunes' THEN 1
    WHEN DAYNAME(FECHA) = 'martes' THEN 2
    WHEN DAYNAME(FECHA) = 'miércoles' THEN 3
    WHEN DAYNAME(FECHA) = 'jueves' THEN 4
    WHEN DAYNAME(FECHA) = 'viernes' THEN 5
    WHEN DAYNAME(FECHA) = 'sábado' THEN 6
    WHEN DAYNAME(FECHA) = 'domingo' THEN 7
END ORDEN,
DAYNAME(FECHA) DIA,
COUNT(FECHA) REGISTROS FROM PERSONA
WHERE WEEK(FECHA)= WEEK(CURDATE())
GROUP BY FECHA,DAYNAME(FECHA)
ORDER BY ORDEN;";

if (mysqli_multi_query($conexion, $sql)) {
    do {
    if ($result = mysqli_store_result($conexion)) {
        while ($row = mysqli_fetch_row($result)) {
        echo 'Dia: '.$row[1];
        echo ' Registros: '.$row[2].'

';
        }
        mysqli_free_result($result);
    }
    if (mysqli_more_results($conexion)) {
        printf("\n");
    }
    } while (mysqli_next_result($conexion));
}

mysqli_close($conexion);
?>

Aqui te dejo un ejemplo del dataset que utilice para que lo puedas adecuar a tu implementacion.
Ejemplo
Espero que sea lo que buscas. Saludos.

A: No sé si todavía estés buscando solución a tu problema pero tomando de referencia la respuesta que te dieron y que tenía un desafío muy parecido al tuyo, pude llegar a una posible solución que comparto y espero y te pueda ser de utilidad.
    SET @@lc_time_names = 'es_MX';

SELECT DATE_FORMAT(`fecha`,'%d/%m/%Y') as FechaRegistro,
CASE
WHEN DAYNAME(fecha) = 'Lunes' THEN 1
WHEN DAYNAME(fecha) = 'Martes' THEN 2
WHEN DAYNAME(fecha) = 'Miércoles' THEN 3
WHEN DAYNAME(fecha) = 'Jueves' THEN 4
WHEN DAYNAME(fecha) = 'Viernes' THEN 5
WHEN DAYNAME(fecha) = 'Sábado' THEN 6
WHEN DAYNAME(fecha) = 'Domingo' THEN 7
END ORDEN,
MONTHNAME(fecha) MES,
DAYNAME(fecha) DIA,
count(fecha) REGISTROS FROM miTabla
WHERE MONTH(fecha) = MONTH(NOW())
GROUP BY MONTH(fecha), DAYNAME(fecha)
ORDER BY ORDEN;

A: Si usas base de datos, suena fácil ya que solo necesitarías incluir el día en la tabla y después mediante un query retornas esos datos.


text:
Q: Run jekyll build Command with Different url Flag My current _config.yml file looks like this:
#Site settings
...
baseurl: "" # the subpath of your site, e.g. /blog/
url: "http://10.0.1.9:3000" # the base hostname & protocol for your site
...

# Build settings
markdown: kramdown
safe: true
lsi: false
highlighter: true
keep_files: [public]
exclude: [src, lib, node_modules, bower.json, Gemfile, gulpfile.js, package.json, README.md]

I've got my url currently set to my local server, where I serve my Jekyll site for local development.
When building for production however, I have to keep manually changing this url to the url of my remote server before running jekyll build. Is there a way I can pass my remote url alongside the jekyll build command to build a site with the correct remote paths?
Something like so:
jekyll build --url mysite.com

Any help is appreciated with this. Thanks in advance!

A: Put your production url in _config.yml eg: url: toto.com.
Create a _config_dev.yml that will be used to override values in development.
In you case
url: "http://10.0.1.9:3000"

Development build is launched with :
jekyll build --config _config.yml,_config_dev.yml

Values in the last config file in the command will override those in first file.
and production build with jekyll build.
See Jekyll documentation http://jekyllrb.com/docs/configuration/#build-command-options configuration paragraphe.


text:
Q: Linear model within a loop (loop used to subset data) I have (what I think should be) a straight forward problem in R, and can't seem to get it to work. Hope you can help.
I have a data frame e.g.:
x  y  z
1  2  a
2  3  a
3  4  a
4  5  b
5  6  b
6  7  b      etc...

And I'm fitting a linear model (y ~ x) for each z value subset (e.g. a, b...) and extracting the gradient.
It works when I select 'a' using a with statement as such:
coef(with(subset(data.frame, z == "a"), {lm(y ~ x)
}))[2]

But my problem is that I have more than 1000 unique values in the Z column. So I tried to set up a loop (I know R users hate loops!) to do this for each value of z in turn and return the result in a data frame. Code is:
gradient.lm = NULL

unique.z <- as.matrix((unique(data.frame$z)))
count.z <- nrow(unique.z)

for (i in 1:count.z) {
  gradient.lm[i] = coef((with(subset(data.frame, z == [i]), {lm(y ~ z)
  })))[2]
}

But this is not working, and giving me the error code:
> for (i in 1:count.z) {
+   activity.lm[i] = coef((with(subset(data.frame, z == [i]), {lm(y ~ x)
Error: unexpected '[' in:
"for (i in 1:count.z) {
  activity.lm[i] = coef((with(subset(data.frame, z == ["
>   })))[2]
Error: unexpected '}' in "  }"
> }
Error: unexpected '}' in "}"

My guess was that it doesn't realise that there is an [i] within the with function.
I can't find a way of making this work, or think of another way of doing it. If you have any suggestions they would be hugely appreciated.

A: I'd strongly recommend a dplyr and broom package solution:
set.seed(44)

dt = data.frame(x = rnorm(40, 5, 5),
                y = rnorm(40, 3, 4),
                z = rep(c("a","b"), 20))

library(dplyr)
library(broom)

dt %>%
  group_by(z) %>%            # group by column z
  do(tidy(lm(y~x, data=.)))  # for each group create model using corresponding x and y values

# Source: local data frame [4 x 6]
# Groups: z [2]
#
#        z        term    estimate std.error  statistic    p.value
#   (fctr)       (chr)       (dbl)     (dbl)      (dbl)      (dbl)
# 1      a (Intercept)  3.54448459 1.8162699  1.9515186 0.06673401
# 2      a           x -0.18140655 0.2260252 -0.8025944 0.43267918
# 3      b (Intercept)  1.69024601 1.1960922  1.4131402 0.17467413
# 4      b           x  0.02647677 0.1914492  0.1382966 0.89154143

You can extract any piece of information of the lm output you want.

A: In base-R, getting you a named vector of only the gradients you're apparently interested in:
gradient.lm <- unlist(lapply(split(df,df$z),function(chunk){
  return(coef(lm(y~x, data=chunk))[[2]])
}))

A: This seems to work:
unique_z = unique(df$z)
coef_vec = vector(mode = "list", length = length(unique_z))

coef_vec[1] =
for (i in unique_z){
  coef_vec[i] =
    coef(
      with(
        subset(df, z==i),
      {lm(y~x)}))[2]
}

print(coef_vec)

Cleary coef_vec[i] corresponds to the z value in unique_z[i] so you have the coefficients matched up to their z values.


text:
Q: Finding the maximum Eigen vector in MATLAB I am trying to apply something I learned in paper regarding finding the maximum eigenvector of a matrix. Lets assume the matrix is $T$ and the max eigen vector of matrix ${\bf T}$ is ${\bf w}$
$${\bf w} =\max  \,eigenvector \, { \bf T}$$
I am trying to implement this in MATLAB, there are four options I am confused with and dont know what to use
[V,e]= eigs(T)
w = T(:,1)

or
[V,e]= eigs(transpose(conj(T))*T)
w = T(:,1)

or
[V,e]= eigs(transpose(T*conj(T)))
w = T(:,1)

or
[U,Sigma,Vh]= svd(T)
w = Vh(:,1) or w= U(:,1)

Thanks looking forward for your help.


text:
Q: Cordova android app is not redirecting to next page after i change the history route mode to hash mode i am building cordova android app using vue js, and i change the history route mode in to hash after that the app is only showing the first login page and is not redirecting to next page after i write my credential. i think the # sign in my url is privatizing it from redirecting to next page. i use push to redirect login user to home page.
below is my route:
const router = new VueRouter({
   mode: "hash",
   base: process.env.BASE_URL,
   routes,
});


text:
Q: PrincipalServerDownException on Windows XP but not on Windows 7 We have a WPF application that runs in full trust.
Part of the application checks the membership of a Windows AD group.
This works fine on a Windows 7 machine, but not on a Windows XP machine.
The error occurs on the following line:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain name");

A: According to the article Managing Directory Security Principals in the .NET Framework 3.5, the "domain name" variable might not be needed. That is, if you are accessing an Active Directory in the same domain as your application, the domain name is not needed.

You use the name parameter on the PrincipalContext constructor in
  order to provide the name of the specific directory to connect to.
  This can be the name of a specific server, machine, or domain. It's
  important to note that if this parameter is null, AccountManagement
  will attempt to determine a default machine or domain for the
  connection based on your current security context.

The solution or workaround to the problem (at least what worked for me on both XP and W7) is the following change:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null);


text:
Q: Database Wrapper Class for Python I am a PHP developer and recently migrated to Python. In PHP, there are many classes available at for example phpclasses.org which saves a lot of developer's time. I am looking for similar kind of repository for python. I need a database wrapper class for accessing the database with python. One of the class i found was at http://www.devx.com/dbzone/Article/22093 . But i didnt find any other similar class. So i m wondering no one in this world has created such kind of classes. Is there any better approach to access database in Python. Am i on the wrong track? I m aware of the ORM and its advantage but for small projects it doesnt make sense to me to use ORM's. Can anyone suggest some suitable python database wrapper class.
Thanks in advance.

A: Following Skurmedel's advice, I remembered reading about SQLAlchemy before. It's pretty well documented and maintained. Here's a good start point: SQLAlchemy 1.4 / 2.0 Tutorial

A: Most databases you choose to use will have a module available that conforms to the DBAPI. That gives you access that is quite easy to use and reasonably portable across different types of database (though not entirely). You can see an example of the API in action with the built-in SQLite support.
If you'll reconsider your opposition to ORMs however, as well as SQLAlchemy mentioned in another answer, SQLObject is another ORM, and is very simple to use. There's also Storm.


text:
Q: How do I detect when a terminal gets focus in Linux? I want to be able to time how long I spend in front of a terminal.  I'm thinking the best way will be to have some sort of timer that starts and stops when the terminal gains/loses focus.  And it will have to work with multiple terminals...
Any ideas?  I'm using GNOME.

A: If your terminal shell has easy access to its own X window ID, you're probably doing something wrong! They have nothing to do with each other - e.g. you could (and should) be running long jobs inside screen which could in theory be outputting to any number of terminals anywhere in the world.
That being said, the way I solve this problem is by using the prompt's ability to update a terminal's "status"/"title" to report the shell's PID, as with the following prompt:
PS1=\u@\H:\w\$\ \[\e]2;\u@\H:\w [$$]\a\]

Any pseudo-terminal showing the shell with this prompt and PID 6399 have a title like user@host:~ [6399]. Then, using a tool like wmctrl, you can write a bash script such as this:
win_from_pid() {
   type wmctrl &>/dev/null || return 1
   wmctrl -l | awk '/^.*\['"$1"'\]$/ { print $1 }'
}

This searches the window list and gives you the X Window ID(s) of any ending with that title. Thus, the function win_from_pid $$ can tell you your window ID(s) on the same host running the script, if any. You can figure out how to determine focus from there. :)

A: I expect you'll have to listen in on the X-window messages for the appropriate FOCUS message. Not sure how easy/difficult that will be though.
Alternatively https://stackoverflow.com/questions/1014822/how-to-know-which-window-has-focus-and-how-to-change-it talks about determining the window with focus and provides a couple of options: you could use that technique and just run it in a loop and track the focus changes.

A: You can do a stat on the terminal and get the Access or Modify times.
stat /dev/pts/2


text:
Q: How should the correct tests be? I am searching to write correct and understandable tests on react. I have read a lot of articles and texts. But I haven't understood a few matters. I have a component which request with axios. So there are requests like GET, POST.
How should the backend behave during frontend testing? Should the backend switch to test mode after frontend tests started ? Should the database reset itself after each frontend test ?
I think I shouldn't mock API to check if component correct render. What is the correct logic ?

A: The way that I approach this will be to mock the API call, the reason to do that will be, that I am reducing my scope of testing, As I am testing the React part, I would mock the success response and mock the error response and check how my components are working.
For the API testing, I will create a separate test case on the backend side. This way there will separation of concern. That is when I am testing react side I limit myself to the react side only and also this will make your test run fast as you are mocking the response, the actual request will not be sent and so you will get the response quickly.


text:
Q: Spawn command not working in electron app I am trying to run a command using spawn using AngularJS in Electron , I am getting an error.
events.js:183 Uncaught Error: spawn dita ENOENT
    at _errnoException (util.js:1024)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:190)
    at onErrorNT (internal/child_process.js:372)
    at _combinedTickCallback (internal/process/next_tick.js:138)
    at process._tickCallback (internal/process/next_tick.js:180)
_errnoException @ util.js:1024
ChildProcess._handle.onexit @ internal/child_process.js:190
onErrorNT @ internal/child_process.js:372
_combinedTickCallback @ internal/process/next_tick.js:138
_tickCallback @ internal/process/next_tick.js:180

This is my spawn command :-
spawn('dita',
            ['--input=C:\Users\aaa\Desktop\ditamaps\mobile-phone\mobilePhone.ditamap', '--output=C:\Users\aaa\Desktop', '--format=pdf'],
            {
              cwd: $scope.ditaPath + "\\bin"
            }, function(error, stdout, stderr) {
              // work with result
              console.log(stdout);
              console.log(stderr);
              console.log(error);
            });

When I am running the same batch code manually it's working fine.
 What is this error? I am not able to get this.

A: creating a process with spawn is not same as running it on the command prompt, You may either pass the absolute path of your executable like,
spawn('/full/path/to/dita',
    ['--input=C:\Users\aaa\Desktop\ditamaps\mobile-phone\mobilePhone.ditamap', '--output=C:\Users\aaa\Desktop', '--format=pdf'],
    {
        cwd: $scope.ditaPath + "\\bin"
    }, function (error, stdout, stderr) {
        // work with result
        console.log(stdout);
        console.log(stderr);
        console.log(error);
    }
);

or if you want to emulate command prompt
spawn('cmd.exe',
    ['dita', '--input=C:\Users\aaa\Desktop\ditamaps\mobile-phone\mobilePhone.ditamap', '--output=C:\Users\aaa\Desktop', '--format=pdf'],
    {
        cwd: $scope.ditaPath + "\\bin"
    }, function (error, stdout, stderr) {
        // work with result
        console.log(stdout);
        console.log(stderr);
        console.log(error);
    }
);

both of the solution should work, but in your scenario i guess 2nd one may easy to implement.


text:
Q: Delphi: IdHTTP+SSL does not work. No errors! I use TidHTTP + TIdSSLIOHandlerSocketOpenSSL + 2 DLLs: ssleay32.dll and libeay32.dll from http://indy.fulgan.com/SSL.
But I can see all work of my program in HTTP Analyzer! It works as HTTP, not as HTTPS. If I use Opera I cannot see downloading with the same site (https://esta.cbp.dhs.gov/esta).
I did not set any special parameters for TidHTTP and TIdSSLIOHandlerSocketOpenSSL (may be I must but I do not know what exactly).
Must I use TIdSSLVersion(sslvSSLv23) + location of a SSL certificate? Where can I get this certificate? Or only RootCertFile?
How to change a port of idHttp to 443 (must I do it?)?
I use:
procedure TForm1.FormCreate(Sender: TObject);
var mem:tmemorystream;
begin
try
  mem:=TMemoryStream.Create();
  try
    idhttp1.Get('https://esta.cbp.dhs.gov/esta/',Mem);
  except
   on E : Exception do ShowMessage(E.Message);
  end;
finally
  mem.Free;
  idhttp1.Free;
end;
end;

Please see my video: http://liga-installer.realservers.info/ssl.mp4
Screen shots:

Thanks Thanks Thanks for help!!!

A: you are using the wrong tool to check the communication. Your observation only shows the used protocol - which is HTTP 1.0 or 1.1 even if using SSL/TLS.
Try a tool like SmartSnif or Wireshark to check the real network traffic. You will see that the entire traffic is using port 443 with encrypted data.
The header response of HTTP/1.1 (or 1.0) is absolutely correct for HTTPS traffic, the SSL/TLS encryption does not change the transferred data but is a transport layer on top of HTTP traffic.
Regarding HTTP Analyzer (from their website at http://www.ieinspector.com/httpanalyzer/):
"Main Features:
Support HTTPS, show you unencrypted data sent over HTTPS / SSL connections as the same level of detail as HTTP."
So as I said it decodes the SSL and shows you the HTTP based, unencrypted traffic.
Regards,
Arvid

A: This simple example works in Delphi XE out of the box, so you don't need to change ports or use a certificate on the client side.  It's based on an example from RosettaCode:
Uses
  IdHttp, IdSSLOpenSSL

...
procedure TForm2.Button1Click(Sender: TObject);
var
  s: string;
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);
    lHTTP.HandleRedirects := True;
    s := lHTTP.Get('https://esta.cbp.dhs.gov/esta/');
    RichEdit1.Text := s;
  finally
    lHTTP.Free;
  end;
end;

The problem is probably the version of the DLLs you need to deploy.  Since recent versions fix security issues, I recommend upgrading your version of Indy to the latest and using the most recent OpenSSL libraries from the fulgan site.
Update:
Did you mean that you can't see the site using a web browser, or that when you do you can't see the traffic in your HTTP analyser?  As Rob mentioned, if the site isn't visible using a regular web browser, then the problem likely isn't your application.


text:
Q: Why can't I see a text input when I have a canvas next to it? I have the following HTML:
<html>
<body>
<canvas id="kartina" width="100" height="100">
<form>
<input type="text" id="xyz" value="abc">
</form>
</body>
</html>

The input box does not appear.  However, when I comment out the canvas like this:
<html>
<body>
<!--<canvas id="kartina" width="100" height="100">-->
<form>
<input type="text" id="xyz" value="abc">
</form>
</body>
</html>

then the input box is visible.
Why is the canvas preventing the text box from showing up?  Is it covering it?  If so, how can I force them to be in separate parts of the page?
EDIT: I'm viewing in Chrome.

A: For what I see, your canvas tag is not closed. Below is a modified version of your code with the tag closed, that displays both the canvas and the form.
<html>
<body>
<canvas  id="kartina" width="100" height="100">    **</canvas>**
<form>
 <input type="text" id="xyz" value="abc" />
</form>
</body>
</html>

Hope this helps :-).


text:
Q: Execute multiple exchange online cmdlets using C# , ASP.NET with only 1 runspace I am working on a ASP.Net webapplication that can connect to Exchange Online and run the commandlets.
The following is the working codebehind for a single button, which gets list of all the mailboxes in asp.net
protected void FinalConnection_Click(object sender, EventArgs e)
    {
        String userName = "";
        String passWord = "";
        SecureString securestring = new SecureString();

        foreach (char pass in passWord) {
            securestring.AppendChar(pass);
        }

        PSCredential pscred = new PSCredential(userName,securestring);
        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://ps.outlook.com/powershell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", pscred);
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
        connectionInfo.MaximumConnectionRedirectionCount = 2;

        using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
        {
            runspace.Open();
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = runspace;
                //Create the command and add a parameter
                powershell.AddCommand("Get-Mailbox");
                //var script = "Get-Mailbox";
                //powershell.AddScript(script);
                //powershell.AddParameter("RecipientTypeDetails", "UserMailbox");
                //Invoke the command and store the results in a PSObject collection
                var results = powershell.Invoke();
                //Iterate through the results and write the DisplayName and PrimarySMTP
                //address for each mailbox
                foreach (PSObject result in results)
                {
                    //Console.WriteLine(string.Format("Name: {0}, PrimarySmtpAddress: {1}",
                    //        result.Properties["DisplayName"].Value.ToString(),
                    //        result.Properties["PrimarySmtpAddress"].Value.ToString()
                    //        ));

                    newpowershell.InnerHtml += result.Properties["Name"].Value;

                }
            }
            runspace.Close();
        }
    }

I want to create different buttons like "Get-Users" "Get-MSOLUsers", but i want to keep only one runspace because of the throttling restrictions, max runspace = 3;
Should i open and close runspace for every button ? That is not a correct idea i believe
Can you please suggest alternatives on this?

A: You can keep the runspace open and create a new pipeline (runspace.CreatePipeline) each time you need to run a script.  I'm not sure if it's threadsafe though. You may need to limit the runspace to 1 open pipeline at a time.


text:
Q: Binary Search Array Object I am using a binary search array for the first time and having troubles. I am pretty sure the issue is in the void FindMyObject. Any ideas? The binary portion is near the bottom. It is labeled. It runs with no errors so I believe that I am close. I have looked at several examples and this seems on, I don't 100% understand the logic yet. Any advice?
string[] myStrArray = new string[] { " I"," am"," a"," Stella"," Student" };
object[] myObjArray = new object[] { " You"," are"," a"," Great"," Learner" };

void Page_Load(object sender, EventArgs e)
{
    //Binary Search Array
    Array.Sort(myStrArray);
    Array.Sort(myObjArray);
    Response.Write("

");

    PrintValues(myStrArray);
    PrintValues(myObjArray);

    object myStr = "Learner";
    FindMyObject(myStrArray, myStr);

    object myObj = "Stella";
    FindMyObject(myObjArray, myObj);
}

void FindMyObject(Object[] myArr, object myObject)
{
    int myIndex = Array.BinarySearch(myArr, myObject);
    if (myIndex < 0)
    {
        Console.WriteLine("The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, myIndex);
    }
    else
    {
        Console.WriteLine("The object to search for ({0}) is at index {1}.", myObject, myIndex);
    }
}

A: Your array initializer has a bunch of strings with spaces in front.  Your search strings do not have spaces, so will not be found.
<rant>
This would have been a lot simpler to answer if you hadn't included all the miscellaneous array manipulations.  It is always a good idea to reduce a problem to a minimum set of code required to reproduce the error, since doing so will very often help you to identify where the problem actually exists.
</rant>
Sorry, had to get that off my chest :P


text:
Q: Getting incorrect colors while scaling up CCSprite I'm getting a strange effect while scaling up a CCSprite loaded from a PVR texture. My original sprite is a simple solid color rectangle but I end up having a dithered color from both edges (left and right) with big scaling (ex: [mySprite setScaleX:100.0]). Note that this doesn't occur when I load my sprite from a standalone PNG file. Any idea what goes wrong or what special parameter could be missing ? BTW, I use TexturePacker and generating PNG textures is not better.
Thx.
[UPDATE] First image is the base sprite I want to expand ("test.png", real size is 3x30pix, here I zoomed 4 times for visibility purpose).

Second image is the expected result (the one I get when loaded from a standalone PNG file).

Code used:
aSprite = [CCSprite spriteWithFile:@"test.png"];
[self addChild:aSprite];
[aSprite setScaleX:300.0];

Third image is the result when loaded from the PVR texture.

Code used:
aSprite = [CCSprite spriteWithSpriteFrameName:@"test"];
[self addChild:aSprite];
[aSprite setScaleX:300.0];


text:
Q: laravel 5.8 scheduler not working automatically have to trigger manual i am running command php artisan schedule:run and it will work . but i want to update thing everyMinute(); automatically without trigger command every time .if i have to trigger it mannualy then what is the meaning of scheduler

*

*my command file

  public function handle()
    {
        $update = Roi::find(12);
        $update->level = 48;
        $update->save();
    }

2.kernal.php
 protected function schedule(Schedule $schedule)
    {
        $schedule->command('level:update')->everyTwoMinutes();
    }

i am checking updates in updated_at timestamp in database

A: That might solve your issue, it's the way you start the scheduler:
php artisan schedule:run >> /dev/null 2>&1

That way you will run every minute and check whatever is due to execute it.

A: https://gist.github.com/Splode/94bfa9071625e38f7fd76ae210520d94 windows not supported for command line task schedule

A: I think running schedule not working on windows locally
the only way worked for me is to create task in windows and related with .bat file
note: bat file content is
@ECHO OFF
php path-of-laravel-project\artisan schedule:run
PAUSE


text:
Q: How to align headers in Bokeh TableColumn I am using Bokeh TableColumn to produce a data table in an interactive dashboard.  I would like to right align the three numeric columns.  However, the headings remain left aligned and do not line up with the numbers in the column.
Is there a way to right align the headers in a Bokeh TableColumn?
I have search stackoverflow and do not believe this has a solution.  A minimum working example of what I am trying to do (with synthetic data) is below.
import pandas as pd
import numpy as np
from bokeh.plotting import figure, show, output_file, curdoc
from bokeh.layouts import layout, row, column, Spacer, widgetbox
from bokeh.models import ColumnDataSource, DataTable, TableColumn, DateRangeSlider, Slider, BoxAnnotation, HoverTool
from bokeh.models.widgets import NumberFormatter, DateFormatter, RangeSlider, Toggle, Button, CheckboxButtonGroup, Div

np.random.seed(10)
data = pd.DataFrame({
    'date':pd.date_range(start='1/1/2000', periods=200, freq='Q'),
    'x': np.random.choice(range(100),200)
})

data['qrtly'] = round(data['x'].pct_change(),4)
data['tty'] = round(data['x'].pct_change(periods=4),4)
source = ColumnDataSource(data)

columns = [
    TableColumn(field='date', title='', formatter=DateFormatter(format='%b-%Y')),
    TableColumn(field='x', title='levels', formatter=NumberFormatter(text_align='right')),
    TableColumn(field='qrtly', title='qrtly', formatter=NumberFormatter(format='0.00%',text_align='right')),
    TableColumn(field='tty', title='tty', formatter=NumberFormatter(format='0.00%',text_align='right'))
]

table = DataTable(source=source, columns=columns, width=635)

curdoc().add_root(table)

A: Here is a method that use css to do it:
give the table a css class:
table = DataTable(source=source, columns=columns, width=635, css_classes=["my-table"])

then use following style to right align the levels columns:
.my-table .slick-header-column:nth-child(3) .slick-column-name{
    float:right !important;
}

You can add style by using Div
from bokeh.models.widgets import Div
table = DataTable(source=source, columns=columns, width=635, css_classes=["my-table"])
style = Div(text="""
<style>
.my-table .slick-header-column:nth-child(3) .slick-column-name{
    float:right !important;
}
</style>
""")
show(column(table, style))


text:
Q: counting pixels using tensorflow and gpu I have mask images with size (N, 256, 256), where N is a value between 1000-10000.
Each pixel has an integer value between 0-2 (0 is just background).
Unfortunately, the mask image is not encoded as (N,256,256,2)
I have a few thousands of these masks. My goal is to find the quickest method counting pixels per frame for each label (1 and 2).
Running below on one mask image with roughly 6000 frames using numpy takes < 2s.

np.sum(ma==1,axis=(1,2))
     np.sum(ma==2,axis=(1,2))

I expect it will take a few hours to run on entire data if I use single process, and maybe less than an hour if I use multiprocessing (CPU).
I'm curious if I can make it even faster if I use GPU. It seems easy to implement the part summing a tensor on axes, but I don't find how I can implement the ma==1 part on tensorflow.
I thought about making the input to encoded shape (N,256,256,2) first and pass to the tensor placeholder, but realized it would take even longer than above to make an array with that shape.
Or, is there a better way to implementing pixel count on this mask data using tensorflow?

A: Think about what's going on in the background
Roughly the following steps are done twice in your original implementation:

*

*Loading the whole array from memory, prove if a value equals the desired value

*Writing the results back to memory (the temporary array is as large as your input array,np.uint8 assumed)

*Loading the whole array into memory and sum up the results

*Writing the results back to memory

It should be clear that this is a quite suboptimal implementation parallelized or not. I could not do it any better in a pure vectorized numpy way, but there are tools available (Numba, Cython) where you can implement this task in a more direct and paralellized way.
Example
import numpy as np
import numba as nb
import time

#Create some data
N=10000
images=np.random.randint(0, high=3, size=(N,256,256), dtype=np.uint8)

def sum_orig(ma):
  A=np.sum(ma==1,axis=(1,2))
  B=np.sum(ma==2,axis=(1,2))
  return A,B

@nb.njit(fastmath=True,parallel=True)
def sum_mod(ma):
  A=np.zeros(ma.shape[0],dtype=np.uint32)
  B=np.zeros(ma.shape[0],dtype=np.uint32)

  #parallel loop
  for i in nb.prange(ma.shape[0]):
    AT=0
    BT=0
    for j in range(ma.shape[1]):
      for k in range(ma.shape[2]):
        if (ma[i,j,k]==1):
          AT+=1
        if (ma[i,j,k]==2):
          BT+=1

    A[i]=AT
    B[i]=BT

  return A,B

#Warm up
#The funtion is compiled at the first call
[A,B]=sum_mod(images)
t1=time.time()
[A,B]=sum_mod(images)
print(time.time()-t1)
t1=time.time()
[A_,B_]=sum_orig(images)
print(time.time()-t1)

#check if it works correctly
print(np.allclose(A,A_))
print(np.allclose(B,B_))

Performance
improved_version: 0.06s
original_version: 2.07s
speedup: 33x


text:
Q: jQuery selector to display the flowplayer tooltip over a td element I'm trying to use the flowplayer tooltip tool (http://flowplayer.org/tools/demos/tooltip/table.html) to display a tooltip over a particular  element.
Here is my html:

   About

Tooltip text.

Note that the tooltip div part above is styled as display:none.
Here is the selector I'm trying to use...
$("#menu-table td[menu-one]").tooltip();

The tooltip() should display the hidden div, but I'm sure I have the selector wrong.
Any suggestions?

A: try
$("#menu-table td[title='menu-one']").tooltip();

to select the TD with an argument title with value 'menu-one'