text:
Q: SOAP WSDL PHP client connecting to .Net Server I need to integrate a web service, and its being like to days, and the closest I get is the following, maybe some of you have more experience than me in this kind of web service.
The XML request I need to generate is the following
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"         xmlns:v2="http://v2.services.cangooroo.net/" xmlns:can="Cangooroo.Webservice.V2">
<soapenv:Header/>
<soapenv:Body>
<v2:getCityData>
<v2:credentialClient>
<can:UserName>?</can:UserName>
<can:Password>?</can:Password>
</v2:credentialClient>
<v2:countryId>US</v2:countryId>
</v2:getCities>
</soapenv:Body>
</soapenv:Envelope>

My PHP code
 $client = new SoapClient("http://v2.cangooroo.net/ws/2013/common_a.asmx?WSDL", array(
       "trace" => 1,
       "compression" => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP,
   ));
    $login = array();
    $login[] = new SoapVar('*', XSD_STRING, null, null, 'UserName', 'Cangooroo.Webservice.V2' );
    $login[] = new SoapVar('*', XSD_STRING, null, null, 'Password', 'Cangooroo.Webservice.V2' );
    $rest = array();
    $rest[] = new SoapVar($login, SOAP_ENC_OBJECT, null, null, 'credentialClient' );
    $rest[] = new SoapVar('US', XSD_STRING, null, null, 'countryId');

    $options = array('location' => 'http://v2.cangooroo.net/ws/2013/common_a.asmx');

    try {
        $resp = $client->__soapCall('getCityData', $rest, $options);

        print_r($resp);
        echo "Request:
" . htmlentities($client->__getLastRequest()) . "
";
    }catch (SoapFault $e){
        echo "REQUEST:
" . htmlentities($client->__getLastRequest()) . "
";
        /*print_r($e);*/

The actual xml the PHP code above generates
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="Cangooroo.Webservice.V2" xmlns:ns2="http://ws_2013.services.cangooroo.net/">
<SOAP-ENV:Body>
<ns2:getCityData>
<ns1:UserName>*</ns1:UserName>
<ns1:Password>*</ns1:Password>
</ns2:getCityData><countryId>US</countryId></SOAP-ENV:Body></SOAP-ENV:Envelope>

Iam not really sure if this is the best way to do it, but I tryed others, with __soapCall,
__doRequest, this last one I got the soapClient php core class extended (as a try) to connect, and nothing seems to work. Pls, I could use a little help here. Tks guys.

A: If you check the wsdl file in http://v2.cangooroo.net/ws/2013/common_a.asmx?WSDL you can see the definition of the getCityData
<s:element name="getCityData">
    <s:complexType>
        <s:sequence>
            <s:element minOccurs="0" maxOccurs="1" name="credential" type="s1:ClientCredential"/>
            <s:element minOccurs="0" maxOccurs="1" name="countryId" type="s:string"/>
        </s:sequence>
    </s:complexType>
</s:element>

the operation getCityData has a credential parameter, not a credentialClient that is what you have in the code that you posted. I've tried with this code:
$wsdlAddress = "http://v2.cangooroo.net/ws/2013/common_a.asmx?WSDL";

$options = array(
    "soap_version" => SOAP_1_2,
    "cache_wsdl" => WSDL_CACHE_NONE,
    "exceptions" => false
);

$webServiceClient = new SoapClient($wsdlAddress, $options);

$requestData = array(
    "countryId" => "US",
    "credential" => array(
        "UserName" => "username",
        "Password" => "Password",
    ),
);

$response = $webServiceClient->__soapCall("getCityData", array("getCityData" => $requestData));

echo "
getCityData Operation Test:
";
echo "
";
print_r($response);
echo "
";

in the response i can see Err: Login_Fail - Invalid user or password., i think i'm getting a valid response. Try with my code and adapt it to your needs.
Happy coding


text:
Q: pushed items to array seem to be reactive to old object I am facing an issue where after I push an object to an array it will be reactive to changes.
// actions.js
export const addToCart = ({ commit }) => {
    commit('addToCart'); // properly commits to change the state

    setTimeout(function () {
        commit('resetToppings');
    }, 10000);
};

// mutations.js
export const addToCart = (state) => {
    state.cart.push(state.orderItem);
};

export const resetToppings = (state) => {
    state.orderItem.toppings = [];
};

// state.js
cart: [],
orderItem: {
    quantity: 1,
    toppings: [],
},

The orderItem gets properly pushed to the cart, but 10 seconds later when I resetToppings, it resets the toppings inside the cart as well as in the orderItem.
How can I make sure that resetToppings does not mutate anything inside cart?

A: When you push state.orderItem you add a reference to it in the array. So when state.orderItem changes, the element inside the array changes, because it (the element inside the array) is actually still pointing to the same (state.orderItem) object.
You can push a shallow clone of the orderItem object instead:
// mutations.js
export const addToCart = (state) => {
    state.cart.push({...state.orderItem});
};

This way what is added to the array is a different object.

Note: you can do:
state.cart.push({...state.orderItem});

But this will only work if you never remove/add elements from/to the toppings array directly after the addToCart is called. That is, if you call resetToppings before adding new elements to toppings (which will work because resetToppings assigns a new array).
If that's not always the case, I mean, if you sometimes edit the toppings array directly after the addToCart is called, you might want to clone it as well:
state.cart.push(Object.assign({...state.orderItem}, {toppings: [...state.orderItem.toppings]}});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is my javascript preventing the browser from going to a link I have a script on http://joelglovier.com to add a class of "active" to each navigation element when it's corresponding section in the document. The script is adapted with permission from w3fools.com, so it was written without my scenario in mind.
The difference is that on w3fools.com, the nav links only refer to elements on the page, whereas in my navigation, there is one element at the end that refers to a new page.
The problem is that as I have adapted it, it works fine for the links that refer to sections on the page. However, for some reason unbeknownst to me (sorry - JS/jQuery novice) it is blocking the browser from following the link to the new page (the Blog link).
I tried reading through the code and understanding what the script is doing - however I cannot seem to understand why it is blocking that external link from being clicked, or more specifically how to fix it.
Can anybody suggest the simplest way to remedy my issue without breaking the original functionality of the script for it's purpose?
See it live here: http://joelglovier.com
Or...
Markup:

            Top

            Background

            Projects

            Random

            Credits

            Blog

Javascript:
(function($) {
  $(function() {

    var $nav = $('#nav-links'),
        $navLinks = $nav.find('a.scroll'),
        cache = {};
        $docEl = $( document.documentElement ),
        $body = $( document.body ),
        $window = $( window ),
        $scrollable = $body; // default scrollable thingy, which'll be body or docEl (html)

    // find out what the hell to scroll ( html or body )
    // its like we can already tell - spooky
    if ( $docEl.scrollTop() ) {
        $scrollable = $docEl;
    } else {
        var bodyST = $body.scrollTop();
        // if scrolling the body doesn't do anything
        if ( $body.scrollTop( bodyST + 1 ).scrollTop() == bodyST) {
            $scrollable = $docEl;
        } else {
            // we actually scrolled, so, er, undo it
            $body.scrollTop( bodyST - 1 );
        }
    }

    // build cache
    $navLinks.each(function(i,v) {
        var href =  $( this ).attr( 'href' ),
            $target = $( href );
        if ( $target.length ) {
            cache[ this.href ] = { link: $(v), target: $target };
        }
    });

    // handle nav links
    $nav.delegate( 'a', 'click', function(e) {
    //  alert( $scrollable.scrollTop() );
        e.preventDefault(); // if you expected return false, *sigh*
        if ( cache[ this.href ] && cache[ this.href ].target ) {
            $scrollable.animate( { scrollTop: cache[ this.href ].target.position().top }, 600, 'swing' );
        }
    });

    // auto highlight nav links depending on doc position
    var deferred = false,
        timeout = false, // so gonna clear this later, you have NO idea
        last = false, // makes sure the previous link gets un-activated
        check = function() {
            var scroll = $scrollable.scrollTop(),
                height = $body.height(),
                tolerance = $window.height() * ( scroll / height );

            $.each( cache, function( i, v ) {
                // if we're past the link's section, activate it
                if ( scroll + tolerance >  v.target.position().top  ) {
                    last && last.removeClass('active');
                    last = v.link.addClass('active');
                } else {
                    v.link.removeClass('active');
                    return false; // get outta this $.each
                }
            });

            // all done
            clearTimeout( timeout );
            deferred = false;
        };

    // work on scroll, but debounced
    var $document = $(document).scroll( function() {
        // timeout hasn't been created yet
        if ( !deferred ) {
            timeout = setTimeout( check , 250 ); // defer this stuff
            deferred = true;
        }
    });

    // fix any possible failed scroll events and fix the nav automatically
    (function() {
        $document.scroll();
        setTimeout( arguments.callee, 1500 );
    })();

});

})(jQuery);

A: You're trying to tell it to scroll to "http://..." which doesn't exist on the current page, so it fails and does nothing.
It should work if you change your code to this
// handle nav links
$nav.delegate( 'a', 'click', function(e) {
//  alert( $scrollable.scrollTop() );
    e.preventDefault(); // if you expected return false, *sigh*
    if ( cache[ this.href ] && cache[ this.href ].target ) {
        // preserve http:// links
        if (this.href.substr(0, "http://".length) == 'http://')
            location.href = this.href;
        else
            $scrollable.animate( { scrollTop: cache[ this.href ].target.position().top }, 600, 'swing' );
    }
});


text:
Q: Single field extraction from a database using lambda My problem is connected to the extraction method called lambda ( I am using it in C# ). I have a database and in it I have a table called Students and I wonder if I would be able to extract the firstName and lastName of certain student whose ID matches my search.
I have tried a few things so far without any luck.
A bit of code from my last attempt :
var studentName =
    context.Student //context is the variable with the entities and Student is the table
    .Where(student => student.StudentID == SomeInt) // extract only the one with the chosen ID
    .Select(student => student.FirstName) // tryng only to select the wanted field(s)
    .ToString() // since I want it to be displayed in a textbox

A: Currently you're calling Select on an IQueryable<string> - your query represents a sequence of student first names, even if it only matches a single one.
If you only want a single name, you can use:
var studentName =
    context.Student
           .Where(student => student.StudentID == SomeInt)
           .Select(student => student.FirstName)
           .FirstOrDefault();

Then assuming FirstName is a string, you don't need ToString() at all. The value will be null if there's no student with that ID. Alternatively, you could use Single(), SingleOrDefault(), First(), Last() or LastOrDefault(). So for example, you'd then use:
if (studentName == null)
{
    // No match found. Return an error or whatever.
}
else
{
    // Use studentName
}

(You should only use FirstOrDefault() if you then check for nullity, or pass it on to something else that does so. Otherwise you can end up with a NullReferenceException later which is hard to diagnose.)
If you want both the first and last names, you need to change your projection. For example:
var studentName =
    context.Student
           .Where(student => student.StudentID == SomeInt)
           .Select(student => new { student.FirstName, student.LastName })
           .FirstOrDefault();

Now the type of studentName will be an anonymous type - again, it'll be null if there are no matches, but otherwise it will have appropriate FirstName and LastName properties.

A: You could try something like this:
var student = context.Student
                     .Where(student => student.StudentID == studentId)
                     .Select(student => new
                      {
                          FirstName = student.FirstName,
                          LastName = student.LastName
                      }).FirstOrDefault();

If any student with studentId exists at all, then you get her first name and her last name, like below:
var firstName = student.FirstName;
var lastName = student.LastName;

If there isn't any student with the given studentId, the result of the above query, would be null. Hence, before you use the dot notation, please validate that the user you are looking for has been found like below:
if(student!=null)
{
   // Here you can access both the LastName and
   // the FirstName of the found student.
}

A: You can write something like:
var name = context.Students.FirstOrDefault(c=>c.Id == SomeId).FirstName;


text:
Q: Using geom_arc_bar in ggforce I want to make a plot that looks like the one attached below which to my understanding can be achieved using the geom_arc_bar() function from the ggforce package:

df <- data.frame(English = sample(1:100,10),
                Math = sample(1:100,10),
                History = sample(1:100,10),
                Science = sample(1:100,10),
                Group = rep(c("A","B","C","D","E"),each=2))

How would I approach this given a sample data frame, where each bar is the mean value of each group, so for this sample df, there should be 5 circles for each group (A,B,C,D,E) and each circle has the mean value of the 4 subject scores plotted in the arc? Other plotting methods are also fine (doesn't necessarily have to be by ggforce). Thanks a lot!

A: First we'd need to reshape the data and precalculate the group means for each subject.
library(ggplot2)
library(ggforce)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

df <- data.frame(English = sample(1:100,10),
                 Math = sample(1:100,10),
                 History = sample(1:100,10),
                 Science = sample(1:100,10),
                 Group = rep(c("A","B","C","D","E"),each=2))

# Reshape and calculate group means
df2 <- df %>%
  tidyr::pivot_longer(-Group) %>%
  group_by(Group, name) %>%
  summarise(value = mean(value), .groups = "keep")

Next we'd need to define a function and some constants to help us generate the plot.
# Map discrete values to continuous
helper <- function(x) {match(x, sort(unique(x)))}

# Helper values
nsubjects <- length(unique(df2$name))
tau <- 2 * pi
arc_part <- tau / nsubjects
circle_size <- 1
circle_spacing <- 0.1
circle_offset <- 0.8 * circle_size

Lastly, we can then use ggforce::geom_arc_bar() to plot the data.
ggplot(df2) +
  # Outline circle
  geom_arc(
    data = ~ subset(.x, !duplicated(Group)),
    aes(x0 = (helper(Group) - 1) * 2 * (circle_size + circle_spacing),
        y0 = 0, r = circle_size, start = 0, end = tau)
  ) +
  # Subject quadrants
  geom_arc_bar(
    aes(x0 = (helper(Group) - 1) * 2 * (circle_size + circle_spacing),
        y0 = 0, r0 = 0,
        r = value * circle_offset / max(value),
        start = (helper(name) - 1) * arc_part,
        end   = helper(name) * arc_part,
        fill  = name)
  ) +
  coord_equal()

Created on 2021-10-22 by the reprex package (v2.0.1)
There is also the vanilla ggplot2 approach:
ggplot(df2, aes(x = name, y = value, fill = name)) +
  geom_col(width = 1) +
  facet_wrap(~ Group) +
  coord_polar(theta = "x")


text:
Q: How to insert an element inside List<> I have a list like this
var mylist = new List<string>();
mylist.Add("apple");
mylist.Add("orange");
mylist.Add("banana");
mylist.Add("mango");

Now I want to add "melon", between orange and banana? How can I do that? Thanks.

A: You can use Insert method to insert new item in list. First parameter to this method is Index and second is the item.
So if you need to insert next to orange you need to find index of orange and insert next to this by using IndexOf orange.
mylist.Insert((mylist.IndexOf("orange") + 1), "melon");

A: Use List<T>.Insert():
mylist.Insert(2, "melon");

The first argument is the index at which the string should be inserted.


text:
Q: Why my VS 2008 will be closed down when try to edit some ASPX file from Nerddinner Project Why my VS 2008 will be closed down when try to open or edit the .ASPX files from Nerddinner Project?
I'm using VS 2008 Professional SP1 version.

A: I have found out the reason. I changed the name of the controller.


text:
Q: Problems with using Ansible 1.9 to assign floating IPs to OpenStack Nova instance I'm trying to configure Ansible 1.9 to launch some OpenStack Nova instances.
For each instance, I'm attempting to auto-assign a floating IP, connecting it to a public segment.
When I try this:
- name: launch  Web01  instance
  hosts: csc
  tasks:
   - nova_compute:
      state: present
      login_username: tenant_2_user
      login_password: hello
      login_tenant_name: tenant_2
      name: Web01
      auth_url: http://mylocalhost:5000/v2.0/
      region_name: RegionOne
      image_id: 95c5f4f2-84f2-47fb-a466-3c786677d21c
      wait_for: 200
      flavor_id: b772be9a-98cd-446f-879e-89baef600ff0
      security_groups: default
   - neutron_floating_ip:
      state=present
      login_username=tenant_2_user
      login_password=hello
      login_tenant_name=tenant_2
      network_name=ext-net
      instance_name=Web01

I get :  ERROR: neutron_floating_ip is not a legal parameter in an Ansible task or handler
And when I try this:
- name: launch  Web01  instance
  hosts: csc
  tasks:
   - nova_compute:
      state: present
      login_username: tenant_2_user
      login_password: hello
      login_tenant_name: tenant_2
      name: Web01
      auth_url: http://mylocalhost:5000/v2.0/
      region_name: RegionOne
      image_id: 95c5f4f2-84f2-47fb-a466-3c786677d21c
      wait_for: 200
      flavor_id: b772be9a-98cd-446f-879e-89baef600ff0
      security_groups: default
      auto_floating_ip: yes

msg: unsupported parameter for module: auto_floating_ip
Here is my Ansible version:  ansible --version
ansible 1.9
  configured module search path = /usr/share/ansible
What can I do to have Ansible assign these floating IPs?
-Eugene

A: I got it working. You dont need to use

auto_floating_ip: yes

just use

  floating_ip_pools:
     - Your-external/public-network-id

Hope this helps.


text:
Q: Can I block inbound traffic from a certain ISP The problem
My server keeps getting DDoS attacks from IP's belonging to Ecatel in The Netherlands. I wrote them a month ago and still haven't heard anything, and keep blocking individual IP addresses whenever my server slows to a crawl isn't a prudent solution.
Server info
I'm running an EC-2 micro on AWS, so if it's possible to do something clever with the AWS security groups, that might be the best solution.
I'm not really sure what options I have here, but I assume I can block traffic from a certain ISP. Is that possible?
inetnum:        *ip-from* - *ip-to*
netname:        NL-ECATEL
descr:          *address*
country:        NL
admin-c:        EL25-RIPE
tech-c:         EL25-RIPE
status:         ASSIGNED PA
mnt-by:         ECATEL-MNT
mnt-lower:      ECATEL-MNT
mnt-routes:     ECATEL-MNT
changed:         20080621
source:         RIPE

role:           Ecatel LTD
address:        *address*
address:        *address*
address:        Netherlands
abuse-mailbox:
remarks:        ----------------------------------------------------
remarks:        ECATEL LTD
remarks:        Dedicated and Co-location hosting services
remarks:        ----------------------------------------------------
remarks:        for abuse complaints :
remarks:        for any other questions :
remarks:        ----------------------------------------------------
e-mail:
admin-c:        EL25-RIPE
tech-c:         EL25-RIPE
nic-hdl:        EL25-RIPE
mnt-by:         ECATEL-MNT
changed:        20130201
source:         RIPE

route:          89.248.172.0/23
descr:          AS29073, Route object
origin:         AS29073
mnt-by:         ECATEL-MNT
changed:        20071119
source:         RIPE

A: For starters, it doesn't take much at all to tie ip a t1.micro instance - if you want the instance to do anything meaningful, you want to be using a larger instance type.
As for blocking requests - you will not be able to drop traffic using the instance's security groups, as it lets you allow traffic, not drop it. You can run a local iptables firewall on the instance and add the subnet manually.
A better solution altogether is to install and configure fail2ban to automatically add individual IPs that exhibit DDoS-like behaviour to an iptables chain. The whole process is beyond the scope of a ServerFault answer, but check these links for some detail: (1) (2)


text:
Q: Confuse: how to use es6 browser module withTypescript (without module bundler) I would like organize my typescript code with es6 module and load them via the script type="module" directly in the browser.  I have checked the support  (https://caniuse.com/#feat=es6-module) and it would work.  I use chrome version 66.
I have tried without success (see code below) and moreover I m confused about the correct strategy to use.
Solution 1 : In app.ts file, should I import the external module but then how to load the correct js file ?
Solution 2 : In app.ts file, should I import directly the .js code but how to reference the .d.ts file to have the type checkin ?
Any help will be greatly appreciated.
=======================================================================
This is the code i have tried
My index.html file

<!DOCTYPE html>

  <title>Welcome</title>

{{ msg }}

My app.ts file
//Solution 1
// import Vue from "vue"; // Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".

//Solution 2
import Vue from "./Vendors/vue.esm.browser.js"; // It works in the browser but i have lost the definition inside Typescript file

var app = new Vue({
    el: '#app',
    data: {
        msg: 'hello :)!'
    }
});

My tsconfig.json file
// tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "target": "es6",
    "module": "es6",
    "moduleResolution": "node",
    "allowJs": true
  }
}

My package.json file
{
  "name": "vuejsbrowseresmodule",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "vue": "^2.5.16"
  }
}

A: After days of research, I have found an answer.
For the moment, it s not possible to do with typescript without using a module loader.
There is a lot of discussion about a native loader in the browser in typescript.
More information are available here =>
https://github.com/Microsoft/TypeScript/issues/16577
https://github.com/Microsoft/TypeScript/issues/13422
An interesting proposition draft has started and is available here =>
https://github.com/domenic/package-name-maps

A: I may have found a solution.
Create a Declaration file say vue.d.ts
In it write
declare var vue: typeof import("vue/index")

Then in your ts code, you have global var vue with the correct type provided
and since this file won't appear in the browser, js code in the browser will use the global vue from your cdn vue.js file.
disclaimer: I haven't tried vue, it worked with @type/bootstrap.


text:
Q: WP Ajax coding Not Working Ok so I am having trouble with converting my html design website to wp. I have everything working except for the ajax code that I am using to load the content into a specified div without reloading the page. This way my music player plays continuously without restarting the music player with every page load or link click. The code I was using for the html of my website worked perfectly exactly how i wanted it to. Please take a look at the page http://www.trillumonopoly.com/index2.html
but when I came here for help I was suggested to used some changes to make it work with wordpress.... I find that the content still doesnt load without reloading the entire page and then the music player starts from the beginning all over again. From a listener and consumer stand point this is annoying and I dont want to lose clients, or fans becuase of this issue so I have been waiting to launch my website untill this problem is fixed so maybe I can have someone assist me with this. please
Here is the Code I was told to put in my functions php
 /**
   * Init js script and its variables
   */
  add_action( 'wp_enqueue_scripts', 'init_js_vars' );
  function init_js_vars() {
    wp_enqueue_script( 'menu_nav', get_template_directory_uri().'/js/nav.js', array( 'jquery') );

    wp_localize_script( 'menu_nav', 'theme', array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'nonce' => wp_create_nonce( 'ajax-get-page-content' ),
            'page' => 4
        ) );
    }

    /**
     * Handle ajax request, returns content of specific page
     */
    add_action( 'wp_ajax_get_page_content', 'get_page_content' );
    add_action( 'wp_ajax_nopriv_get_page_content', 'get_page_content' );
    function get_page_content() {
        check_ajax_referer( 'ajax-get-page-content', 'nonce' );

        $post_id = absint( $_POST['page_id'] );

        $post = get_post( $post_id );
        $content = apply_filters('the_content', $post->post_content);

        wp_send_json_success( array( 'content' => $content ) );
    }

heres the JS/ajax code that I am using (Which still doesnt function correctly as in the link i provided)
$( document ).ready(function() {
  $.ajax({
    url: theme.ajaxurl,
    method: 'GET',
        data: {
        action: 'get_page_content',
        nonce: theme.nonce,
        page_id:
    }
    success: function( response ) {
        $('#contentarea').html( response.content );
    }
  });
});

See the script live in action here http://wp.trillumonopoly.com
Please help me to figure this out to make it function like it does in my html version of the website from the first link I provided above. (few pages are missing but you can still get the just of what I am trying to do)


text:
Q: User-defined errno range values (POSIX or Linux-specific) Questions for POSIX if possible, else for Linux-specific platforms:

*

*Is there user-defined errno values? (as for signals SIGUSR1 and SIGUSR2)

*How to find an errno value not used by the system? (negative values?)

*How to prevent strerror() break? (check before the errnum sign?)

My code open() a resource and notifies another object. The notification Event conveys the system errno if a failure occurs (zero on success).
But failures can also be detected in my code, e.g. if(count>=size). And I want to reuse the field Event::errnum to convey this failure. Therefore my user-defined failure code should not overlap system-defined errno values.
I have found errno range 9000–11000 reserved for user, but this seems to be specific to Transaction Processing Facility...
Note my question is not about library-defined errno. The struct Event is not exposed outside my code. My code does not overwrite errno.
Below snippet is in c++ but my question also applies for c.
#include <cerrno>

#define E_MY_USER_DEFINED_ERROR 9999

struct Event
{
    int fd;
    int errnum;
};

struct Foo
{
    Foo( int sz ) : count(0), size(sz) {}

    Event open( const char name[] )
    {
        if( count >= size )
            return { -1, E_MY_USER_DEFINED_ERROR };

        int fd = 1; // TODO: open ressource...
        if (fd < 0) return { -1, errno };
        else        return { fd, 0 };
    }

    int count, size;
};

int main()
{
    Foo bar(0);
    Event e = bar.open("my-ressource");
    // send Event to another object...
}

A: The actual errno values  are not defined by the C and C++ standards. So there's no way to return a particular (positive) integer and guarantee it to not clash with the one that an implementation uses.
The C standard requires only three marco:
C11 draft, 7.5  Errors

The macros are
EDOM
  EILSEQ
  ERANGE
which expand to integer constant expressions with type int, distinct
  positive values, and which are suitable for use in #if preprocessing
  directives;

So you don't know what other errno values are defined in your implementation.
The errno values are postive integers in standard C and POSIX. So you could use your own enumaration with negative values to define your own error numbers.
But then you can't use the strerror/perror interfaces. So you may need additional wrapper for strerror/perror to interpret your own error numbers.
Something like:
enum myErrors{
ERR1 = -1,
ERR2 = -2,
...
ERR64 = -64
};

char *my_strerror(int e)
{
   if (e>=ERR1 && e<=ERR2)
      return decode_myerror(e); // decode_myerror can have a map for
                                //your error numbers and return string representing 'e'.
   else
      return strerror(e);
}

and a similar one for perror.
Note you should also set errno to 0 before calling your "open-resource" to make sure the errno was indeed set by your function.
I'd avoid the standard errno altogether in situations like this and define my own enumeration for errors. You could do that if your "open-resource" is not too complicated and returns too possible error codes.

A: P.P.'s answer proposes using negative value as the user-defined range. This is perfect in my case.
Below is my question snippet using the suggestion from P.P. This snippet is also available on coliru.
#include <cerrno>
#include <cstring>
#include <iostream>

#define E_MY_USER_DEFINED_ERROR -1

struct Event
{
    int fd;
    int errnum;
};

struct Foo
{
    Foo( int sz ) : count(0), size(sz) {}

    Event open( const char name[] )
    {
        if( count >= size )
            return { -1, E_MY_USER_DEFINED_ERROR };

        int fd = std::strlen(name); // TODO: open ressource...
        if (fd < 0) return { -1, errno };
        else        return { fd, 0 };
    }

    int count, size;
};

int main()
{
    Foo bar(0);
    Event e = bar.open("my-ressource");
    std::cout << std::strerror( e.errnum ) << std::endl;
}

Output using GCC
Unknown error -1

Output using Clang
Unknown error -1


text:
Q: unable to change width of image with bootstrap I'm working on Carousel image slider with bootstrap. I'm unable to change the height of the image. If I try to change the height it's effecting for both height and width both. But I need to modify only width.
My code is like below :

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/
    bootstrap.min.css">

Carousel Example

        Previous

        Next

A: You can try this:
.carousel-inner .item img{
   max-width: none;
   width: your-width:
   height: your-height;
}

A: Percent height is tricky because it depends on parent height, which in this case there are none, resulting in that your image height means nothing.
You can set a fixed height on the parent (not using percent) Or you can set a percent-based height on the parent, but then IT'S parent needs a fixed height. And the same is true all the way up to the html-element, which you can set a 100% height on and the browser will respect it, but it's a really ugly way of doing things.
There are ways around this of course. It also seems like you don't mind if the image is stretched, so that is another assumption I'm making. With that said I think the easiest option here is to use vw/vh units. They work almost as percent, but vw/vh is based on viewport width or height and not parent height. Thus:

Of course, if you don't know the exact ratios, the image will be stretched. (use height: auto for a non-stretched image).
Here is various browser support for the vh/vw units.
If you want the image to appear cropped, you are better off using css background-image and background-size instead of a img element. (Your intentions are not obvious from your question.)


text:
Q: Allow user to set custom order to a list of custom taxonomies? I have a custom category checkbox on each individual bio attorney page that shows what practice areas these attorneys are involved in. Currently I have them sorting alphabetically. I am wondering if there is anyway to allow each attorney to set their own custom order when selecting their practice areas.
Here is a screenshot of the post:
https://www.dropbox.com/s/1si99a5elkmdwbr/Screen%20Shot%202013-02-14%20at%2011.50.02%20AM%20copy.png
UPDATE:
For those interested I figured it out.
I added this to my functions.php:
function set_the_terms_in_order ( $terms, $id, $taxonomy ) {
$terms = wp_cache_get( $id, "{$taxonomy}_relationships_sorted" );
if ( false === $terms ) {
    $terms = wp_get_object_terms( $id, $taxonomy, array( 'orderby' => 'term_order' ) );
    wp_cache_add($id, $terms, $taxonomy . '_relationships_sorted');
}
return $terms;
}
add_filter( 'get_the_terms', 'set_the_terms_in_order' , 10, 4 );

function do_the_terms_in_order () {
    global $wp_taxonomies;  //fixed missing semicolon
    // the following relates to tags, but you can add more lines like this for any taxonomy
    $wp_taxonomies['post_tag']->sort = true;
    $wp_taxonomies['post_tag']->args = array( 'orderby' => 'term_order' );
}
add_action( 'init', 'do_the_terms_in_order');

then when I register my taxonomy I set:
'hierarchical' => false,
'orderby' => 'term_order'

CREDIT: http://wordpress.kdari.net/2011/07/listing-tags-in-custom-order.html

A: For those interested I figured it out.
I added this to my functions.php:
function set_the_terms_in_order ( $terms, $id, $taxonomy ) {
$terms = wp_cache_get( $id, "{$taxonomy}_relationships_sorted" );
if ( false === $terms ) {
    $terms = wp_get_object_terms( $id, $taxonomy, array( 'orderby' => 'term_order' ) );
    wp_cache_add($id, $terms, $taxonomy . '_relationships_sorted');
}
return $terms;
}
add_filter( 'get_the_terms', 'set_the_terms_in_order' , 10, 4 );

function do_the_terms_in_order () {
    global $wp_taxonomies;  //fixed missing semicolon
    // the following relates to tags, but you can add more lines like this for any taxonomy
    $wp_taxonomies['post_tag']->sort = true;
    $wp_taxonomies['post_tag']->args = array( 'orderby' => 'term_order' );
}
add_action( 'init', 'do_the_terms_in_order');

then when I register my taxonomy I set:
'hierarchical' => false,
'orderby' => 'term_order'

CREDIT: http://wordpress.kdari.net/2011/07/listing-tags-in-custom-order.html


text:
Q: Community Bulletin only showing Events, not Meta posts Some time recently the Community Bulletin stopped showing Meta posts:
UX:

CogSci:

According to SE discussions and featured meta posts should be in there (and were, last I checked before now) so that it always shows 4 items. It doesn't show up right on Main or Meta for any site I've checked.
The bulletin is just gone on Workplace where there are no events. All of these sites have featured tags and meta discussions so they should be full.

A: We had a short blog outage which has been resolved.  This appears to impact the community bulletin as well.  The cache will clear and display correctly within the hour.


text:
Q: SQL (Custom) Unique Constraint for a set of rows How to create a ( may be custom) unique constraint for a particular no.of rows.
I have table data as below

I want my itemFK column to be Unique for same productionsessionKey value. i.e for all yellow (101) itemFK should be Unique and for all blue (102) itemFK should be unique. Else they can be duplicate.

A: Add a unique constraint on a tupple for those 2 columns
F.e.
ALTER TABLE your_table
  ADD CONSTRAINT UC_Your_Table_ProdSession_Item UNIQUE (productionsessionKey, itemFK);


text:
Q: Is three-stage lead acid battery charging possible with PWM solar charger? I have studied lead acid battery charging methods from the website http://batteryuniversity.com/learn/article/charging_the_lead_acid_battery. In which they mention three stages of charging:

My question:  I already made a PWM solar charger unit using the P-MOSTFET IRF4905, in which I can control the PWM duty cycle and can be reduce the current, but when reducing the current the voltage applied to the battery will also be reduced, then how can I implement these three stage of charging by use of PWM? i.e. constant current mode ok, but how can we apply top charging?

A: You just need to measure both the charging voltage and the charging current. During the first charging phase you adjust the PWM duty cycle so the charger is current limited at its maximum current. That is, you measure both the current and voltage but the duty cycle is adjusted to maintain the desired current. Meanwhile, you monitor the voltage and once the voltage rises to the desired voltage (say 2.4V per cell for lead-acid) you switch to constant-voltage charging. Now you adjust the duty cycle to maintain a constant voltage. Meanwhile, you monitor the current and when the current falls below the level that indicates a full charge you move into the final charging stage. The third stage is also a constant-voltage mode, but at a much lower voltage.

I designed and built a charger that does this. Schematics and source code can be found at my Wordpress pages. It's based on the NXP LPC1114, a Cortex-M0 microcontroller. I didn't use solar panels for the source of power but I don't see why you couldn't reuse most of what I did.


text:
Q: Which services to get multiple outbound Ip address? Im looking for a service that would allow me to NAT HTTP traffic through multiple outbound IP address. I've seen services taht can offer ~100 different public IP addresses, and let users change it every minutes for example. Can you suggest one such provider?

A: Why not just setup 10 Amazon EC2 micro instances running Linux/Squid and use them as a proxy?
To get a decent variant of IP addresses, you would need to terminate them fairly often and even that isn't a guarantee that they'll be different each time, but if you vary the availability zones, for each instance, you should be able to rotate IP addresses fairly well.
The nice thing about Amazon is that the ec2-tools are very robust/scriptable, so if this pilot works well for you, you could partially/fully automate the process using the response code (403 forbidden I'm assuming) as your condition (say by syslog'ing Squid to your "proxy master"), which would then fire off a new EC2 instance, record the IP, and write it to your proxy .PAC file/URL (that would be configured in your browser).
All this is just back-of-the-napkin "architecture" talk here, but I think the core notion of EC2 instance rotation is sound.


text:
Q: restart bash script on exit(1) from php script? I have a php script that works as long as the internet is on. When problems occur, it exits with code 1.
the code in windows looks like this:
:start
php myScript.php
IF %ERRORLEVEL% NEQ 0(
   ECHO "BAD EXECUTION, RESTARTING..."
   GOTO start)

I am looking for the equivalent script for linux?

A: It's about the same with the addition of sleeps in order not to create a fork bomb:
/* edited */
COMMAND="php myScript.php"
SLEEPSEC=10

$COMMAND
RC=$?

while [ $RC -eq 1 ] ; do
    echo "BAD EXECUTION, RESTARTING..."
    sleep $SLEEPSEC
    $COMMAND
    RC=$?
done


text:
Q: How do I get given value is Integer Or String I am trying to find solution of my problem. And my problem is that I am getting a parameter value named "key" and its data-type is Object. Before starting of any kind of use of this key I wanna check first is it Integer or String and any kind of data-type(main aim is to check between Integer & String).
I already try google but i got nothing  useful.
please provide some solution .
Many many thanks in advance.
Example
if(key is Integer){
  //do something here
}else{
  // do something here
}

A: for Integer -
if(key instanceof Integer){
 //Integer
}

And for String -
if(key instanceof String){
 //String
}

Or you may use key.getClass()

A: I use as below
public static void main(String... args) {
    Test test = new Test();
    test.invoke(1);
    test.invoke("something");

}
public void invoke(Object obj) {
    if (obj != null) {
        if (obj.getClass() == Integer.class) {
            System.out.println("It is integer !");
        }
        else if (obj.getClass() == String.class) {
            System.out.println("It is String !");
        }
    }
}

Output

It is integer !
It is String !

A: You can try using instatnceOf operator. It will tell you if the key is of Integer type or not.
if(key instanceOf Integer)
 {
    //key is Integer type
 }


text: Q: Can changing magnetic field make a ferromagnetic material into a paramagnetic material Suppose a ferromagnetic material (iron bar) is placed inside a solenoid that produces a sufficiently high changing magnetic field (due to AC current). In this case, will the iron bar will become paramagnetic or it will remain ferromagnetic? Please help.


text:
Q: Proving (or disproving) that these maps are linear representations I am working in $V = C(\mathbb{R})$, the complex vector space of continuous $\mathbb{C}$-valued functions on $\mathbb{R}$. I have the following series of maps $\rho : \mathbb{R} \rightarrow GL(V)$ defined as:

*

*$\rho(t) : f(x) \mapsto f(x-t)$

*$\rho(t) : f(x) \mapsto f(tx)$

*$\rho(t) : f(x) \mapsto f(e^tx)$

*$\rho(t) : f(x) \mapsto e^t f(x)$
I must determine which of these maps define a linear representation of the additive group $(\mathbb{R}, +)$. From Serre, I am given the following definition to work with: $\rho(st) = \rho(s) \rho(t)$ where $s,t \in G$. So, I just need to determine which of these maps satisfy this definition - which seems like a routine task, but I'm getting stuck in how to proceed. Perhaps I am getting too tangled up in the notation, but I'm having a hard time with what I need to do here.

A: You may be confused by the fact that your definition $\rho(st)=\rho(s)\rho(t)$ uses multiplicative notation and you want to apply it to the additive group $(\mathbb R,+)$. In additive notation, this is $\rho(s+t)=\rho(s)\rho(t)$.
I'll do the first two and leave the other two for you.
$$
\rho(s+t)(f)(x)=f(x-(s+t))\;,\\\rho(t)(f)(x)=f(x-t)\;,\\\rho(s)\rho(t)(f)(x)=f((x-s)-t)\;,
$$
so indeed $\rho(s+t)=\rho(s)\rho(t)$.
$$
\rho(s+t)(f)(x)=f((s+t)x)\;,\\\rho(t)(f)(x)=f(tx)\;,\\\rho(s)\rho(t)(f)(x)=f(t(sx))\;,
$$
and in general $f((s+t)x)\neq f(tsx)$, so this one is not a representation of the additive group. (In fact, it's a representation of the multiplicative group $(\mathbb R^*,\cdot)$.)


text:
Q: Twig incorrect truncated html I save news text in DB as HTML:

Hello, i'm a text!

 More text

When i render text like this
{{ post.body | raw }}

everything goes well, but i need to truncate text to 20-30 symbols for preview on main page.
So, i tried
{{ p.body[:20] ~ '..' }}

and then text looks like

Hello, i'm..

How can a hide than html tags? "|raw" filter also does not working while truncation.
Please help

A: Conveniently, Twig has a built in function for stripping out HTML tags.
The following would output "Hello, i'm a text ..."
{% set some_html = "
Hello, i'm a text!

 More text
" %}
{{ some_html[:20]|striptags ~ ' ...' }}


text:
Q: How should we reduce the number of files generated by nuxt generate? We generate our Jamstack site with nuxt generate and deploy to Cloudflare. Going Full Static. However we have a problem with frequent failures to deploy to Cloudflare. We contacted Cloudflare and were told we had too many deploy files.
So we want to reduce the number of files generated by nuxt generate. How can we configure our settings to reduce the number of files generated? For example, is there a setting that combines some of the generated files into one?
Initially, we tried to reduce the file size and display it more quickly. However, as it is now, deployments fail and information is not updated. We are now willing to sacrifice a little file size and display speed in order to always provide the latest information.
We have not added any special settings. Part of nuxt.config.js is as follows.
export default {
  target: 'static',

  build: {
    html: {
      minify: {
        collapseBooleanAttributes: true,
        decodeEntities: true,
        minifyCSS: false,
        minifyJS: false,
        processConditionalComments: true,
        removeEmptyAttributes: true,
        removeRedundantAttributes: true,
        trimCustomFragments: true,
        useShortDoctype: true,
      },
    },
  },

  generate: {
    subFolders: false,
  },
}

We tried the following settings to no avail.
export default {
   splitChunks: {
      layouts: false,
      pages: false,
      commons: false
   }
}


text:
Q: Read from stdin in C without max buffer length The following code sets a maximum line size read from stdin. I'd rather not hard-code a specific line length, and have the flexibility to handle any buffer length. What are good strategies to allow processing of any size?
If these strategies are much more complex, is there a way to at least guarantee that getline will not overflow? Thanks.
 #include<stdlib.h>
 #include<stdio.h>
 #include<string.h>

 #define P 20

 int main()
 {
   size_t size = 1920;
   char *line;
   // record row; /* structure to store fields */
   char tokens[P][41];
   int p;
   char delims[] = ",";     /* ", |" */
   char *result = NULL;

   line = ( char * ) malloc( size + 1 );

   while( getline(&line, &size, stdin) != -1 )
   {
      /* chomp */
      line[strlen(line)-1] = '\0';

      /* load char array */
      result = strtok( line , delims );
      p = 0;
      while( result != NULL && ( p < P ) )
      {
         strcpy( tokens[p++] , result );
         result = strtok( NULL, delims );
      }

      if (p != P)
      {
         fprintf(stderr,"Wrong number of input fields.\nFormat: ID,x1, ... ,x%d\n",P);
     exit(-1);
      }

      /* load record ( atol, atof etc... , skipped for brevity ) and work with record */

      return 0;
 }

A: You can have getline allocate memory for you (which is the whole point of using the non-standard getline function over the standard fgets function).  From the getline manual page:

If  *lineptr is NULL, then getline() will allocate a buffer for storing
  the line, which should be freed by the user program.  (The value in *n
  is ignored.)
Alternatively, before calling getline(), *lineptr can contain a pointer
  to a malloc-allocated buffer *n bytes in size.  If the buffer is not
  large  enough  to  hold the line, getline() resizes it with realloc,
  updating *lineptr and *n as necessary.

So you can do:
line = NULL;
while (getline(&line, &size, stdin))
{
    // ... Do stuff with `line`...
}
free(line);

(Or leave your code as-is, since getline will resize your allocated buffer for you.)

A: Here's the code I've been using - Fgetstr(FILE*, const char*).  It roughly doubles the buffer size for each realloc, and won't crash on a failed malloc/realloc.  Called like:  char *text = Fgetstr(stdin, "\n"); or whatever.
The library getdelim() function is similar, although mine might be much older.  The manpage on getline and getdelim doesn't detail what happens if the malloc and realloc fail on my system, and only mention a possible error EINVAL (no ENOMEM).  Hence, the behavior in the face of memory exhaustion may be undefined for getline/getdelim.
Also, as starrify points out, many systems don't have getline.
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>

#ifdef TEST
#define DEBUG
#endif

#ifdef DEBUG
#undef DEBUG
#define DEBUG(b) {b}
#else
#define DEBUG(b)
#endif

#ifdef TEST
int main (int argc, char **argv)
{
    char *text = (char*)0;
    char *ends = "\n";

    if(argc > 1) ends = argv[1];

    while(text = Fgetstr(stdin, ends))
    {
        puts(text);
        free(text);
    }

    return 0;
}
#endif

/*  return specifications -
 *
 *  terminators include : ends, \0, and EOF
 *
 *  root    EOF?    text?   ended?  stat    returned value
 *          -       -       -       ...
 *  1       -       -       1       return  ""
 *          -       1       -       ...
 *  2       -       1       1       return  "text"
 *  3       1       -       -       return  -null-      EOF-*accepted*
 *  4       1       -       1       return  ""          EOF-postponed
 *  5       1       1       -       return  "text"      EOF-postponed/fake-end
 *  6       1       1       1       return  "text"      EOF-postponed/true-end
 *
 *  on ENOMEM, return -null-
 *
 */

static char *Fgetstr_R(FILE *ifp, const char *ends, unsigned int offset)
{
    char *s = (char*)0;                     /* the crucial string to return */
    unsigned int bufmax = offset;           /* as large as so far */
    unsigned int bufidx = 0;                /* index within buffer */
    char buffer[bufmax + 1];                /* on-stack allocation required */
    int ended = 0;                          /* end character seen ? */
    int eof = 0;                            /* e-o-f seen ? */

    DEBUG(fprintf(stderr, "(%d", offset););

    while(bufidx <= bufmax)     /* pre-recurse - attempt to fill buffer */
    {
        int c = getc(ifp);

        if( (ended = ( !c || (ends && strchr(ends,c)))) || (eof = (EOF==c)) )
            break;

        buffer[bufidx++] = (char)c;
    }

    /* note - the buffer *must* at least have room for the terminal \0 */

    if(ended || (eof && offset))                    /* root 1,2,4,6 5 */
    {
        unsigned int offset_max = offset + bufidx;
        DEBUG(fprintf(stderr, " malloc %d", offset_max + 1););
        if(s = (char*)malloc((offset_max + 1) * sizeof(char)))
            s[offset_max] = '\0';
        else
            s = (char*)0, perror("Fgetstr_R - malloc");
    }
    else
    {
        if(eof && !offset)  /* && !ended */     /* root 3 */
            s = (char*)0;
        else
            s = Fgetstr_R(ifp, ends, offset + bufidx);  /* recurse */
    }

    /* post-recurse */

    if(s)
        strncpy(&s[offset], &buffer[0], bufidx);  /* cnv. idx to count */

    DEBUG(fprintf(stderr, ")", offset););
    return s;
}

char *Fgetstr (FILE *ifp, const char *ends)
{
    register char *s = (char*)0;
    DEBUG(fprintf(stderr, "Fgetstr "););
    s = Fgetstr_R(ifp, ends, 0);
    DEBUG(fprintf(stderr, ".\n"););
    return s;
}


text:
Q: Adding custom type in Umbraco 8 I've been testing Umbraco 8 for a while, and i'm stuck on an attempt to add a custom workflow type to umbraco forms.
I tried the simple example from https://our.umbraco.com/documentation/Add-ons/UmbracoForms/Developer/Extending/Adding-a-Workflowtype, but my issue starts at the guide about registering this new type so it shows up in umbrack (https://our.umbraco.com/documentation/Add-ons/UmbracoForms/Developer/Extending/Adding-a-Type)
Part of the doc doesn't match the visual code project i'm working on:
Finally compile the project and copy the .dll to your website /bin folder or copy the .cs file to the app_code directory.

There's no app_code directory, however i found that if i put the file in /App_data/Models it'll try to compile it when i launch the umbraco project, but this fails as it can't find any of the using directives e.g. Umbraco.BusinessLogic or Umbraco.Forms.Core.
I haven't been able to find anyone with a similar problem. I tried creating a new Umbraco project using visual studio, installing Umbraco via Nuget, but the folder structure still doesn't match any documentation, keeping me at a loss for how to continue.
Does anyone know what i'm missing, and why my folder structure doesn't match any of the assumptions in our.umbraco.com guides and docs ?

A: I've added a few workflows on a recent project in Umbraco 8. I created a new folder in the website root called UmbracoForms and within that created the custom workflow classes.
This class then inherits from WorkflowType and is automatically picked up by Umbraco.
e.g. public class SaveUsersContactDetailsToSession : WorkflowType {}
Just be mindful of setting the ID, Name, and Description. All Umbraco namespaces will be available and you'll be able to use Dependency Injection.


text:
Q: This is code of image and video of instagram dowloading by link.. after downloading 4 ,5 photos or videos this code not work This is code of image and video of instagram  dowloading by link.. after downloading 4 ,5 photos or videos this code not work .and getting error findata class ..
public class   FindData {
private Context context;
private GetDat getData;
String netsubType;
NetworkInfo activeNetworkInfo1;
Boolean s;

public FindData(Context context, GetDat getData) {
    this.context = context;
    this.getData = getData;
}

public void data(String stringData) {

    ArrayList<String> arrayList = new ArrayList<>();

    if (stringData.matches("https://www.instagram.com/(.*)")) {
        String[] data = stringData.split(Pattern.quote("?"));
        String string = data[0];

//            if (isNetworklow()) {
//
//                Toast.makeText(context, "network low", Toast.LENGTH_SHORT).show();
//            }
        if (isNetworkAvailable()) {

            if (Method.isDownload) {
                AsyncHttpClient client = new AsyncHttpClient();
                client.get(string + "?__a=1", null, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                        String res = new String(responseBody);

                        try {
                            JSONObject jsonObject = new JSONObject(res);
                            String link = null;
                            JSONObject objectGraphql = jsonObject.getJSONObject("graphql");
                            JSONObject objectMedia = objectGraphql.getJSONObject("shortcode_media");
                            boolean isVideo = objectMedia.getBoolean("is_video");
                            if (isVideo) {
                                link = objectMedia.getString("video_url");
                            } else {
                                link = objectMedia.getString("display_url");
                            }
                            arrayList.add(link);

                            try {
                                JSONObject objectSidecar = objectMedia.getJSONObject("edge_sidecar_to_children");
                                JSONArray jsonArray = objectSidecar.getJSONArray("edges");
                                arrayList.clear();
                                String edgeSidecar = null;

                                for (int i = 0; i < jsonArray.length(); i++) {

                                    JSONObject object = jsonArray.getJSONObject(i);
                                    JSONObject node = object.getJSONObject("node");
                                    boolean is_video_group = node.getBoolean("is_video");
                                    if (is_video_group) {
                                        edgeSidecar = node.getString("video_url");
                                    } else {
                                        edgeSidecar = node.getString("display_url");
                                    }
                                    arrayList.add(edgeSidecar);
                                }
                            } catch (Exception e) {
                                Log.e("error_show", e.toString());
                            }
                            getData.getData(arrayList, "", true);
                            Toast.makeText(context, "success", Toast.LENGTH_SHORT).show();

                        } catch (JSONException e) {

                            Log.e("........POOR NETWORK ........",  e.toString());
                            getData.getData(arrayList, context.getResources().getString(R.string.not_support), false);
                            Toast.makeText(context, " poor network", Toast.LENGTH_SHORT).show();

                        }
                    }
                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        Log.e("...........on failure +Tag............",error.toString());
                        Toast.makeText(context, "try again error", Toast.LENGTH_SHORT).show();
                        getData.getData(arrayList, context.getResources().getString(R.string.wrong), false);
                    }
                });
            } else {
                getData.getData(arrayList,"ff ", false);
            }
        } else {

             getData.getData(arrayList, context.getResources().getString(R.string.internet_connection), false);
           Toast.makeText(context, "no network", Toast.LENGTH_SHORT).show();
        }
    } else {
        getData.getData(arrayList, "invalid link copy again", false);
    }
}
//network check
public boolean isNetworkAvailable() {
    Log.e("TAG", "=============onFailure===============");

    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    assert connectivityManager != null;
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    //netsubType.equals( TelephonyManager.NETWORK_TYPE_EDGE)||netsubType.equals( TelephonyManager.NETWORK_TYPE_1xRTT ));
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

}
public class DownloadService extends Service {
private int position = 0;
private RemoteViews rv;
private OkHttpClient client;
private final int CHANEL_ID = 105;
private NotificationCompat.Builder builder;
private NotificationManager notificationManager;
private static final String CANCEL_TAG = "c_tag";
private final String NOTIFICATION_CHANNEL_ID = "download_service";
public static final String ACTION_START = "com.download.action.START";
public static final String ACTION_STOP = "com.download.action.STOP";

private final Handler mHandler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(@NotNull Message message) {
        int progress = Integer.parseInt(message.obj.toString());
        switch (message.what) {
            case 1:
                rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
                rv.setProgressBar(R.id.progress, 100, progress, false);
                rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(" + progress + " %)");
                notificationManager.notify(CHANEL_ID, builder.build());
                break;
            case 2:
                if (Constant.downloadArray.size() - 1 != position) {
                    position++;
                    init(Constant.downloadArray.get(position));
                } else {
                 //   Toast.makeText(getApplicationContext(), getResources().getString(R.string.downloading), Toast.LENGTH_SHORT).show();
                    position = 0;
                    stopForeground(false);
                    stopSelf();
                    Events.AdapterNotify adapterNotify = new Events.AdapterNotify("");
                    GlobalBus.getBus().post(adapterNotify);
                    Method.isDownload = true;
                }
                break;
        }
        return false;
    }
});

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();

    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    builder.setChannelId(NOTIFICATION_CHANNEL_ID);
    builder.setSmallIcon(R.drawable.ic_baseline_notes);
    builder.setTicker(getResources().getString(R.string.downloading));
    builder.setWhen(System.currentTimeMillis());
    builder.setOnlyAlertOnce(true);

    rv = new RemoteViews(getPackageName(), R.layout.my_custom_notification);
    rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
    rv.setProgressBar(R.id.progress, 100, 0, false);
    rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(0%)");

    Intent intentClose = new Intent(this, DownloadService.class);
    intentClose.setAction(ACTION_STOP);
    PendingIntent closeIntent = PendingIntent.getService(this, 0, intentClose, 0);
    rv.setOnClickPendingIntent(R.id.nf_close, closeIntent);

    builder.setCustomContentView(rv);
    NotificationChannel mChannel;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getResources().getString(R.string.app_name);// The user-visible name of the channel.
        mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
        notificationManager.createNotificationChannel(mChannel);
    }
    startForeground(CHANEL_ID, builder.build());
}

@Override
public void onDestroy() {
    super.onDestroy();
    stopForeground(false);
    stopSelf();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    try {
        if (intent.getAction() != null && intent.getAction().equals(ACTION_START)) {
            Method.isDownload = false;
            init(Constant.downloadArray.get(position));
        }
        if (intent.getAction() != null && intent.getAction().equals(ACTION_STOP)) {
            if (client != null) {
                for (Call call : client.dispatcher().runningCalls()) {
                    if (call.request().tag().equals(CANCEL_TAG))
                        call.cancel();
                }
            }
            Method.isDownload = true;
            stopForeground(false);
            stopSelf();
        }
    } catch (Exception e) {
        Log.d("error", e.toString());
        stopForeground(false);
        stopSelf();
    }
    return START_STICKY;
}

public void init(final String downloadUrl) {

    final String iconsStoragePath = Environment.getExternalStorageDirectory() + getResources().getString(R.string.download_folder_path);

    File file = new File(iconsStoragePath);
    if (!file.exists()) {
        file.mkdir();
    }

    //Using Date class
    Date date = new Date();
    //Pattern for showing milliseconds in the time "SSS"
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    String stringDate = sdf.format(date);

    //Using Calendar class
    Calendar cal = Calendar.getInstance();
    String s = sdf.format(cal.getTime());

    final String string;

    if (downloadUrl.contains(".jpg")) {
        string = "Image-" + s + ".jpg";
    } else {
        string = "Image-" + s + ".mp4";
    }

    Log.d("file_name", string);

    new Thread(new Runnable() {
        @Override
        public void run() {

            client = new OkHttpClient();
            Request.Builder builder = new Request.Builder()
                    .url(downloadUrl)
                    .addHeader("Accept-Encoding", "identity")
                    .get()
                    .tag(CANCEL_TAG);

            Call call = client.newCall(builder.build());

            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e("TAG", "=============onFailure222===============");
                    e.printStackTrace();
                    Log.d("error_downloading", e.toString());
                    // Method.isDownload = true;
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    Log.e("TAG", "=============onResponse===============");
                    Log.e("TAG", "request headers:" + response.request().headers());
                    Log.e("TAG", "response headers:" + response.headers());
                    assert response.body() != null;
                    ResponseBody responseBody = ProgressHelper.withProgress(response.body(), new ProgressUIListener() {

                        //if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
                        @Override
                        public void onUIProgressStart(long totalBytes) {
                            super.onUIProgressStart(totalBytes);
                            Log.e("TAG", "onUIProgressStart:" + totalBytes);
                        }

                        @Override
                        public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
                            Log.e("TAG", "=============start===============");
                            Log.e("TAG", "numBytes:" + numBytes);
                            Log.e("TAG", "totalBytes:" + totalBytes);
                            Log.e("TAG", "percent:" + percent);
                            Log.e("TAG", "speed:" + speed);
                            Log.e("TAG", "============= end ===============");
                            Message msg = mHandler.obtainMessage();
                            msg.what = 1;
                            msg.obj = (int) (100 * percent) + "";
                            mHandler.sendMessage(msg);
                        }

                        //if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
                        @Override
                        public void onUIProgressFinish() {
                            super.onUIProgressFinish();
                            Log.e("TAG", "onUIProgressFinish:");
                            Message msg = mHandler.obtainMessage();
                            msg.what = 2;
                            msg.obj = 0 + "";
                            mHandler.sendMessage(msg);
                            if (downloadUrl.contains(".jpg")) {
                                if (Constant.imageArray != null) {
                                    Constant.imageArray.add(0, new File(iconsStoragePath + "/" + string));
                                }
                            } else {
                                if (Constant.videoArray != null) {
                                    Constant.videoArray.add(0, new File(iconsStoragePath + "/" + string));
                                }
                            }
                            try {
                                MediaScannerConnection.scanFile(getApplicationContext(), new String[]{iconsStoragePath + "/" + string},
                                        null,
                                        (path, uri) -> {

                                        });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });

                    try {

                        BufferedSource source = responseBody.source();
                        File outFile = new File(iconsStoragePath + "/" + string);
                        BufferedSink sink = Okio.buffer(Okio.sink(outFile));
                        source.readAll(sink);
                        sink.flush();
                        source.close();

                    } catch (Exception e) {
                        Log.d("show_data", e.toString());
                    }

                }
            });
        }
    }).start();
}

}
**error in FindData class2022-03-11 08:32:20.701 1631-1631/?
E/downloaderinst: Unknown bits set in runtime_flags: 0x8000
2022-03-11 08:59:02.413 1631-1631/com.pinit.downloaderinst3 E/TAG: =============onFailure===============
2022-03-11 08:59:02.539 1631-1631/com.pinit.downloaderinst3 E/DecorView: mWindow.mActivityCurrentConfig is null
2022-03-11 08:59:03.999 1631-1631/com.pinit.downloaderinst3 E/........POOR NETWORK ........: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
2022-03-11 08:59:04.007 1631-1631/com.pinit.downloaderinst3 E/InputMethodManager: prepareNavigationBarInfo() rootView is null
2022-03-11 08:59:04.123 1631-1631/com.pinit.downloaderinst3 E/ViewRootImpl: sendUserActionEvent() mView returned.


text:
Q: Programmatically create attribute of type select and options I am having following category structure.
Category 1
Category 2
Category 3
    - Category 3.1
        - Category 3.1.1
        - Category 3.1.2
        - Category 3.1.3
        - Category 3.1.4
        - Category 3.1.5
    - Category 3.2
        - Category 3.2.1
        - Category 3.2.2
        - Category 3.2.3
        - Category 3.2.4
        - Category 3.2.5
    - Category 3.3
        - Category 3.3.1
        - Category 3.3.2
        - Category 3.3.3
        - Category 3.3.4
        - Category 3.3.5
Category 4

In my layered navigation I need this as follows:
Category 3.1 (attribute)
    - Category 3.1.1 (options)
    - Category 3.1.2 (options)
    - Category 3.1.3 (options)
    - Category 3.1.4 (options)
    - Category 3.1.5 (options)

Category 3.2 (attribute)
    - Category 3.2.1 (options)
    - Category 3.2.2 (options)
    - Category 3.2.3 (options)
    - Category 3.2.4 (options)
    - Category 3.2.5 (options)

I need to make this dynamically and programmatically.
Please let me know how to achieve this.

A: If you are trying to create a Layered Navigation then all you need to do is make the category an Anchor by setting is Anchor to "Yes" in the category page then make sure that the Attributes for your product are able to be used in a Layered Navigation.


text:
Q: Center div in div margin auto doesn't work Hi I have the following code:
CSS
.center{
    width: 100%;
    margin: 0 auto;
    border: 1px solid red;
}

.nav{
    background: #606060;
    width: 90%;
}

HTML
<!DOCTYPE html>

        <meta charset="utf-8">
        <link rel="stylesheet" href="css/stylesheet.css" />
        <title></title>

Ahoj

I also tried .center without width: I searched throught themes here but I didn't find a solution. .nav div still stays on the left.
Thank you for your help.

A: Give margin:0 auto to .nav class not to .center class.

.center{
  width: 100%;
  border: 1px solid red;
}

.nav{
  background: #606060;
  width: 90%;
  margin:0 auto;
}
<!DOCTYPE html>

        <meta charset="utf-8">
        <link rel="stylesheet" href="css/stylesheet.css" />
        <title></title>

Ahoj

A: You don't need to define margin: 0 auto; when width is 100%. It is required if you want to position division of fixed width to the center of parent div.

.center{
    width: 100%;
    border: 1px solid red;
}

.nav{
    background: #606060;
    width: 90%;
    margin: 0 auto;
}

Ahoj

A: Add this CSS to your .nav class
.nav {
 .
 .
 margin: 0 auto;
 text-align: center
}

A: block level elements can't be centerd because its always fit in 100% width of its container so I suggested to use inline-block instead.

.center{
    width: 100%;
    margin: 0 auto;
    border: 1px solid red;
    text-align:center;
}

.nav{
    background: #606060;
    width: 90%;
    display:inline-block;
}

Ahoj

A: .nav {
background: #606060;
width: 90%;
display: block;
margin: 0 auto;

}


text:
Q: Integrate indefinite function :$\int {dx\over\sqrt x \sqrt {1-x}}$ How do you integrate indefinite $\int {dx\over \sqrt x \sqrt {1-x}}$ using substitution? I know that the answer is $2*\arcsin(\sqrt x)+c$ by substituting $u=\sqrt x$ and $2du={dx\over\sqrt x}$ but I don't understand how plugging it in will make the function $\int {2du\over\sqrt {1-u^2}}$

A: After appropriately substituting, you do get an integral of the form $$\int \frac {2\,du}{\sqrt{1 - u^2}}$$
After all, you've correctly computed $ u = \sqrt x \implies \color{blue}{\bf u^2 = x}\;\;\text{and}\;\;\color{red}{\bf 2 \,du = \frac{dx}{\sqrt x}}$. Now, just substitute, piece for piece (match up the colors, if needed), into $$\int \dfrac{\color{red}{\bf dx}}{\color{red}{\bf \sqrt x}\cdot \sqrt{1 - \color{blue}{\bf x}}}$$
This is the form that applies here: Now you can use the substitution $u = \sin \theta$.
Recall that when $a^2 - u^2$ occurs in an integrand, you can use the substitution $u = a\sin \theta$.

A: Let $x=\sin^2 t$. Then $dx=2\sin t\cos t\,dt$ and $\sqrt{x}\sqrt{1-x}=\sin t\cos t$. Thus
$$\int \frac{1}{\sqrt{x}\sqrt{1-x}}\,dx=\int 2\,dt=2t+C.$$
Thus our integral is $2\arcsin(\sqrt{x})+C$.
Remark: The "normal" thing is to complete the square. However, $\sqrt{x(1-x)}$ is in many ways just as nice as $\sqrt{1-u^2}$, and one can take advantage of the special form to bypass the standard completing the square.


text:
Q: How to get variables data from php to javascript? I have following two files and want to get data from php and recieve it in javascript file.
1) PHP file:
<?php
    $i;
    for($i = 0; $i < 1000; $i++) {
        echo $i;
    }
?>

2) JavaScript file:
<script>
    var j = -1;
    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            j = this.responseText;
        }
    };

    xhttp.open("GET", "www.mywebsite.com/php_file.php", true);

    while(j < 999) {
        xhttp.send();
        document.getElementById("demo").innerHTML = j;
    }
</script>

Now, the problem is, when run my java script it return me the final value of 'i', but i want to retrieve every value of 'i' while it is in for-loop, like from 0 to 999.. but it return only when php file fully executes it self

A: Change your php file as follows : you are outputting j outside of loop
<?php
  $i;
  $j = 0;
 for($i = 0; $i < 1000; $i++){
     $j = $i * $i;
     echo $j;
 } ?>


text:
Q: Getting values from HTML5 Canvas to Javascript I am working on a small project in google app engine. Using html5 canvas i need to show a canvas to the user on which user can draw nodes and connecting edges. I need to find the shortest path with dijkstras algorithm.
My problem is, i want to get the values from the canvas on clicking the submit button. The values are the co ordinates of nodes and corresponding edges. It will be a json data structure that could store lists. Major issue is on getting the values from canvas to javascript to store on the json.
My body part contains

<canvas id="canvas" height="500" width="1000" style="border:1px solid #c3c3c3;"></canvas>

<input type="button" value="Submit" onclick="submit()">

What to write on the submit function???

A: This would be a breeze if you were doing it in SVG. Unfortunately canvas is an immediate drawing surface, meaning when you draw something the canvas keeps no memory of anything that was drawn.
During your drawing phase you are going to have to keep track of all the necessary information (nodes and edges) yourself as you draw. Otherwise the information is simply not there.


text:
Q: Applying translation to custom WordPress plugin I'm trying to apply a translation to my cusom plugin. I've alredy created brau-ru_RU.mo and brau-ru_RU.po files. My translation domain is 'brau'.
What I've tried is to put files in wp-content/languages/plugins/ and execute this code in my plugin.
$domain = 'brau';
$mo_file = WP_LANG_DIR.'/plugins/'.$domain.'-'.get_locale(). '.mo';

var_dump(load_textdomain( $domain, $mo_file ));
var_dump(load_plugin_textdomain( $domain ));
var_dump(__('This is the test', 'brau'));

Result is:
bool(true) bool(true) string(16) "This is the test"

I also got this code in my config
define ('WPLANG', 'ru_RU');

The text shoud be translated from English to Russian, but it's not. What am I missing?
This is a link to test version of the plugin: https://github.com/Brezgalov/brezgalovauth

A: If you want to add language files to your plugin then you can create a folder called languages inside your plugin folder  and in the plugin main file you can define like this
// Localiztion with language files
function custom_langs_i18n() {
    load_plugin_textdomain( 'textdomain', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
add_action( 'init', 'custom_langs_i18n' );

Please remember to use textdomain where you are using string.


text:
Q: Divide SQL data in different tables I want to split users' data in different tables so that there isn't an huge one containing all data...
The problem is that in tables different from the main one I can't recognize who each data belongs to.
Should I store the same user id in every table during the signup? Doesn't it create unnecessary duplicates?
EDIT:
example
table:
| id | user | email | phone number| password | followers | following | likes | posts |

becomes
table 1:
| id | user | email | phone number| password |

table 2:
| id | followers num | following num | likes num | posts num |

A: This looks like a "XY problem".
You want to "not have a huge table". But why is it that you have this requirement?
Probably it's because some responses in some scenarios are slower than you expect.
Rather than split tables every which way, which as Gordon Linoff mentioned is a SQL antipattern and liable to leave you more in the lurch than before, you should monitor your system and measure the performances of the various queries you use, weighing them by frequency. That is, if query #1 is done one hundred thousand times per period and takes 0.2 seconds, that's 20,000 seconds you should chalk up to query #1. Query #2 which takes fifty times longer - ten full seconds - but is only run one hundred times will only accrue one twentieth of the total time of the first.
(Since long delays are noticeable by the end users, some use a variation of this formula in which you multiply the instances of one query for the square - or higher powers - of its duration in milliseconds. This way, slower queries are brought more attention to).
Be it what may, once you know which queries you should optimize first, then you can start optimizing your schema.
The first thing to check are indexes. And maybe normalization. Those cover a good two thirds of the "low performing" cases I have met so far.
Then there's segmentation. Not in your case maybe, but you might have a table of transactions or such where you're usually only interested in the current solar or fiscal year. Adding a column with that information will make the table larger, but selecting only those records that at minimum match a condition on the year will make most queries run much faster. This is supported at a lower level also (see "Sharding").
Then there are careless JOINs and sub-SELECTs. Usually they start small and fast, so no one bothers to check indexes, normalization or conditions on those. After a couple of years, the inner SELECT is gathering in one million records, and the outer JOIN discards nine hundred and ninety-nine thousand of them. Translate the discarding condition inside the subselect and see the query take off.
Then you can check whether some information is really rarely accessed (for example, I have one DB where each user has a bunch of financial information, but this is only needed in maybe 0.1% of requests. So in that case yes, I have split that information in a secondary table, also gaining the possibility of supporting users with multiple bank accounts enrolled in the system. That was not why I did it, mind you).
In all this, also take into account time and money. Doing the analysis, running the modifications and checking them out, plus any downtime, is going to cost something and possibly even increase maintenance costs. Maybe - just maybe - throwing less money than that into a faster disk or more RAM or more or faster CPUs might achieve the same improvements without any need to alter either the schema or your code base.

A: I believe I understand your question and if you are wondering, you can use a foreign key. When you have a list of users, make sure that each user has a specific id.
Later, when you insert data about a user you can insert the users id via a session variable or a get request. (insert into different table)
Then, when you need to pull data for that specific user from that different table/s, you can just select from table where id = session[id] or get[id]
does that help?
answer: use foreign key to identify users data using gets and sessions
don't worry about duplicates if you are removing those values form the main table.

A: I think you want to use a LEFT JOIN
SELECT t1.[user], t2.[posts]
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 ON t1.id= t2.id

EDIT: Here is a link to documentation that explains different types of JOINS

A: One table would probably have an AUTO_INCREMENT for the PRIMARY KEY; the other table would have the identical PK, but it would not be AUTO_INCREMENT.  JOINing the tables will put the tables "back together" for querying.
There is rarely a good reason to "vertically partition" a table.  One rare case is to split out the "like_count" or "view_count".  This way the main table would not be bothered by the incessant UPDATEing of the counters.  In some extreme cases, this may help performance.


text:
Q: I2C transmission gate transistors I have been looking at a design that uses DMN31D5UDJ-7s for gating I2C signals that are connected to 4.7 kΩ pull-ups to VIO = 1.8 V.

I was wondering if I could replace these transistors with BSS138PSs since I already have them in the design, and I don't want many different transistors for assembly.
My only concern about the BSS138PS compared to the DMN31D5UDJ-7 is that it has a higher VGS(th):
BSS138PS:
VGS(th): min: 0.9 V, max: 1.5 V
DMN31D5UDJ-7:
VGS(th): min: 0.4 V, max: 1 V
Can I make this replacement?
This I2C is between a KB8010 re-timer and a CYPD6227 USB PD controller.
It looks like we have a one side level shifter from 3.3 V to 1.8 V from the HOST_TWI signals (PD controller side from the left) towards the re-timer (right side) which means the only scenario I can think of is that the PD controller is the master and the re-timer is the slave, and it can't be the opposite, since we don't have a bi-directional level shifter, am I right?
From the CYPD6227 datasheet,  I2C_SCL_SCB3/P3.2 and I2C_SDA_SCB3/P3.1 to which HOST_TWI.SDA/SCL are connected, are GPIOs that can have an internal PU, and their input voltage level is: min = -0.5 V, max = VDDIO + 0.5 V where VDDIO is 3.3 V.

A: This circuit requires that the transistors switch with a gate-to-source voltage of VIO = 1.8 V.
The BSS138PS guarantees switching only for 5 V (this is the test condition for RDS(on)). And the lowest gate voltage for which typical (not even guaranteed) values are shown in figures 6/8 is 2 V. And figure 9 shows that you should not try anything below or near 2 V:

The DMN31D5UDJ is guaranteed to work at 1.8 V or lower (you can also use any other MOSFET with such a specification):


text:
Q: Carousel view or Custom Render Tabs? I have question - what is rightn and correct way to implement this design in Xamarin (Xamarin forms)
Design principle
I see here 2 ways for implementations:
First way - is TabbedPage. And right Custom Render (For IOS - move tabs to top, and for android - Icons)
Second way - is CarouselView - but not sure is good.
Additional requirements is - Animation switch between content of "tabs"
Switch by finger slide is NICE TO HAVE option.

A: There is no right and wrong way. There is only what meets your requirements and what is easiest to implement and maintain.
Your linked picture clearly shows a TabbedPage. However your additional requirements would make this an issue. iOS shows the tabs at the bottom. I'm not sure if it is easy to move them to the top. It would require a custom renderer if it is even possible. I think iOS allows you to swipe between tabbed pages but I'm not sure that Android does.
It would probably be easier to implement a CarouselView with buttons above. That way you will be able to place your buttons where you like, allow you to swipe between them and have animation. This meets all your requirements.


text:
Q: Newey West standard errors in regression model without constant I'm estimating $y_i= \beta_1 \times x_{1i} + \varepsilon_i$ on a time series on $y$ and $x$, so in presence of heteroskedasticity and autocorrelation. My model does not include any intercepts. Are Newey West standard errors calculated on such model appropriate (in other words, the NW correction requires a full model with intercept)? I am using R sandwich and lmtest packages.

A: Here are two screenshots (if that is not OK I hope moderators will let me know) of the papers by Newey and West (Review of Economic Studies 1994) and Andrews (Econometrica 1991), which are follow up papers to the more high-level Newey/West paper:

Andrews:

As you can see, having constant plays no role. What matters is that the coefficient estimates for which you want autocorrelation-robust standard errors are themselves ($\sqrt{T}$-)consistently estimated, so, more or less, that they are computed from a correctly specified model.
Now, if your model is such that it indeed does not need a constant (which may happen), that should be fine.


text: Q: Deeplinking to youtube content on Samsung TV (Tizen) Could you please provide us with instructions for deep linking on youtube from other application on Samsung TV? For example, we want to launch youtube and open a specific channel on youtube from our application. Is this possible? And how we can do it? (We've already managed to open youtube but only homepage).


text:
Q: Sql query- Get results between two different date columns with its exact days match I have the following 2 columns in 'deals' table.
- subscribed_date
- expired_date
I want the SQL query that to filter the records with 2 columns difference as follows

(expired_date - subscribed_date) == 7 days

For eg:
id  |  subscribed_date      | expired_date
1   |  2015-07-04 04:13:29  | 2015-09-03 04:13:29
2   |  2015-06-03 04:13:29  | 2015-06-10 04:13:29
3   |  2015-01-05 04:13:29  | 2015-02-08 04:13:29

In the above example, the result should be id=2 because its difference is 7 days.
Is it possible through SQL query without iterations?
Thanks in advance for your help!

A: The easiest way would be to use timestampdiff function
mysql> select timestampdiff(day,'2015-06-03 04:13:29','2015-06-10 04:13:29') as d ;
+------+
| d    |
+------+
|    7 |
+------+

So the query becomes
select * from deals
where timestampdiff(day,subscribed_date,expired_date) = 7

A: Why not just SELECT * FROM deals WHERE DATEDIFF(expired_date, subscribed_date) = 7?
Further info here.


text:
Q: Calculating unbiased survival rate of Titanic passengers I want to calculate unbiased ratio of the survival chance of the passengers according to the classes(1st,2nd,3rd class)- so passengers from which class had higher chance to survive.
So let's say in the data we have number of passengers  survived and the total number of passengers(per class). So how should i calculate the ratio to be unbiased? I was told that dividing the number of survivors by total passengers in that class was biased since there were much less 1st class passengers so they could easily fit into the rescue boats.
So i was told to calculate the total number of survivors and assume that this is the amount of available seats in the rescue boats. Then i divide the number of survivors for each class by this new total number. Is it the correct way of doing that? Is there a better way?
The data is here if needed:
https://www.kaggle.com/c/titanic

A:
Biased, since they could easily fit into the rescue boats.

Biased in terms of them surviving, yes. However, it will not cause any bias in terms of your estimates. It may cause lower confidence due to smaller sample size, however. This may have been what they were referring to.
Think about it logically. If we removed the circumstances that gave the higher class a greater chance to survive, we'd end up with every single class having approximately the same survival rate. If we want useful statistics, we need to factor in the advantages of the higher class. This method of using total survivors as available seats assumes that all passengers had equal access to all rescue boats. I would assume that higher class passengers would have greater access to safety due to purchasing premium tickets, and therefore we shouldn't combine these samples.
EDIT: In reference to:

Divide the number of survivors for each class by [total number of survivors].

This result will simply just tell you what proportions of survivors were which class (e.g 10% higher, 40% middle, 50% lower). Since we're calculating survival chance per class, using these values is meaningless, since the percentage of survivors that were [x class] is heavily dependent on the number of passengers that were in [x class].
For example, if 50 out of 50 higher class passengers survived, but there were 10,000 people on board and 5,000 were rescued, higher class would make up 1% of all survivors despite having a 100% survival rate.


text:
Q: Sticky navbar - Bootstrap I want to have a sticky navbar on my website, which should stick to the top of the page after the user scroll over the header.
I have this code: http://jsfiddle.net/df8tb/1849/
Here is the main code:
.goToTop {
  position: fixed;
  top: 0;
  height: 70px;
  z-index: 1;
}

$(document).ready(function(){
  $(window).bind('scroll', function() {
    var navHeight = 100; // custom nav height
    ($(window).scrollTop() > navHeight) ? $('nav').addClass('goToTop') : $('nav').removeClass('goToTop');
  });
});

But it doesn't really work.
My question is how can I fix the behavior that when the user scroll there is a 'jumping' (The content goes up)?

A: instead of sticking the nav bar when you have scrolled the "navBar height", do it when you have scrolled the "header" height (or header height PLUS its padding + margins)

A: See here:
http://jsfiddle.net/augburto/df8tb/1851/
There are two main things you need to fix.
One thing is your navHeight isn't exactly where the navigation is. What you want is the location of your nav in respect to the viewport top. You can do that by doing.
var navTop = $('#nav').offset().top;

I changed the naming convention because its more accurate to say its the navTop rather than the height.
Your other issue where the content jumps is because when you set the navigation to position: fixed, it takes it out of the document flow. One way of getting around this is to calculate the actual height of the nav and then set the position to offset it by that much when the navigation gets stickied.
var navHeight = $('#nav').height();
$('#content').css('top', navHeight);

A: Your styling should be like this.
.goToTop {
    position: fixed;
    top: 0;
    height: 70px;
    width:100%;
    z-index: 2000;
}
Why I changed z-index to 2000 is because bootstrap assigns z-index of 1000, 1020 etc for certain elements. So if you want this on top of all that, your z-index should be 2000.
And your script should be like this
$(document).ready(function(){
     $(window).scroll(function(){
         var navHeight = 100;
         if($(this).scrollTop() > navHeight ){
             $('nav').addClass('goToTop');
         }
         else{
             $('nav').removeClass('goToTop');
         }
     });
});

A: Because you changed the nav to fixed, it no longer has collision (layout, whatever). So we need to compensate for the extra space. We can do this by padding the top of your content.
.addSpace {
    padding-top : 60px;
}

Now all we have to do is update your JavaScript to put this class onto the things you want to pad:
$(document).ready(function () {
    $(window).bind('scroll', function () {
        var navHeight = 100; // custom nav height
        if ($(window).scrollTop() > navHeight) {
            $('nav').addClass('goToTop');
            $('#content').addClass('addSpace');
        } else {
            $('nav').removeClass('goToTop');
            $('#content').removeClass('addSpace');
        }
    });
});

and it works perfectly! (I added a #content id to the content element, but you can use any selector you can think of).