text:
Q: fixing my hide default and show/hide when it is mouse hover My show/hide mouseover is working good and my only problem is by defult when i refresh the page it shows my span class that i want it to by default hide. How can i edit my code to make it definitely hide it by default. I already added in my display:none in my css and when i tried it, this code hide definitely and disable my javascript in show/hide mouseover. By the way i am in wordpress environment and i was looping it because it is a post.
So all i want is to make it default: hide using this code below
Here is my code something like this:
<?php $count = 0; ?>
<?php
if( $projectsBlog->have_posts() ) : ?>

    <?php while ( $projectsBlog->have_posts() ) : $projectsBlog->the_post(); ?>

        <div class="col-xs-4 col-box1" onMouseOver="show_title<?php echo $count ?>()" onMouseOut="hide_title<?php echo $count ?>()">

        <span class="effect" id="hoverli<?php echo $count ?>"><?php the_title( sprintf('', esc_url(get_permalink())),''); ?>

        <?php the_post_thumbnail(); ?>

    <?php if($count==2) :
    echo '
';
    echo '
';
    endif; ?>

    <?php $count++; endwhile; ?>

    <?php endif; ?>

here is my javascript i made it one by one because it was looping :
function show_title0(){
  document.getElementById('hoverli0').style.visibility="visible";
}
function hide_title0(){
  document.getElementById('hoverli0').style.visibility="hidden";
}

function show_title1(){
  document.getElementById('hoverli1').style.visibility="visible";
}
function hide_title1(){
  document.getElementById('hoverli1').style.visibility="hidden";
}

function show_title2(){
  document.getElementById('hoverli2').style.visibility="visible";
}
function hide_title2(){
  document.getElementById('hoverli2').style.visibility="hidden";
}

function show_title3(){
  document.getElementById('hoverli3').style.visibility="visible";
}
function hide_title3(){
  document.getElementById('hoverli3').style.visibility="hidden";
}

function show_title4(){
  document.getElementById('hoverli4').style.visibility="visible";
}
function hide_title4(){
  document.getElementById('hoverli4').style.visibility="hidden";
}

function show_title5(){
  document.getElementById('hoverli5').style.visibility="visible";
}
function hide_title5(){
  document.getElementById('hoverli5').style.visibility="hidden";
}

here is my css with display attribute where i tried only one li class but the default hidden doest display all:
#hoverli0 {
    display:none;
}

A: Instead of creating seperate functions for each elements create two generalize functions as below. And to hide and show you should have to use display:none and display:block as below.
function show_title(id){
    document.getElementById('id').style.display="block";
}

function hide_title(id){
    document.getElementById('id').style.display="none";
}

And pass the id of element in the php code as below.
<div class="col-xs-4 col-box1" onMouseOver="show_title('hoverli<?php echo $count ?>')" onMouseOut="hide_title('hoverli<?php echo $count ?>')">

In this way you can achieve by only two functions no need of redundant functions.

A: For this you don't need javascript. I think the CSS :hover Selector is here the right choice.
You can hide the spanby default with display: none; or with visibility: hidden;(with visibility: hidden; the element will still take up the same space as before. The element will be hidden, but still affect the layout).
Example:

ul.image li span.effect {
  display: none;
}

ul.image li:hover span.effect {
  display: inline;
}

  span content
  -image-

  span content
  -image-

  span content
  -image-

  span content
  -image-

  span content
  -image-

  span content
  -image-

A: IMO, use toggleClass in a single query.
If you would like to do it using jQuery only, you can compress your code and do it in a simple way by using following query.
//Hide all the span by default
$('li.top-featured-image > span').addClass('hide');
//Use mouse enter and leave events in a query
$(document).on('mouseenter mouseleave', '.top-featured-image',function(){
   $(this).find('span').toggleClass('show hide');
});

$('li.top-featured-image > span').addClass('hide');
$(document).on('mouseenter mouseleave', '.top-featured-image',function(){
  $(this).find('span').toggleClass('show hide');
});
.show
{
  display: block;
}
.hide
{
  display: none;
}

  span content1
  -image-1

  span content2
  -image-2

  span content3
  -image-3

  span content4
  -image-4

  span content5
  -image-5

  span content6
  -image-6


text:
Q: Clear displayed data with default frame in Progress OpenEdge I'm trying to find a way to clear displayed data from the screen before return to the calling procedure.
For example:
FIND FIRST table NO-LOCK NO-ERROR.
DISPLAY table WITH 1 COLUMN.
/* data gets displayed */
PAUSE.

Now how do I clear it before returning to the calling procedure?

A: To make it easy for yourself your should actually ALWAYS name your frames. Otherwise you will run into problems sooner or later. I will let examples below reflect both named and unnamed frames.
You clear it:
FIND FIRST tablename NO-LOCK NO-ERROR.
DISPLAY tablename WITH 1 COLUMN.
PAUSE.
CLEAR.
PAUSE.

You can also pinpoint a frame to clear:
FIND FIRST tablename NO-LOCK NO-ERROR.
DISPLAY tablename WITH FRAME x1 1 COLUMN.
PAUSE.
CLEAR FRAME x1.
PAUSE.

Or if clearing is not really what you want but rather removing (or actually hiding) the entire frame:
FIND FIRST tablename NO-LOCK NO-ERROR.
DISPLAY tablename WITH FRAME x1 1 COLUMN.
PAUSE.
HIDE FRAME x1.
PAUSE.

You can also hide without pinpointing a frame:
FIND FIRST tablename NO-LOCK NO-ERROR.
DISPLAY tablename.
PAUSE.
HIDE.
PAUSE.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JSF Generating pages from Database objects I am working on a JSF application and have two pages: on one page I have a datatable with list of items from the database (call them page1.xhtml & page2.xhtml).
When I click on any of these items second page opens, where I can see more relevant information about that item.
Currently, when I open an item, in the browser URL all I can see is the localhost:8080/myapp/page2.xhtml. But I need to generate a link, which will point to my item from the database.
How can I achieve this?
Now page1 loads an array of items from database, and preserves this array in a ManagedBean. Afterwards, page2 accesses a particular product from this array, receiving all the needed information.


text:
Q: Tracking events with prometheus and grafana There's an article "Tracking Every Release" which tells about displaying a vertical line on graphs for every code deployment. They are using Graphite. I would like to do something similar with Prometheus 2.2 and Grafana 5.1. More specifically I want to get an "application start" event displayed on a graph.
Grafana annotations seem to be the appropriate mechanism for this but I can't figure out what type of prometheus metric to use and how to query it.

A: You can get the same result purely from Prometheus metrics, no need to push anything into Grafana:

If you wanted to track all restarts your search expression could be something like:
changes(start_time_seconds{job="foo",env="prod"} > 0

Or something like this if you only wanted to track version changes (and you had some sort of info metric that provided the version):
alertmanager_build_info unless max_over_time(alertmanager_build_info[1d] offset 5m)

The latter expression should only produce an output for 5 minutes whenever a new alertmanager_build_info metric appears (i.e. one with different labels such as version). You can further tweak it to only produce an output when version changes, e.g. by aggregating away all other labels.

A: The simplest way to do this is via the same basic approach as in the article, by having your deployment tool tell Grafana when it performs a deployment.
Grafan has a built-in system for storing annotations, which are displayed on graphs as vertical lines and can have text associated with them. It would be as simple as creating an API key in your Grafana instance and adding a curl call to your deploy script:
curl -H "Authorization: Bearer <apikey>" http://grafana:3000/api/annotations -H "Content-Type: application/json" -d '{"text":"version 1.2.3 deployed","tags":["deploy","production"]}'

For more info on the available options check the documentation:
http://docs.grafana.org/http_api/annotations/
Once you have your deployments being added as annotations, you can display those on your dashboard by going to the annotations tab in the dashboard settings and adding a new annotation source:

Then the annotations will be shown on the panels in your dashboard:

A: A note here as technology has evolved. We get deployment job state information in Prometheus metrics format scraped directly from the community edition of Hashicorp's Nomad and we view this information in Grafana.
In your case, you would just add an additional query to an existing panel to overlay job start events, which is equivalent to a new deployment for us. There are a lot of related metrics "out of the box," such as for a change in job version that can be considered as well. The main point is no additional work is required besides adding a query in Grafana.


text:
Q: How to use non-blocking HTTP requests in Mulesoft 4 Custom Connector I'm trying to build a Mulesoft custom connector which makes HTTP requests to a third-party system, and I'd like these HTTP requests to be made in a non-blocking manner such that execution can continue without waiting on the HTTP response to be returned.
There is an example of this in the Mulesoft documentation here which shows this example code:
public void request(String url, @Connection HttpClient client, @Content String body,
    CompletionCallback<InputStream, HttpAttributes> callback ) {
 client.send(url, body, new HttpResponseCallback() {
   void onResponse(HttpResponse response) {
     callback.success(Result.<InputStream, HttpAttributes>builder()
                          .output(response.getBody())
                          .attributes(toAttributes(response))
                          .build());
   }

   void onError(Exception e) {
     callback.error(e);
   }
 });
}

It also states that non-blocking behaviour can be provided

by an HttpClient that supports asynchronous responses

Mulesoft's custom connector documentation states

The HttpClient is capable of using non-blocking I/O to make the requests.

but I don't understand how!
The example code above calls a method send(String, String, HttpResponseCallback) from the HttpClient interface. However, the HttpClient interface, as documented in  Mulesoft's API javadoc does not have such a method.
I see that the HttpClient interface does have sendAsync(HttpRequest request) methods, but I'm failing to understand how that could be used with the example code.
I understand that Mulesoft's HttpClient is implemented using Project Grizzly's HTTP client, and that supports non-blocking requests, so I feel this is possible to do, I just don't understand how...
Thanks for any tips!

A: Hi was trying to achieve the same thing, with the same non-blocking-operations documentation, but I wasn't able, So I try based on the
Slack connector, it has a lot of examples there, and they use other code to achieve async calls ChannelOperations with CompletionCallback
However, this did not work for me, I think maybe I have to make another workaround on the server-side to achieve async calls.
Anyway, In the end, I use CompletableFuture to run the request in other thread,
the request is in sync way but is performed Async in the CompletableFuture.runAsync

public void request(String url, @Connection HttpClient client, @Content String body) {

HttpResponse response = null;
HttpEntity entity = new ByteArrayHttpEntity(body.toString().getBytes());
HttpRequest httpRequest = HttpRequest.builder().uri(url).addHeader("Content-Type", "application/json")
                .method("POST").entity(entity).build();
CompletableFuture.runAsync(() -> {
 try {
            client.start();
            response = client.send(httpRequest, 30000, true, null);
        } catch (IOException | TimeoutException e) {
                LOGGER.error(response.toString());
        }
    LOGGER.info(response.toString());
        client.stop();

    LOGGER.info("Finish");
});
}

There is a Mule connector similar to DMI where the calls are made async


text:
Q: How do I import only the number and separate between 'n' and 'p'? I have a file like this:
 primario =  980 pione n, en=   0.10229 GeV
 primario =  980 pione n, en=   0.10506 GeV
 primario =  980 pione p, en=   0.65135 GeV
 primario =  980 pione p, en=   0.44895 GeV
 primario =  980 pione p, en=   3.15166 GeV
 primario =  980 pione n, en=   1.03541 GeV
 primario =  989 pione n, en=   1.14979 GeV
 primario =  990 pione p, en=   0.72569 GeV
 primario =  992 pione p, en=   5.80965 GeV
 primario =  993 pione p, en=   0.24496 GeV
 primario =  993 pione n, en=   0.39453 GeV
 primario =  993 pione n, en=   1.07869 GeV
 primario =  997 pione p, en=   0.11673 GeV

I have to import only the number after en and separate the result into two lists of p and n. Using something like "FieldSeparators" -> {"=", ",", "primario", "en", "pione", "=", "GeV"} I should be able to import only the numbers and the strings p and n.
Now my problem is: I am left with a list like this
{{262, "p", 2.58277}, {272, "p", 1.17827}, {275, "p", 2.35279}, {281, "p", 0.17932}, {281, "p", 0.74644}, {292, "p", 1.44102}, {292, "p",0.41372}, {292, "p", 5.4164}, {297, "p", 0.38317}, {297, "p", 0.50133}, {297, "n", 0.91764}, {307, "p", 0.08304}, {307, "p", 0.16932}, {307, "n", 2.11982}, {307, "p", 2.78014}}

how do I separate the list into two lists containing only the last numbers? This lists, then, should be separated into a p list and a n list? The final lists should be something like this:
p list: {2.58277,1.17827,...} n list: {0.91764,...}

A: The easiest way would be to use GroupBy:
a = {{262, "p", 2.58277}, {272, "p", 1.17827}, {275, "p",
2.35279}, {281, "p", 0.17932}, {281, "p", 0.74644}, {292, "p",
1.44102}, {292, "p", 0.41372}, {292, "p", 5.4164}, {297, "p",
0.38317}, {297, "p", 0.50133}, {297, "n", 0.91764}, {307, "p",
0.08304}, {307, "p", 0.16932}, {307, "n", 2.11982}, {307, "p",
2.78014}};
assoc = GroupBy[a, Extract[2] -> Last]

This groups the lists based on the second element of those lists, and the values it groups together is the last element of these lists.
Then the list p and the list n can be found using:
assoc["p"]
assoc["n"]

Alternatively, it can be done using Select:
plist = Select[a,EqualTo["p"]@*Extract[2]][[All,3]]
nlist = Select[a,EqualTo["n"]@*Extract[2]][[All,3]]

A: Here are two simple options:
Using Cases
a = {{262, "p", 2.58277}, {272, "p", 1.17827}, {275, "p",
    2.35279}, {281, "p", 0.17932}, {281, "p", 0.74644}, {292, "p",
    1.44102}, {292, "p", 0.41372}, {292, "p", 5.4164}, {297, "p",
    0.38317}, {297, "p", 0.50133}, {297, "n", 0.91764}, {307, "p",
    0.08304}, {307, "p", 0.16932}, {307, "n", 2.11982}, {307, "p",
    2.78014}};

Cases[a, {_, "p", i_} :> i]

{2.58277, 1.17827, 2.35279, 0.17932, 0.74644, 1.44102, 0.41372,
  5.4164, 0.38317, 0.50133, 0.08304, 0.16932, 2.78014}

Cases[a, {_, "n", i_} :> i]

{0.91764, 2.11982}

Or using Select
Select[a, #[[2]] == "p" &][[All, 3]]
Select[a, #[[2]] == "n" &][[All, 3]]

A: One way is to use Sow and Reap.  For example:
a = {{262, "p", 2.58277}, {272, "p", 1.17827}, {275, "p",
    2.35279}, {281, "p", 0.17932}, {281, "p", 0.74644}, {292, "p",
    1.44102}, {292, "p", 0.41372}, {292, "p", 5.4164}, {297, "p",
    0.38317}, {297, "p", 0.50133}, {297, "n", 0.91764}, {307, "p",
    0.08304}, {307, "p", 0.16932}, {307, "n", 2.11982}, {307, "p",
    2.78014}};

res = Reap[Sow[#1[[3]], #1[[2]]] & /@ a, _, Rule][[2]]

/* {"p" -> {2.58277, 1.17827, 2.35279, 0.17932, 0.74644, 1.44102,
   0.41372, 5.4164, 0.38317, 0.50133, 0.08304, 0.16932, 2.78014},
 "n" -> {0.91764, 2.11982}} */

And then use ReplaceAll to give the individual lists, e.g.
"n" /. res

/* {0.91764, 2.11982} */


text:
Q: Error detected on pass 2 at Winmips64 I have some assembly code which is giving me the error:

Errors detetected on pass 2

It highlights the halt command at the end in red. If I press "ok", the program opens but when I try to run it, I think it behaves differently from what I expected (more cycles).
Code:
.data
.text
main:
ld $s2, 0($s1)
ld $s1, 40($s6)
dsub $s6, $s1, $s2
dadd $s6, $s2, $s2
or $s3, $s6, $zero
sd $s6, 50($s1)
halt


text:
Q: SDL Mixer No available audio device This is what I have and I keep getting no available audio devices when trying to run the program.
By the way I'm on ubuntu 11.04.
#include <iostream>
#include <stdio.h>
#include <smpeg.h>
#include <SDL.h>
#include <SDL_mixer.h>
int main(){
        std::cout << "TEST" << std::endl;

        int sdlret = SDL_Init(SDL_INIT_AUDIO);
        if(sdlret == -1){
                std::cout << "SDL value: " << sdlret << std::endl;
                std::cout << SDL_GetError();
        }
        int mixret = Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024);
        std::cout << "Mix value: " << mixret << std::endl;
        std::cout << Mix_GetError() << std::endl;
        return 0;
}


text:
Q: Where can I find the UUIDs for TI SensorTag services? I have been working through the book Getting Started with Bluetooth Low Energy and have fished around on the TI site.  TI must have taken down the Android sample that I have seen referenced, I have found the attribute table, but would like to see a document with the UUIDs that I get back from uiAvailableServices callback.  I am using the Bluetooth Application Accelerator.

A: All UUIDs for Gatt Services and Characteristics are listed in this document:
http://processors.wiki.ti.com/images/a/a8/BLE_SensorTag_GATT_Server.pdf

A: For a detailed list of TI SensorTag provided services and their UUIDs, please take a look at Gatt Services in this document.
In your app, you should be able to match the UUIDs you got from the device with the one's in the above spec.


text:
Q: Fixed header stays on top of wrapper I'm trying to build a Wordpress site with a fixed header. So far so good. The header is ok, but the wrapper is the problem now. When I give the wrapper a margin-top: 100px the header wil go down 100px and header will stay above the wrapper (See image).
http://imgur.com/x1ssQhM
 . The transparent white is the header and it stays above the wrapper.
Code link:
http://jsfiddle.net/b1u83a7z/enter code here
 .Here you can see that the header is on top of the wrapper the wrapper should have a margin-top of 100px.

A: Add header styles the top property to define at what position should be placed:
#top {
    top:0;   <-- Added
    width:100%;
    height:60px;
    margin:0 auto;
    background-color:rgba(255, 255, 255, 0.9);
    position:fixed;
    z-index:500;
    border-bottom:1px solid #DEDEDE;
}

Updated JSFiddle


text:
Q: C# image to URL throws an error 403 When I put the following code in my program I get the 403 error
        var req = WebRequest.Create("http://floralegacy.s3.amazonaws.com/files2/449/44977-371x400.jpeg");

        using (var resp = req.GetResponse())
        using (var stream = resp.GetResponseStream())
        {
            pictureBox1.Image = Bitmap.FromStream(stream);
        }

anyone have an idea for a solution?

A: 403 indicates access denied which suggests that the bucket permissions might not allow non-authenticated access.
Try changing the bucket permissions:
http://docs.aws.amazon.com/AmazonS3/latest/UG/EditingBucketPermissions.html


text:
Q: Django: Processing form data in views.py I have this form for users to enter their zip code and the radius they would like to search:
class DistanceFilter(forms.ModelForm):

    distance = forms.IntegerField()

    class Meta:
        model = Event
        fields = ['zipcode']

here is the template(filter.html):
{% extends 'ItsAllSport/base.html' %}

{% block content %}
{{ block.super }} {# includes previous content in block #}

      <form action="" method="get">
          {{ filter.form.as_p }}
          {{ distance }}

Date: <input type="text" id="id_myDate">

          <input type="submit" />
      </form>

                {% for obj in filter.qs %}

{{ obj.title }}

                          More Info

                {% endfor %}

{% endblock content %}

views.py:
def event_list(request):
    advanced = EventFilter(request.GET, queryset=Event.objects.all())
    distance = DistanceFilter(request.POST or None)
    results = []

    if request.method == 'POST':
        form = DistanceFilter(request.POST)
        if form.is_valid():
            distance = form.cleaned_data['distance']
            zipcode = form.cleaned_data['zipcode']

            for obj in Event.objects.all():
                number = check_distance(zipcode, obj.latitude, obj.longitude)
                if number <= distance:
                    results.append(obj.title)
    new = Event.objects.filter(title__in=results)

    context = {
        'filter': advanced,
        'distance': distance,
        'new': new,
        'categories':EventType.objects.all(),
        'event': Event.objects.all(),
        'login_form': LoginForm(),
        'signup_form': SignupForm(),
        }
    return render(request, 'ItsAllSport/filter.html', context)

Here is the check_distance function that is used on line 8:
import requests
from geopy.distance import vincenty

#takes in the zip code and finds the latitude and longitude
def find_coordinates(zipcode):
    url = "https://gist.githubusercontent.com/erichurst/7882666/raw/5bdc46db47d9515269ab12ed6fb2850377fd869e/US%2520Zip%2520Codes%2520from%25202013%2520Government%2520Data"
    r = requests.get(url, stream=True)

    for line in r.iter_lines():
        if line[0:5] == str(zipcode):
            coords = {
                'lat': line[6:15],
                'lon': line[17:]
            }
            break

    return coords

#takes in the zip code the user entered and compares it to each Event in the database
def check_distance(user_zipcode, event_lat, event_long):
    coords = find_coordinates(user_zipcode)
    user_lat = coords['lat']
    user_long = coords['lon']

    user = (user_lat, user_long)
    event = (event_lat, event_long)

    return vincenty(user, event).miles

I think that the issue is in the views.py file. I have tested check_distance() and it works fine, but when I try to use the filter on the website it reloads the page and nothing happens. I do not get any errors so I assume that is not using the form data at all.


text:
Q: How can I add a caption to an R plotly scatterplot? I'm trying to add a caption to a basic plot_ly to include more information about the scatter plot I have.
I've had a look at this thread:
plotly adding a source or caption to a chart but the caption here is inline with the x-axis title.
I can't seem to get the caption underneath the plot and x-axis title.

A: Starting with the post you link to, you need to set the margin in the plot_ly layout and then change the x, and y in the annotations
library(plotly)
plot_ly(x=~hp, y=~mpg, data=mtcars, type="scatter", mode="marker") %>%
  layout(margin = list(b=160), ##bottom margin in pixels
         annotations =
           list(x = 0.5, y = -0.75, #position of text adjust as needed
                text = "Source: data I found somewhere.",
                showarrow = F, xref='paper', yref='paper',
                xanchor='right', yanchor='auto', xshift=0, yshift=0,
                font=list(size=15, color="red"))
  )


text:
Q: Relation between symmetries and asymptotics for Painlevé equations The first Painlevé equation
$$P_I:y''=6y^2-x $$
has the symmetries $$x \mapsto \omega x \\y \mapsto \omega^3 y$$
for any fifth root of unity $\omega$. At the same time, the near-infinity asymptotics of $P_I$ involve the five rays $$\Gamma_k= \left\{x:\arg x= \frac{2 \pi i k}{5} \right\}, \quad k=0,1,2,3,4.$$
Looking at the second Painlevé equation
$$P_{II}: y''=2y^3+xy+\alpha $$
the scaling symmetries are
$$x \mapsto \omega x \\ y \mapsto \omega^2 x $$
for any third root of unity $\omega$. However, the near-infinity asymptotics of $P_{II}$ actually involve six rays
$$\Gamma_k= \left\{x:\arg x= \frac{2 \pi i k}{6} \right\}, \quad k=0,1,2,3,4,5.$$
My question is: is there a direct relationship between the discrete symmetries of the second Painlevé equation, and its near-infinity asymptotics, as in the case of the first Painlevé equation? If so, how come I only found three symmetries, which should correspond to the rays
$$\left\{x: \arg x=\frac{2 \pi i k}{3} \right\}, \quad k=0,1,2 $$
Thanks!

A: Yes, there are relationships, they depend on the weights chosen to compactify the system at infinity. First, write the equation as the companion autonomous vector field in $\mathbb C^3$  $$X(x,y_1,y_2)=\partial_x+y_2\partial_{y_1}-6z_1^2\partial_{z_2}$$
  For $P_1$, you use the Boutroux compactification given by the chart transition mapping $(t,u_1,u_2)\mapsto(x,y_1,y_2)$ with $$\begin{cases}{x=t^{-4/5}}\\{y_1=(u_1+\frac{i}{\sqrt6})t^{-2/5}}\\{y_2=u_2t^{-3/5}}\end{cases}$$The new vector field, after division by $-\frac{5}{4t^{1/5}}$, writes $$W(t,u_1,u_2)=t^2\partial_t+(\cdots)\partial_{u_1}+(\cdots)\partial_{u_2}$$which has an irregular singularity  at $(0,0,0)$ with Poincaré rank-$1$.
The lines $\Gamma_k$ are the preimages in the starting chart of the Stokes line of the previous vector field.  There are five of them because of the order-$5$ ramification in the $x$-variable.
In the case of $P_2$ after compactification and reduction, you obtain two irregular singularities at infinity (Poincaré rank-$1$), each one bringing a Stokes line in. Hence the $6=2\times3$ lines in the original chart. (I need to check that precisely, though, I'll update the answer).


text:
Q: how I change the frame data into time series? I have a daily rainfall data for 36 years. I want to analyze the time series, but my data is still in the form of frame data, how I change the frame data into time series. My data is a variable, how to unify the year number with the date and month, so the data is only in one column

A: You could use a time series package for that, such as fpp i.e. install.packages('fpp'). Since you don't give an example code, I can't really help you properly with it but it's quite easy.
ts(your_data, start =, frequency = ) At start = you put the year or month where you'd start and at frequency = you'd put e.g. 36 since you talk about 36 years.
You might want to check out https://robjhyndman.com/. He has an online (free) book available that walks you through the use of his package as well as providing useful information with respect to time series analysis.
Hope this helps.


text:
Q: Request.host in initializer Rails 4 I am using the Apartment gem for a multi-tenant app and I'm using the "host_hash elevator" to switch the tenant based on the subdomain and host of the request.
This is done with the below code (from their documentation):
#initalizers/apartment.rb

# application.rb
module MyApplication
  class Application < Rails::Application
    config.middleware.use 'Apartment::Elevators::HostHash', {'example.com' => 'example_tenant'}
  end
end

Where it says 'example.com' => 'example_tenant' I need to send a hash with the request.host to find the company in my Company model where the value of the request_host database field matches request.host. If that makes sense?
if I hard code in an example so it's like the below code I can get it to work, but I don't know how to dynamically do it based on the request:
#initalizers/apartment.rb

# application.rb
module MyApplication
  class Application < Rails::Application
    config.middleware.use 'Apartment::Elevators::HostHash', {'test.lvh.me:3000' => 'test.lvh.me:3000'}
  end
end

The above code works because that's the domain that I'm currently on and it matches a field and apartment tenant that I had set up.
However, since this in an initializer when I put 'request.host' there I get an error: undefined local variable/method 'request'
If I use 'Rack::Request.new(env).host' I get undefined local variable/method 'env'
How can I get request.host in an an initializer to solve this problem?

A: thanks to some help I got on the apartment gem's github issues I was able to figure out a solution.
#company.rb model
def self.full_hosts_hash
    Company.all.inject(Hash.new) do |hash, company|
      hash[company.request_host] = company.request_host
      hash
    end
end

#apartment.rb initializer
require 'apartment/elevators/host_hash'
Rails.application.config.middleware.use 'Apartment::Elevators::HostHash', Company.full_hosts_hash


text:
Q: PHP will not write *some* of the string to mysql Basically writing a string to an entry in a database.
The string is concatenated from $firsthalf and $secondhalf. $secondhalf is being pulled from a file-upload form
var_dump() repeatedly says both variables are working just fine, before and after the mysql statement. Yet it only writes the $firsthalf part of the concatenated string. I would assume at some point $secondhalf is just null, but according to var_dump(), it isn't.
Here is the code.
<?php
$firsthalf="0000";
$secondhalf=($_FILES['file']['name']);
var_dump($secondhalf); //success!
$TheFileName = $firsthalf.$secondhalf;
var_dump($TheFileName); //success!

/* Write to db */
$table = "category_images";
mysql_connect($dbhost,$dbuser,$dbpassword) or die("Unable to connect to database");
@mysql_select_db($dbname) or die("Unable to select
database $dbname");
$sqlquery = "INSERT INTO $table
VALUES('$category_id','$TheFileName')";
$results = mysql_query($sqlquery);
mysql_close($link);
/* End write to database */

//Database reads the category number and the $firsthalf.
//Magically, the $secondhalf goes disappears!

var_dump($TheFileName); //success, it's still good…wtf?

?>

<form id="Upload" action="./" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="240000">
    <input id="file" type="file" name="file">
    <input id="submit" type="submit" name="submit" value="Upload me!">
</form>

A: Does the file name contain any special characters ?
Replace your 2nd line with :
$secondhalf=mysql_real_escape_string($_FILES['file']['name']);
This would make sure your filename is properly formatted for the query
Also as Dagon pointed out: Make sure you have the right type of field in the DB and a good length.


text:
Q: CSS Transition making a image move up and down on hover http://imgur.com/bXU8I
I have this image and know i need to use css transition to make the vinyl move down when scrolled over? How would you go about doing this?

A: Apply position:relative to the "vinyl" element, then on its hover state, set top:#px.
For example:
#vinyl {
 position: relative;
 /* transition properties here */
}

#vinyl:hover {
 top: 5px;
}

A: Well, the simplest way only involves one element with two backgrounds. The cover is the one on top and the other one is the vinyl itself.
On hover, you simply change the background-position of the second item.
DEMO
HTML is just:

and the CSS is:
.vinyl {
    width: 109px;
    height: 162px;
    margin: 135px auto;
    background: url(http://img842.imageshack.us/img842/7524/albumm.jpg)
            no-repeat 0 100%,
        radial-gradient(circle, transparent 3%, navy 4%, navy 5%, #4774a2 5%,
                #4774a2 8%, navy 8%, navy 9%, #4774a2 10%, #4774A2 20%,
                black 21%, #1c1c1c, black 69%, transparent 70%)
            no-repeat 50% 0%;
    background-size: 109px 109px;
    transition: .65s;
}
.vinyl:hover {
    background-position: 0 100%, 50% 95%;
}

If you want the transition to happen only on hover on the vinyl itself (no transition on hover on the cover), then you'll need to use two elements.
DEMO - I've made .vinyl a child of .cover, gave it positioning and set its z-index to -1 (so that it would go under the cover).
HTML is now:

and the CSS is:
.cover {
    width: 111px;
    height: 111px;
    margin: 135px auto;
    background: url(http://img842.imageshack.us/img842/7524/albumm.jpg);
}
.vinyl {
    position: relative;
    z-index: -1;
    top: -49%; left: 1.5%;
    width: 109px;
    height: 109px;
    border-radius: 50%;
    background: radial-gradient(transparent 3%, navy 4%, navy 5%, #4774a2 5%,
                #4774a2 8%, navy 8%, navy 9%, #4774a2 10%, #4774A2 20%,
                black 21%, #1c1c1c, black 69%, transparent 70%) no-repeat 50% 0%;
    background-size: 109px 109px;
    transition: .65s;
}
.vinyl:hover { top: -3%; }


text:
Q: fill an array of n with random numbers from 0 to 10 i need to write a program that will load a natural number n (n<20). It will then fill an array of n with random numbers from 0 to 10.
It will write out the elements of the array on the screen.
Next, it will load a natural number x.
It will check and write out on the screen how many times the number x occurs in the array.
int n;
int array[n]={0};
int values[10];

cin >> n;

for(int i = 0; i < n; i++) {
    values[i] = i;
int left = 10;
for(int i = 0; i < 10; i++)
{
    int n = rand() % left;
    array[i] = values[n];
    left--;
    values[n] = values[left];
    cout << array[i] << endl;
}

}
```

A: Your code doesn't look like what I'd expect from current C++.
This is not unsurprising since most code you find online, in books or C++ courses mostly show code with raw loops and "C" style arrays.
In any case array[n] is NOT standard C++ (in standard C++ n should be a constant), standard C++ doesn't know about variable length arrays. For that there is std::vector.
Another thing to learn early is never to trust your users input, and always check it.
For most things that are needed frequently the standard library header<algorithm> has someting for you like counting.
And instead of index based for loops, have a look at range based for.
Or use algorithms to visit each element in your collection.
#include <algorithm>
#include <random>
#include <vector>
#include <iostream>
#include <format>

int main()
{
    std::mt19937 generator(std::random_device{}());
    std::uniform_int_distribution<int> distribution(1, 10);

    std::size_t number_of_numbers;

    do
    {
        std::cout << "Enter a number between 1-20 : ";
        std::cin >> number_of_numbers;
    } while ((number_of_numbers < 1) || (number_of_numbers > 20));

    std::vector<int> values(number_of_numbers);
    std::generate(values.begin(), values.end(), [&]
    {
        return distribution(generator);
    });

    for (const auto value : values)
    {
        std::cout << value << " ";
    }
    std::cout << "\n";

    int expected_value;

    do
    {
        std::cout << "Enter a number between 1-10 to count : ";
        std::cin >> expected_value;
    } while ((expected_value < 1) || (expected_value > 10));

    auto count = std::count(values.begin(), values.end(), expected_value);
    std::cout << std::format("That number occurs {} times\n", count);

    return 0;
}


text:
Q: System identification, machine learning and time series I have recently become a bit familiar with the machine learning techniques, and examples of problems where they are ought to be applied. For example, we can try deriving models for the time series or train our machines to predict their dynamics. For example, in reinforcement learning we are trying to develop a good controller for an unknown system while learning from this system.
It seems that system identification tries to approach a similar problem: at least in most of the cases I heard of one assumes that a system in question (e.g. wind power generator) is a linear dynamic system with some stochastic input (wind in this case) and the task is to estimate the transfer function - e.g. in discrete time the coefficients and the depth of the ARMA model.
Since these two fields have such similar methods and problems, I would expect them to be very well connected, however it seems that two communities are rather separated. Is that true? In such case, what are the major differences in their approaches? A related question was asked on TCS, but have not received much attention there (unsurprisingly as it's not that close to theoretical compute science).

A: There is an increasing amount of cross-over between the two, particularly in control theory (nonlinear MPC, which involves system identification to obtain the plant model). I am aware of both neural networks and SVMs being used in such applications, but probably other methods have seen the light of day too.


text:
Q: Calculate total price on flutter with mysql hey guys i need some help i could not calculate total price at checkout procces i am getting data from my mysql server. i already tried many things but i could not solve that provem. Is there anybody can help me?
the returnTotalAmount function is wrapped by BottomBar widget it is just UI therefore i did not share it.
AND THIS IS THE THE CODE OF WIDGET  WHICH IS I WRAPPED
          home: new Scaffold(
    appBar: new AppBar(title: const Text('MySQL Images Text')),
    body: new Center(
      //FutureBuilder is a widget that builds itself based on the latest snapshot
      // of interaction with a Future.
      child: new FutureBuilder<List<Employee>>(
        future: Services.getEmployees(),
        //we pass a BuildContext and an AsyncSnapshot object which is an
        //Immutable representation of the most recent interaction with
        //an asynchronous computation.
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            List<Employee> _employee = snapshot.data;
            Services.getEmployees();
            return  Scaffold(
              body: SafeArea(
                child: CustomListView(_employee),
              ),
              bottomNavigationBar: BottomBar(_employee),
            );
          } else if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }

String returnTotalAmount(List<Employee> _employee) {
double totalAmount = 0.0;

for (int i = 0; i < _employee.length; i++) {
  totalAmount = totalAmount + _employee[i].price * _employee[i].quantity;
}
return totalAmount.toRadixString(2);
}

       Container totalAmount(List<Employee> _employee) {
        return Container(
        margin: EdgeInsets.only(right: 10),
        padding: EdgeInsets.all(25),
        child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
        Text(
         " Total:",
         style: TextStyle(fontSize: 25, fontWeight: FontWeight.w300),
        ),
        Text(
        "\$${returnTotalAmount(_employee)}",
         style: TextStyle(fontWeight: FontWeight.w700, fontSize: 28),
        ),
      ],
    ),
   );
  }

this is my checkout page i should calculate the price

this is my Employee Page

  class Employee{
  String id;
   String firstName;
  String price;
  String path;
  String quantity;

   Employee({this.id, this.firstName,this.price,this.path,this.quantity});

  factory Employee.fromjson(Map<String, dynamic> json){
   return Employee(
    id: json['id'] as String,
    firstName: json['first_name'] as String,
    price: json['price'] as String,
    path: json['path'] as String,
    quantity: json['quantity'] as String,
    );
    }}

and  this is my api code to getting data from database
    static Future<List<Employee>> getEmployees() async {
    try {
    var map = Map<String, dynamic>();
    map['action'] = _GET_ALL_ACTION;
    final response = await http.post(ROOT, body: map);
    print('getEmployees Response: ${response.body}');
    if (200 == response.statusCode) {
     List<Employee> list = parseResponse(response.body);
     return list;
    } else {
      return List<Employee>();
    }
  }  catch (e) {
   return List<Employee>(); // return an empty list on exception/error
  }
 }

A: String returnTotalAmount(List _employee) {
    double totalAmount = 0.0;
for (int i = 0; i < _employee.length; i++) {
  totalAmount = totalAmount + (double.parse(_employee[i].price)*double.parse(_employee[i].quantity));
}
return totalAmount.toString();

}


text:
Q: upnp, c++ and boost asio I use miniupnpc with my wrapper. When my friend run my app, the app create upnp.

But, he still do not receive messages from my computer. What I do wrong ?
Source client:
upnp::upnp_wrapper upnp{};
upnp.redirect(upnp::internal_port{ 41052 },
              upnp::external_port{ 41052 },
              upnp::eProtocol::UDP, "Description");

io_service service;
ip::udp::socket socket{ service };
socket.open(ip::udp::v4());
socket.bind(ip::udp::endpoint{ ip::udp::v4(), 41052 });

ip::udp::endpoint server_ep{ ip::address::from_string("100.71.188.14"s), 9999u };

std::cout << "open: " << socket.local_endpoint().address().to_string() << ':' << socket.local_endpoint().port() << '\n';

cout << "send request\n";
socket.send_to(buffer("open: " + socket.local_endpoint().address().to_string() + ':' + std::to_string(socket.local_endpoint().port()) + '\n'), server_ep);
cout << "request sent\n\n";

array<char, 60> buff = {};
cout << "wait answer\n";
auto answer_length = socket.receive(buffer(buff));
cout << "answer recived: ";
cout.write(buff.data(), answer_length);

cout << "\nsend goodd\n";
socket.send_to(buffer("GOOOOD"s), server_ep);

cout << "\n\nEND";
cin.get();

and server test source:
using namespace std;
using namespace literals;
using namespace boost::asio;

io_service service;
ip::udp::socket socket{ service };
socket.open(ip::udp::v4());
socket.bind(ip::udp::endpoint{ ip::udp::v4(), 9999u });
ip::udp::endpoint client_ep;

array<char, 100> buff = {};
cout << "start recive\n";
auto recived_length = socket.receive_from(buffer(buff), client_ep);
cout << "message recived from: " + client_ep.address().to_string() + ':' + to_string(client_ep.port()) + "\n-> ";
std::cout.write(buff.data(), recived_length);

cout << "\n\nsend answer\n";
socket.send_to(buffer("ANSWER"s), client_ep);
cout << "answer sent\n";

cout << "start good\n";
 recived_length = socket.receive_from(buffer(buff), client_ep);
std::cout.write(buff.data(), recived_length);

cout << "\nEND";
cin.get();

What I do wrong with upnp and boost asio? how correctly using upnp opened internal and external port?

A: I think it was because of firewall. Probably turn server is the solution


text:
Q: Include jQuery in intern test How can I test custom JavaScript app (including jQuery as a dependency)? I have tried jQuery as Node package with no success...
Do I need to define it somehow in the test suite dependencies? I tried this:
define([
    'intern!bdd',
    'intern/chai!expect',
    'node-jquery'
], ...

A: You're on the right track. If you are trying to load and test arbitrary JavaScript, you just do so like this:
define([
  'intern!bdd',
  'intern/chai!expect',
  'libs/jquery.js',
  'app/foo.js',
  'app/bar.js'
], function (bdd, expect) {
  bdd.describe('my test', function () {
    bdd.it('should find foos on the page', function () {
      expect(jQuery('.foo')).to.have.length.of.at.least(2);
    });
  });

  // access other global variables here
});


text:
Q: Calculate pixel from bitmap using ndk How can I calculate total amount of transparent color from a given bitmap using ndk
Java code:
    static {
    System.loadLibrary("bitmap-processing");
}

public native void calculatePixel(Bitmap bitmap);

Cpp code
extern "C" JNIEXPORT jobject JNICALL
Java_com_example_myapplication_CustomLayout_calculatePixel(JNIEnv *env, jobject thiz,
                                                       jobject bitmap) {
uint8_t *bitmapPixel;

AndroidBitmapInfo info;

if (AndroidBitmap_getInfo(env, bitmap, &info) < 0) {
    __android_log_print(ANDROID_LOG_INFO, "bitmap-processing", "ret valude = %d",
                        AndroidBitmap_getInfo(env, bitmap, &info));
    return NULL;
}

if ((AndroidBitmap_lockPixels(env, bitmap, static_cast<void **>((void *) bitmapPixel))) < 0){
    __android_log_print(ANDROID_LOG_INFO, "bitmap-processing", "Bitmap type error");
    return NULL;
}

struct pixel { uint8_t r, g, b, a; };
uint32_t num_transparent = 0;
for (int y = 0; y < info.height; y++) {
    pixel* row = (pixel *)(bitmapPixel + y * info.stride);
    for (int x = 0; x < info.width; x++) {
        const pixel& p = row[x];
        if (p.a == 0)
            num_transparent++;
    }
}

float proportion_transparent = float(num_transparent) / (info.width * info.height);

__android_log_print(ANDROID_LOG_INFO, "Bitmap-processing", "Transparent value : %f", proportion_transparent);

AndroidBitmap_unlockPixels(env, bitmap);
return nullptr;
}

As I am new to ndk trying out image processing
You can even rewrite the whole code

A: Since your pixel format is RGBA8888, every fourth byte contains its alpha value.
We can thus walk the bitmap line by line (where every line is info->stride bytes long), and there are info->height lines.
uint8_t* bitmapPixel;
if ((AndroidBitmap_lockPixels(env, bitmap, (void **)&bitmapPixel)) < 0){
    __android_log_print(ANDROID_LOG_INFO, "bitmap-processing", "Bitmap type error");
    return NULL;
}

struct pixel { uint8_t r, g, b, a; };
uint32_t num_transparent = 0;
for (int y = 0; y < info->height; y++) {
    pixel* row = (pixel *)(bitmapPixel + y * info->stride);
    for (int x = 0; x < info->width; x++) {
        const pixel& p = row[x];
        if (p.a == 0)
            num_transparent++;
    }
}

float proportion_transparent = float(num_transparent) / (info->width * info->height);

Don't forget to AndroidBitmap_unlockPixels when you're done!


text:
Q: How to judge a integer type to be a built-in type or not in C++? For example, int is a built-in type, but int128 is not.
How to know an integer type is a built-in type or not?
I want the compiler give me the answer, not using the doc, because I have to use the result of whether a type is built-in type in my program.

A: You're probably looking for std::is_fundamental<T>::value or std::is_arithmetic<T>.

A: You can't. On a platform with a 128 bit int, you may well find that int128 is a typedef for int. In which case,
std::is_fundamental<int128>::value

will be 1.
C++ provides no way of distinguishing a typedef.

A: Study the type_traits module, apart from std::is_fundamental which can tell if a type is fundamental (standard arithmetic types, void or nullptr_t), there is multiple templates for compile-time check of type properties, is it a pointer, is it arithmetic, signed or not, is it reference.
The problem with large integer types is that, if an integer type is supported by compiler, it IS a built-in type. Otherwise its support as an integer type is impossible. But it is NOT guaranteed to be detected as a fundamental. std::is_trivial<__int128>::value is true while std::is_trivially_assignable<__int128,__int128>::value would return false though, but that's not 100% guarantee that __int128 is or isn't something emulated, it's up to implementation.
There are libraries which use classes to emulate large integers and those, obviously, can be detected as usually non-trivial classes.
There is no cross-platform  way to detect int128 support but you can rely on fact that it is possible only a) on 64 bit systems, and b) for gcc and clang and some other compilers there is  __SIZEOF_INT128__ built-in macro.
Some 32bit platform like ARM with NEON support have another 128 bit type albeit it's not used as an integer but as a SIMD type for intrinsic functions, they shouldn't be mixed up with arithmetic type, because alignment requirement might be stricter.

A: You can find a list of built in types here https://learn.microsoft.com/en-us/cpp/cpp/fundamental-types-cpp?view=msvc-160


text:
Q: Reactjs clientside and Server side both together I am new in Reactjs. I create architecture using Reactjs.
When user comes for site and hit url then server.js (server side Rendering) file call. and in browser javascript enable then it's call client side call and if java script disable then run server side. show, How can I achieve this. i take refernce below url:
http://jmfurlott.com/tutorial-setting-up-a-simple-isomorphic-react-app/
Please help me.

A: In SSR(Server side rendering) the first render is performed on the server and the rendered HTML is returned to the user unlike in CSR(Client Side Rendering) where a basic html is sent and then react populates the DOM on the client side. Check out this project. They are based on this SSR architecture.
https://github.com/reactGo/reactGo


text:
Q: How to read a GBK-encoded file into a String? use std::env;
use std::fs::File;
use std::io::prelude::*;

fn main() {
    let args: Vec<String> = env::args().collect();
    let filename = &args[1];
    let mut f = File::open(filename).expect("file not found");
    let mut contents = String::new();
    f.read_to_string(&mut contents).expect("something went wrong reading the file");
    println!("file content:\n{}", contents);
}

When I attempt to read a GBK encoded file, I get the following error:
thread 'main' panicked at 'something went wrong reading the file: Error { repr: Custom(Custom { kind: InvalidData, error: StringError("stream did not contain valid UTF-8") }) }', /checkout/src/libcore/result.rs:860

It says the stream must contain valid UTF-8. How can I read a GBK file?

A: I figured out how to read line by line from a GBK-encoded file.
extern crate encoding;

use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;

use encoding::all::GBK;
use encoding::{Encoding, EncoderTrap, DecoderTrap};

fn main() {
    let args: Vec<String> = env::args().collect();
    let filename = &args[1];

    let mut file = File::open(filename).expect("file not found");
    let reader = BufReader::new(&file);

    let mut lines = reader.split(b'\n').map(|l| l.unwrap());

    for line in lines {
        let decoded_string = GBK.decode(&line, DecoderTrap::Strict).unwrap();
        println!("{}", decoded_string);
    }
}

A: You likely want the encoding crate.


text:
Q: Python: Gibbs sampler for regression model I am trying to write a function for Gibbs sampler in the Bayesian framework. I got the code from this [website][1], which is a straightforward regression model. However, I am tackling a more complicated model which is: y= beta0 + beta1* x + x^gamma * sigma * epsilon where sigma is the variance of the model. That means I need to estimate p(beta0|y,x,beta1,sigma,gamma) and so on(in the Gibbs sampler method). my question is how should I modify the code to sample beta0, beta1 and other variables as there are extra variables to condition on.
My codes are:
import numpy as np
import pymc as pm
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams['figure.figsize'] = (10, 5)
conda install -c conda-forge pymc3=3.0

def sample_beta_0(y, x, beta_1, sigma, gamma, mu_0,  tau_0):
    N = len(y)
    assert len(x) == N
    tau_i = 1/((x**gamma)*sigma)**2
    precision = tau_0 + sum(tau_i)
    mean = tau_0 * mu_0 +  np.sum((y - beta_1 * x)*tau_i)
    mean /= precision
    return np.random.normal(mean, 1 / np.sqrt(precision))

def sample_beta_1(y, x, beta_0, sigma, mu_1, sigma_1):
    N = len(y)
    assert len(x) == N
    precision = sigma_1 + sigma * np.sum(x * x)
    mean = sigma_1 * mu_1 + sigma * np.sum( (y - beta_0) * x)
    mean /= precision
    return np.random.normal(mean, 1 / np.sqrt(precision))

def sample_sigma(y, x, beta_0, beta_1, alpha, beta):
    N = len(y)
    alpha_new = alpha + N / 2
    resid = y - beta_0 - beta_1 * x
    beta_new = beta + np.sum(resid * resid) / 2
    return np.random.gamma(alpha_new, 1 / beta_new)

beta_0_true = -1
beta_1_true = 2
sigma_true = 1

N = 50
x = np.random.uniform(low=0, high=4, size=N)
y = np.random.normal(beta_0_true + beta_1_true * x, 1 / np.sqrt(sigma_true))

synth_plot = plt.plot(x, y, "o")
plt.xlabel("x")
plt.ylabel("y")

# print('Y are', y)
# print('X are', x)
plt.show()

"""GIBBS Sampler"""
# specify initial values
init = {"beta_0": 0,
        "beta_1": 0,
        "sigma": 2}

# specify hyper parameters
hypers = {"mu_0": 0,
         "sigma_0": 1,
         "mu_1": 0,
         "sigma_1": 1,
         "alpha": 2,
         "beta": 1}

def gibbs(y, x, iters, init, hypers):
    assert len(y) == len(x)
    beta_0 = init["beta_0"]
    beta_1 = init["beta_1"]
    sigma = init["sigma"]

    trace = np.zeros((iters, 3))  # trace to store values of beta_0, beta_1, sigma

    for it in range(iters):
        beta_0 = sample_beta_0(y, x, beta_1, sigma, hypers["mu_0"], hypers["sigma_0"])
        beta_1 = sample_beta_1(y, x, beta_0, sigma, hypers["mu_1"], hypers["sigma_1"])
        sigma = sample_sigma(y, x, beta_0, beta_1, hypers["alpha"], hypers["beta"])
        trace[it, :] = np.array((beta_0, beta_1, sigma))

    trace = pd.DataFrame(trace)
    trace.columns = ['beta_0', 'beta_1', 'sigma']
    print(trace)
    return trace

iters = 1000
trace = gibbs(y, x, iters, init, hypers)

traceplot = trace.plot()
traceplot.set_xlabel("Iteration")
traceplot.set_ylabel("Parameter value")

trace_burnt = trace[500:999]
hist_plot = trace_burnt.hist(bins = 30, layout = (1,3))
print(trace_burnt.median())
print(trace_burnt.std())

I know is really long but please help!


text:
Q: Split directories on python I'm trying to split my working directory to get the base path of the script to be able to access a configuration file.
For example the directory I'm working is: C:\Users\testUser\PycharmProjects\my_script\script\bin
The directory I need is: C:\Users\testUser\PycharmProjects\my_script
So first I use os.getcwd() to get the path. --> C:\Users\testUser\PycharmProjects\my_script\script\bin
Then I apply os.path.dirname(path) this will return the directory name. --> C:\Users\testUser\PycharmProjects\my_script\script
Finally, I used my_path, stuff = os.path.split(the_dirname) this will give me the directory I need --> C:\Users\testUser\PycharmProjects\my_script
I would like to know if there is any better to do it?

A: The way you did it is fine, but if you want to just get the parent directory of the current directory you are in, you can use os.pardir.
For example, on my machine (Mac OS) (note my current working directory was /User/headless/Pictures/wallpapers):
>>> import os
>>> current_path = os.getcwd()
>>> os.path.abspath(os.path.join(current_path, os.pardir))
'/Users/headless/Pictures'
>>> os.path.abspath(os.path.join(os.path.abspath(os.path.join(current_path, os.pardir)), os.pardir))
'/Users/headless'

Basically, all I did was ask for the parent directory. Then ask for the parent directory of the parent directory.

A: Maybe you can create a package in your diretory and go back to the root using: __PATH__.
https://docs.python.org/3/reference/import.html#packages
Or
os.path.dirname(os.path.dirname(__file__))


text:
Q: Отправка сообщение чат-ботом телеграмм в приватную группу в определенное время Ребята всем привет.
Небольшая предыстория.
Есть чат с друзьями где мы общаемся, у есть друг который всегда обещает нам замутить девчёнок, но никогда не мутит.
Каждый раз говорит что в субботу, но прокатывает нас.
Вот созрела идея, сделать бота, что бы слал ему непристойные сообщение каждый день в определенное время.
Собственно всё ради веселья :)
Сделал, а точнее подглядел следующий способ:
import telegram
import schedule
import time

# Указываем id бота и токен
bot = telegram.Bot(token='api токен от BotFather')
chat_id = 'id приватного чата'

# Функция, которая будет отправлять сообщение

def send_message():
  message = 'Сообщение, которое нужно отправить'
  bot.send_message (chat_id=chat_id, text=message)

# Задаем время отправки сообщения
schedule.every().day.at("15:00:00").do(send_message)

# Бесконечный цикл для проверки расписания
while True:
  schedule.run_pending()
  time.sleep(1)

Но пишет следующую ошибку
RuntimeWarning: coroutine 'Bot.send_message' was never awaited
  bot.send_message (chat_id=chat_id, text=message)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

A: Ошибка возникает из-за того, что метод bot.send_message возвращает корутину, тут надо использовать await.
Измененный код такой
import telegram
import schedule
import time
import asyncio

# Указываем id бота и токен
bot = telegram.Bot(token='api токен от BotFather')
chat_id = 'id приватного чата'

# Функция, которая будет отправлять сообщение
async def send_message():
  message = 'Сообщение, которое нужно отправить'
  await bot.send_message(chat_id=chat_id, text=message)

# Задаем время отправки сообщения
schedule.every().day.at("15:00:00").do(asyncio.run, send_message())

# Бесконечный цикл для проверки расписания
while True:
  schedule.run_pending()
  time.sleep(1)


text:
Q: Why does R's attributes() function fail when using explicit arguments? I am working with RODBC and parallel to make multiple queries against a data system for some internal reporting. To facilitate making new connections, I am going to extract the connection string from the RODBC object. To do this, I planned to use attributes(). However, I've encountered a behavior that I do not understand. A minimal working example is below:
> example.data <- data.frame(letters = sample(x = LETTERS,size = 20,replace = T),
+                            numbers = sample(x = 0:9,size = 20,replace = T))
>
> attributes(obj = example.data)
Error in attributes(obj = example.data) :
  supplied argument name 'obj' does not match 'x'
> attributes(example.data)
$names
[1] "letters" "numbers"

$row.names
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

$class
[1] "data.frame"

It should be noted that the obj = behavior is the one tab-suggested by RStudio. However, it causes an error. I tried to review the source code for attributes, but it is a primitive, so I would have to go digging into the C source - with which I am not nearly as familiar.
Why does attributes() fail when an explicit argument (obj =) is used, but runs fine when it is not used? (And should the behavior of RStudio with regard to suggesting obj = be changed?)

A: This seems like a bug in the documentation for attributes. The parameter probably should be named x. You can call it that way
attributes(x = example.data)

The problem is that attributes() is a primitive function and primitive functions behave differently than regular functions in R. They don't have formal parameters (formals(attributes) returns NULL). For these types of functions, R typically isn't going to parse out parameters by name and will assume they are in a certain positional order for efficiency reasons. That's why it's better not to name them because you cannot change the order of these parameters. There should be no need to name the parameter here.
There are other functions out there that have mismatches between the parameter name in the documentation and the value checked by the code. For example
isS4(pi)
# [1] FALSE
# documented parameter name is "object"
isS4(object=pi)
# Error in isS4(object = pi) :
#   supplied argument name 'object' does not match 'x'
isS4(x=pi)
# [1] FALSE

But there are also other primitives out there that use names other than x: e.g. seq_along (uses "along.with=") and quote (uses "expr=").


text:
Q: Trying to get log4j1.x to work alongside log4j2.x I have successfully migrated our application from log4j 1.x to log4j 2.x.
But there is one external component which cannot be migrated. Meaning calls to log4j 1.x should remain as they are.
I have log4j2.xml for our application and the old log4j.properties for the external component.I am getting the logs for the appenders in log4j2.xml but nothing for the one defined in log4j.properties. I read the post -
Mixing log4j 1.x and log4j 2
and have added the required jars. Earlier with log4j 1.x we used to have 2 log4j.properties - one for the applciation and another one for the external component using PropertyConfigurator. Now with log4j2.xml I am not sure how we can achieve this.
Configuring log4j2 and log4j using a single log4j2 xml file
This post says we cannot have log4j.properties in the classpath. Does that mean that I need to transfer all the appenders defined in log4j.properties to log4j2.xml ? Can I have a seperate log4j2.xml just for the external component.

A: You cannot have two log4j2.xml configurations (well, separate web apps can have separate configurations but in general each process has one config).
Option 1: The easiest thing to do is to use the bridge log4j-1.2-api-2.x.jar and merge the log4j.properties configuration into the log4j2.xml. Then all logging is done by lo4j 2 and it should all work.
If you want to do things the hard way you may be able to succeed but it may take some fiddling.
Option 2: If by "migrated our application from log4j 1.x to log4j 2.x" you mean your application now uses the log4j 2 API, then you should be able to use both log4j 1.x to log4j 2 at the same time. (log4j 1.x for the external component.)
In that case, do not use the bridge log4j-1.2-api-2.x.jar. If you use the bridge, it will route calls to the log4j 1.x API to log4j 2. Usually that is what you want, but in this case it sounds like your external component wants to use the log4j 1.x internals. (Is this true? If not, consider option 1.)
If your application now uses the log4j 2 API, except for the external component, then put these jars and config files in your classpath:

*

*log4j-api-2.x.jar

*log4j-core-2.x.jar

*log4j-1.2.x.jar

*log4j2.xml - the log4j 2 configuration for your application

*log4j.properties - the log4j 1.x configuration for the external component

But again, simply merging the configurations is probably easier to maintain.


text:
Q: ASP.NET MVC Bundling wrong Bootstrap version I have an issue where the Bundling in MVC4 in production is somehow bundling an older version of Bootstrap that I no-longer have in my project.
I updated the version of Bootstrap as I wanted to use some Glyphicons that the old version in my project didn't support.
Running locally in debug or release mode, all of the Glyphicons show as expected, but once deployed to production (using msbuild to deploye to Azure Web App), the newer Glyphicons are missing, and the minified+bundled css file is missing references to the newer Gyphicons - it's essentially an older version of bootstrap.css
This is my RegisterBundles method:
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.UseCdn = false;

        // Clear out the list and add back the ones we want to ignore.
        // Don't add back .debug.js.
        bundles.IgnoreList.Clear();
        bundles.IgnoreList.Ignore("*-vsdoc.js");
        bundles.IgnoreList.Ignore("*intellisense.js");

        bundles.Add(new StyleBundle("~/style/global").Include(
            "~/Content/css/lib/bootstrap.css",
            "~/Content/css/global.css"));
    }

Then I'm using...
@Styles.Render("~/style/global")

To include the styles.

A: I had a similar issue where my ASP.NET MVC 5 application was still using an older version of bootstrap.css (3.0) even after I had removed the older bootstrap.css file from the project, and installed Bootstrap 3.3.7 NuGet package.  When I ran the application and did "View Page Source" from the browser, then clicked the "/Content/bootstrap.css" rel="stylesheet" link, it STILL brought up the old bootstrap.css file content.
I was baffled and messed with it for over an hour until I realized that the css page was cached.  I figured this out because when I clicked the "/Content/bootstrap.css" rel="stylesheet" link to bring up the bootstrap.css then REFRESHED the page, it changed to my 3.3.7 version.
Anyway, I decided to post this response because maybe it would help someone else to understand that the issue could be because of caching.

A: Use the ResetAll() method to clear and reset. More about it here.


text:
Q: Defining truth in a topos model My colleague and I are working through Goldblatt's Topoi, and we're stuck on exercise 2 in chapter 11, section 4.
The exercise is to show that $\|\phi\|^m \circ f = \|\phi\|^m \circ h$, for any formula $\phi$ with $n$ free variables, where $f, h : a^m \to a^n$ are such that $pr^m_{i_k} \circ f = pr^m_{i_k} \circ h = pr^n_k$ for all $1 \leqslant k \leqslant n$.
Here $f$ is defined to be a product arrow whose $j$-th component $p_j$ is defined as follows:
$$
p_j =
\begin{cases}
 pr^n_k : a^n \to a &\text{if } j = i_k \text{, for some } 1 \leqslant k \leqslant n \\
 g &\text{otherwise }
\end{cases}
$$
where $g$ is any arrow from $a^n$ to $a$. Then $h$ is defined to be the same as $f$, except perhaps with a different arrow from $a^n$ to $a$ in place of $g$. The point of the exercise is to show that it doesn't matter whether we define the arrow representing truth in a model $\|\phi\|_{\mathfrak{A}}$ to be $\|\phi\|^m \circ f$ or $\|\phi\|^m \circ h$.
We're on the inductive step where we need to show that $\forall_a \circ |\phi|^m_i \circ f = \forall_a \circ |\phi|^m_i \circ h$, where $|\phi|^m_i$ is the exponential adjoint of $\|\phi\|^m \circ \langle pr^{m + 1}_1, \ldots, pr^{m + 1}_{i - 1}, pr^{m + 1}_{m + 1}, pr^{m + 1}_{i + 1}, \ldots, pr^{m + 1}_m \rangle$.
One strategy we've tried has been to show that $T^{m + 1}_i \circ (f \times \mathsf{1}_a) = T^{m + 1}_i \circ (h \times \mathsf{1}_a)$, so that $|\phi|^m_i \circ f$ and $|\phi|^m_i \circ h$ would be the exponential adjoint of the same arrow, and hence identical, but we haven't been able to show this.


text:
Q: mocute 053 - can't use on windows I have a mocute 053 bluetooth game controller. I successfully connected it to my windows 7 PC but I can't use it in any game. I tried connecting it to overwatch and battlegrounds. when I move the stick on the controller nothing happens. How can I configure it?
Thanks.

A: You can try the "JoyToKey". Good Luck!


text:
Q: Debugging Topshelf service that won't run under restrictive account I have a Windows service written using Topshelf. I'm trying to configure it to run using a Windows account with restricted privileges rather than using LocalSystem. That's also necessary as I'd like to connect to a database using integrated authentication.
The service works when run as LocalSystem (albeit with a database connection string containing credentials) and running the console application as my limited account (using runas) also works.
However, when I try to start the service the service control manager times out waiting for a response:

The service did not respond to the start or control request in a timely fashion.

I also get the following in the Application Popup event log:

Application Error : The exception unknown software exception (0xc06d007e) occurred in the application at location 0x77e4bef7.

The first thing that the application does is writes to a log file but it doesn't reach that when I start the service. The logging works if I run via the console.
Any suggestions what I might be missing or what I might try next?

A: This problem seems to be related to the server (a domain controller) rather than TopShelf. A service built with the .NET service component also exhibits the same behaviour.
The service runs successfully on a different machine (in the same domain).
Unfortunately this doesn't help diagnose the problem but gives me an acceptable workaround.

A: Check the MSDN article Debugging windows services which describes how you debug windows services.

A: I've just started seeing this on a few of my services written in .net 2.0.  They'll start fine when the server boots, but if I were to restart them throughout the day, they would not start, and give this error message.
They currently ran under a domain account which has admin rights on the box, but for kicks, I switched it to Local System, and the service started normally.  I stopped it, changed it back to the domain account (reentering the password), and it started normally again as expected.
Don't know if this counts as a 'fix' so much, but that's what worked for me.


text:
Q: Deploying Qt-based app on Mac OS X I wrote a cross platform application and I distributed it successfully for Windows and Linux (and tested them on "clean" virtual systems, with no other additional software and/or libraries installed).
I have already compiled my application on my Mac computer, but I don't know if my application will work on other Mac computers.
I don't have two Macs, also, (as far as I know) it's difficult to install Mac OS X on a virtual machine with "legal" discs or without having to perform a process similar to building a Hackintosh, this means that I cannot test my app on a virtual machine (in VirtualBox).
So may question would be: Is there any way of making sure that my application will actually run on other Mac systems (without the need of using another computer)?
As an additional note, I wrote my application by using the Qt framework.

A: You can use a VM running on your Mac. I've done this with Parallels: http://kb.parallels.com/en/112121
If I understand correctly, you have a Mac on which you have compiled the app but you want a clean environment to test deployment. So if you set up a VM on that same Mac that you compiled on, you will have a clean OSX to test with.

A: I came up with this problem last week and I got my information from this source:
You can check what other libraries your application links to using the otool:
otool -L plugandpaint.app/Contents/MacOs/plugandpaint

Here is what the output looks like for a Qt application example:
plugandpaint.app/Contents/MacOS/plugandpaint:
/System/Library/Frameworks/Carbon.framework/Versions/A/Carbon
        (compatibility version 2.0.0, current version 128.0.0)
/System/Library/Frameworks/QuickTime.framework/Versions/A/QuickTime
        (compatibility version 1.0.0, current version 10.0.0)
/usr/lib/libz.1.dylib
        (compatibility version 1.0.0, current version 1.2.3)
/System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices
        (compatibility version 1.0.0, current version 22.0.0)
/usr/lib/libstdc++.6.dylib
        (compatibility version 7.0.0, current version 7.3.0)
/usr/lib/libgcc_s.1.dylib
        (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libmx.A.dylib
        (compatibility version 1.0.0, current version 92.0.0)
/usr/lib/libSystem.B.dylib
        (compatibility version 1.0.0, current version 88.0.0)

If you see Qt libraries in the output, it probably means that you have both dynamic and static Qt libraries installed on your machine.
I don't take credit for this answer, I'm just a pointer to the source of information.
I use macdeployqt for my applications.


text:
Q: ASP.NET MVC 5 - JSON - (Dynamic?) Model Binding - REST services - Webhooks - Chargebee This should be easy but I'm stuck. I've set up a webhook with a service (ChargeBee) that is successfully posting my site JSON. Here is the model I'm trying to bind:
public class ChargeBeeWebhookModel
{
    public string id { get; set; }

    public string occurred_at { get; set; }

    public string source { get; set; }

    public string @object { get; set; }

    public string content { get; set; }

    public string event_type { get; set; }

    public string webhook_status { get; set; }
}

Everything is binding except "content", which is null. The problem is that "content" will change depending on what type of event is triggered. It could be something like this for example, for the "customer created" event:
 "customer": {
        "id": "8avVGOkx8U1MX",
        "first_name": "Benjamin",
        "last_name": "Ross",
        "email": "Benjamin@test.com",
        "auto_collection": "on",
        "created_at": 1317407411,
        "object": "customer",
        "card_status": "valid",
        "payment_method": {
            "object": "payment_method",
            "type": "card",
            "gateway": "chargebee",
            "reference_id": "tok_KyVr8xPHl5BSx1",
            "status": "valid"
        },
        "account_credits": 0
    },
    "card": {
        "customer_id": "8avVGOkx8U1MX",
        "status": "valid",
        "gateway": "chargebee",
        "iin": "411111",
        "last4": "1111",
        "card_type": "visa",
        "expiry_month": 1,
        "expiry_year": 2016,
        "object": "card",
        "masked_number": "************1111"
    }

I just need to bind these complex objects to some type. String isn't working. Once it's bound, I can easily check if it's an event I want to handle using the event_type property and deserialize it into the appropriate custom type.
How do I do this? I feel like I'm missing something really simple. Chargebee won't let me have a different URL for each type of event as far as I know, which is what I thought would make the most sense. It's one URL and I have to bind many possible responses.
Do I need a custom model binder or something? Is there an easier way?
Also maybe someone could make a ChargeBee tag?
Thanks everyone.

EDIT:

As requested, this is what the sample request looks like:
Headers
POST HTTP/1.1
Host:********.ngrok.io //(obviously I commented this out)
Authorization: Basic cGF0cmlvdGN5YmVybmV0aWNzZHJvbmVtYXN0ZXI6c3VuZGV2aWxjb2NvYXJhZ2luZ2J1bGw=
Content-Type: application/json; charset=utf-8
User-Agent: ChargeBee

Body
{
    "id": "ev_3Nl8ERLPElBCRU6",
    "occurred_at": 1341167306,
    "source": "admin_console",
    "object": "event",
    "content": {
        "subscription": {
            "id": "3Nl8ERLPElBCGl1",
            "plan_id": "basic",
            "plan_quantity": 1,
            "status": "future",
            "start_date": 1341772105,
            "trial_start": 1341772105,
            "trial_end": 1344450505,
            "created_at": 1341167305,
            "has_scheduled_changes": false,
            "object": "subscription",
            "addons": [{
                "id": "data_usage",
                "quantity": 1,
                "object": "addon"
            }],
            "due_invoices_count": 0
        },
        "customer": {
            "id": "3Nl8ERLPElBCGl1",
            "first_name": "Benjamin",
            "last_name": "Ross",
            "email": "Benjamin@test.com",
            "auto_collection": "on",
            "created_at": 1341167305,
            "object": "customer",
            "card_status": "valid",
            "payment_method": {
                "object": "payment_method",
                "type": "card",
                "reference_id": "3Nl8ERLPElBCGl1",
                "status": "valid"
            }
        }
    },
    "event_type": "subscription_created",
    "webhook_status": "not_configured"
}

Unless I'm mistaken, I just don't think the model binder can handle this situation. It needs pre-defined types and can't handle variability or dynamic stuff as far as I can tell. Please correct me if I'm wrong. Anyway, I'll answer this question with a full code sample later but for now I've ditched a pure model-binding approach and am reading the Request.InputStream to get the JSON data I need. Then, depending on event_type, which the model binder had no problems with, I'm deserializing into my predefined types. It's just that I've never actually had to manually pick something out of a request before; I've always used the model binder.

A: Here is what I was trying to achieve. Request.InputStream is the way to go; I started trying to do this manually but luckily ChargeBee has an official .NET library (unlike Mandrill) to do it all for me:
    [HttpPost]
    [BasicAuthentication(username: "x", password: "y", BasicRealm = "z")]
    public HttpStatusCodeResult ChargeBeeWebhook()
    {
        if (ModelState.IsValid)
        {
            Event chargeBeeEvent = new Event(Request.InputStream);

            EventTypeEnum? eventType = chargeBeeEvent.EventType;

            Event.EventContent eventContent = chargeBeeEvent.Content;

            if (eventType == EventTypeEnum.SubscriptionCreated)
            {
                Subscription subscription = eventContent.Subscription;

                Customer customer = eventContent.Customer;

                // more stuff
            }

            return new HttpStatusCodeResult(200);
        }
        else
        {
            return new HttpStatusCodeResult(400); // bad request
        }
    }

A: Okay the following should work. Instead of passing a Javascript object for content, use JSON.stringify on your object and set the result of it to content. This way in your Controller the value of content will be a string.


text:
Q: Postfix: delivering "local" mail to GMail, but sending other mail I need to set up a server to send messages to a few different people automatically. The recipients are at two different domains, let's say mydomain.com and otherdomain.com. The messages need to come from a email address at mydomain.com. mydomain.com is a Google Apps for Enterprise domain.
I have configured Postfix to say that it is mydomain.com (myhostname = mydomain.com and mydomain = mydomain.com). It currently sends messages to otherdomain.com just fine. However, when sending mail to mydomain.com, I don't want it to deliver locally, but rather to GMail's server, so that the mail actually gets to the recipient. When delivering today, postfix tries to deliver it locally and gets an error "User unknown in local recipient table"
I tried setting transport_maps with the following entry:
localdomain smtp:aspmx.l.google.com
Hoping that that would redirect local messages over to Google's SMTP server, but that did not work.
Any ideas would be appreciated.

A: Two things to consider

*

*ensure mydestination parameter doesn't contain mydomain.com, mydomain or myhostname

*Set relay_domains = mydomain.com  in main.cf


text:
Q: De2 Board reading sensor reading I wish to operate a LVMAX Sonar EZ1 sonar rangefinder.
They say

With 2.5V - 5.5V power the LV-MaxSonar EZ1 provides very short to long-range detection and ranging, in an incredibly small package. The LV-MaxSonar-EZ1 detects objects from 0-inches to 254-inches (6.45-meters) and provides sonar range information from 6-inches out to 254-inches  with 1-inch resolution. Objects from 0-inches to 6-inches range as 6-inches. The interface output formats included are pulse width output, analog voltage output, and serial digital output.

I wish to control this using an Altera DE2 Education and development board,
User manual, Getting started guide
They say:

The Altera® DE2 Development and Education board is an ideal vehicle for learning about digital logic, computer organization, and FPGAs. Featuring an Altera Cyclone® II 2C35 FPGA, the DE2 board is suitable for a wide range of exercises in courses on digital logic and computer organization, from simple tasks that illustrate fundamental concepts to advanced designs.

I am not sure how I can do this. The two possibilities I see are the expansion headers and the rs232. But i have never used them and am not able to find any links on how to do analog read using the expansion headers. The rs232 serial interface just looks a lot more challenging.

A: RS232 looks like a straightforward way to interface the two devices.
You have to get the baud rate the same at each end, connect appropriate pins and deal with th eincoming data -  s "simple matter of programming " :-).
Data output:
It sounds like the EZ1 can be persuaded to output RS232 data continually

Data input:
Page 42 of the DE2 users manual and
 pages 26 & 27 of the DE2 Getting Started Guide
 show how to configure an RS232 interface using the onboard PS/2 socket.
They advise that:

*

*The DE2 Board uses the standard 9-pin D-SUB connector for RS-232
communications between PC and the board.
The transceiver chip used is MAX232.
For detailed information on how to use the chip, users can refer to the spec under C:\DE2\Datasheet\RS232.     <- Probably on the supplied CD ROM
Figure 3.11 shows the related schematics.
The pin assignment of the associated interface is shown in Table 3.9.
As long as you do NOT have a "brown dot part" then the EZ1 Sonar can be easily configured to calculate range repeatedly and to output the results as a  continual sequence of R232 strings. ie

*

*TX – ,   When the *BW is open or held low, the TX output delivers
asynchronous serial with an RS232 format, except voltages are 0-
Vcc.
The output is
-an ASCII capital "R",
-followed by three ASCII
character digits representing
-the range in inches up to a maximum
of 255,
-followed by a carriage return (ASCII 13).
The baud rate is
9600, 8 bits, no parity, with one stop bit.
Although the voltage of 0-
Vcc is outside the RS232 standard, most RS232 devices have
sufficient margin to read 0-Vcc serial data.
If standard voltage
level RS232 is desired, invert, and connect an RS232 converter
such as a MAX232.

*Brown dot parts: When BW pin is held high the TX output
sends a single pulse, suitable for low noise chaining (no serial data)

A: Russell discussed the RS232, so I'll look at the other options.
The analog output is not really practical since the DE2 doesn't appear to have an ADC.
The PWM output would be pretty easy to use though. All you would need to do is connect one of the FPGA pins (set to input) to the PWM output, and use a timer on the FPGA to time the pulse width. Altera will probably have a generic PWM core you can set up appropriately and drop in. Or you can write your own pretty easily. Detect rising edge, start counter, detect falling edge, stop counter and calculate results.
For 147us per inch from the sonar, and say using the 50MHz clock on the FPGA, then you get 147us / 20ns = 7350 counts per inch. So divide the counter result by e.g. 73.5 and you have results in hundredths of an inch.
Whatever you are connecting, make sure the supply voltages are the same or the lower supply pin is tolerant of the higher supply (e.g. if the FPGA runs at 3.3V and the sonar at 5V, you need to make sure the FPGA pin is 5V tolerant)
Easiest way is to run the sonar at the FPGA IO supply (probably 3.3V, though could be less. Sonar says 2.5V-5.5V so it's within range)
If the levels have to be different for some reason and there is no "tolerance", then you would need a level shifter. Since this would only be a one way data stream you could just use a simple resistive divider.


text:
Q: highcharts xaxis label data display The date displayed on the highcharts xaxis label is showing non-existent dates, not actual data. What should be set on the xaxis label to show the existing date values?
My code is below.
Highcharts.stockChart('dataChart', {
                        credits: {
                            enabled: false
                        },
                        rangeSelector: {
                            selected: 5
                        },
                        title: {
                            text: result[0].chartRptCdNm
                        },
                        xAxis: {
                            type: "datetime",
                            labels: {
                                formatter: function() {
                                    return Highcharts.dateFormat('%Y-%m-%d', this.value);
                                }
                            }
                        },
                        yAxis: {
                            title: {
                                text: result[0].graphYaxis
                            },
                            opposite: false,
                            lineWidth: 1,
                            margin: 0,
                            labels: {
                                format: '{value}' + result[0].graphYaxisUnit,
                                align: "right",
                                y: -5,
                                x: -5
                            }
                        },
                        tooltip: {
                            headerFormat: "",
                            useHTML: true,
                            valueDecimals: 2,
                            split: true,
                            formatter: function () {
                                var s = "";

                                $.each(this.points, function() {
                                    s += '\u25CF' + this.series.name + '
';
                                    s += ' 일자 : ' + Highcharts.dateFormat('%Y-%m-%d', new Date(this.x)) + '
';
                                    s += ' 금리 : ' + (Math.floor(this.y * 100) / 100) + '
';
                                });
                                return s;
                            }
                        },
                        series: seriesArr
                    });

I am making a chart using a single line series.


text:
Q: How does Apple's Podcasts app's Auto-Download of podcasts work? 1) In the Apple Podcasts app, one of the subscription options is Keep Most Recent Episode.  Is this the most recent unplayed episode or the most recent episode in the feed? If the former, is there any way to get the latter behavior?
I subscribe to a couple daily news podcasts that I may not want to listen to every day. I just want the latest episode to be downloaded to my phone, so on the chance I want to listen, I'm listening to today's news and not last week's.
2) How often does it check for new episodes?  How do I ensure that it does check?  Sometimes I turn my phone off, and when I turn it back on again, the Podcasts app won't check for new ones until the next time I open it.  This seems weird; I would expect it to work more like the calendar which is running in the background syncing silently.
3) If 1 & 2 are not possible, is there an alternative app you can recommend?  Can I use the iTunes app without syncing to my computer, for example?

A: I'm not sure about your first question. I suspect that Keep Most Recent refers to the most recent in the feed, but I don't know for sure.
As for the second question, the Podcasts app adheres to Apple's rules about background/scheduled downloading. That is to say, it only checks for new episodes when the app is open. This is a power and performance optimization decision, and for better or worse, no third party apps are allowed to schedule background checks either (although in theory they could on a jailbroken device, but I don't know if there are any apps that do this). Apps can trigger background downloads using geofencing however (the same way Reminders can trigger an alert when you leave your office).
There are several other podcast apps on the App Store, which have finer grained controls for subscriptions, and so forth. Downcast and Instacast are likely the two most popular ones.


text:
Q: How do I set a wildcard for CSRF_TRUSTED_ORIGINS in Django? After updating from Django 2 to Django 4.0.1 I am getting CSRF errors on all POST requests. The logs show:
"WARNING:django.security.csrf:Forbidden (Origin checking failed - https://127.0.0.1 does not match any trusted origins.): /activate/"
I can't figure out how to set a wildcard for CSRF_TRUSTED_ORIGINS? I have a server shipped to customers who host it on their own domain so there is no way for me to no the origin before hand. I have tried the following with no luck:
CSRF_TRUSTED_ORIGINS = ["https://*", "http://*"]

and
CSRF_TRUSTED_ORIGINS = ["*"]

Explicitly setting "https://127.0.0.1" in the CSRF_TRUSTED_ORIGINS works but won't work in my customer's production deployment which will get another hostname.

A: The Django app is running using Gunicorn behind NGINX. Because SSL is terminated after NGINX request.is_secure() returns false which results in Origin header not matching the host here:
https://github.com/django/django/blob/3ff7f6cf07a722635d690785c31ac89484134bee/django/middleware/csrf.py#L276
I resolved the issue by adding the following in Django:
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

And ensured that NGINX is forwarding the http scheme with the following in my NGINX conf:
proxy_set_header X-Forwarded-Proto $scheme;

A: Yes, it had changed in the 4.0 version as you can see here here

Changed in Django 4.0:
The values in older versions must only include
the hostname (possibly with a leading dot) and not the scheme or an
asterisk.
Also, Origin header checking isn't performed in older versions.

Note: you are not supposed to use * in production.


text:
Q: In generic how convert one type data to another type data Work on C#,In generic as doesn't work with value types (like int),Want a extension method for all datatype like:int,long,string.conversion method is bellow
public static T Translate<T>(this T inputNumber) where T : class
{
    return inputNumber.ToString()
        .Replace("1", "1")
        .Replace("2", "2")
        .Replace("3", "3")
        .Replace("4", "4")
        .Replace("5", "5")
        .Replace("6", "6")
        .Replace("7", "7")
        .Replace("8", "8")
        .Replace("9", "9")
        .Replace("0", "0") as T;
}

var result= 2.Translate<longTypeData>();

want a long type data in result variable.

A: It is not very clear what you are trying to do. But if you want this function to use as some kind of converter, I would pass two generic type arguments in:
public static T Translate<Q, T>(this Q inputNumber) {
    string value = TypeDescriptor.GetConverter(typeof(Q)).ConvertToString(inputNumber);

    string replacedValue = value.ToString()
        .Replace("1", "1")
        .Replace("2", "2")
        .Replace("3", "3")
        .Replace("4", "4")
        .Replace("5", "5")
        .Replace("6", "6")
        .Replace("7", "7")
        .Replace("8", "8")
        .Replace("9", "9")
        .Replace("0", "0");

    return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(replacedValue);
}

Later you can use it like this:
int result = "444".Translate<string, int>();

But keep in mind: passing invalid type combinations will generate an exception!


text:
Q: Dynamic CRM Shared Variables Thread Safety I have a Dynamic CRM plugin which has two steps. One is running on pre-create and second is running on post-create. I have used Shared Variables. I am setting the values in shared variables on pre-create and retriving the values on post-create.
Now is it thread safe. If two users trigger the same plugin in same org would not they over write each others data?
Set values in Shared Variables:
context.SharedVariables.Add("statecode", stateCodeValue);
context.SharedVariables.Add("statuscode", statusCodeValue);

Get values from Shared Variables:
int statecode = (int)context.SharedVariables["statecode"];
int statuscode = (int)context.SharedVariables["statuscode"];

A: Yes, this is thread-safe. The IPluginExecutionContext passed to your plugin class is an object that is uniquely created for a plugin execution pipeline. Shared variables are passed from one stage to the next (PreValidation => PreOperation => PostOperation => AsyncOperation).
An execution pipeline is specific for any single operation processed by the CRM platform. (E.g. a create or update message regarding a specific record.)


text:
Q: Pick an image from the Gallery I have seen a lot of posts about this, and it seems like the code below should work.  I have created an SD Card image and added it to the emulator (and that works fine).
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        //intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, 1);

It does launch and allow selection of images, but when I click on an image, everything exits and the emulator returns to the home screen, not the back to my app.  My onActivityResult is never called either.
What am I missing?

A: I found my issue.  I was launching the gallery from a sub-activity and that sub activity Intent had the flag FLAG_ACTIVITY_NO_HISTORY which prevented the call back from going to that activity.
thanks.

A: Use the following intent :
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 1);


text:
Q: About 'a, an, the' to introduce company my name is Ashok Choudhary. My company name is 'Expert'. I want to introduce my company by advertisement and I also want to show my name with my company. Which one is right

(1) Expert, An ashok choudhary co.

(2) Expert, A Ashok choudhary co.

(3) Expert, Ashok choudhary co.

A: The only expression with a correct use of English is "Expert. An Ashok Choudhary company".  This suggests that it is one of many companies that you run.  (Company is rarely abbreviated except in forms like ".... co. ltd.")
The overall impression is odd.  You don't see adverts for "Microsoft. A Bill Gates company".  The only reason you would do this is that you believe your name is so respected that people will only respond to the advert if they see your respected name next to it. (And unless you are the Building and Construction Minister of Bihar, you aren't the most famous person with the name Ashok Choudhary)
So my I would prefer a description of your company to the name of the person who founded it. For example "Expert. We provide technical solutions to software problems"  Or just "Expert"  You don't really need anything else.


text:
Q: Limiting scroll bar length I am trying to create a simple notepad like GUI using Perl Tk. I have used the Scrolled widget to create a Text widget with two scrollbars - one on the right and one on the bottom. The place where the two scrollbars meet looks like this:

However I would like to make it look like what is seen in the "Notepad" application by Microsoft. This is how I want it:

As you can see, there is a now an "empty square" where the two scrollbars meet. One more feature of notepad is that this "square" can be used to resize the window size. I want to be able to achieve the same.
How do I go about doing this?
Thanks!

A: The trick is to place the widgets with the grid geometry manager, which essentially creates an (uneven-sized) 4x4 grid with the text widget at "North-West", the vertical scrollbar at "North-East", the horizontal scrollbar at "South-West", and the empty square at "South-East".  There is a relevant example on the man page.
I think I'm allowed to quote the man page example as fair use (noting that it's Copyright © 1995-1997 Roger E. Critchlow Jr. Copyright © 1996 Sun Microsystems, Inc.).
# Make the widgets
toplevel .t
text .t.txt -wrap none -xscroll {.t.h set} -yscroll {.t.v set}
scrollbar .t.v -orient vertical   -command {.t.txt yview}
scrollbar .t.h -orient horizontal -command {.t.txt xview}

# Lay them out
grid .t.txt .t.v -sticky nsew
grid .t.h        -sticky nsew

# Tell the text widget to take all the extra room
grid rowconfigure    .t .t.txt -weight 1
grid columnconfigure .t .t.txt -weight 1

You'll have translate to Perl-Tk yourself, however.  There is some Perl-Tk-related discussion of grid (though not specifically about scrollbars) here at TkDocs that might get you started.  The "Learning Perl/Tk" sample chapter Geometry Management also discusses grid.
Oh! You wanted a resizing control in the fourth square as well.  In Tcl/T(t)k, it's called a ttk::sizegrip and it's documented here.  I've never used it myself (as there are other ways to resize the window) and don't know if it's in Perl-Tk.  If it's not, there is a wiki page discussing how to fake it (again, I've never tried that code myself).


text:
Q: repeat a if else statement How do I make it after the if statement comes true it will not execute and I can re-enter another set of numbers?... to stop it though i will have it to enter -1 to exit.
static void Main(string[] args)
{
    {
        // first enter 2016, then 2000, then 2015 and get multiple results
        int Year;
        Console.WriteLine("Please enter a year: ");
        Year = Convert.ToInt32(Console.ReadLine());
        if ((Year % 4 == 0) && (Year % 100 != 0 || Year % 400 != 0)) // <--- entered 2016
        {
            Console.WriteLine("The Year you have entered is a Leap Year {0}.", Year);
        }
        if ((Year % 4 == 0) && (Year % 100 == 0)) // <--- year 2000
        {
            Console.WriteLine("the 2000 works", Year);
        }
        if ((Year % 5 == 0) && (Year % 100 != 0)) // <--- year 2015
        {
            Console.WriteLine("2015 works", Year);
        }
        else
        {
            // startover
        }
        Console.ReadLine();
    }
}

A: It is bit unclear, since you want to recur the process until you press -1, you could do something like this .
int Year;
do
{
    Console.WriteLine("Please enter a year: ");
    if(!int.TryParse(Console.ReadLine(), out Year))
    {
          Console.WriteLine("invalid input");
          continue;
    }

    if ((Year % 4 == 0) && (Year % 100 != 0 || Year % 400 != 0)) // <--- entered 2016
    {
        Console.WriteLine("The Year you have entered is a Leap Year {0}.", Year);
    }
    if ((Year % 4 == 0) && (Year % 100 == 0)) // <--- year 2000
    {
        Console.WriteLine("the 2000 works", Year);
    }
    if ((Year % 5 == 0) && (Year % 100 != 0)) // <--- year 2015
    {
        Console.WriteLine("2015 works", Year);
    }

}   while(Year != -1);

//Console.ReadLine(); not required.

Working Code

A: If you are just testing to see if the year entered is a leap year, you could just use DateTime.IsLeapYear()
if(DateTime.IsLeapYear(Year))
{
    Console.WriteLine("The Year you have entered is a Leap Year {0}.", Year);
}
else
{
    Console.WriteLine("The Year you have entered is NOT a Leap Year {0}.", Year);
}


text:
Q: "had been able" vs. "could have" In each of the following pairs of phrases, what is the difference between the two?

1a. "Had been able" vs.
1b. "Could have"
2a. "Hadn't been able" vs.
2b. "Couldn't have"

A: In each pair, the first phrase is about having accomplished (or not) something in the past:

Before arthritis got to his back, he had been able to change his own oil
Before he got his GED, he hadn't been able to get anything better than work as a laborer

The second phrase in each pair is about opportunity, most typically that was missed:

He could have gotten her autograph if he'd had the courage to walk up and say "hi".
He couldn't have eaten the last piece of cake, he was away at school all day.


text:
Q: Convert Raw to Wav Streams in NodeJS I am using a nodeJS library naudio —link— to record sound from a 2 microphones (total 4 channel audio with each microphone being stereo). This library spits out  a .raw file in the following specs: 16 BIT, 48000Hz Sample Rate, Channel Count 4
// var portAudio = require('../index.js');
var portAudio = require('naudiodon');
var fs = require('fs');

//Create a new instance of Audio Input, which is a ReadableStream
var ai = new portAudio.AudioInput({
  channelCount: 4,
  sampleFormat: portAudio.SampleFormat16Bit,
  sampleRate: 48000,
  deviceId: 13
});

ai.on('error', console.error);

//Create a write stream to write out to a raw audio file
var ws = fs.createWriteStream('rawAudio_final.raw');

//Start streaming
ai.pipe(ws);
ai.start();

process.once('SIGINT', ai.quit);

Instead of the .raw file, I am trying to convert this to two individual .wav files. With the above encoding and information, what would be the best way to do so? I tried to dig around for easy ways to deinterleaving and getting .wav but seem to be hitting a wall.

A: The addon is a wrapper around a C++ library called portaudio which according to its documentation supports writing to a WAV file.
What you could do is extend the addon and bind a NodeJS function to the underlying C++ function that write to WAV.
This will give you a good performance if it is an issue.
If you want something easier you could look up utilities that do the conversion and call them from within your script using ex like this

A: Look similar to this question.
You may also take a look here to know how to create wav file from javascript.