text:
Q: How do I specify the "path" section of a HTTP Post using Apache HttpClient? For example, this example is given on http://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039 :
POST /foo.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; <blah, blah>
<other blah goes here>

I'm using Apache's HttpClient ( v.3.4.5 ), and I want to be able to specify the 'path' shown above, the '/foo.php' section.  How do I do this?
Thanks for your help.

A: Specify the whole URL with hostname and path in your HttpPost:
HttpUriRequest request = new HttpPost("http://host.com/foo.php");


text:
Q: search engine and pagination Hello Friends I want to know how to add pagination in search engine. I have tried so many times to add pagination in search engine but every time i was fail. Is there anybody who modify my following code to add pagination:
index.php
<?php include 'func.inc.php'; ?>

<title>Search</title>

 Search

<form action="" method="POST">

            <input type="text" autocomplete="off" name="keywords" /> <input type="submit" value="Search" />

</form>
<?php
if (isset($_POST['keywords'])) {
$suffix = "";
$keywords = mysql_real_escape_string (htmlentities (trim($_POST['keywords'])));

    $errors = array();

    if (empty($keywords)) {
        $errors[] = 'Please enter a search term';
    } else if (strlen($keywords)<3) {
        $errors[] = 'Your search term must be three or more character';
    } else if (search_results($keywords) === false) {
        $errors[] = 'Your search for ' .$keywords. ' returned no result';
    }

    if (empty($errors)) {
        $results = search_results ($keywords);
        $results_num = count ($results);

        $suffix = ($results_num !=1) ? 's' : '';

        echo '
 Your search for ', $keywords,' returned ',$results_num,' result',$suffix,'
';
        foreach($results as $result) {
            echo '
', $result['title'],'
', $result['description'],'...
', $result['url'],'
';
            }

    } else {
    foreach ($errors as $error) {
        echo $error, '
';
    }
        }

    }

?>

func.inc.php
   <?php
include 'db.inc.php';

function search_results($keywords) {
    $returned_results = array();
    $where ="";

    $keywords = preg_split('/[\s]+/', $keywords);
    $total_keywords = count($keywords);

    foreach ($keywords as $key=>$keyword) {
      $where .="`keywords` LIKE '%$keyword%'";
      if ($key != ($total_keywords - 1)) {
        $where .= "AND";
        }
    }

    $results = "SELECT `title`, LEFT(`description`, 70) as `description`, `url` FROM `articles` WHERE $where";
    $results_num = ($results = mysql_query($results)) ? mysql_num_rows($results): 0;

    if ($results_num === 0) {
    return false;
    } else {

    while ($results_row = mysql_fetch_assoc($results)) {
        $returned_results[] = array(
                    'title' => $results_row['title'],
                    'description' => $results_row['title'],
                    'url' => $results_row['url']

        );
    }

    return $returned_results;
}
}

?>

And i have one more question  to make a close button at the top of the Div for closing itself.

A: I'd amend the function signature to include page number and number of results per page:
function search_results($keywords,$pagenum,$resultsperpage) {

and then amend the SQL to pull out only the results for the page in question:
$startresult=($pagenum-1)*$resultsperpage;
$results = "SELECT `title`, LEFT(`description`, 70) as `description`, `url` FROM `articles` WHERE $where LIMIT $startresult,$resultsperpage";

(assuming you'd be numbering you pages starting from 1)
Then all you'd need is a list of links to let the users select their page. I normally use a GET variable for this (searchpage.php?p=1 maybe), so you'd have to sanitize that as you have done with your search terms.

A: Please not remember Likes
  <?php
    include 'func.php';
    include 'config.inc.php';
    ?>

    <form action="" method="POST">

                <input type="text" autocomplete="off" name="keywords" > <input type="submit" value="Search" />

    </form>
    <?php

    $suffix = "";
    $v='';

    if(isset($_POST['keywords'])){$v=$_POST['keywords'];}
    else{
         if(isset($_GET['q'])){$v=$_GET['q'];}

        }

    $keywords = mysql_real_escape_string (htmlentities (trim($v)));

        $errors = array();

        if (empty($keywords)) {
            $errors[] = 'Please enter a search term';
        } else if (strlen($keywords)<3) {
            $errors[] = 'Your search term must be three or more character';
        } else if (search_results($keywords) === false) {
            $errors[] = 'Your search for ' .$keywords. ' returned no result';
        }
        if (!($errors)) {
            $results = search_results($keywords);

            $results_num = count ($results);
            $suffix = ($results_num !=1) ? 's' : '';

            echo '
 Your search for ', $keywords,' returned ',$results_num,' result',$nom,'
';

            foreach($results as $result) {

                echo '
', $result['name'],'
', $result['id'],'...
', $result['message'],'
';

                   }

    if($pages>=1 && $page<=$pages){
    for($x=1;$x<=$pages;$x++){

    echo ($x==$page) ? ''.$x.' ' : ''.$x.' ';
     }
    }
         } else {
        foreach ($errors as $error) {
            echo $error, '
';
        }
            }
    ?>

func.in.php
    <?php

    function search_results($keywords) {
    global $page,$start,$pages_query,$per_page,$pages,$returned_results,$total_keywords,$nom;
        $returned_results = array();
        $where ="";

        $keywords = preg_split('/[\s]+/', $keywords);
        $total_keywords = count($keywords);

        foreach ($keywords as $key=>$keyword) {
          $where .="`message` LIKE '%$keyword%'";
          if ($key != ($total_keywords - 1)) {
            $where .= "AND";
            }
        }

    $per_page=6;
    $pages_query = mysql_query(' SELECT COUNT(`id`) FROM `paginate` ') or die(mysql_error());

    //$pages=ceil(mysql_result($pages_query,0) / $per_page);

        $resultt = "SELECT * FROM paginate WHERE $where  ";
        $queryt =mysql_query($resultt) ;
        $nom=mysql_num_rows($queryt);
    $pages=ceil($nom / $per_page);

    $page= (isset($_GET['page'])) ? (int)$_GET['page'] :1;

    $start=($page - 1) * $per_page;

        $results = "SELECT * FROM paginate WHERE $where LIMIT $start,$per_page ";
        $results_num = ($results = mysql_query($results)) ? mysql_num_rows($results): 0;

        if ($results_num === 0) {
        return false;
        } else {

        while ($results_row = mysql_fetch_assoc($results)) {
            $returned_results[] = array(
                        'id' => $results_row['id'],
                        'name' => $results_row['name'],
                        'message' => $results_row['message']

            );
        }

        return $returned_results;
    }
    }

    ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I use 'amicable' in a sentence? I've made some sentences with the word 'amicable':

An amicable family.
Our relationships are amicable.
We get on amicably.

Does it sound normal for a native English speaker?
If my sentences are wrong, please feel free to correct me.

A: The most common usage of "amicable" is to indicate that a situation is friendly and peaceable when it could easily be hostile.
Consider the example from dictionary.com:

adjective
characterized by or showing goodwill; friendly; peaceable:
an amicable settlement.

A "settlement"? This is about an argument or legal battle - something that is disagreeable.
Or if you asked someone about another person and they said:

"We are on amicable terms"

It implies a potentially conflicting relationship, although not at the moment.
The standard word "friendly" is more colloquial, and doesn't have these implications about disagreement.
The Latin-derived amicable has a literary flavor to it, and isn't frequently used in casual conversations.

An amicable family.

Doesn't sound idiomatic.

We get on amicably.

Could be a literary way to say "we are good acquaintances", as written by Mark Twain.

How do I use 'amicable' in a sentence?

Linguee offers dozens of example sentences with the target word.

The provincial commissions are the first point of appeal in case of failure to reach an amicable settlement.

d) to encourage amicable solutions with a view to obtaining voluntary payment of maintenance, where suitable by use of mediation

As mentioned above, the best interests of the child are likely to be best served if an amicable solution can be reached.


text:
Q: Is there a way to set the maximum number of message redeliveries in ActiveMQ when using the Apache.NMS libraries? I'm using Apache.NMS 1.4. I need to be able to programmatically set the maximum number of times a message can be delivered before being placed in the DLQ (Dead Letter Queue). Is there a way to do it?

A: add this to your connection string nms.RedeliveryPolicy.MaximumRedeliveries=5
Example:
tcp://localhost:61616?nms.RedeliveryPolicy.MaximumRedeliveries=5


text:
Q: How to replace deprecated control HorizontalDivider? The control sap.ui.commons.HorizontalDivider is deprecated since version 1.38 of both sapui5 and openui5. How can I replace this control?

A: To create a horizontal divider the HTML tag
 (horizontal ruler) can be displayed in an instance of sap.ui.core.HTML.
So instead of
   new sap.ui.commons.HorizontalDivider()

you can use
   new sap.ui.core.HTML({content:"
"})

to get a horizontal divider (which looks almost identical to me).


text: Q: Flipping the time axis and applying TimeDistributed RNN for preserving the spatial dimension The input shape of my Keras model is (batch_size, time_steps, spatial_dim, features), which was fed through a TimeDistributed 1D convolution with N filters. The output of the TimeDistributed convolution is (batch_size, time_steps, spatial_dim, N). I wanted to feed this output to an RNN, however, I did not want to lose the spatial_dim by flattening the last two dimensions. So I reshaped my convolution output as (batch_size, spatial_dim, time_steps, N) as an input to a TimeDistributed RNN layer. Is this valid to flip the time axis and apply TimeDistributed RNN for preserving the spatial dimension? Any other alternative to preserve the spatial_dim while applying RNN?


text:
Q: How can I remove https and http from ruby on rails I need to remove the "https" and the "http" from a url from my form in order to show the image later, I got the form where i'm including title and url like this:
Form:
<%= form_for( @article, :html => { class: "form-test", role: "form"}) do |f| %>
    <%= f.label :Titulo %>
    <%= f.text_field :title%>

    <%= f.label :Imagen%>
    <%= f.text_field :img%>

     <%= f.submit "Post"%>
<% end %>

View:

    <%= image_tag("https://#{@article.img}") %>
    <%= @article.title%>

I'am looking for option how should I remove the https I will really appreciate if you can tell me.

A: Ruby's URI maybe?
~ ᐅ irb                                                                                [ruby-2.5.3]
2.5.3 :001 > uri = URI('https://my.domain.com/my_image.png')
 => #<URI::HTTPS https://my.domain.com/my_image.png>
2.5.3 :002 > [uri.hostname, uri.path].join
 => "my.domain.com/my_image.png"

You can define a helper for that:
def url_without_scheme(url)
  uri = URI(url)
  uri.hostname + uri.path
end

View:

  <%= image_tag(url_without_scheme @article.img) %>
  <%= @article.title%>

A: Best practice is to use ruby URI so long as your string only contains a valid url.  See answer by @CAmador from which this answer evolved.  Either solution can be wrapped in a helper and used in the view.
def url_no_scheme(url)
  url = "https://foobar.com"
  uri = URI(url)
  uri.hostname + uri.path
end

url_no_scheme('https://foobar.com')
=>"foobar.com"
url_no_scheme('http://foobar.com')
=>"foobar.com"

In the view you can call the helper
<%= image_tag(url_without_scheme @article.img) %>

This might be helpful for someone looking to do this outside of rails and may have a string with multiple URLs which can be removed with a regular expression:
str = "https://foobar.com or http://foobar.com"
str.gsub(/https:\/\/|http:\/\//, "")
=> "foobar.com or foobar.com"


text:
Q: If statement for admin page How should I write if condition to display specific code only when I enter this page:
/wordpress/wp-admin/post-new.php?post_type=slideshow

This is what i was trying to get ;) Thanks to Krzysiek!
function plu_admin_enqueue($hook) {
  $screen = get_current_screen();

if ( 'post.php' == $hook && $screen->post_type == 'slideshow' ) {
      wp_enqueue_script('plupload-all');

      wp_register_script('cplupload', get_template_directory_uri() . '/js/cplupload.js', array('jquery'));
      wp_enqueue_script('cplupload');

      wp_register_style('cplupload', get_template_directory_uri() . '/css/cplupload.css');
      wp_enqueue_style('cplupload');
  };
};

add_action( 'admin_enqueue_scripts', 'plu_admin_enqueue', 10 );

A: I would use get_current_screen(); to do this. It returns a WP_Screen object.
You should remember that this function will return NULL if it's called before admin_init action.
In your case it should look like this:
$screen = get_current_screen();

if ( $screen && $screen->action == 'add'
    && $screen->base == 'post' && $screen->post_type == 'slideshow' ) {
    // do your stuff
}

A: I believe you want to show a sub menu to the custom post types use the add_submenu_page for this.
Here is the example for your code
add_submenu_page('edit.php?post_type=slideshow','page_title','menu_title','capability','menu_slug','function_example');

function function_example ()
{
//here you put your code in order to apper in the sub menu

}

Hope this will help:)


text:
Q: Middleman permalink end with slash error I use Middleman for blogging with Gemfile
gem "middleman", "~> 3.3.6"
gem "middleman-blog", "~> 3.5.3"

I want to config Middleman permalink end with slash.
My configuration config.rb
activate :blog do |blog|
    blog.permalink = "{year}/{month}/{day}/{title}/"
    blog.default_extension = ".markdown"
end

When I run command middleman or middleman server, It work perfect! I can link to localhost:4567/2014/11/03/my-article/
The problem is when I create middleman build and try to run command on build folder
python3 -m http.server 9999
when link to article, error file not found,  404 - Nothing matches the given URI. but file already exist when I open folder

How to matches URI end with slash instead of file extension (.html)?
Note:  If I config permalink end with .html, It's OK.
activate :blog do |blog|
    blog.permalink = "{year}/{month}/{day}/{title}.html"
    blog.default_extension = ".markdown"
end

A: From memory you need to enable active directory_indexes if you want to have Pretty URLs.
Try
activate :blog do |blog|
    blog.permalink = "{year}/{month}/{day}/{title}/"
    blog.default_extension = ".markdown"
end
activate :directory_indexes

If that doesn't work try putting the {title}.html back in permalink


text:
Q: LSTM **kwargs understanding python I made a LSTM based model for disease forecasting a few months back and I am now writing my work. I used Functional API. I followed a tutorial but they didn't mentioned about it. I understand most of LSTM parameters but failed to understand the following:
lstm_kwargs = {'dropout': 0.20, 'recurrent_dropout': 0.1, 'return_sequences': True, 'implementation': 2}
lstm1 = LSTM(200, name='lstm1', **lstm_kwargs)(input_layer)

The only problem is the 'implementation': 2. What does implementation means here?
Regards.


text:
Q: Overdispersion in logistic model I'm relatively a newbie in R, and I've been trying to make a silly example of logistic regression to predict, according to Age and Sex whether someone dies of corona or not. I'm from Colombia, so my data is from here. The thing is, when I check the model, I find a super-duper over dispersion when comparing deviance, pearson statistics and residual degrees of fredom:
> c(deviance(muertecovid), sum(resid(muertecovid, type = "pearson")^2) ,df.residual(muertecovid))`

[1]  889.5579 1305.8099  176.0000
I made two models, one with binomial distribution (using logit, the canonical link function), an another with the quasibinomial one. From both, I get the same above results. The link for my data in this :
https://docs.google.com/spreadsheets/d/1CDiBclH6I1UZFSZR1BwS9E1qpUXdPbxseepgUkmKyxw/edit?usp=sharing
This are the models:
muertecovid = glm(Proporcion_m ~ Edad * Sexo, family = binomial, weights = Total, data = FinalCovid)
muertecovid_quasi = glm(Proporcion_m ~ Edad * Sexo, family = quasibinomial, weights = Total, data = FinalCovid)

I made a plot of qresiduals vs fitted values:

Please help me wit this, and If you need anything from my code tell me. This might be a silly thing, but you know, we learn from mistakes :)


text:
Q: Creating dataframe from dict inside dict with new column names I have a dictionary which looks something like:
dictionary = {'A' : {'a': 2,
                     'b': 3,
                     'c': 4},

              'B' : {'a': 4,
                     'd': 3,
                     'e': 3}}

I want to create a dataframe that looks like,
   P1   P2   P3
0  A    a     2
1  A    b     3
2  A    c     4
3  B    a     4
4  B    d     3
5  B    e     3

I want to have the keys of first dictionary as one column and keys and values of the inner dictionary as second and third column respectively with new column names.

A: Use from_dict, stack and sort_values:
(pd.DataFrame.from_dict(dictionary)
            .stack()
            .reset_index()
            .set_axis(['P2','P1','P3'], axis=1, inplace=False)
            .sort_values(['P1','P2'])
            .sort_index(1))

Output:
  P1 P2   P3
0  A  a  2.0
2  A  b  3.0
3  A  c  4.0
1  B  a  4.0
4  B  d  3.0
5  B  e  3.0

A: Convert your nested dict into a list of lists before you create the data frame:
>>> pd.DataFrame([[k, kk, vv] for k, v in dictionary.items() for kk, vv in v.items()],
                  columns=['P1', 'P2', 'P3'])

  P1 P2  P3
0  A  a   2
1  A  b   3
2  A  c   4
3  B  a   4
4  B  d   3
5  B  e   3

A: Using pd.Serise
pd.Series(d).apply(pd.Series).stack().reset_index()
Out[464]:
  level_0 level_1    0
0       A       a  2.0
1       A       b  3.0
2       A       c  4.0
3       B       a  4.0
4       B       d  3.0
5       B       e  3.0

A: My answer is very similar to Scott's, however like we both mentioned in the comments, if you do not have version 0.21.0+ you will receive TypeError: set_axis() got multiple values for argument 'axis'. Below is my solution that is working on 0.20.2
pd.DataFrame.from_dict(dictionary).stack().sort_values()\ #original read and stack
.reset_index()\ #reseting the index
.sort_values(['level_1', 'level_0'])\ #sorting the values based on your needed ouput
.rename(index=str, columns={'level_0': 'P2', 'level_1' : 'P1', 0:'P3'})\ #renaming the columns
.reindex_axis(axis = 1, labels=['P1', 'P2','P3']) #putting the columns in correct order

    P1  P2  P3
0   A   a   2.0
1   A   b   3.0
5   A   c   4.0
4   B   a   4.0
2   B   d   3.0
3   B   e   3.0


text:
Q: Create Spark UDF of a function that depends on other resources I have a code for tokenizing a string.
But that tokenization method uses some data which is loaded when my application starts.
val stopwords = getStopwords();

val tokens = tokenize("hello i am good",stopwords)

def tokenize(string:String,stopwords: List[String]) : List[String] = {

   val splitted = string.split(" ")

   // I use this stopwords for filtering my splitted array.
   // Then i return the items back.

}

Now I want to make the tokenize method an UDF for Spark.I want to use it to create new column in DataFrame Transformations.
I created simple UDFs before which had no dependencies like it needs items that needs to be read from text file etc.
Can some one tell me how to do these kind of operation?

This is what I have tried ,and its working.

      val moviesDF = Seq(
        ("kingdomofheaven"),
        ("enemyatthegates"),
        ("salesinfointheyearofdecember"),
      ).toDF("column_name")

      val tokenizeUDF: UserDefinedFunction = udf(tokenize(_: String): List[String])

      moviesDF.withColumn("tokenized", tokenizeUDF(col("column_name"))).show(100, false)

      def tokenize(name: String): List[String] = {

        val wordFreqMap: Map[String, Double] = DataProviderUtil.getWordFreqMap()
        val stopWords: Set[String] = DataProviderUtil.getStopWordSet()
        val maxLengthWord: Int = wordFreqMap.keys.maxBy(_.length).length

        .................
        .................
      }

Its giving me the expected output:
+----------------------------+--------------------------+
|columnname                  |tokenized                 |
+----------------------------+--------------------------+
|kingdomofheaven             |[kingdom, heaven]         |
|enemyatthegates             |[enemi, gate]             |
|salesinfointheyearofdecember|[sale, info, year, decemb]|
+----------------------------+--------------------------+

Now my question is , will it work when its deployed ? Currently I am
running it locally. My main concern it that this function reads from a
file to get information like stopwords,wordfreq etc for making the
tokenization possible. So registering it like this will work properly
?

A: At this point, if you deploy this code Spark will try to serialize your DataProviderUtil, you would need to mark as serializable that class. Another possibility is to declare you logic inside an Object. Functions inside objects are considered static functions and they are not serialized.


text:
Q: Angular 7 - ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forEach' of undefined When I set the animations inside my component.ts I do not get any errors. But when exporting animations to a separate file I get the error shown below.
animations.ts
import { trigger, state, transition, style, animation, animate } from '@angular/animations';

export const transAnimation = animation([
  trigger('fade', [
    state('void', style({ opacity: 0 })),
    transition(':enter', [
      animate(300)
    ])
  ]),
  trigger('fadeOut', [
    state('void', style({ opacity: 0 })),
    transition(':leave', [
      animate(300)
    ])
  ]),
  trigger('shake', [
    state('false', style({ transform: 'translateX(10px)' })),
    transition('0 => 1', [
      animate(300)
    ])
  ]),
  trigger('slideIn', [
    state('void', style({ transform: 'translateX(10px)' })),
    transition(':enter', [
      animate(300)
    ])
  ]),
  trigger('hideShow', [
    state('false', style({ opacity: 0 })),
    transition('0 => 1', animate(300)),
  ])
]);

component.ts
import { transAnimation } from '../../animations';
[enter image description here][1]
@Component({
  selector: 'app-card-update',
  templateUrl: './card-update.component.html',
  styleUrls: ['./card-update.component.scss'],
  animations: [transAnimation]
})

A: The problem was I was exporting an array. When exporting each trigger separately it works!


text:
Q: filters not working on specific workspace rally I have two workspaces
When I load my application on one workspace it works with the filters but when I use same code it doesn't work.
Then I tried commenting out filters then it gave me whole records. Not able to figure what's the difference,
I am using Rally sdk2.0rc3
below are my code snippet
this._startDate value is 2014-09-10
this._endDate value is 2015-03-03
and when I print operation it gives false
and iterations = []
@nickm help me
            _onDataLoaded: function() {
                console.log("this.getContext().getProject()._ref", this.getContext().getProject()._ref);
                console.log("this._startDate", this._startDate);
                console.log("this._endDate", this._endDate);
                var project_oid = this.getContext().getProject()._ref;

                var startDateFilter = Ext.create('Rally.data.QueryFilter', {
                    property: 'StartDate',
                    operator: '>',
                    value: this._startDate
                });
                startDateFilter = startDateFilter.and({
                    property: 'StartDate',
                    operator: '<',
                    value: this._endDate
                });
                startDateFilter = startDateFilter.and({
                    property: 'StartDate',
                    operator: '!=',
                    value: null
                });
                var endDateFilter = Ext.create('Rally.data.QueryFilter', {
                    property: 'EndDate',
                    operator: '<',
                    value: this._endDate
                });
                endDateFilter = endDateFilter.and({
                    property: 'EndDate',
                    operator: '>',
                    value: this._startDate
                });
                endDateFilter = endDateFilter.and({
                    property: 'EndDate',
                    operator: '!=',
                    value: null
                });
                var filter = startDateFilter.or(endDateFilter);
                //filter.toString();
                Ext.create('Rally.data.WsapiDataStore', {
                    model: 'Iteration',
                    limit: Infinity,
                    context: {
                        project: project_oid,
                        projectScopeDown: true,
                        projectScopeUp: false
                    },
                    fetch: ['Name','Project', 'StartDate', 'EndDate', 'Parent', 'Children'],
                    autoLoad: true,
                    filters: [
                        filter
                    ],
                    listeners: {
                        load: this._loadGrid,
                        scope:this
                    }
                }, this);
            },
            _loadGrid: function(store, iterations, operation) {
                console.log("hi there", operation);

A: My first guess was that if the same code works in one workspace and does not work in another workspace, and the culprit is the filter based on date values, check if your workspaces have different date format. For example like this:

or like this:

But I tested '2015-02-06' value in a workspace that using mm/dd/yyyy format and it worked.
In any case, if it works in one workspace and does not work in another chances are this is not an issue with the code but with the data. Maybe in the second workspace the same query returns 0 results. Also, depending on the meaning of the dates used in code, it is possible to avoid hard-coding dates. For example, to get current iteration try this:
var today = new Date().toISOString();
filters: [
                {
                    property: 'StartDate',
                    operator: '<=',
                    value: today
                },
                {
                    property: 'EndDate',
                    operator: '>=',
                    value: today
                }
            ]


text:
Q: Using mongodb, how can you get the dates that have an item value of 0 to still be displayed I'm creating a dashboard using mongodb. I want to have a line graph that shows the dates along with the number of orders per a day. As of right now, I am able to get the graph to display the dates when the orders were made and the number of orders, but I would like to be able to see the dates in between these dates when the number of orders is 0. Below, I have included what I currently have. I would really appreciate any help or guidance on how to do this. Thank you!
const dailyOrders = await Order.aggregate([
      {
        $group: {
          _id: { $dateToString: { format: '%m-%d-%Y', date: '$createdAt' } },
          orders: { $sum: 1},
        },
      },
      { $sort: { _id: 1 } },
    ]);


text:
Q: How can I use a cursor with a common table expression in SQL Server 2005 I have a cursor in need to use with a CTE and I'm getting an error every time I run it.
DECLARE @retVal VARCHAR(max),
        @curDist VARCHAR(3),
        @curDealer VARCHAR(6)
        @dist VARCHAR(3)
SET @dist='304';

WITH dist (DSCD,PREV_DSCD,level) AS (

    SELECT d.DSCD,d.PREV_DSCD, 0 AS level FROM scdst AS d WHERE d.DSCD = @dist
    UNION ALL
    SELECT d.DSCD,d.PREV_DSCD, level + 1 FROM scdst AS d
    INNER JOIN dist AS d2 ON d.DSCD=d2.PREV_DSCD
)

DECLARE distListCursor CURSOR FOR SELECT DSCD FROM dist

OPEN distListCursor
FETCH NEXT from distListCursor INTO @curDist

Error message:

Msg 156, Level 15, State 1, Line 17
  Incorrect syntax near the keyword 'DECLARE'.

I've used this recursive CTE before but never with a cursor, what am I doing wrong?
Thanks.


text:
Q: Set Y-axis grid density in Rickshaw.js
I have a graph detailing wind speeds where I would like to have the grid on the Y axis have ticks every 5 (m/s).
How do I set the density of the Y axis grid?
// triggered when data has been loaded via ajax
$graph.on('graph.render', function(e, d) {
    var graph, y_axis;

    // Fixtures
    palette = new Rickshaw.Color.Palette();

    graph = new Rickshaw.Graph( {
        element: $graph.find('.chart');
        width: $graph.innerWidth() - 20,
        height: $graph.innerHeight() - 20,
        series: [
            {
                key: 'min',
                name: 'Min Wind Speed',
                color: palette.color(),
                data: d[0].data
            } // ...
        ]
    });

    x_axis = new Rickshaw.Graph.Axis.Time({
        graph: graph,
        timeUnit: {
            seconds: 600,
            formatter: function(d) {
                return d.toUTCString().match(/(\d+:\d+):/)[1];
            }
        }
    });

    y_axis = new Rickshaw.Graph.Axis.Y( {
        graph: graph,
        orientation: 'left',
        element: $graph.find('.y-axis')
    });
});

A: You could set the number of  ticks via ticks or the values to display via tickValues explicitly:
var yAxis = new Rickshaw.Graph.Axis.Y( {
  graph: graph,
  tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
  //ticks: 5, //static number of ticks, only works
  tickValues: [50,100,150,200,250,300,350], // values to use/display
  element: document.getElementById('y_axis')
} );

You would use either ticks or tickValues, not both. If you use tickValues as above and your max y value is 180, the y-scale would only show the values [50,100,150,200], 250 and above would not be shown. If you add more data with a higher y-value, the scale would automatically re-scale and show the higher values as specified by you.
More information about ticks and tickValues can be found at the D3's SVG axes page.


text:
Q: How would I convert a set of Styles to DataTemplates for an enum type? Currently we have an enum type where each unique value is being represented by a unique style:
<Style x:Key="EnumValue1" TargetType="CheckBox">
<Setter Property="FontSize" Value="11" />
<Setter Property="Margin" Value="0 0 1 0" />
<Setter Property="VerticalAlignment" Value="Top" />
<Setter Property="Height" Value="18" />
<!-- ... common property setters etc. -->

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="CheckBox">
            <Border>
                <StackPanel>
                    <!-- custom enum value-specific control content -->
                    <ContentPresenter Content="{TemplateBinding Content}" />
                </StackPanel>
            </Border>
            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Trigger.Setters>
                        <Setter Property="Foreground" Value="WhiteSmoke" />
                    </Trigger.Setters>
                </Trigger>
                   <!-- ... custom triggers etc ... -->
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Setter.Value>
</Setter>
</Style>

Currently the Checkboxes are being created programmatically in code-behind - I'm changing this to a ListBox bound to a collection of these enum values and I think it makes sense to convert these to a DataTemplate instead - question is, how do I maximize re-use?
I have roughly 10 unique values and 10 unique styles ...9/10 of the styles use the same Setters, the ControlTemplate.Triggers are the same for all 10 but obviously the visual tree in the ControlTemplate is different
I thought about using a base Style class and having each specific-variant derive / override it with another Style and use a StyleSelector, but then how would I vary the ControlTemplate visual tree per style without having to re-define the triggers?
But this seems 'philosophically' wrong ...I feel like I should be using DataTemplates, because this is by definition what they're meant to be use for

A: Can you create a ValueConverter that evaluates the enum value and returns the appropriate template?
public enum TemplateEnum
{
    firstValue,
    secondValue
}

public class TemplateConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {

        var templateEnum = (TemplateEnum)value;
        switch (templateEnum)
        {
            case TemplateEnum.firstValue:
                return Application.Current.Resources["FirstValueTemplate"];
            case TemplateEnum.secondValue:
                return Application.Current.Resources["SecondValueTemplate"];
            default:
                return null;
        }
    }
}

<ContentPresenter Content="{Binding EnumVal, Converter={x:Static local:Converters.templateConverter}}" />


text:
Q: Can ∅, as being an element of a set, be handled as any other element? I know that by definition, ∅ is a subset of every set but I have a doubt about it appearing as an explicit element of a set. In a union between sets and the finding of the Power of that set, can it be handled as any other normal element?
Eg.:
Set A={∅, {∅}}, P(A) = {∅, {∅}, {{∅}} {∅,{∅}}};
{∅}U{{∅}}={∅,{∅}}?
Edit: the question was edited to make it a little more usefull for other people, if any other editions are necessary, feel free.

A: When you speak about "contained in" there's a risk of confusion, because this language doesn't distinguish reliably between "is an element of" and "is a subset of", which are entirely different concepts. In many cases, the types of things can help disambiguate -- if you see "$A$ is contained in $B$" and you already know $A$ and $B$ as sets of real numbers, you can conclude that "subset" is what was meant. Conversely if you know $A$ as a single number and $B$ as a set of number, it's a safe bet that "element" was meant. But when you're talking about pure untyped set theory, "contained in" is ambiguous language and should be avoided.
The empty set as a member of another set works just like any other mathematical object.
So $\{\varnothing\}\cup\{\{\varnothing\}\} = \{\varnothing,\{\varnothing\}\}$, simply because $\varnothing$ and $\{\varnothing\}$ are all the elements of $\{\varnothing\}$ and $\{\{\varnothing\}\}$.
However, you're missing an element of $\mathcal P(A)$, it should be
$$\mathcal P(\{\varnothing,\{\varnothing\}\}) = \{\varnothing, \{\varnothing\}, \{\{\varnothing\}\}, \{\varnothing,\{\varnothing\}\}\} $$

A: First of all it is not true, that $\emptyset$ is contained in every set. Counterexample is $A=\{1\}$, then $\emptyset \notin A$, even is we write $1$ into the form $1=\{ \emptyset \}.$
Your example is also wrong. Let $A=\{ \emptyset, \{ \emptyset \} \}$, then $\wp\left(A\right) = \left\{ \emptyset, \{ \emptyset \}, \{ \{ \emptyset \} \}, \{ \emptyset,  \{ \emptyset \} \} \right\} $. In general if $A$ is a finite set and the cardinality of $A$ is $n$, then $\wp(A)$ has $2^n$ elements. And your example has $3$ elements not $4$ so even because of that it couldn't be correct.
And to answer you question. Yes,
$$\{ \emptyset \} \cup \{ \{ \emptyset \} \} = \left\{ \emptyset, \{ \emptyset \} \right\}.$$


text:
Q: Get the created file ID - Google Drive API Flutter Yesterday I implemented functionality to backup the data to Google Drive using a Flutter app. Everything worked correctly, except the part where I've to get the ID of the uploaded File.
This is the function which uploads a given File, situated at this path
Future<dynamic> gDriveFileCreator(googledrive.DriveApi drive,
      googledrive.File fileToUpload, String path) async {
    File file = File(path);
    fileToUpload.name = p.basename(file.absolute.path);
    var response = await drive.files.create(
      fileToUpload,
      uploadMedia: googledrive.Media(file.openRead(), file.lengthSync()),
    );
    return response;
  }

This is how I trigger this function :
responsePdfUpload =
              await gDriveFileCreator(drive, fileToUpload, pdfPath!);

Now, It works like a charm. My next requirement is to get the ID and store it in the local DB. However, when I try to get the ID from responsePdfUpload by doing : responsePdfUpload.getId(), It throws an exception stating "Class 'File' has no instance method 'getId'".
Any idea what I'm doing wrong? Or is there another way to get the ID from the File that google Drive returned ? As far as I know, the same method was working without any issues until yesterday.
I also debugged and I am indeed getting an id in the response.

Can somebody please help me here?


text:
Q: Coordinator layout, нижний слой налазит на верхний Есть Coordinator layout в котором 3 элемента
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"/>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/main_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_tab">
    </FrameLayout>

    <android.support.design.widget.TabLayout
        android:id="@+id/bottom_tab"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="bottom"
        app:tabIndicatorColor="@color/colorAccent"
        app:tabIndicatorHeight="?attr/actionBarSize"
        android:background="@color/white">

    </android.support.design.widget.TabLayout>
</android.support.design.widget.CoordinatorLayout>

FrameLayout отрисовывается поверх toolbar, а TabLayout поверх FrameLayout, а нужно что бы FrameLayout был между toolbar и TabLayout, что бы FrameLayout ничто не перекрывало и он ничто не перекрывал. Как это сделать?
Нужно именно в CoordinatorLayout.

A: Попробуйте FrameLayout прописать поведение стандартное:
app:layout_behavior="@string/appbar_scrolling_view_behavior">


text:
Q: Function with multiple columns to get one output I want to write a function that will classify each row based on the values within three columns as either poor, medium or good
Here is example data
C = c(1, 0.4, 3, 6, 2)
N = c(0.1, 3, 5, 7, 13)
P = c(2, 3, 3, 4, 2)

mydf = data.frame(C,N,P)

Lets say I want to classify all things with C < 0.5 as poor, regardless of N or P. Likewise for all values of N > 10
Any values with C such that 1 < C < 4, and P such that 1 < P < 4 are classified as good
Everything else is classified as medium
Currently I have used a several if functions that checks for each condition at a time and then a final function to see if all required conditions are good then the final classification is good, if there any that are poor then its poor, otherwise medium.
Instead I would like a way to do it all in one function because I have to expand it to many more conditions (20+). I have tried using the ifelse function but I couldn't really figure it out
If there are any good sources to read about such functions I appreciate any input, thanks

A: Try:
> mydf$result = with(mydf, ifelse(C<0.5 | N>10, 'poor',ifelse(C<4 & C>1 & P>1 & P<4, 'good', 'medium')))
>
> mydf
    C    N P result
1 1.0  0.1 2 medium
2 0.4  3.0 3   poor
3 3.0  5.0 3   good
4 6.0  7.0 4 medium
5 2.0 13.0 2   poor

To create a function:
myfn = function(ddf){
    ddf$res = with(ddf, ifelse(C<0.5 | N>10, 'poor',ifelse(C<4 & C>1 & P>1 & P<4, 'good', 'medium')))
    ddf
}

To write ifelse repeatedly:
ddf$res = with(ddf, ifelse(C<0.5 | N>10, 'poor',
                    ifelse(C<4 & C>1 & P>1 & P<4, 'good',
                        'medium'
                    ))  # number of these closing brackets should be same as number of 'ifelse'
                    )  # this closing bracket is for 'with' function


text:
Q: Upgrade failed- forbidden downloading I use proxy to connect to the Internet. I am trying to upgrade to 12.10. The problem is that some(nearly all) packages are downloaded but some 3 Mb data is not downloading, due to which the upgradation aborts reporting a forbidden error. These are some files related to gnome-games and facebook integration. Facebook is blocked on the proxy server which i am using, so i guess the error appears due to that. I want to ask if there is any way i can skip downloading the last 3 Mb packages(which i don't need) so that my upgradation continues to Ubuntu 12.10?
This is the error i am getting:
Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/g/gnome-games/gnomine_3.6.0.2-0ubuntu1.2_i386.deb 403  Forbidden
Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/g/gnome-games/mahjongg_3.6.0.2-0ubuntu1.2_all.deb 403  Forbidden
Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/g/gnome-games/gnome-mahjongg_3.6.0.2-0ubuntu1.2_i386.deb 403  Forbidden
Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/g/gnome-games/gnome-sudoku_3.6.0.2-0ubuntu1.2_all.deb 403  Forbidden
Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/g/gnome-games/gnome-games-data_3.6.0.2-0ubuntu1.2_all.deb 403  Forbidden
Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/a/account-plugins/account-plugin-facebook_0.8-0ubuntu2_i386.deb 403  Forbidden
Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/g/gwibber/gwibber-service-facebook_3.6.0-0ubuntu1.1_all.deb 403  Forbidden

A: If you don't want to upgrade/install those packages, is actually very easy. If you don't use them just uninstall them:
sudo apt-get remove <packages to remove>

To prevent that they try to get installed/upgraded you could put them on hold:
echo <package> hold | sudo dpkg --set-selections


text:
Q: xlwings error using caller from excel I am trying to call python code from excel using
wb = xw.Book.caller()

If file path is in English, it works. However, if the path has other language, it raise below Error popup
---------------------------
Error
---------------------------
C:\Anaconda2\lib\site-packages\xlwings\main.py:2692: UnicodeWarning: Unicode unequal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

  throw = (os.path.normpath(os.path.realpath(impl.fullname.lower())) != os.path.normpath(fullname.lower()))

Traceback (most recent call last):

  File "<string>", line 1, in <module>

  File "test.py", line 13, in plot_chart

    wb = xw.Book.caller()

  File "C:\Anaconda2\lib\site-packages\xlwings\main.py", line 545, in caller

    return cls(impl=app.books.open(fullname).impl)

  File "C:\Anaconda2\lib\site-packages\xlwings\main.py", line 2695, in open

    "Cannot open two workbooks named '%s', even if they are saved in different locations." % name

ValueError: Cannot open two workbooks named 'test.xlsm', even if they are saved in different locations.

Guess this has something to do with unicode problem. I did not have this kind of problem with previous version. (e.g. 0.6 or 0.7) This is new problem after I updated to version 0.9.2.
Thank you for any help
p.s. I am using Python 2.7

A: xlwings version 0.9.3 solve above problem. Self closing the question.


text:
Q: Eliminate a directory in the URL and redirect? I want to redirect all instances of:
http://example.com/projects/title-of-project

To:
http://example.com/title-of-project

How would I do this?
htaccess
# WordPress
<IfModule mod_rewrite.c>

RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
</IfModule>

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
</IfModule>

# END WordPress

RewriteEngine On
RewriteRule ^projects/(.*)$ /$1 [R=301,L]

A: You can put this code in your htaccess (in root folder)
# BEGIN WordPress
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /wordpress/

  RewriteRule ^projects/(.*)$ $1 [R=301,L]
  RewriteRule ^index\.php$ - [L]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^ index.php [L]
</IfModule>
# END WordPress

Make sure mod_rewrite is enabled (and htaccess files allowed)


text:
Q: Handling a string from text file and continue with java program The Text file:
9310,12,120,2,1
9333,12,120,2,1
PRINT
9533,5,45,0,0
8573,10,120,1,0
6343,6,18,170,0
PRINT
9311,12,120,2,1
3343,7,20,220,0

Code
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
i mport java.util.Comparator;
import java.util.List;

public class FantasyPlayers {

    int player_ID;
    int total_score;

    public FantasyPlayers(int player, int total) {
        player_ID = player;
        total_score = total;
    }

    public String toString() {
        return player_ID + "," + total_score;
    }

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        FileInputStream fstream = new FileInputStream("Stats.txt");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        String delims = "[,]";
        List<FantasyPlayers> Stats = new ArrayList<FantasyPlayers>();
        int a = 2;
        int b = 1;
        int c = 6;
        int d = -1;
        for (String line; (line = br.readLine()) != null;)
        {
            String[] parsedData = line.split(delims);
            if (line != "PRINT")
            {
            int score = Integer.parseInt(parsedData[1])*a + Integer.parseInt(parsedData[2])*b +  Integer.parseInt(parsedData[3])*c + Integer.parseInt(parsedData[4])*d ;
            Stats.add(new FantasyPlayers(Integer.parseInt(parsedData[0]), score));
            }
            else
                continue;
        }
        br.close();

        System.out.println("Unordered");
        for (FantasyPlayers str : Stats)
        {
                System.out.println(str);
        }
        Collections.sort(Stats, new Comparator<FantasyPlayers>()
            {
            public int compare(FantasyPlayers one, FantasyPlayers two)
            {
                if (one.total_score == two.total_score){
                    Integer playerOne = one.player_ID;
                    Integer playerTwo = two.player_ID;

                    return playerTwo.compareTo(playerOne);
                }
                Integer scoreOne = one.total_score;
                    Integer scoreTwo = two.total_score;

                return scoreTwo.compareTo(scoreOne);
                }
        });
        System.out.println("Ordered");
        for (FantasyPlayers str : Stats)
        {
            System.out.println(str);
        }

     }

}

I Keep getting the Error ArrayIndexOutOfBoundsException:1 at the int score = location.
My question is how do I handle the PRINT statements in the code...I'm able to do what I want with the data but I need the logic to do something when I read in the print statement. Any suggestions?

A: You, my friend has fallen for the most common java mistakes....
try this
   if (!line.equalsIgnoreCase("PRINT"))

A: Try to change this line
String delims = "[,]";

to
String delims = ",";

and this line
line != "PRINT"

to
!line.trim().equals("PRINT")


text:
Q: Chef - Notify an execute before resource I have a simple execute[apt-update] resource in an apt recipe:
execute "apt-update" do
  command "apt-get update"
  action :nothing
end

And I want to be able to notify it, only if a package needs to be installed. I was hoping for something like:
include_recipe "apt"

package "openssh-server" do
  action :install
  notifies :run, 'execute[apt-update]', :before
end

The :before isn't currently a valid timing, and probably wont be any time soon
It's something that is possible with Puppet, and was wondering if I'm missing something simple.

A: Keeping the APT Cache Up-to-Date
While this is not an answer to your question, I can hopefully provide you an answer to your actual problem (which is a pretty common one btw.):
The apt cookbook that you should include in your run list before you use the package resource will automatically pull the repos.
In order to avoid pulling repos during every chef run, it by default pulls them only once per day, while this minimum delay can be configured via node['apt']['periodic_update_min_delay'].
Therefore, at least for the use cases I had during the last years with Chef, I think I never needed to notify a resource doing apt-get update. Even when adding an additional apt repository, this can easily be done as follows:
apt_repository 'security-ubuntu-multiverse' do
  uri        'http://security.ubuntu.com/ubuntu'
  distribution 'trusty-security'
  components ['multiverse']
  deb_src 'true'
 end

The clever thing with the apt_repository resource is that it automatically triggers an apt-get update run.
The Smell of Triggering a Resource To Run Before
(Added with permission from original Author, contributed by @Tensibai)
On why a :before is a false 'good idea' 99% of the time:
When you think about it on an isolated package install, it sounds the way to go, ask the package to notify an execute to run apt-get update before.
Now when you extend this to N packages (in 1 or more recipes), you will wish to ensure apt-get update has been run before each package if it has to be installed.
Here's come the dragons, how many time would we call apt-get update ? with a straight :before, :immediately it will be called N times, once before each package, that's silly but could be your wish.
You may object it should be done only once, and as :delayed it should be queued up, but when ? At compile time we don't know if the package will need to be installed or not, this suppose adding a new 'compile' phase to test those resources and build the 'pre-notification' queue.
That's part of what Puppet does, and where it comes a problem when you wish complete control over execution order.
More details on this here
The New :immediately_before Resource
Now I said why it should be used sparingly, here the good news:
A new :immediately_before is on its way into chef in a near future per rfc-154 and this PR

A: The functionality in question was added in Chef 12.6:
https://docs.chef.io/release_notes.html#what-s-new-in-12-6
So you can write code exactly like you pasted above now.


text:
Q: looping all user in list and check the logged user then hides the delete button using ejs I am using NodeJS with ejs Templates and mongoDB. I created an ejs which can print a table dynamically which represents a table in the Database and add buttons now I tried to hide the delete button of current logged user but it hides all the delete button of other users that are not logged in
The Code looks like this:
<% users.forEach( (user) => { %>

            <%= user.fullName %>
            <%= user.email %>

                Edit |
                <% if(user.userEmail !== user.email) { %>
                Delete
                <% } %>

<% }) %>

is there way that I can fix this.
Thank you


text:
Q: How to generate a data sample along a annulus (between fixed radii)? I would like to create a random data sample to test a clustering algorithm using python. One specific data sample I would like to generate consists of two non-overlapping annuluses (annuli?); however, it's okay if the inner-most annuli is a circle - as in the image below (taken from this question).

I realize that I can sample N values of angles ti such that 0 ≤ ti ≤ 2 pi. Based on some reading online, I think one can generate N samples of circular data by specifying a fixed radius r such that xi = r cos(ti) and yi = r sin(ti). Applying this reasoning to the desired annulus, I am thinking one can repeat the process for variable radii rmin and rmax; however, I am not sure how to proceed from this point. My thinking is to generate n samples of radii ri (where n < N, the annulus cluster is a subset of all the data) such that rmin ≤ ri ≤ rmax; doing so necessarily means the first cluster should be the n points within the the outer-most annulus and the second cluster should be the N-n points within the inner-most annulus/circle.
So my questions are as follows:
1) Is my approach so far reasonable? Are there (dis)advantages to this approach, such as clustering more near centers or borders?
2) If my approach is wrong, why is it wrong and what would be a better approach?
EDIT:
The original post that serves as a potential duplicate actually shows how to sample points within a circle, not an annulus. I am concerned with the case of an annulus.

A: Your approach will suffer from the problem the poster in the proposed duplicate pointed out, with a higher density near the center than near the outer boundary. This will afflict both the annulus and the disk, but more so the disk.
whuber's answer in the proposed duplicate directly gives you the disk part, and by constraining the part where rho is generated, you get the annulus. Note that you need to constrain "on the square root scale".
Here is an adoption of whuber's original R code, which should be easy to translate to Python:
outer_radius <- 1
inner_radius <- 0.7
n <- 1e4
rho <- sqrt(runif(n,inner_radius^2,outer_radius^2))
theta <- runif(n, 0, 2*pi)
x <- rho * cos(theta)
y <- rho * sin(theta)
plot(x, y, pch=19, cex=0.6, col="#00000020")


text:
Q: Inverse limit and union of $\mathbb{Z} / p^{n}\mathbb{Z} $ Let $p$ be a prime number and let the natural embeddings $\mathbb{Z}/p\mathbb{Z} \subset \mathbb{Z}/p^{2}\mathbb{Z} \subset  \dots \subset \mathbb{Z}/p^n\mathbb{Z} \subset  \dots $
Questions: Does the object $\bigcup_n \mathbb{Z}/p^n\mathbb{Z}$  make sense?
If so, what's the difference with the inverse limit $\varprojlim \mathbb{Z}/p^n\mathbb{Z} =: \mathbb{Z}_p$ (the $p$-adic integers)?

A: The object $\bigcup_n \mathbb{Z}/p^n\mathbb{Z}$ is the colimit of the sequence
$\mathbb{Z}/p\mathbb{Z} \hookrightarrow \mathbb{Z}/p^2\mathbb{Z} \hookrightarrow \cdots$
where the maps are given by multiplication by $p$. This is known as the Prüfer $p$-group (see nLab). On the other hand, the $p$-adic integers $\mathbb{Z}_p$ are the limit of the inverse system
$\mathbb{Z}/p\mathbb{Z} \leftarrow \mathbb{Z}/p^2\mathbb{Z} \leftarrow \cdots$
where the transition maps are given by taking residue classes.
Wikipedia claims that the ring of endomorphisms of the Prüfer $p$-group is given by $\mathbb{Z}_p$ (see here).


text:
Q: My images table has a category field. Should I have the Id or the name of the category in that field? I'm not sure whether to use the Id or the name of the category. I think using the Id is the convention but I wasn't too sure so I decided to ask here.

A: Yeah sure you must add id(int) for joins purpose.


text:
Q: Html tags inside strings.xml is not working with Kotlin While trying to define the text color in strings file like below it is working fine using java
<string name="price_value">Rp %1$s (-%2$s) </string>

and the above string is getting used like this in my java code:
Html.fromHtml(String.format(
              getString(R.string.price_value),
              price,
              discount + "%"
            ));

But the same string is not working with Kotlin. Below is the code for Kotlin
Html.fromHtml(String.format(
              getString(R.string.price_value),
              price,
              discount + "%"
            ))

This string was supposed to change the color of 2nd dynamic parameter but it's only working in java but Kotlin it's not changing the color.
So can someone please tell that why is it not working with Kotlin?
I asked the same question on Kotlin Discussion page also, but did not get any answer there.
https://discuss.kotlinlang.org/t/html-tags-inside-strings-xml-is-not-working-with-kotlin/7739

A: Im not sure 100% sure this is what you wanted. But this will make the second parameter red.
var tekst = Html.fromHtml(String.format(
                getString(R.string.price_value),
                100,
                ""+10 + "%"
        ))

        tv_textview.text = tekst

Above results in the tekst: "Rp 100 (-10%)" with (-10%) in red.


text:
Q: Showing that if $F\subset X,F\in Ba(X)$ is closed, $A\subseteq F$ implies $A\in Ba(F)\iff A\in Ba(X)$ - important for Baire regularity $\newcommand{\ba}{\mathcal{Ba}}$I understand that there are different used definitions, so here are mine:

The Baire $\sigma$-algebra $\ba(X)$ on a topological space, $X$, is the smallest $\sigma$-algebra on $X$ for which all the compactly supported continuous real valued functions on $X$, $C_c(X)$ are measurable. If $A\subseteq X$ has $A\in\ba(X)$, then $A$ is a "Baire set".

The motivation for this lemma is that I need it in order to show that every Baire measure on a $\sigma$-compact space is regular, which is the culmination of a chapter of topological measure.
If $X$ is a locally compact Hausdorff space (LCH) it can be shown that $\ba(X)$ is the smallest $\sigma$-algebra containing the compact $G_\delta$ sets of $X$. I know further that LCH spaces possess the property that you can always extend the characteristic function of a compact set to get a function in $C_c(X)$; you can even do this with a "partition of unity". Further, for every compact $G_\delta$ set $K$ in a LCH space $X$ there is an $f\in C_c(X)$ with $K=f^{-1}\{1\}$. I do not have any more knowledge than this, from the text I am following - Royden and Fitzpatrick, $4$th edition - so I presume that the above is sufficient to complete the exercise.
I need to show the following as an exercise:

Let $X$ be an LCH space, and $F\subseteq X$ a closed Baire set. Show that: $$\forall A\subseteq F:A\in\ba(F)\iff A\in\ba(X)$$

So I know that $F$ forms a LCH subspace as it is closed. I have shown further that: $$\mathcal{F}=\{A\subseteq F:A\in\ba(X)\}$$Forms a $\sigma$-algebra on $F$, where it is closed under relative complementation with $F$ since $F\in\ba(X)$. The result is the same as saying $\mathcal{F}=\ba(F)$. The problem:

*

*Since $F$ is closed, we cannot say that a set is open in $F$ iff. it is open in $X$, so the $G_\delta$ sets of $F$ are not necessarily the $G_\delta$ sets of $X$.

It is very unclear to me how to make the argument. I have confused myself heavily on whether or not it is sufficient to show that every $G_\delta$ subset of $F$, in the $F$-topology, is a $G_\delta$ subset of $F$ in the $X$-topology; or whether or not it is sufficient to show that every $f\in C_c(F)$ is $\mathcal{F}$-measurable.
I think that, for an $f\in C_c(F)$, since its support is entirely contained in $F$ the continuous extension to the $0$ function outside of $F$ will yield an $f_0\in C_c(X)$ and $f_F^{-1}(\mathcal{O})=f_0^{-1}(\mathcal{O})$ for any open $\mathcal{O}\subset\Bbb R\setminus\{0\}$ and this will be an open set in $X$ and in $F$ as it will be a pure subset of $F$; likewise will $f^{-1}\{0\}$ be closed in $X$, but I am not convinced that in general $f$ will be continuous in the $X$-topology for those problem sets $\mathcal{O}\ni0$. Then I cannot confirm that $f\in C_c(F)$ will be $\mathcal{F}$-measurable without further assistance.
Any help would be appreciated.

A: $\newcommand{\o}{\mathcal{O}}\newcommand{\f}{\mathcal{F}}\newcommand{\ba}{\mathcal{Ba}}$The bullet point I marked as a "problem" is not actually a problem:
Let $K$ be compact and $G_\delta$ in $X$, $K=\bigcap_{n\in\Bbb N}\o_n$ for $\o_n$ open in $X$. Then:
$$K\cap F=\bigcap_{n\in\Bbb N}(F\cap\o_n)$$And althought $F\cap\o_n$ is not open in $X$, it is open in $F$ for each $n$ by definition of subspace topology. Then $K\cap F$ is a $G_\delta$ set in $F$ - it is compact since $F$ is closed. Likewise, now let $K$ be compact and $G_\delta$ in $F$. We can express:
$$K=\bigcap_{n\in\Bbb N}(F\cap\o_n)$$For some $\o_n$ open in $X$, by definition of subspace topology. We know $K$ is compact in $X$ as well, since $F$ is closed. If $K=F$, then $K=F=\bigcap_{n\in\Bbb N}\o_n$ and $K=F$ is $G_\delta$ in $X$. IF $K\subset F$ strictly, then there will be an $N\in\Bbb N$ for which $n\gt N$ has $\o_n\subset F$ and $F\cap\o_n=\o_n$. Then $K$ is $G_\delta$ in $X$ with $K=\bigcap_{n\gt N}\o_n$ (we may wlog take the sequence $\{\o_n\}$ as descending).
$\ba(F)$ is generated by the compact $G_\delta$ sets in $F$. From the above, we know every such set is the intersection $K\cap F$ for a compact $G_\delta$ set in $X$. Then the collection of all such $(K\cap F)$ will generate the $\sigma$-algebra of $\ba(F)$, but we know that $\f$ contains all such sets $K\cap F$ and is a $\sigma$-algebra (on $F$) itself, so by minimality $\f=\ba(F)$, since $F\in\ba(X)$. $\blacksquare$


text:
Q: Why directly modifying basic_string.h does not recompile I am not so familiar with std containers. It seems basic_string.h is a template and can be modified to use directly without recompile libstdc++.
Am I correct on this?
Thanks for helps.

A: There is no way to modify the std headers of a C++ program under the standard.
Any changing of those files is going to have implementation defined results, where that implementation is your entire compiling tool chain and system library install.
Practically, the most common problem is going to be violating the one definition rule of C++, and the most common symptom of violating the one definition rule is that your changes act as if they didn't happen, because the compiler found two definitions of an inline structure and silently discarded one of them.  The second most common symptom of violating the one definition rule is memory corruption.
In almost no situation does violating the one definition rule end well.
I can type more words that describe why what you are doing is a bad idea, but I think I have written more than enough.
Your question is akin to asking "if I stab myself with a knife randomly, what will actually kill me?"  Working out the exact mechanism distributions of how it kills you is hard, but the real problem is you are stabbing yourself with a knife.


text:
Q: Von Neumann integers definition I am learning the ZF (C) set theory
considering all the 6 standard axioms, here is how I defined the set of natural integers $\mathbb{N}$. Is it correct and how do I prove the Lemma 2 ?

Axiom of Infinity :  There exist a set ($A$) s.t
($\emptyset \in A ) \wedge (\forall X \in A, X\cup \left\lbrace X\right\rbrace \in A)$

Lemma there exist a (unique)  set $\mathbb{N}$ that satisfies the axiom and such that $\mathbb{N} \subset A$
Proof :
Let $\mathcal{B}$ the power  set of all subsets  B of $A$ which have the above property (exists, power set axiom), $\mathbb{N}=\bigcap_{B \in \mathcal B} B,$ then $\forall P \in B, P \, \cap A  $ also has this property (ie. $P \, \cap A  \in \mathcal{B}$). Thus, by definition  $\mathbb{N} \subset P \, \cap A$. Whence $ \mathbb{N} \subset P$. (this also proves the uniqueness)
Lemma 2 :
$\forall n \in \mathbb{N}^* \exists m \in \mathbb{N}^*, n=m\cup \left\lbrace m\right\rbrace$
This one I can't find a proof by myself
Can you help me ?
T.D

A: You're definitely thinking along the right lines, but I'm a bit puzzled by your 'definition' of $\mathbb{N}$, since $\mathbb{N}$ appears in the condition defining itself. (In fact, all sets $A$ satisfying the axiom of infinity should satisfy $\mathbb{N} \subseteq A$.) It's also not clear what kind of uniqueness you're trying to prove—$\mathbb{N}$ is the unique set such that... what?
Here's what I'd do.

*

*We start off doing what you did: fix a set $A$ satisfying the axiom of infinity, let $\mathcal{B}$ be the set of subsets of $A$ which satisfy the axiom of infinity, and define $\mathbb{N} = \bigcap \mathcal{B}$.

*Next, prove that $\mathbb{N}$ satisfies the axiom of infinity. To see that $\varnothing \in \mathbb{N}$, note that $\varnothing \in B$ for each $B \in \mathcal{B}$; and given $X \in \mathbb{N}$, you have for each $B \in \mathcal{B}$ that $X \in B$, and hence $X \cup \{ X \} \in B$. Piecing this together tells you that $\mathbb{N}$ satisfies the axiom of infinity.

*You might now want to prove that $\mathbb{N}$ is the unique set such that $\mathbb{N} \subseteq C$ for all sets $C$ satisfying the axiom of infinity. (You know this when $C \subseteq A$.) Proving that $\mathbb{N} \subseteq C$ for each $C$ satisfying the axiom of infinity goes just like the previous step; proving that $\mathbb{N}$ is the unique such is easy (let $\mathbb{N}'$ be another such set, and note that $\mathbb{N} \subseteq \mathbb{N}'$ and $\mathbb{N}' \subseteq \mathbb{N}$ by the condition we just proved).

Something is also awry with your 'Lemma 2'. I don't know what $\mathbb{N}^*$ means, and in any case the expression $\exists m \in \mathbb{N},~ n = m \cup \{ m \}$ is only true when $n \ne \varnothing$. So instead let's prove
$$\forall n \in \mathbb{N} \setminus \{ \varnothing \},~ \exists m \in \mathbb{N}, ~ n = m \cup \{ m \}$$
Proceed by contradiction, and suppose there is some $\varnothing \ne n \in \mathbb{N}$ which is not of the form $m \cup \{ m \}$. Now define $\mathbb{N}' = \mathbb{N} \setminus \{ n \}$. You will see that $\mathbb{N}'$ satisfies the axiom of infinity. You can deduce a contradiction from this, using the facts we already proved earlier.


text:
Q: Open xml runtime requirements I am creating a .NET application to manipulate word files using OpenXml SDK.
What are the prequisites (in runtime environment) to use Open Xml? Do i need to install Open XML SDK or toolkit on client machine?
Is it possible to just provide the referenced libraries with application, and do away with any open xml installer related dependency?

A: The second download in the link that's referenced in your question contains and installs the DocumentFormat.OpenXml dll. Your visual studio project needs a reference to this dll. You also need .NET 3.5 and above. Then you can get started on using Open XML.
The first download contains a link to Open XML SDK 2.0 Productivity tool. This tool allows you see how the XML structure of a document looks like. It also helps you to "reverse-engineer" an excel or a word document and thus is highly recommended (though not mandatory.)
Also I would highly recommend going through the MSDN documentation

A: If you are using .NET Core install the DocumentFormat.OpenXml from the NuGet package.
Right Click on Packages - > Manage NuGetPackages - > Select - >DocumentFormat.OpenXML
Import the below namespaces
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;

for reference please go through below link
https://learn.microsoft.com/en-us/office/open-xml/open-xml-sdk


text:
Q: python coverage report lists things as files and not packages When I run coverage report, I get something looking like this:
foo/
foo/bar/
foo/bar/baz

I was expecting something like:
foo
foo.bar
foo.bar.baz

This is a problem when I try to do coverage xml since everything gets lumped into a single nameless package.


text:
Q: How to achieve the metro user area in WPF? http://ledfrog.com/uploads/2011/06/zune-sw-screenshot-client-mossyroc.jpg
I want to have my user be able to login and access his profile pretty much like what is shown in that zune software screenshot in the upper right corner below the minimize/maximize/close buttons.
I already have the metro window setup thanks to MahApps.Metro library. Ive got myself a good metro-looking icon for when the user (Which is done in XAML thanks to Syncfusion's Metro Studio) has yet to login and i can login users easily.
The problem i am facing right now is that the icon is done in XAML, but the picture for each user is in a remotely-stored bitmap. Is there a control that can host XAML or bitmaps on the fly? or do i have to rasterize the icon into plain png? Also, is there a way that i can store the XAML making up the icon in another file so i don't have to embed it into my window's XAML file?
On a sidenote, i'd prefer not to rasterize the icon to avoid pixelation.

A: To answer my own question:
Using the App.xaml ResourceDictionary entry, i can store the XAML generated by the tool, then use a rectangle, set its fill property to a visualbrush that has its visual property set to {StaticResource xxx} where xxx is the name i put on the ResourceDictionary. After the user logs in, i just replace the visual property  of the brush to a image pointing to the url of the user's avatar.
Problem solved.


text:
Q: Best location for properties file I'm working on a small java application that needs to load/save configuration properties. At first I tried using a properties file that lived inside the jar but I was concerned if someone were to upgrade to a later version (replace the existing jar) they would loose all of their settings.
My next idea was to write the configuration file to the disk and reference it but I'm not sure what location I should save to. I don't want to use the current directory because the user could move the jar between directories and forget about the configuration file.
Is there a common location for configuration property files (specifically on windows)? If so how would I access it (I assume it would be some sort of wild card character like %appdata%\my app\config.properties)?
Thanks!

A: You might want to look into using the Preferences API instead. It provides a lightweight and simple way of storing application and user preferences, without directly accessing the file system.

A: Try the java.util.prefs Preferences API... as long as you are using Java 1.4 or newer. I think that will do what you want. I wrote a little post about them a while back: http://coffeaelectronica.com/blog/2009/07/java-preferences-api/
Hope this helps.

A: The user.home system property provides the path to a users home directory if you want to store on the file system.
There is also the Preferences API that was added to Java to solve this exact problem.


text:
Q: Python returns this error when I quit my window without use the button 'arret' from tkinter import *
from tkinter.ttk import *
import random as rd
import math as mt
import time

fin = 0

def touche (event):
    global xa, xb, ya, yb
    key = event.char
    print(key)

def arret ():
    global fin
    fin = 1

def boucle ():
    global a,b,xa,xb,ya,yb,x0,y0,x1,y1,r
    x = xa+10
    y = ya
    r = (xb-xa)/2
    for i in range (0, len(a)):
        x0 = x-a[i]*r
        y0 = y-b[i]*r
        x1 = x+a[i]*r
        y1 = y+b[i]*r
        can.coords(helice,x0, y0, x1, y1)
        can.update()
        time.sleep(0.02)

fen = Tk()

fin = 0

key = 'v'

can = Canvas(fen, bg = 'deep sky blue', width = 200, height = 200)
can.pack()

quit = Button(fen, text = 'quit', command = fen.destroy)
quit.pack(side = BOTTOM)

xa = rd.randint(5, 195)
ya = rd.randint(5, 195)
xb = xa+20
yb = ya

list_color = ['black', 'lavender blush', 'aquamarine', 'blue violet', 'tomato', 'dark cyan', 'green yellow',
              'medium spring green']
number = rd.randint(0,7)
for i in list_color:
    if list_color.index(i)==number:
        color = i

helice = can.create_line(xa, ya, xb, yb, width = 4, fill = color)

arret = Button(fen, text = 'arret', command = arret)
arret.pack(side = BOTTOM)

a = [-1, 0, 1, 1, 1, 0, -1, -1]
b = [-1, -1, -1, 0, 1, 1, 1, 0]

while fin != 1:
    boucle()

fen.bind ('<Key>', touche)

fen.mainloop()

The return :
TclError                                  Traceback (most recent call last)
Input In [71], in <cell line: 64>()
     62 b = [-1, -1, -1, 0, 1, 1, 1, 0]
     64 while fin != 1:
---> 65     boucle()
     68 fen.bind ('<Key>', touche)
     70 fen.mainloop()

Input In [71], in boucle()
     26 x1 = x+a[i]*r
     27 y1 = y+b[i]*r
---> 28 can.coords(helice,x0, y0, x1, y1)
     29 can.update()
     30 time.sleep(0.02)

File ~\anaconda3\lib\tkinter\__init__.py:2766, in Canvas.coords(self, *args)
   2762 """Return a list of coordinates for the item given in ARGS."""
   2763 # XXX Should use _flatten on args
   2764 return [self.tk.getdouble(x) for x in
   2765                    self.tk.splitlist(
-> 2766            self.tk.call((self._w, 'coords') + args))]

TclError: invalid command name ".!canvas"

I have tried to create a function to solve the problem but it doesn't work.
And if I click on my button named 'arret' Python don't show me this error but for the next exercice that I have to do. I must add an keyboard event which is not able to run before the 'click'.
I think the problem come to my while loop but I don't understand why.

A: from tkinter import *
from tkinter.ttk import *
import random as rd
import math as mt
import time

fin = 0

def touche (event):
    global xa, xb, ya, yb
    key = event.char
    print(key)

def arret ():
    global fin
    fin = 1

def boucle ():
    global a,b,xa,xb,ya,yb,x0,y0,x1,y1,r,fin
    try:
        while(fin !=1):
            x = xa+10
            y = ya
            r = (xb-xa)/2
            for i in range (0, len(a)):
                x0 = x-a[i]*r
                y0 = y-b[i]*r
                x1 = x+a[i]*r
                y1 = y+b[i]*r
                can.coords(helice,x0, y0, x1, y1)
                can.update()
                time.sleep(0.02)
    except:
        pass

fen = Tk()

fin = 0

key = 'v'

can = Canvas(fen, bg = 'deep sky blue', width = 200, height = 200)
can.pack()

quit = Button(fen, text = 'quit', command = fen.destroy)
quit.pack(side = BOTTOM)

xa = rd.randint(5, 195)
ya = rd.randint(5, 195)
xb = xa+20
yb = ya

list_color = ['black', 'lavender blush', 'aquamarine', 'blue violet', 'tomato', 'dark cyan', 'green yellow',
              'medium spring green']
number = rd.randint(0,7)
for i in list_color:
    if list_color.index(i)==number:
        color = i

helice = can.create_line(xa, ya, xb, yb, width = 4, fill = color)

arret = Button(fen, text = 'arret', command = arret)
arret.pack(side = BOTTOM)

a = [-1, 0, 1, 1, 1, 0, -1, -1]
b = [-1, -1, -1, 0, 1, 1, 1, 0]

fen.after(0, boucle)

fen.bind ('<Key>', touche)

fen.mainloop()

or you can use this code:
from tkinter import *
from tkinter.ttk import *
import random as rd
import math as mt
import time

fin = 0

def touche (event):
    global xa, xb, ya, yb
    key = event.char
    print(key)

def arret ():
    global fin
    fin = 1

def boucle ():
    global a,b,xa,xb,ya,yb,x0,y0,x1,y1,r,fin

    while(fin !=1):
        x = xa+10
        y = ya
        r = (xb-xa)/2
        for i in range (0, len(a)):
            x0 = x-a[i]*r
            y0 = y-b[i]*r
            x1 = x+a[i]*r
            y1 = y+b[i]*r
            if(fin!=1):
                can.coords(helice,x0, y0, x1, y1)
                can.update()
                time.sleep(0.02)

def die():
    global fin
    fin=1
    fen.quit()
    fen.destroy()
fen = Tk()

fin = 0

key = 'v'

can = Canvas(fen, bg = 'deep sky blue', width = 200, height = 200)
can.pack()

quit = Button(fen, text = 'quit', command = die)
quit.pack(side = BOTTOM)

fen.protocol("WM_DELETE_WINDOW", die)

xa = rd.randint(5, 195)
ya = rd.randint(5, 195)
xb = xa+20
yb = ya

list_color = ['black', 'lavender blush', 'aquamarine', 'blue violet', 'tomato', 'dark cyan', 'green yellow',
              'medium spring green']
number = rd.randint(0,7)
for i in list_color:
    if list_color.index(i)==number:
        color = i

helice = can.create_line(xa, ya, xb, yb, width = 4, fill = color)

arret = Button(fen, text = 'arret', command = arret)
arret.pack(side = BOTTOM)

a = [-1, 0, 1, 1, 1, 0, -1, -1]
b = [-1, -1, -1, 0, 1, 1, 1, 0]

fen.after(0, boucle)

fen.bind ('<Key>', touche)

fen.mainloop()

have fun :)


text:
Q: Plotting equation with some unknown parameters I am new to the Mathematica and I have a question about the plotting. I am trying to plot the transcendental equation
$$\tan{(z)}=\sqrt{\frac{1}{2m_0}\left (\frac{z_0}{z}\right)^2-1}
$$
where the parameter $z_0=4.8$.
I am just wondering can I keep the parameter $\frac{1}{2m_0}$ without specifying an exact value to it? I have searched some similar questions but still don't figure this out. Could anyone give some suggestions? Thanks!

A: In this particular case, you can view the solution set in the $z,m_0$ plane (i.e. allowing $m_0$ to vary) with ContourPlot:
z0 = 4.8;

ContourPlot[
 Tan[z] == Sqrt[(1/(2 m0)) (z0/z)^2 - 1], {z, -5, 5}, {m0, 0, 2},
 PlotPoints -> 50]

(PlotPoints -> 50 just makes the resolution a bit better.)

Note: as @Artes mentions in a comment on the original question, these sorts of equations are difficult to handle. As such, the above plot might not reveal the full solution set. However, by plotting both sides of the equation in 3D and viewing the result from directly above to see where the intersections lie, it does seem we've got them all in this range.
Plot3D[{Tan[z], Sqrt[(1/(2 m0)) (z0/z)^2 - 1]}, {z, -5, 5}, {m0, 0, 2},
 PlotPoints -> 50, ViewPoint -> {0, 0, Infinity},
 ViewAngle -> All, Ticks -> False, AxesLabel -> Automatic,
 PlotRange -> {-100, 100}]


text:
Q: Use custom formatting to offset text in a cell How can I offset a text in my cell if it contains a specific value, without adding new caractéres ?
I would like something like a tabulation before my text if it contain (lvl 1) and two tabuation if it contain (lvl 2) ...
I'm specificaly looking for a custom formatting to apply to a text but I'm open to any other solution.


text:
Q: Why is this URI producing a runtime error in the OData service? The following URI triggered an error in the public OData service:
http://services.odata.org/V4/Northwind/Northwind.svc/Suppliers?$filter=Address eq '<A'
Entity type Supplier contains property Address of type Edm.String. So, the value of Address may contain any UTF-8 character from the definition (see section 6. Primitive data types).
The server responds with:

Runtime Error: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons).

Is the there something wrong with this URI or it is really a problem on the server side (e.g. inappropriate parsing of the $filter query option)?

A: You should encode your query URL, e.g. with help of
http://prasannaadavi.com/2014/06/handling-special-characters-in-odata-queries.html
How are special characters handled in an oData query?
In your special case you should try encoding "<A" with "<A"
--> found in https://web.archive.org/web/20150101222238/http://msdn.microsoft.com/en-us/library/aa226544(SQL.80).aspx)


text:
Q: C++ How do I access and modify an array with using []? For an assignment, I have take a class with a first and last name (string) and reverse the order, one method using array notation[] and it accepts an char varible[], and another method that does the same thing, but without using any bracket notation ie[] and accepts a char *varible. I don't know any other way to reference a certain character in the list without using [] and only using pointer method. How would I go about starting the pointer method, I already finished the array method? main.cpp supplied below for context.
I know that an array is essentially a block of memory that is the data type size multiplied by how many containers you specify. Is there a way to traverse an array using the bit location in the memory allocated for the array?
#include <iostream>
#include <string>
using namespace std;
class Name
{
 public:
 string TheName;
 Name() { TheName=""; }
 Name(string name) { TheName=name; }
 string ReverseUsingString();
 void ReverseUsingArray(char Reversed[]);
 void ReverseUsingPtrs(char *Reversed);
 void operator =(char *name) {TheName=name;}
};
#include "NameClassImplementation.cpp" // You supply this file!
int main()
{
 Name Names[5]; Names[0] = "Ben Dover";
 Names[1] = "Chuck Roast"; Names[2] = "Jim Naysium";
 Names[3] = "Ella Quint"; Names[4] = "Justin Case";
 char reversedname1[100], reversedname2[100];

 for (int i=0; i<5; ++i)
 {
 Names[i].ReverseUsingArray(reversedname1);
 Names[i].ReverseUsingPtrs(reversedname2);
 cout << "Original Name : " << Names[i].TheName << endl;
 cout << " reversed with arrays: -->" << reversedname1 << "<--\n";
 cout << " reversed with ptrs : -->" << reversedname2 << "<--\n";
 cout << " reversed with string: -->"
 << Names[i].ReverseUsingString() << "<--\n\n";
 }
 system("pause"); return 0;
}

A: this is some example code that may be able to guide you in completing your task.
#include <iostream>

int main()
{
    //  create an array
    int x[1] = {1};

    //  create a pointer that points to an adress of particular element of aforementioned array
    int *a = x+0;

    //  modify array
    *a = 3;

    //  access element of array
    std::cout<<*a;
}


text:
Q: Issue in removing Grandchild in a recursive component What I have been trying to achieve?
Create a nested context menu that is driven by a config.

Where am I stuck:
Sub menus are rendering correctly, but if there is more than 2 level, the change in root level only affects its sub-menu and not its entire tree
Here is the sandbox link for you to check.

Steps to reproduce:

*

*On load, a menu is displayed (say menu)

*Click on File, it will open its sub menu (say sub-menu1).

*Click on Open in the sub-menu1, again another sub menu (say sub-menu2) is open.

*Now when you click on Edit in menu, sub-menu1 disappears but not sub-menu2

I think, I know the problem. sub-menu2 is not refreshing because props or state is not changed. To hide it, we will need to trickle down some prop but can't think of elegant way to do it without state management system.

A: You'll have a better time if the ContextMenu component is responsible for state management and recursion is flattened into iteration.

function ContextItem({ item, onClick }) {
  return (

 onClick(item)}>

{item.title}

        {item.children && item.children.length > 0 ? {">"} : null}

  );
}

function MenuList({ list, onClick }) {
  return (

      {list.map((listItem) => (
        <ContextItem item={listItem} key={listItem.title} onClick={onClick} />
      ))}

  );
}

const ContextMenu = ({ list }) => {
  const [openSubmenus, setOpenSubmenus] = React.useState([]);
  const clickHandler = React.useCallback((item, level) => {
    if (item.children && item.children.length) {
      setOpenSubmenus((oldItems) => {
        return [...oldItems.slice(0, level), item.children];
      });
    } else {
      setOpenSubmenus([]); // item selected, clear submenus
      alert(item.title);
    }
  }, []);
  const menus = [list, ...openSubmenus];
  return (

      {menus.map((menu, level) => (
        <MenuList
          key={level}
          list={menu}
          level={level}
          onClick={(item) => clickHandler(item, level)}
        />
      ))}

  );
};
const menuList = [{
  title: "File",
  children: [{
    title: "Close",
    children: [],
    action: "fileClose",
  }, {
    title: "Open",
    children: [{
      title: "A:\\",
      children: [],
      action: "",
    }, {
      title: "C:\\",
      children: [],
      action: "",
    }, {
      title: "\\",
      children: [],
      action: "",
    }],
    action: "",
  }, {
    title: "Find",
    children: [{
      title: "here",
      children: [],
    }, {
      title: "elsewhere",
      children: [],
    }],
    action: "",
  }, {
    title: "Backup",
    children: [],
    action: "backup",
  }],
  action: "",
}, {
  title: "Edit",
  children: [],
  action: "edit",
}];

function App() {
  return <ContextMenu list={menuList} />;
}

ReactDOM.render(<App />, document.getElementById("root"));
.menu {
  display: flex;
  flex-direction: row;
}

.menu-container {
  display: flex;
  flex-direction: column;
  background-color: #eee;
  border: 1px solid gray;
  border-radius: 4px;
}

.menu-item {
  display: flex;
  flex-direction: row;
  margin: 2px;
  max-width: 200px;
  line-height: 30px;
  padding: 5px 10px;
}

.menu-title {
  min-width: 80px;
  height: 30px;
  flex-grow: 1;
  margin: 0;
  vertical-align: middle;
}
.menu-title.active {
  background-color: blue;
  color: white;
}
.right-icon {
  width: 25px;
}

A: You could use the label as the key to reset the ContextMenu state when selectedItem change (assuming the label is unique at a given depth, but it seems reasonable, otherwise you could add unique ids).
export const ContextMenu = ({list}) => {
    const [selectedItem, setSelectedItem] = useState();

    return (

                {list.map((listItem) => {
                    return (
                        <ContextItem
                            item={listItem}
                            key={listItem.title}
                            onClick={setSelectedItem}
                        />
                    );
                })}

            {selectedItem?.children.length > 0 && <ContextMenu
                key={selectedItem.title}
                list={selectedItem.children}/>}

    );
};


text:
Q: Psycopg2 - SQL Result to json list Trying to return Psycopg2 results to a Python json list.
        self.cursor.execute("SELECT user FROM app.feeders")
        ex1 = self.cursor.fetchall()
        print(ex1)

        json_output = json.dumps(ex1)
        print(json_output)

        result = [r[0] for r in self.cursor.fetchall()]
        print(result)

        return json_output

The table app.feeders has a list of users, who I'd like to be represented in a json list ["apple", "banana", "cherry"] however the results for my above attempts are:
[('apple',), ('banana',), ('cherry',)]
[["apple"], ["banana"], ["cherry"]]
[]

A: You could make an array directly in Postgres:
self.cursor.execute("SELECT array_agg(user) FROM app.feeders")
print(cur.fetchone()[0])

Out:
['tony', 'tom', 'kim']

A: So the issue was passing through the cursor.fetchall() directly. Making the below changes resolved the issue:
From:
result = [r[0] for r in self.cursor.fetchall()]

To:
result = [r[0] for r in ex1]


text:
Q: c# WinForm Marquee Progress Bar does not scroll Background:
I have a VB6 application that currently does some processing in a database and then calls a COM exposed c# class. The c# class then does some other long processing on a background worker. During that time, I have a status window pop up that has a status label as well as a progress bar. I want the progress bar to show with the marquee style but it does not animate. It is visible and functions properly but only as the Block style. I can set the value and it will display the Block style but when I set the style to marquee, it just does not do anything. Is it the VB6 application that's killing it? How do I get the animation to display properly?
What I have done:

*

*I have made sure to set Application.EnableVisualStyles(); (I tried
setting it in different places!)

*I have programmatically set the marque style and even verified the
style is set while debugging.

*I have tried calling ProgressBar.Show(); even though its already
visible on the form.

*I have tried using both a static and non-static (displayed below) helper class.
Here is the small helper class I created that I use.
internal class EStatusHelper
{
    private EStatus status = null;

    public void ShowStatusForm<T>(Action<T> process, T arguments)
    {
        var bg = new BackgroundWorker();

        bg.WorkerReportsProgress = true;

        using (status = new EStatus(bg.RunWorkerAsync))
        {
            bg.DoWork += (o, args) =>
            {
                process(arguments);
            };

            bg.RunWorkerCompleted += (o, args) =>
            {
                status.DialogResult = DialogResult.Cancel;
            };

            status.ShowDialog();
        }
    }

    public void UpdateStatusMessage(
        string message)
    {
        if (status != null)
        {
            if (status.StatusMessage.InvokeRequired)
            {
                try
                {
                    status.StatusMessage.Invoke(
                        new Action<string>(UpdateStatusMessage),
                        message);
                }
                catch { }
            }
            else
            {
                status.StatusMessage.Text = message;
            }
        }
    }
}

And here is the Form EStatus just to show how the BackgroundWorker gets started.
public partial class EStatus : Form
{
    public Action ShowAction = null;

    public EStatus()
    {
        Application.EnableVisualStyles();
        InitializeComponent();
    }

    public EStatus(Action a) : this()
    {
        ShowAction = a;
    }

    private void EStatus_Shown(object sender, EventArgs e)
    {
        if (ShowAction != null)
            this.BeginInvoke(ShowAction);
    }
}

And here is the basic call to use the helper function.
// helper variable that can be passed around.
// Also tried Static methods instead of passing around a local variable.
var helper = new EStatusHelper();
helper.ShowStatusForm(MethodToInvoke, paramsToPass);

Thank you!


text:
Q: Property of bounded linear transformation between Hilbert spaces I've asked a question on related question in a previous thread, but I wanted to ask a follow up question.

If a bounded linear transformation $T: X \to Y$ where $X$ and $Y$ are Hilbert spaces has closed range, show that the set $B = \{f \in \text{Ran}(T): \|T^*f\|_X \leq 1 \} $ is bounded.

I was going to first use surjectivity of the closed range to prove $B$ is weakly bounded, and go from there, but I have no how to prove weak bounded and also how to  go from there. Thanks!

A: Say $R=T(X)$. Then $R$ is a closed subspace of $Y$, so $R$ is a Hilbert space. The Open Mapping Theorem applied to $T:X\to R$ shows that there exists $\delta>0$ such that for every $f\in R$ there exists $g\in X$ with $Tg=f$ and $\|g\|\le\delta\|f\|$.
Now suppose $f\in R$, $\|T^*f\|\le 1$ and choose $g$ as above. Then $$\|f\|^2=\langle f,f\rangle=\langle Tg,f\rangle =\langle g,T^*f\rangle \le\|g\|\le\delta\|f\|.$$


text:
Q: Impulse on different screen sizes Spritekit Xcode Hi I'm making a game where you tap to give an upward impulse to the ball of lets for example say a cgvector (4,0).
This if for both 4inch and 3.5 inch retina displays.
Will the impulse move the ball the same amount in pixels or same amount relative to the screen size different. I need the ball to move the same amount relative to the size or else the game will become easier on i5's . I have an idea of how to achieve it.
Could someone with knowledge of how impulse works clear this up?
Only asking because i recently played it on a i5 and got higher scores than usually on the i4
Thanks

A: physics simulation does not depend on screen size, however the scene may be scaled (see scaleMode) which can affect how much of the scene you can see on each device.


text:
Q: open jQuery UI dialog in front of edit/add dialog jqGrid I costomize edit-/add-dialog jqGrid. In an "beforeShowForm" event I add buttons and fields. After pressing the button there is a jqUi Dialog. I can achieve the opening of a new jQuery UI dialog, but is opens behind the edit-/add-dialog jqGrid. How can I make it opening in front of the edit-/add-dialog jqGrid?
this is my code:
var gridWidth = 1000,
    gridHeight = 600;

var pagerSettings = {
    add: true,
    addtext: "Добавить",
    edit: true,
    edittext: "Редактировать",
    del: true,
    deltext: "Удалить",
    search: false,
    refresh: false
};
var editSettings = {
    closeAfterEdit: true,
};
var addSettings = {
    closeAfterAdd: true,
    closeOnEscape: true
};
var searchSettings =
    deleteSettings = {
        closeOnEscape: true
    };

function CustomForm(form) {
    AddSelector(form);
    AddButtons(form);
};

function AddSelector(form) {
    var nameColumnField = $('#tr_WebUri', form).show();
    var tr = $('<tr />', { class: "FormData", id: "tr_ActivitiesID" });
    var td_row_one = $('<td />', { class: "CaptionTD" }).appendTo(tr);
    var td_row_two = $('<td />', { class: "DataTD" }).appendTo(tr);
    var sel = $('<select />', { id: "ActivitiesID", multiple: "multiple" }).appendTo(td_row_two);
    tr.insertAfter(nameColumnField);

    $("#ActivitiesID").multiselect({
        autoOpen: false
    }).multiselectfilter();
};

function AddButtons(form) {
    var arr = [
                { id: "CitiesID", text: "Cправочник населенных пунктов" },
                { id: "ActivitiesID", text: "Cправочник видов деятельности" }
    ];
    $.each(arr, function (i, val) {
        var nameColumnField = $('#tr_' + val.id, form).show();
        var tr = $('<tr />', { class: "FormData", id: "tr_" + val.id + "Button" });
        var td_row_one = $('<td />', { class: "CaptionTD" }).appendTo(tr);
        var td_row_two = $('<td />', { class: "DataTD" }).appendTo(tr);
        $('<div />', { id: val.id + "Dialog", title: val.text }).appendTo($('body:first'));
        $('<Button />', { id: val.id + "Button", text: val.text }).button().click(function () {
            $("#" + val.id + "Dialog").dialog({
                modal: true,
                buttons: {
                    Ok: function () {
                        $(this).dialog("close");
                    }
                }
            }).css('zIndex', 1000);
        }).appendTo(td_row_two);
        tr.insertAfter(nameColumnField);
    });
};

// Основная таблица:
$('#objectsMap').jqGrid({
    type: "GET",
    datatype: "json",
    url: "/Map/GetOrganizations",
    editurl: "/Map/EditOrganizations",
    colNames: new Array('ID', 'Наименование*', 'Номер', 'Адрес*', 'Населенный пункт', 'Телефон', 'Сайт', 'Дополнительно'),
    colModel: new Array(
                { name: 'ID', key: true, width: 50 },
                { name: 'Name', editable: true, editrules: { required: true } },
                { name: 'Number', editable: true, formoptions: { elmsuffix: $('<p />').text('номер по реестру, код таможенного органа').css('margin', '2px 5px') } },
                { name: 'Address', editable: true, editrules: { required: true }, formoptions: { elmsuffix: $('<p />').text('улица, дом, корпус, строение, офис').css('margin', '2px 5px') } },
                {
                    name: 'CitiesID', editable: true, edittype: 'select',
                    editoptions: {
                        defaultValue: 2,
                        value: function () {
                            var cities = new Object();
                            $.ajax({
                                url: "/Map/GetCities",
                                dataType: "json",
                                async: false,
                                success: function (data) {
                                    $.each(data.rows, function (index, item) {
                                        cities[item.cell[0]] = item.cell[1];
                                    });
                                }
                            });
                            return cities;
                        }
                    }
                },
                {
                    name: 'Phone', editable: true,
                    editoptions: {
                        dataInit: function (item) {
                            $(item).attr('placeholder', '+7 (812) 702-60-65');
                        }
                    }
                },
                {
                    name: 'WebUri', editable: true, editrules: { url: true },
                    editoptions: {
                        dataInit: function (item) {
                            $(item).attr('placeholder', 'http://rlp.su');
                        }
                    }
                },
                {
                    name: 'Additionally', editable: true, edittype: 'textarea',
                    editoptions: {
                        rows: "3", cols: "56"
                    }
                }
    ),
    toolbar: [true, "top"],
    sortname: 'Name',
    viewrecords: true,
    rownumbers: true,
    sortorder: "desc",
    width: gridWidth,
    height: gridHeight,
    pager: '#objectsMapPager',
    caption: "Справочник организаций"
}).jqGrid('navGrid', '#objectsMapPager', pagerSettings,
            // Edit
            {
                recreateForm: true,
                beforeShowForm: function (form) {
                    CustomForm(form);
                }
            },
            // Add
            {
                recreateForm: true,
                beforeShowForm: function (form) {
                    CustomForm(form);
                }
            },
            // Delete
            deleteSettings,
            // Search
            searchSettings
);
//$('#objectsMap').jqGrid('filterToolbar');