text:
Q: Encode iOS compatible h264 audio stream with FFMPEG I am using FFMPEG with Python to encode a low bit rate version of videos that I import.  I would like the output to be playable on several devices, including Roku and iOS.  This link states that Apple supports H264 High profile, level 4.1 and MP3 audio.
ffmpeg -preset veryslow -y -profile:v high -level 4.0 -movflags +faststart -codec:a libmp3lame -qscale:a 2 -s 1280x720 out.mp4

The resulting videos play fine in an HTML5 browser on a computer.  However, on the iPhone the video appears but the audio stream does not play.  Is there an issue with the mp3 settings?
From ffprobe:
[STREAM]
index=1
codec_name=mp3
codec_long_name=MP3 (MPEG audio layer 3)
profile=unknown
codec_type=audio
codec_time_base=1/44100
codec_tag_string=mp4a
codec_tag=0x6134706d
sample_fmt=s16p
sample_rate=44100
channels=1
channel_layout=mono
bits_per_sample=0
id=N/A
r_frame_rate=0/0
avg_frame_rate=0/0
time_base=1/44100
start_pts=-1105
start_time=-0.025057
duration_ts=2321489
duration=52.641474
bit_rate=94949
max_bit_rate=N/A
bits_per_raw_sample=N/A
nb_frames=2016
nb_read_frames=N/A
nb_read_packets=N/A
DISPOSITION:default=1
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=0
TAG:language=und
TAG:handler_name=SoundHandler
[/STREAM]

I tried using AAC, but did not get good results with the native FFMPEG encoder

A: The document you reference is for HTTP Live Streaming, which uses a transport stream format, not an ISO mp4 format. Either way I have found many issues with mp3+video in ios. My recommendation is to use AAC (-acodec fdk-aac) instead of mp3. It is just as  universally supported, and will provide you with better audio at lower bitrates. If that is not an option, try to specify all audio settings on the command line (-channles -samplerate, etc)


text:
Q: (400) Bad Request on Azure server while communicating with service I have a website and service in Azure webrole. The application uses a ServiceCommunicator class to communicate with the Service. The following code is working fine on my local machine..
        private string _url;
        public ServiceCommunicator(string url)
        {
            _url = url;
        }
        public object GetDataFromService()
        {
            //create request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
            request.Method = "GET";
            request.ContentLength = 0;

            //get response
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

But when this is deployed on cloud (it uses Server 2008 R2 Enterprise) the code  throws following exception
The remote server returned an error: (400) Bad Request.

I am unable to understand why is it happening as the code works properly on local machine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF: Make Application Resources override usercontrol library resources I have a wpf application project, with user controls in a separate project.
I'd like to have different resource dictionaries in the different projects
When I view the user controls from the user control project, I'd like to use the user control library's dictionary.
when I run the Application, i'd like to use the application's dictionary.
Right now, when i run the application, the application still has it's own dictionary, but the user controls are still using the user control library's dictionary
I've tried combinations of dictionaries and merged dictionaries.
Not really sure how to do this.
thanks in advace

A: So I found a workaround:
Include an App.xaml file in the user control library. Define the user control design time resources in the user control App.xaml file
In the regular wpf application project, include the run time resources.
At design time, the user controls only see its own App.xaml file, while at run time, the appliction is run and uses the resources defined in the application projects App.xaml file
Don't know if this is the optimal method of doing this. If anyone has any comments on doing it this way, please feel free to post
Thanks


text:
Q: Get each day between a date range in an array of string in php It easier to explain in example so let just dive into it:
I have a range of date, say, 1st of December 2019 - 1st of Feb 2020.
So my requirement is to get :
Sunday - 01 December - 2019
Monday - 02 December - 2019
Tuesday - 03 December - 2019
Wednesday - 04 December - 2019
...
...
...
...
...
...
Friday - 31 January - 2020
Saturday - 01 February - 2020

in an array of string in PHP.

A: You can use strtotime() to increase your date by 1 date:
$start = strtotime("1 December 2019");
$end = strtotime("1 Feb 2020");
$dateArray = [];
while($start <= $end) {
    $dateArray[] = date("l - d F Y", $start);
    $start = strtotime("+1 day", $start);
}

A: I think you are looking for some thing like this
function getDatesFromRange($start, $end, $format = 'l - d F - Y') {

    // Declare an empty array
    $array = array();

    // Variable that store the date interval
    // of period 1 day
    $interval = new DateInterval('P1D');

    $realEnd = new DateTime($end);
    $realEnd->add($interval);

    $period = new DatePeriod(new DateTime($start), $interval, $realEnd);

    // Use loop to store date into array
    foreach($period as $date) {
        $array[] = $date->format($format);
    }

    // Return the array elements
    return $array;
}

// Function call with passing the start date and end date
$dates = getDatesFromRange('2010-10-01', '2010-10-05');
echo '<pre>';
print_r($dates);

Output :
Array
(
    [0] => Friday - 01 October - 2010
    [1] => Saturday - 02 October - 2010
    [2] => Sunday - 03 October - 2010
    [3] => Monday - 04 October - 2010
    [4] => Tuesday - 05 October - 2010
)

A: Please use the below code.
<?php
    function getDatesFromRange($start, $end, $format = 'l-d-F-Y') {

        // Declare an empty array
        $array = array();

        // Variable that store the date interval
        // of period 1 day
        $interval = new DateInterval('P1D');

        $realEnd = new DateTime($end);
        $realEnd->add($interval);

        $period = new DatePeriod(new DateTime($start), $interval, $realEnd);

        // Use loop to store date into array
        foreach($period as $date) {
            $array[] = $date->format($format);
        }

        // Return the array elements
        return $array;
    }

    // Function call with passing the start date and end date
    $Date = getDatesFromRange('2019-12-01', '2020-02-01');

    var_dump($Date);

 ?>

Thanks,Arun


text:
Q: fscanf to read an array of floats, but only getting first number in array Reading a file, first number is an int that's the size of the array, then the rest are double
Here is the function:
void read1dascii(double** a, int* m, char* infile)
{
 FILE * fp = fopen(infile, "r");

 fscanf(fp, "%d", m);
 alloc1d(a, *m);

 fscanf(fp, "%lf\n", *a);

 fclose(fp);
}

Here is the alloc1d function it calls:
void alloc1d(double** a, int m)
{
 *a = malloc(sizeof(double) * m);
}

I'm getting the first number which is the size and then the first number in array, but then the rest are reading in as zeros.

A: You need to read all of them using loop.
int i;
for (i = 0; i < *m; ++i) {
  fscanf(fp, "%lf", *a + i);
}

A: fscanf(fp, "%lf\n", *a);

Here you are only reading once, so it's just receiving the first float, to read the rest of the array, you need something like
while ( fscanf(fp, "%lf\n", &a) == 1 )
{
    /* do stuff with 'a' here */
}


text:
Q: How to create two Aggregates from one View I have two Aggregates called CompanyAggregate and ProfileAggregate and their Aggregate Root are Company and Profile respectively, a Company can have many Profiles. The view responsible for creating Companies has the possibility to create Profiles too at the same time (there is a list and an append button, it is a View requirement), so when the user clicks the save button both Aggregates should be saved. The question is what is the best approach to achieve that?
I have a workflow on mind that is like the following:

*

*Call Company's API to create the Company;

*Get the created Company's Id;

*Call Profiles' API to create each Profile;

*Done.

Should those calls be made from the client side or from our API Gateway (API Decomposition opposed to Composition) OR should I use a domain event? In the latter case I would have to pass Profile data to the Company Aggregate just to raise a domain event leading to a boundary violation.
Some will say Profile should go inside Company Aggregate, but that is not the case as Profile can be directly referenced by another Roots.

A: Since you mentioned that it is possible to create profiles but not mandatory, I would make it two separate commands at the CQRS level. Your intuition about passing Profile data to Company is certainly correct. A profile does not look like a byproduct of the company coming into existence.
On the other hand, making it two distinct requests at the client level will probably cause some ordering problems. I would pack the two in a single HTTP request unless you have some way of pre-generating an identifier for the company to put in both requests.


text:
Q: Dealing with "PHP HTML DOM Parser", including the same library into two different files I have two PHP files (same folders) that access the library simple_html_dom.php
The first one, caridefine.phphas this:
include('simple_html_dom.php');
$url = 'http://www.statistics.com/index.php?page=glossary&term_id=209';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
libxml_use_internal_errors(true);
$dom = new DomDocument();
$dom->loadHtml($curl_scraped_page);
$xpath = new DomXPath($dom);
print $xpath->evaluate('string(//p[preceding::b]/text())');

The second one, caridefine2.php has this:
include('simple_html_dom.php');
$url = 'http://www.statsoft.com//textbook/statistics-glossary/z/?button=0#Z Distribution (Standard Normal)';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);

$html = new simple_html_dom();
$html->load($curl_scraped_page);
foreach ($html->find('/p/a [size="4"]') as $font) {
    $link = $font->parent();
    $paragraph = $link->parent();
    $text = str_replace($link->plaintext, '', $paragraph->plaintext);
    echo $text;
}

Separately, each of them worked fine, I ran the caridefine.php, it worked well, so did the caridefine2.php.
But when I tried to load these two files in other PHP files:

            <?php
                $this->load->view('definer/caridefine.php');
            ?>

            <?php
               $this->load->view('definer/caridefine2.php');
            ?>

None of them worked. Just gave me a blank page, when I pressed CTRL+U, it said: Cannot redeclare file_get_html() (previously declared in C:\xampp\htdocs\MSPN\APPLICATION\views\Definer\simple_html_dom.php:70) in C:\xampp\htdocs\MSPN\APPLICATION\views\Definer\simple_html_dom.php on line 85
I googled for this problem, I found that "if you load many objects without clearing the previous ones, it can be a problem."
I've tried doing $html->clear() and unset($dom). It gave me nothing.
What is it that makes me like in the end of the line?
Thanks..

A: I have tried analyse my own problem:
Here is the correction:
Change include('simple_html_dom.php'); in each file into: require_once('simple_html_dom.php');
What happened was the file called the file simple_html_dom.php twice. So it won't work.
That should do it.


text:
Q: including an external file in postfix aliases file using ":include:" directive Some entries in my postfix alias file are static, whereas others are intended to be dynamic, and updated via a cron-job script every hour.  I would like to have the static entries be in a file by themselves, and simply include the dynamic entries via an ":include:" directive to another file.  That way, my script can modify the dynamic entries without ever touching the static entries file.
Is this possible?
( P.S.  I know the :include: directive can be used as the right-hand-side of an alias, I just want to know if it can also be used to include new aliases entirely )

A: Just use multiple alias_maps (or virtual_alias_maps).
Example:

alias_maps = hash:/etc/mail/aliases hash:/etc/mail/aliases-crongend

Though if you really want dynamic aliases you might try a different table type, such as mysql and skip the cronscript all together.


text:
Q: Include mouse cursor in screenshot I'm making a program that streams my screen to another computer(like TeamViewer), I'm using sockets, PIL ImageGrab, Tkinter.
Everything is fine but the screenshot I get from ImageGrab.grab() is without the mouse cursor, which is very important for my program purpose.
Do you know how can I take screenshot with the mouse cursor?

A: The cursor isn't on the same layer as the desktop or game your playing, so a screenshot won't capture it (try printscreen and paste into mspaint). A workaround is to get the position of the cursor and draw it on the image. you could use win32gui.GetCursorPos(point) for windows.


text:
Q: How to send custom error message to user in node.js + ajax Can someone help me with sending an error message from the server to client side via ajax? For example, if my server side returns a 404 error, I want it to also send a custom message: 'something is wrong'
server.js
api.get('/api/some_route', function(req, res, next) {

    res.sendStatus(404, 'something is wrong');

});

client.js
$.ajax({
    type: "POST",
    data: data,
    success: function(data, status) {
        console.log(status);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(textStatus) //returns error
        console.log(errorThrown) //returns bad request
        //I want to someohow print the 'something is wrong' message from the api
    }
});

Thanks in advance!

A: You just have to call the status method before calling send or json:
res.status(404).send({ error: "Something is wrong"});


text:
Q: How do I use APA-style citations with BibTeX?
Possible Duplicate:
How to APA 6th in LaTex?

I am just getting started with BibTeX for the first time, and wondering how do I can use APA format.  I assume there's more than one way to do this, so what are my options, and what do you recommend?  Not doing anything fancy, just a simple article.
Right now I just have this LaTeX document, "doc.tex":
    \documentclass[11pt]{article}
    \usepackage{cite}

    \begin{document}

    \title{Sample Document}
    \author{Bob Smith}
    \date{Today}
    \maketitle

    Blah blah blah blah blah blah by Bob ~\cite{BobsBook01}.

    \bibliography{mybib}{}
    \bibliographystyle{plain}
    \end{document}

And I have this bibliography file, "mybib.bib":
    @misc{ BobsBook01,
           author = "Bob Smith",
           title = "The Book of Bob",
           publisher = "Bob's Publishing",
           year = "2011"
    }

I'm compiling this into a pdf with pdflatex using this Makefile:
    doc.pdf : doc.tex doc.bbl
            latex doc
            pdflatex doc
    doc.bbl : doc.tex doc.aux mybib.bib
            bibtex doc
    doc.aux : doc.tex
            latex doc

The output of the bibliography looks like this:
    [1] Bob Smith. The book of bob, 2011.

But I need it in APA format, which I think should be something like this:
    [1] Smith, B. (2011). The book of bob. Bob's Publishing.

Thanks.

A: You can use the package apacite.
\documentclass{article}
\usepackage{apacite}

...
\bibliographystyle{apacite}
\bibliography{mybib.bib}

See:
apacite package and
apa document class


text:
Q: Is there another solution for write the algorithm by matlab? I have an algorithm as you can see below and i wrote it with different 2 ways but it seems there are problems for both solutions.is there any alternative to write it with different way?
$$X_i(k+1)= X_i(k)+ 0.1*\sum_{j\in N_i} (X_j(k)-X_i(k))$$
while( k < t )
    for i = 1 : N
       for j = 1 : N

Solution 1---> X(:,k+1) = X(:,k) + 0.1* ((sum(bsxfun(@minus,X(:,k).',X(:,k)),2)));
Solution 2---> X(i,k+1) = X(i,k) + 0.1*((( X(j,k)-X(i,k))));
      end
    end
   k = k + 1;
end

A: In explicit form
$$X_1(k+1)=X_1(k)+0.1\bigg((X_1(k)-X_1(k))+(X_1(k)-X_2(k))+...+(X_1(k)-X_N(k))\bigg)$$
$$X_2(k+1)=X_2(k)+0.1\bigg((X_2(k)-X_1(k))+(X_2(k)-X_2(k))+...+(X_2(k)-X_N(k))\bigg)$$
$$...$$
$$X_N(k+1)=X_N(k)+0.1\bigg((X_N(k)-X_1(k))+(X_N(k)-X_2(k))+...+(X_N(k)-X_N(k))\bigg)$$
The algorithm should be
while( k < t )
   for i = 1 : N
      sum=0;
      for j = 1 : N
         sum=sum+0.1*(X(i,k)-X(j,k));
      end
      X(i,k+1)=X(i,k)+sum;
   end
k = k + 1;
end


text:
Q: How can i send a email notification to a person who triggered the pipeline? Usecase
I am having a cross-account codepipeline where my codecommit in one account and my pipeline is in another account. My codecommit is source for the pipeline means any commit in that will trigger the pipeline. Codecommit is shared among 50 developers.
Codepipeline Features
I know the codepipeline will trigger emails based on cloudwatch events rules when there is a change in pipeline. For triggering emails we need to create SNS topic and add the subscribers to it. But the problem is the mail will trigger to all the guys who are in that topic.
What i want
I want to send an email to the owner and also to the person who triggered the codepipeline(i.e.Developer). Sending the email to the owner process can be done since the owner is one entity. But sending a mail to the person who triggered might be a tricky one. Is there any feature that AWS has for this type of usecase ?
What i did and planning to do
For now, i can able to the get the developer email id by using codecommit API method getcommit which will take commitID as input. So, that means i need to pass the commitID manually to get the email id of the developer. So, in the codepipeline i need to create a lambda function which create a SNS topic and add  developer emailID to it and create a cloudevent event rule with this SNS topic and delete as soon as the codepipeline gets complete.
Is there any better approach ?
Any help is appreciated
Thanks


text:
Q: How to calculate the evaluation metrics on streaming data for online ML algorithms I am working on a binary classification problem where I need to develop an online ML model that can work on streaming data. However, I am not sure how can I use the evaluation metrics for classification such as precision, recall and F-score to evaluate the performance of the model on the streaming data.
One way that I found was that we can apply a sliding window and calculate the evaluation metrics per window. Then, we calculate the final results for all windows. I am not sure if this is a naive way to do it and there is more advance way to do it.
Note, we assume the data arrive sequential in streaming manner, which it is different from batch settings where we have all the data in advance. This requires us to calculate the evaluation metrics according to the streaming settings.


text:
Q: MySQL join / sum value from one table colum with a count values from another Table 1 - "news"
--------------------------------------
|news_id|news_title|fb_comments_count|
--------------------------------------
|     1|        XYZ|                0|
|     2|        ABC|               32|
|     3|        DEF|                5|
--------------------------------------

Table 2 - "news_comments"
------------------------------
|com_id|   news_id|   comment|
------------------------------
|     1|         1| blablabla|
|     2|         2| test     |
|     3|         1| comment  |
|     4|         1| asdf     |
------------------------------

I need to get total comments sum for every single news, where facebook comments count from the first table and total count of comments for every specific news from the other table, are counted together.
Like this - "Total comments":
-----------------------------------
|   id | news_id  | total comments (fb_comments + count of comments from comments table)
-----------------------------------
|     1|        2 |             33|
|     2|        3 |              5|
|     3|        1 |              3|
-----------------------------------

Thanks in advance! :)

A: A simple join and a group by can count all your comments with COUNT(). Then simply add this to the fb_comment_count. We use a LEFT JOIN to make sure it also includes news_id's that don't occur in news_comments, and apply the COUNT() only to c.com_id, to ensure this will give 0 for these situations when there are no news_comments for this news_id.
SELECT n.news_id, COUNT(c.com_id) + n.fb_comments_count AS total_comments
FROM news n
LEFT OUTER JOIN news_comments c ON c.news_id = n.news_id
GROUP BY n.news_id, n.fb_comments_count

A: SET @rank=0;

SELECT @rank:=@rank+1 AS id,t.*
FROM(
      SELECT n.news_id,
        (COALESCE(nc.totalComments,0) + n.fb_comments_count) AS total_comments
      FROM news n
      LEFT JOIN
      (
        SELECT news_id,COUNT(*) as totalComments
        FROM news_comments
        GROUP BY news_id
      )nc
      ON n.news_id = nc.news_id
      ORDER BY total_comments desc

     ) t

SQL Fiddle Demo


text:
Q: "@Where" and "cascade = CascadeType.ALL" not working at the same time I have JPA entity(Product Entity) which use the @Where annotation per bellow , and at the same time , I am using cascade = CascadeType.ALL as well.  ( Product is a Parent Entity and Storage is a Child Entity)
 @OneToMany(cascade = CascadeType.ALL, mappedBy = "productid")
    @Immutable
    @Where(clause = "isprimary='true'")
    private List<Storage> storageList;

Problem happens when I want to delete the Product (Parent) Entity. Since "Product" Entity has a relation to "Storage" Entity and I am using "Where" annotation with the criteria "isprimary=true" , It would not delete the "Storage" Entity which has a isrimary=false .
Any suggestion that how can I resolve the issue .
My request is , how may I delete all Storage(Child) Entity ( whether has isprimary is true or false) and at the same time , I can use the @Where anotation as well.

A: Maybe add a second list with the other entries:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "productid")
@Immutable
@Where(clause = "isprimary='true'")
private List<Storage> storageList;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "productid")
@Immutable
@Where(clause = "isprimary='false'")
private List<Storage> storageListNotPrimary;


text:
Q: trouble with iframe and php I have an issue and need some clarification
I have a wordpress site i am building and every time i try and code jquery into the theme i get errors so my work around has been to use two iframes....one being the menu
Can you have a link in a iframe load that links content in the area outside the iframe...if so how....if not is there a work around.
<iframe src="http://www.heartkidsplayshop.com/wp-content/themes/outreach/menu/all-examples.html" width="620" height="110" frameborder="0"></iframe>

A: Yes, use target="_parent" on the links in the iFrame.


text:
Q: My ASP.NET Website throws an error because a referenced assembly is missing a dependent assembly My ASP.NET website is throwing an exception on the first request - which is when the app is first starting.

So it's saying that some Assembly has a dependency on another assembly (in this case, Json v 4.5) and that dependency is missing.
How can I figure out what is the parent Assembly is?


text:
Q: Docker Installation: ImportError: cannot import name '_gi' from 'gi' (/usr/lib/python3/dist-packages/gi/__init__.py) I am getting following error while Adding the Docker repository to APT sources for installing docker in ubuntu 18.04 using this tutorial install docker ubuntu 18.04:
$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable"
Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 12, in <module>
    from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 67, in <module>
    from gi.repository import Gio
  File "/usr/lib/python3/dist-packages/gi/__init__.py", line 42, in <module>
    from . import _gi
ImportError: cannot import name '_gi' from 'gi' (/usr/lib/python3/dist-packages/gi/__init__.py)

Tried to change the python version from 3.7 to 3.6 with no luck.  Any help would be highly appreciated.
Thanks.

A: Worked using this command in python3.7 Source
sudo ln -s /usr/lib/python3/dist-packages/gi/_gi.cpython-{36m,37m}-x86_64-linux-gnu.so


text:
Q: AND and OR in Mongo Query I'm using multiple operators in this query. I get no syntax errors, but I'm not getting any data back (and should be), so I'm pretty certain that I'm looking at a logical error. Problem is, I don't see it.
Query:
db.questions.find(
    {'$and': [
        {'answers.s_user_id': {'$ne': s_user_id}},
        {'$or': [
                {'s_text': re.compile(s_term, re.IGNORECASE)},
                {'choices': re.compile(s_term, re.IGNORECASE)}
        ]}
    ]}
)

Any tips are appreciated.

A: I just found the issue as documented here: https://jira.mongodb.org/browse/SERVER-2585
Nested $OR is not supported until MongoDB 1.9.1 as of 7-24-2011. I'm on an older version.

A: Please find the query
AND Queries With Multiple Expressions Specifying the Same Operator

Consider the following example:

db.inventory.find( {
    $and : [
        { $or : [ { price : 0.99 }, { price : 1.99 } ] },
        { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
    ]
} )


text:
Q: POST the dropdown selected values to nodejs I want to post the dropdown value from react to NodeJS.
my react code:
import React from 'react'
import axios from 'axios'
export default class Inference extends React.Component {
    constructor(props) {
      super(props);
      this.state = {

        model: "",

        options: [
          { label: "Cat", value: "cat" },
          { label: "Traffic", value: "traffic" },
          { label: "Dog", value: "dog" },
        ],
      };
      this.handleChange = this.handleChange.bind(this);
    }

    handleChange(e) {

      this.setState({ model: e.target.value });
      console.log("Model Selected!!");
    }

    handleSubmit(event) {
      event.preventDefault();
      const { example } = event.target;
      console.log("value", example.value);
    }

    componentDidMount() {
        axios
    .post('http://localhost:5000/getmodel', {

      model: this.state.model,

    })
    .then((res) => {
      // Res.data is the response from your server
      console.log(res.data);
    });

    }

    render() {

      const {  options } = this.state;

      return (

                Model
                <form method="post" action="/getmodel" onSubmit={this.handleSubmit}>
                  <select
                    className="custom-select"
                    name="example"
                    value={this.state.model}
                    onChange={this.handleChange}
                    style={{ paddingTop: "5px", marginTop: "10px" }}
                  >
                    <option>--Select--</option>
                    {options.map((option) => (
                      <option
                        value={option.value}
                        onChange={(e) => this.setState({ model: e.target.value })}
                      >
                        {option.label}
                      </option>
                    ))}
                  </select>

                  <button
                    type="submit"
                    class="btn btn-success"
                    style={{ marginTop: "100px" }}
                  >
                    Inference
                  </button>
                </form>

      );
    }
  }

my nodejs code:
  app.post('/getmodel', (req, res) => {
        // Logs course sent from front end
        console.log(req.body.model);
      });
      app.get('/', function (req, res) {
        // Cookies that have not been signed
      console.log('hello: ',req.body)

      })

please guide me how to post the value to NodeJS so I can get value by req.body.model or something like that. how to get value from react as well I needed
Main motive: i want to get the dropdown selected value from reactjs to  NodeJS. i need some help in react post code and node get(for that post code) kindly help me

A: You can use axios to submit the request and include the information in the body of the request. The second parameter of the post method from axios is the body of your request. Here is an example of how to make an axios POST request with data.
axios
    .post('/some_endpoint', {
      dataset: this.state.dataset,
      model: this.state.model,
      course: this.state.course,
    })
    .then((res) => {
      // Res.data is the response from your server
      console.log(res.data);
    });

Now on your backend, you can access course through req.body
router.post('/some_endpoint', (req, res) => {
  // Logs course sent from front end
  console.log(req.body.course);
});

A: You added the axios in componentDidMount which is wrong, POST should happen when you submit the form. componentDidMount will call after every render it is a a lifecycle method. Please go through react documentation for a better explanation
Try this code POST API will call  when you click the submit button which is "Inference" button
import React from 'react'
import axios from 'axios'
export default class Inference extends React.Component {
    constructor(props) {
      super(props);
      this.state = {

        model: "",

        options: [
          { label: "Cat", value: "cat" },
          { label: "Traffic", value: "traffic" },
          { label: "Dog", value: "dog" },
        ],
      };
      this.handleChange = this.handleChange.bind(this);
    }

    handleChange(e) {

      this.setState({ model: e.target.value });
      console.log("Model Selected!!");
    }

    handleSubmit(event) {
      event.preventDefault();
      axios.post('http://localhost:5000/getmodel', {
        model: this.state.model,
      })
       .then((res) => {
        // Res.data is the response from your server
        console.log(res.data);
      });
    }

    render() {

      const {  options } = this.state;

      return (

                Model
                <form onSubmit={this.handleSubmit.bind(this)}>
                  <select
                    className="custom-select"
                    name="example"
                    value={this.state.model}
                    onChange={this.handleChange}
                    style={{ paddingTop: "5px", marginTop: "10px" }}
                  >
                    <option>--Select--</option>
                    {options.map((option) => (
                      <option
                        value={option.value}
                        onChange={(e) => this.setState({ model: e.target.value })}
                      >
                        {option.label}
                      </option>
                    ))}
                  </select>

                  <button
                    type="submit"
                    class="btn btn-success"
                    style={{ marginTop: "100px" }}
                  >
                    Inference
                  </button>
                </form>

      );
    }
  }


text:
Q: Reverse number after inputting an integer and doubling it the directions are the following: input an integer, then double integer value, then call your static void reverse( long i ) method. The method void reverse( long i) displays the integer in reverse terminated by a new line.
I need help in reversing the integer. I think I have the rest of the code correctly. But, correct me if I'm wrong.
    import java.util.Scanner;

public class Exercise5_3M {
    public static void reverse(String[] args) {
    Scanner input = new Scanner(System.in);

    //input an integer
    int num= input.nextInt();
    int result=0;

     //Double the intger
    while(num>0){
    result= num *2;

        }

System.out.print(result);
    }
}

A: at first of all you need void reverse( long i) instead void reverse(String[] args)
at second
while(num>0){
    result= num *2;
}

never end, because num never change

A: Your method should be called "main" when you want to execute it on start.
Second you created an infinity loop with your while when sb enters a positive number. A negative always returns 0.
Third you have no method called reverse(long i).
Fourth boundary check. Are only positive numbers allowed or negative also?
For a tip: You can reverse it in multiple ways. Convert your number to a string or char array and reverse it. Or you want to have a look at the mod operator "%".


text:
Q: Twitter API V2 - Increase Rate Limit and Get Rate Limit Status I'm using following Twitter APIs

*

*https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets

*https://developer.twitter.com/en/docs/twitter-api/tweets/retweets/api-reference/post-users-id-retweets

*https://developer.twitter.com/en/docs/twitter-api/users/follows/api-reference/post-users-source_user_id-following
The rate limit for these APIs are https://developer.twitter.com/en/docs/twitter-api/rate-limits here.
Twitter API Rate Limit Image
The solutions I needed:

*

*How can I increase the APIs rate limit?

*I'm using https://developer.twitter.com/en/docs/twitter-api/v1/developer-utilities/rate-limit-status/api-reference/get-application-rate_limit_status API to get the APIs usage status, but it's returning same value in limit and remaining field. How can I get the exact usage details of APIs?

*How I can get the daily API APP limits? The API seems to be returning 15 minutes limits, but I need to know how much app limit quota is remaining.

A: The post limits (Tweets, retweets, Direct Messages etc) are per-user quota. You can find out more about them from Twitter's help pages.

The current technical limits for accounts are:

*

*Direct Messages (daily): The limit is 1,000 messages sent per day.

*Tweets: 2,400 per day. The daily update limit is further broken down into smaller limits for semi-hourly intervals. Retweets are counted as Tweets.

These limits are shared across all of the apps a user might use within a day. There is no API endpoint or header that shows what the current quota is - you have to account for this in your code.


text:
Q: Анимация при нажатии css Хочу попробовать повторить анимационный эффект который, пример его по ссылке пример, при переходе с вкладки на вкладку "О репетиторе" и "отзывы" медленно появляется и исчезает нижний бордер.
Имею конструкцию

Где при клике на блок добавляю class1 JSoм
Пробовал втупую скопировать не получилось. Читал материалы о transition и в основном примеры с hover. Подскажите пожалуйста как работать с кликом.

A: Вместо border лучше использовать псевдо-элемент after, с ним можно придумать больше вариантов анимации

const $tabs = $('.block');

$tabs.on('click', function () {
  $tabs.removeClass('active');

  $(this).addClass('active');
})
.block {
  position: relative;
  display: inline-block;
  font-family: Arial, sans-serif;
  font-size: 16px;
  padding: 5px 10px;
  margin-right: 15px;
  cursor: pointer;
}

.block:after {
  content: '';
  position: absolute;
  bottom: -2px;
  height: 2px;
  background: #333;
}

.block.animation1:after {
  left: 100%;
  right: 0;
  transition: left .3s ease;
}

.block.animation2:after {
  left: 0;
  right: 100%;
  transition: right .3s ease;
}

.block.active:after {
  left: 0;
  right: 0;
}

  Раз Кнопка

  Два Кнопка

A: В указанном выше ответе не совсем точно копирует действия из примера, так как анимация меняется в зависимости от позиции предыдущего активного пункта, то есть анимация может быть слева на право, либо наоборот. Вот примерно так (красоту оставлю на ваше усмотрение):

$(function() {
  var menuItem = '.menu-item',
      $menuItem = $(menuItem);

  $menuItem.on('click', function() {
    var lastIndex = $(menuItem + '.active').index(),
        newIndex = $(this).index();

    $menuItem.removeClass('active active-from-left active-from-right');

    var className = 'active-from-right';

    if (lastIndex <= newIndex) {
        className = 'active-from-left';
    }

    $(this).addClass(className).delay(1).queue(function(next) {
        $(this).addClass('active');
        next();
    })
  })
})
.menu-item {
  display: inline-block;
  position: relative;
}
.menu-item.active-from-left.active:before {
  right: 0px;
}
.menu-item.active-from-left:before {
  content: '';
  position: absolute;
  bottom: 0px;
  left: 0px;
  right: 100%;
  height: 2px;
  background: red;
  transition: all .4s;
}
.menu-item.active-from-right.active:before {
  left: 0;
}
.menu-item.active-from-right:before {
  content: '';
  position: absolute;
  bottom: 0px;
  left: 100%;
  right: 0;
  height: 2px;
  background: red;
  transition: all .4s;
}

Пункт 1

Пункт 2

Пункт 3


text:
Q: Netezza INSERT - ignore invalid dates? Is there an option or setting that will tell Netezza to ignore invalid dates ?  The entire INSERT fails in the example below because the 3rd row of the source table has an invalid date.  I would expect that the offending row may be skipped, but to insert zero rows seems a tad extreme.
I tried the following, but it failed as well.  The alternative is parsing the source date and verifying each component for validity ( including days/month, leap years etc.. )
insert into db.test ( cmclmn, effdt, efftm )
        select cmclmn, case when to_date(effdt,'yyyymmdd') is null
                         then null
                         else to_date(effdt,'yyyymmdd') end,
               cast(lpad(efftm,6,0) as time) as efftm
          from db.test_src
          ;

Entire script:
CREATE TABLE db.test
(
        cmclmn integer,
        effdt   date,
        efftm   time
        )
DISTRIBUTE ON ( cmclmn );

drop table db.test_src;
create table db.test_src
(
        cmclmn integer,
        effdt integer,
        efftm integer)
        distribute on ( cmclmn );

insert into db.test_src ( cmclmn, effdt, efftm ) values  ( 1,20140120, 102000);
insert into db.test_src ( cmclmn, effdt, efftm ) values  ( 2,20140121, 231212);
insert into db.test_src ( cmclmn, effdt, efftm ) values  ( 3,0,111111 );
insert into db.test_src ( cmclmn, effdt, efftm ) values  ( 4,20140123 ,90909 );

insert into db.test ( cmclmn, effdt, efftm )
        select cmclmn, to_date(effdt,'yyyymmdd'), cast(lpad(efftm,6,0) as time) as efftm
          from db.test_src
          ;

A: You can create a user defined function to do a full test.  For your case, perhaps some simpler things will do:
insert into db.test ( cmclmn, effdt, efftm )
    select cmclmn, to_date(effdt,'yyyymmdd'), cast(lpad(efftm,6,0) as time) as efftm
    from db.test_src
    where effdt between 20010000 and 20150000 and
          effdt % 10000 between 0101 and 1231 and
          effdt between 01 and 31;

I'm not sure if Netezza ever optimizes queries so the to_date() might run before the filter.  If so, then use case as well:
insert into db.test ( cmclmn, effdt, efftm )
    select cmclmn,
           (case when effdt between 20010000 and 20150000 and
                      effdt % 10000 between 0101 and 1231 and
                      effdt % 100 between 01 and 31
                 then to_date(effdt,'yyyymmdd')
            end),
           cast(lpad(efftm,6,0) as time) as efftm
    from db.test_src
    where effdt between 20010000 and 20150000 and
          effdt % 10000 between 0101 and 1231 and
          effdt % 100 between 01 and 31;

The date checking isn't perfect, but it might be sufficient for your purposes.

A: Netezza Analytics Package 3.0 ships with some sample LUA functions, isdate() and todate() are two of the functions there.
Those functions trap the return code before it craps out the query.  isdate() returns a boolean result that tells you if the date is valid or not, todate() will return the Netezza date value or null if the incoming argument is not a valid date.
Thanks.


text:
Q: Unable to scan with IrfanView (SAMSUNG Xpress M2070) I have recently installed the drivers from the disc, but i'm unable to scan with IrfanView. I did some screenshots of the problem:

How could I solve the problem?

*

*Windows 8.1 x64

*SAMSUNG Xpress M2070

*IrfanView 4.3.8

A: I was able to use IrfanView finally. I just didn't select any of the TWAIN sources and now it works.


text:
Q: Fillable list ignored while inserting related model I am using Ardent and I faced strange behaviour of ignoring $fillable list while inserting/updating related models.
I have the following models defined:
class User extends LaravelBook\Ardent\Ardent
{
    protected $table = 'users';

    public static $relationsData = [
        'contacts' => [self::HAS_MANY, 'Contact'],
    ];
}

class Contact extends LaravelBook\Ardent\Ardent
{
    protected $table    = 'user_contacts';
    protected $guarded  = ['*'];
    protected $fillable = [
        'user_id',
        'type',
        'value'
    ];

    public static $relationsData = [
         'user' => [self::BELONGS_TO, 'User'],
    ];
}

Now I am trying to add new contact to user:
    $user->contacts()->create([
    'type' => 'some type',
    'value' => 'some value',
    'unknown_field' => 'unknown value'
]);

... and I got SQL insert error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'unknown_field' in 'field list'     (SQL: insert into `user_contacts` (`type`, `value`, `unknown_field`, `user_id`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?)) (Bindings: array ( 0 => 'some type', 1 => 'some value', 2 => 'unknown value', 3 => 2, 4 => '1384854899', 5 => '1384854899', ))

In the same time this is working fine:
UserContact::create([
    'user_id'       => 2,
    'type'          => 'some type',
    'value'         => 'some value',
    'unknown_field' => 'unknown value'
]);

I didn't get any SQL errors and 'unknown_field' was just ignored.
Any ideas why $fillable fields could be ignored while working via builder?!

A: I don't understand why the HasManyOrOne relationship intentionally ignores fillable. It seems really counter intuitive. Either way, I think this should work for you.
$user->contacts()->save(Contact::create([ ... ]));

A: It seems I found the reason of this behaviour. This is explicitly implemented in HasOneOrMany abstract class.
abstract class HasOneOrMany extends Relation {

    ...

    /**
     * Create a new instance of the related model.
     *
     * @param  array  $attributes
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function create(array $attributes)
    {
        $foreign = array(
            $this->getPlainForeignKey() => $this->parent->getKey()
        );

        // Here we will set the raw attributes to avoid hitting the "fill" method so
        // that we do not have to worry about a mass accessor rules blocking sets
        // on the models. Otherwise, some of these attributes will not get set.
        $instance = $this->related->newInstance();

        $instance->setRawAttributes(array_merge($attributes, $foreign));

        $instance->save();

        return $instance;
    }

    ...
}

I am still looking for the suffitient solution to control this behaviour.

A: As stated in the offical documentation:

To get started, set the fillable or guarded properties on your model.

You have set both. You should remove the following line: protected $guarded  = ['*'];

A: Fortunately this will be fixed in version 4.2: https://github.com/laravel/framework/pull/2846
Added to all this, you can also filter the attributes manually:
$input = [
    'user_id'       => 2,
    'type'          => 'some type',
    'value'         => 'some value',
    'unknown_field' => 'unknown value'
];

$fillable = $user->contacts()->getRelated()->fillableFromArray($input);

$user->contacts()->create($fillable);

Keeping in mind that the example are using Eloquent\Model\fillableFromArray() method, which is protected, so it will be necessary, for example, replicate it:
class BaseModel extends Eloquent
{
    public function fillableFromArray(array $attributes)
    {
        return parent::fillableFromArray($attributes);
    }
}

A: Use protected $guarded  = array(); instead of protected $guarded  = ['*'];
by using [*] you're telling laravel to guard all entities from autohydration / mass assignment!
array() sets this $guarded list to null.

The fillable property specifies which attributes should be mass-assignable. This can be set at the class or instance level.
The inverse of fillable is guarded, and serves as a "black-list" instead of a "white-list":

Read more at Laravel documentation on mass assignment

A: The update methods are not on the model level, and won't respect the $fillable fields.
You could filter the input data by using Input::only['fillable fields here']


text:
Q: SNMP for Local printer? I am searching for a way to Get Information from a local printer. Maybe with the SNMP Protocol?
The printer is connected with USB or PPI (parallel port). All printers have a internal TotalPagesCount and support SNMP.
Here some examples of the Printers:

*

*Brother HL1430

*Brother HL5150

*Brother HL1230

*Kyocera 1118

*Kyocera 1128

*Kyocera 2000

*Kyocera 1300

*Kyocera 3920

*Kyocera 1920

*Kyocera 1350

Is this possible? Thanks

A: You can get out quite a bit of information about printers via WMI, though I'm not sure if it contains the information you're looking for:
http://msdn.microsoft.com/en-us/library/Aa394363
I think HP printers store their Serial-numbers somewhere under this registry key (possibly a key called identity or similar):
HKEY_LOCAL_MACHINE\SOFTWARE\Hewlett-Packard\
I've never used SNMP, though I remembered this library that might be of use if you go down that route:
http://www.codeproject.com/KB/cs/SNMPDLL.aspx

A: I think SNMP is the correct approach. Most printers implement the standard printer MIB and the RFC 1213 MIB so any property you can get from there is going to be model independent. For instance, if you look for the serial number your property is probably prtGeneralSerialNumber 1.3.6.1.2.1.43.5.1.1.17
For other properties you are going to need to search in the specific MIBs, for instance in the HP Laserjet MIB you have a lot of stuff like printed-media-usage,  printed-media-simplex-count, printed-media-duplex-count, usage-average-toner-coverage, scanned-media-usage,  total-color-page-count.....
To use SNMP the most extended library is Net-SNMP but it uses a C API and I don't recommend it if you need to use it in heavy multithreaded applications or using SNMPv3. There are other libraries like link text that look very promising, but most of the reliable libraries out there commercial and not very cheap.
All the above is quite easy to implement if the printer is network connected, now if the printer is USB or PPI connected you need to get your hands into the HP SNMP Proxy Agent, you can find a great post here.
It says that basically it is a little Windows software that piggy-backs on the standard Windows SNMP service and provides SNMP data on the default HP printer connected to a computer via USB or parallel cable. I don't know if it works with any other brands but it looks like it uses the standard protocol DOT4 over USB to emulate typical TCP/IP communications. If there is any standard method to connect to all those printers this one is the most promising.
Another method that I can think of is to hack the individual drivers of each model to see if they provide such information (which most certainly do) and make the respective calls to them to get it, but on this task I think that you are on your own.
EDIT
With driver hacking I mean reverse engineering probably the tools of each driver. For example, if a printer has a utility that shows the toner status try to understand how it works, I would start using Depends to open the executable and see which dlls it is using and what methods they publish, if you find a method like GetTonerStatus in the dll it is worth to try to use it.

(source: dependencywalker.com)
If the tool is written in .Net it much easier because yo can have access to the source code by decompiling it (I don't know about legal issues of this method). Use reflector to do it and you will see it clearly.

(source: corypeters.net)
There is a great book that covers this aspects called Reversing: Secrets of Reverse Engineering
As said before this is a long path but probably the only one to achieve what you want to do, you might want to reconsider the viability of project after investigating a bit the topics I mentioned.

A: SNMP standard does not support USB or other connection types. It only supports TCP/IP stack over Ethernet. Therefore, the answer should be NO or impossible.
But we do see some companies immplement SNMP over other network/connection types. However, such customization is not standardized, and you cannot make SNMP queries using standard MIB browsers or so on.


text:
Q: AppleScript to Launch 1Password mini I use 1Password to store my passwords, and fluid.app to create a few site-specific apps/browsers
While 1Password integrates well with Chrome, Safari and other browsers, it doesn't play nicely with Fluid apps, which is where my troubles lie.
I have therefore created a shortcut (with Keyboard Maestro) to run an applescript to open the mini, when I am in Fluid apps. However, I can't seem to get the applescript to launch the mini. Here are my attempts:

*

*tell application "1Password mini" to launch does nothing, though AppleScriptEditor doesn't report any errors

*tell application "1Password mini" to open nothing, though AppleScriptEditor doesn't report any errors

*tell application "1Password mini" to activate is pointless, as 1Password mini is already activated

*tell application "1Password" to open opens the main 1Password application, not the mini, which is what I need.

Interestingly, when I run (1), (2), and (3), AppleScriptEditor automatically replaces 1Password mini with 2BUA8C4S2C.com.agilebits.onepassword-osx-helper, which doesn't clarify things for me at all.
Does anybody have any clue how this can be solved?
I'm on OSX 10.10.2 (Yosemite), if it matters

A: I work for AgileBits, the developer of 1Password.
Looks like you found a solution, but here's another option for you:
open location "x-onepassword-helper://search/"

That AppleScript will open 1Password mini ready to search.
And if you're able to get the current website's domain from Fluid, you could even open 1Password Mini with a search term already filled in:
open location "x-onepassword-helper://search/twitter.com"

I hope that helps!

A: The solution was quite simple, with a little UI scripting:
tell application "System Events" to tell process "1Password mini"
    tell menu bar item 1 of menu bar 1 to click
end tell


text:
Q: Pass a list of directories to a find command How can I pass a list of directories to a find command?
Imagine you got the list as:
ls -d mydir*/

which would output mydir1, mydir2 and so on, but exclude otherdirs1, otherdirs2.
I'd like to run the following command on the list:
find <put here the name of each dir>  -type f -name "*.mp3" -print0 | xargs -0 ...

Trying to run this command on each directory separately:
find -type f -name "*.mp3" -print0 |
xargs -0  mplayer -vo dummy -ao dummy -identify 2>/dev/null |
 perl -nle '/ID_LENGTH=([0-9\.]+)/ && ($t +=$1) && printf "%02d:%02d:%02d\n",$t/3600,$t/60%60,$t%60' |
 tail -n 1

That means: find the mp3s, run mplayer to obtain meta-data on each file, sum all ID_LENGTH of each mp3 file, output sum of all mp3s in directory.

A: ls -d lists exactly what you passed it (except for the non-existing files). So assuming that there is at least one directory whose name begins with mydir, it's simply
find mydir*/ -type f -name .mp3 -print0 | …

Note that mydir*/ matches symbolic links to directories, and find will traverse the linked directories.
Normally xargs runs the command as few times as possible, passing it multiple arguments at a time. If you need to run the command for each file separately, tell it so:
find mydir*/ -type f -name .mp3 -print0 |
xargs -0 -n1 mplayer … |
perl …

Or do the simple thing and use the -exec option of find. You do lose the ability to filter the errors from find and from mplayer separately.
find mydir*/ -type f -name .mp3 -exec mplayer -vo dummy -ao dummy -identify {} \; 2>/dev/null |
perl …

By the way, why print all the lines if you only need the last one?
… | perl -nle '/ID_LENGTH=([0-9\.]+)/ && ($t +=$1); END {printf "%02d:%02d:%02d\n",$t/3600,$t/60%60,$t%60}'

In bash after running shopt -s globstar, in ksh after running set -o globstar, or in zsh out of the box, you can also use ** to match files in subdirectories recursively.
mycommand mydir*/**/*.mp3
for f in mydir*/**/*.mp3; do …

This also matches directories and symbolic links whose name ends in .mp3. Bash traverses symbolic links to directories while ksh and zsh do traverse mydir* if they're symbolic links to directories but omit symbolic links when recursing.
for f in mydir*/**/*.mp3; do
  mplayer -vo dummy -ao dummy -identify "$f" 2>/dev/null
done | perl …

ksh93 and zsh (but not bash, dash or pdksh) have floating point arithmetic, so you don't even need to invoke another tool such as Perl to do the sum.
typeset -F length=0
for f in mydir*/**/*.mp3; do
  length+=$(mplayer -vo dummy -ao dummy -identify "$f" 2>/dev/null |
            sed -n 's/^ID_LENGTH=//p')
done | perl …
printf "%02d:%02d:%02d\n" $((t/3600)) $((t/60%60)) $((t%60))


text:
Q: Creating multiple circles in a domain to represent multiple solid obstacles using python np. fromfunction command I am trying solve fluid flow around multiple cylinders in 2D. So I need to create circular obstacles in order to do that in the domain. I have tried to create multiple circles but plt.imshow() command is displaying only one. The following is the code for creating one circular obstacle.
import numpy as np
nx=300
ny=100
cx, cy, r= nx//4, ny//2, ny//9 #Circle coordinates
def circle(x, y):
    return (x-cx) **2+(y-cy) **2<r**2
obstacle=np.fromfunction(circle, (nx, ny))

Here one solid circular obstacle is created properly. However, I am unable to create multiple circular obstacles in the domain. Can you please help?


text:
Q: Books / Guides / Courses for mixed model? I have started working for a pharmaceutical firm as a junior statistician recently . In the daily basis I work with lots of studies where I have to apply the mixed models in order to demonstrate the equivalence or difference between 2 groups, given the experimental design (with presence of random factor, repeated measures, etc). Tbh I feel a bit lost, that is why I am looking for some books / courses so I can learn more about the mixed model. Below are what I would like to achieve:

*

*For a given design, know what to put in the model (e.g in SAS know how to write the model with the right syntax). I would also like to know how to set up a specific design in order to respond the request of the client.

*Understand the formulas and calculation, be able to interpret the results and to troubleshoot if there are problems.

Any suggestion would be greatly appreciated.
Thank you


text:
Q: How to make a "krul" (unofficial Dutch symbol for OK) Time and again I have been wanting to use a krul/krulletje in my documents. For instance in proofs consisting of multiple parts, as an alternative \qedsymbol, etc. But never could I find one.
How can I get it?
EDIT:
N.B. The krul can come in different forms. Compare for instance the tails of
 and .
I personally consider the first one sloppy and the second one desireable. But this is of course a very unofficial and hanwaving definition of what the krul should actually look like. I bet there will also be people who prefer the first type.
A short example of the krul in use can be seen here.

A: Have a look at http://detexify.kirelabs.org/classify.html, a VERY useful site!

A: If you are using pdfTeX then you can use \pdfliteral which draws the desired character directly. For example:
\def\krul{\leavevmode\hbox{\lower2.5pt\vbox to10pt{}\kern1.8pt
   \pdfliteral{q
   1 j .7 0 0 .7 0 0 cm
   -2 1 m
   3 2 4 5 4 7  c
   4 9 3 10 2 10 c
   1 10 0 9 0 7  c
   0 3 5 2 5 0 c
   5 -2 2 -3 1 -3 c
   S Q}\kern4.5pt}}

aha \krul.

\bye

yields

A: Here are some fonts which you could use with help of Lua- or XeLaTeX:
% arara: lualatex

\documentclass{article}
\usepackage{fontspec}

\begin{document}
\setmainfont{Arial}
\symbol{"20B0}
\setmainfont{Cambria}
\symbol{"20B0}
\setmainfont{Consolas}
\symbol{"20B0}
\setmainfont{Courier New}
\symbol{"20B0}
\setmainfont{Dejavu Sans}
\symbol{"20B0}
\setmainfont{Symbola}
\symbol{"20B0}
\setmainfont{Quivira}
\symbol{"20B0}
\setmainfont{Code2000}
\symbol{"20B0}
\setmainfont{Free Serif}
\symbol{"20B0}
\end{document}

A: The marvosym package has a symbol called \Denarius.  The package documentation says, "The \Denarius symbol is also known as the correction sign "Deleatur"."   The deleatur (https://en.wikipedia.org/wiki/Dele) is a proofreading symbol that would seem to be the counterpart to "stet".
In fact, the topic of the correspondence of deleatur and krul was discussed at our sister website https://graphicdesign.stackexchange.com/questions/58320/what-is-the-name-or-unicode-for-this-symbol-similar-to-%E2%82%B0-dutch-called-krul, as some of the answers allude to.
Below I show it as given, and then two clipped versions, as some might not like the extra curl.
\documentclass{article}
\usepackage{marvosym,trimclip,graphicx}
\def\krulA{\Denarius}
\def\krulB{\kern-1.5pt\rotatebox[origin=center]{22}{%
  \clipbox{5.5pt 0pt 0pt 0pt}{\rotatebox[origin=center]{-22}{\Denarius}}}\kern-2.5pt}
\def\krulC{\clipbox{4.5pt 0pt 0pt 0pt}{\rotatebox[origin=center]{-10}{\Denarius}}}
\begin{document}
\krulA, \krulB, or this \krulC.
\end{document}

The German wikipedia, https://de.wikipedia.org/wiki/Deleatur, says that the symbol has a unicode of  U+20B0, though I have not yet found a font that contains it.  However, the German rendition is not quite the same as shown above.

A: Thought I'd have a go ...
Using Drawing on an image with TikZ, I took your "desirable" krul symbol and drew on it until I had something that looked fairly similar.  I used the hobby package to define the béziers rather than fiddling with control points (to avoid recomputing the path each time the symbol is used, I used a nifty feature of the hobby package that allows for reuse of a hobbily defined path; a bit of box magic puts the definition at the start of the document without - I hope - taking up any space).
The key feature of this implementation is the use of the calligraphy package to style the lines.  This, in my opinion, makes it look more like a letter drawn with a pen than a squiggle.
For added bonus, I made it scale according to the fontsize.
\documentclass{article}
%\url{https://tex.stackexchange.com/q/313281/86}
% Uses:
%\url{https://tex.stackexchange.com/q/54771/86} (hobby package)
%\url{https://tex.stackexchange.com/q/16899/86} (calligraphy)
\usepackage{tikz}
\usetikzlibrary{calligraphy,hobby}

\AtBeginDocument{%
\setbox0=\vbox{\tikz \path[use Hobby shortcut,save Hobby path={krul}] (-.2,0.25) ..  (0,.45) .. (.2,.65) ..  (0.3,0.76) .. (0.4,.97) .. (.1,.8) .. (.05,.65) .. (.3,.5) .. (.3,.4) .. (.15,.1) .. (.15,.05) .. (.3,.05) .. (1,.7);}%
}

\newcommand{\krul}{%
  \tikz[scale=1em/1cm] \calligraphy[copperplate,restore and use Hobby path={krul}{}];%
}
\begin{document}

This statement is true \krul

{\Large This statement is true \krul }

{\Huge This statement is true \krul }

\end{document}

A: I created the symbol using tikz.  I chose to scale the krul to about a letter size, but one can of course change this.
Here's the code:
     \newcommand{\krul}{
\begin{tikzpicture}[scale=0.095]
\clip(2.8,0.95) rectangle (6.3,4.9);
\draw[very thick,color= black, ]
(2.916,1.685) ..controls %0
(3.100,1.594) and %1
(6.104,3.990) .. %2
(5.061,4.437) ..controls %3
(4.166,4.827) and %4
(3.077,3.853) .. %5
(3.535,3.119) ..controls %6
(3.857,2.580) and %7
(4.430,2.844) .. %8
(4.889,2.522) ..controls %9
(5.267,2.282) and %10
(4.086,0.929) .. %11
(5.129,1.238) ..controls %12
(6.150,1.548) .. %13
(6.150,1.548); %13
\end{tikzpicture}}

I got the code via Bézier curves in Geogebra. Once I got the krul, I exported the file as tikz-code.
In my humble opinion, it looks quite nice:

A: I think you can go with an inverted ampersand, I made it lowered a bit, too:

\documentclass{article}

\usepackage{graphicx,amsmath}

\DeclareRobustCommand*\krul{\text{\scalebox{-1}[1]{\raisebox{-0.7\dp\strutbox}{\&}}}}

\begin{document}

\section*{Hello, world \krul}

Hello, world \krul

\end{document}


text:
Q: Error installing Google OR-Tools in python I am trying to install the OR tools using this command:
python -m pip install --upgrade --user ortools

The reponse of the command line is the following:

ERROR: Could not find a version that satisfies the requirement ortools (from versions: none)
ERROR: No matching distribution found for ortools

I already installed the 64 bit python version 3.8 for Windows, but that did not seem to be the problem.
What can I do to install the ORtools?

A: Python 3.8 is too new.
You will need to wait for the next release or downgrade to python 3.7 for now. (I do not recommend install from source on windows)
See: issue at github
lperron commented on Nov 9
[...] should be next release.

CURRENT release:

v7.4 (2019-10)
lperron released this on Oct 11 · 143 commits to master since this release

Python 3.8 was released on October 14th, 2019.


text:
Q: A master RAML file with references to child RAMLs I have 2 RAML files (the must be v0.8) completely describing 2 resources: animals.raml and plants.raml.
They both contain something like:
#%RAML 0.8
---
title: Animals API
baseUri: http://something/
documentation:
  - title: Overview
    content: The */animals* resource allows you to...
mediaType: application/json

protocols:
  - HTTPS

/animals:
  post:
    description: Create a new animal
    body:
      schema: !include ./schemas/animal.schema.json
    responses:
      202:
        description: In a few months, your new pet will be born.

Now I would like to have a master file, api.raml, that would give a generic overview about the animals and plants resources.
The API reader would navigate to the api.raml and from there he would be able to navigate again to the specific raml. Or it can be all inlined, on the same page.
I naively tried
#%RAML 0.8
---
title: Zoo & Botanical garden APIs
documentation:
  - title: Overview
    content: The *Zoo & Botanical garden APIs* contain resources that allow you to ...

resourceTypes: !include animals.raml
resourceTypes: !include plants.raml

Obviously very naive, failed with many complaints about the title elements and many other.
How should I approach creating the master api.raml which basically need to contain only a generic info and then include/link to the specific RAMLs?

A: You cannot have "resourceTypes:" keyword twice, you either separate your resource types like this:
#%RAML 0.8
title: Example API
version: v1
resourceTypes:
   - collection: !include resourceTypes/collection.raml
   - member: !include resourceTypes/member.raml

or you include everything in one file and do like this:
#%RAML 0.8
title: Example API
version: v1
resourceTypes: !include resourceTypes.raml

Check here for more info on how to use includes.


text:
Q: How does the x86 ROR instruction works? My EAX register contains the xxxxxx9D value and I have the following assembly code:
C0C8 14 --> ROR AL,14

To me, it means that the last 8 bits of the EAX's 32 bits value are rotated bitwise by 14 mod 8 = 6 positions
0x9D = b1001 1101

will be transformed into
b0111 0110 = 0x76

However, OllyDbg tells me that EAX = xxxxxxD9, which means EAX has been rotated bitwise by 4 bits!
Where am I wrong?

A: You are trying to rotate an 8-bit register by 20 positions.  That's a bit much, rotating by 8 produces the same value.  Rotating by 9 is the same as rotating by 1.  Etcetera.  The processor will thus rotate by 20 mod 8 = 4 positions.

A: Post your complete code, with this:
mov     al,$9d
ror     al,14

I get 76 as expected.
Edit If you rotate by $14 positions, you will get d9.


text:
Q: How to get element from a collection with _.each() I have a backbone collection of models, now I want to access to each model from the collection and do something with it with _.each(), after looking into the underscore documentation, I come up with this first
_.each(this.someCollection, function(element) {
    console.log(element);
}

but element is undefined..., did some further reading and in the second try:
_.each(this.someCollection, function(element, index, list) {
    console.log(list.at(index);
}

this seem to work and get each model I want, but it seems very complicated to me to just get the element from each iterate. Is there a better/elegant way to do it? and what is first argument "element" good for? One would think it's should actually do what I needed...

A: this.collection returns not a models array but object containing properties of particular collection like
{length:2, models:(2) [s,s], _byId:{c119: s, c123: s}, _events:{…}, _listenId:"l1"}

if you want to access models of a collection, use models attribute, which returns you an array of models
_.each(this.someCollection.models, function(model) {
    console.log(model.toJSON());
    console.log(model.get('someProperty');
}

or use straight toJSON() on collection like
_.each(this.someCollection.toJSON(), function(model) {
    console.log(model);
    console.log(model.someProperty);
}


text:
Q: Unable to install my custom pip package from https://packagecloud.io/ I have created my package using python. I'm trying to distribute the package via https://packagecloud.io/. So I build pip package and updated in https://packagecloud.io/
But I'm getting an error when I try to install the same package in Ubutbu 18.04 .
root@1522cdc94a23:/# pip3 install mycli==0.0.1a0
Collecting mycli==0.0.1a0
Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 353, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/lib/python3/dist-packages/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 795, in get_page
    resp.raise_for_status()
  File "/usr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl/requests/models.py", line 935, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://pypi.org/simple/mycli/

Verified the extra-index-url parameter in ~/.pip/pip.conf. Its having the packagecloud.in url
Added --index-url as per the suggestion.
Yep. it's working. But another default sample package ( from packagecloud.io) is working as expected without --index-url
~$ cat ~/.pip/pip.conf
[global]
extra-index-url=https://<token>:@packagecloud.io/sivak/MyTest/pypi/simple

packagecloud_test-0.9.7b1.tar.gz is the test package which is provided by packagecloud.io for testing.

A: By default, pip search for packages on pypi.org.
Just tell pip to search in another repository with:
pip install --index-url https://packagecloud.io/ mycli==0.0.1a0

Trying that may confirm a pip configuration problem in your pip.conf file.

A: Are you sure that the version you ask exists on the desired remote?
It seems that available versions in the error message below does not mention version 0.0.1a0:
ERROR: Could not find a version that satisfies the requirement mycli==0.0.1a0 (from versions: 1.0.0, 1.0.1, 1.1.1, 1.2.0, 1.3.0, 1.4.0, 1.5.0, 1.5.1, 1.5.2, 1.6.0, 1.7.0.0, 1.7.1, 1.8.0, 1.8.1, 1.9.0, 1.10.0, 1.11.0, 1.12.0, 1.12.1, 1.13.0, 1.13.1, 1.14.0, 1.15.0, 1.16.0, 1.17.0, 1.18.0, 1.18.1, 1.18.2, 1.19.0, 1.20.0, 1.20.1)
ERROR: No matching distribution found for mycli==0.0.1a0

Just remove the revision requirement on install command:
pip3 install mycli

A: The issue has been resolved when I update the pip. I guess there was a bug in pip version: 9.0.1.


text:
Q: pygame.sprite.Sprite.add() argument after * must be an iterable, not int so i'm working on my game on python. i wanted to add damage text, so i made a class for it.
class damageShow(pygame.sprite.Sprite):
    def __init___(self, x, y, dmg):
        pygame.sprite.Sprite.__init__(self)
        self.image = myfont.render(dmg, True, red)
        self.rect = self.img.get_rect()
        self.rect.center = (x, y)
        self.timer = 0
    def update(self):
        self.rect.y -= 1
        self.timer += 1
        if self.timer >= 30:
            self.kill()

and i called it in my attack function.
if ability2:
            #the indentation is fine, idk why it pasted like this
            if self.xp >= spellDC:
                rand2 = random.randint(int(self.spellD*.8), self.spellD)
                target.hp -= rand2

                self.xp -= spellDC
                target.damaged()
                if target.hp < 1:
                    target.hp = 0
                    target.alive = False
                    target.death()
                damageText = damageShow(target.rect.centerx, target.rect.y, (str(rand2))) # here
                #i defined damageGroup with pygame.sprite.Group()
                damageGroup.add(damageText)
                self.action = 2
                self.frame = 0
                self.update_time = pygame.time.get_ticks()
                self.xp += random.randint(20, 30)

it shows an error of "pygame.sprite.Sprite.add() argument after * must be an iterable, not int" how do i get rid of the error?


text:
Q: How to find deeply embedded children with jquery I have a dom tree that looks like this:

How would I use jquery to go through each anchor tag and add a target="_blank";
Adding classes is not an option. I'm using node with an api call off to a cms to pull in markdown and parse it into html.
What I have:
$('#specs-container.specs > ul > li').children('a').each(function () {
            $(this).attr('target', '_blank');
        });

Thanks!

A: You can write it like this:
$('.specs ul li a').attr('target', '_blank');

But don't forget to fix your HTML code (quotes and missing closing
 tag).
HTML should be like this:

A: There were a few issues with your code. Firstly, you were missing a closing " for your specs element in the HTML, next you were missing a closing
 at the end of your list, and finally your jQuery code was targeting an ID which does not exist in the HTML you provided.

$(function() {
  $('.specs > ul > li').children('a').each(function () {
      $(this).attr('target', '_blank');
  });
});

      Test

      Test 2


text:
Q: What is the name of the basis writing stroke? I can't recall the name of the standard writing stroke in the English script. Apologies in advance if this is off topic.
This stroke is the single vertical stroke fundamental to many letters. A single stroke is the basis for the letter i, a lengthened one above is the basis for l, lengthened below is the basis for j. Likewise, connecting two at the top is basis for n, two at the bottom basis for u, and the bases for m and w follow by connecting three.
Does anyone know the actual term for this basis stroke?

A: I never heard it called anything other than a downstroke.

A: I believe stem is the word you are looking for.

A: Writing the alphabet in different strokes was established even earlier than 18th century and modern English alphabet strokes are called "breaks" and "joints". Joints strokes are taught for secretarial writing usually and the other is for standard writing of English alphabet.


text:
Q: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray). tensorflow please help explaining what am I doing wrong here for a complete newbie.
This is my first ever ml code and it is used for object detection. Please tell me my mistakes and how to make them right!
from numpy.lib.shape_base import split
from numpy.core.fromnumeric import var
from numpy.core.memmap import ndarray
from tensorflow_datasets.object_detection.voc import Voc
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np
import matplotlib.pyplot as plt

voc = tfds.object_detection.voc
(training_images,training_labels) = tfds.as_numpy(tfds.load(
    'voc',
    split=['train','train'],batch_size=-1))
x = dict.items(training_images)
x =list(x)
x = np.array(x)

model = tf.keras.Sequential([   tf.keras.layers.Flatten(input_shape=(0,0,3)),
                                tf.keras.layers.Dense(18, activation = tf.nn.relu),
                                 tf.keras.layers.Dense(10)])

model.compile(optimizer=tf.keras.optimizers.Adam(0.1) , loss='sparse_categorical_crossentropy',
              metrics = ('accuracy'))
model.fit( x ,epochs=100)

Here is the full error message:
ValueError Traceback (most recent call last) <ipython-input-1-fbcca47159b2> in <module>
41 model.compile(optimizer=tf.keras.optimizers.Adam(0.1) , loss='sparse_categorical_crossentropy',
42 metrics = ('accuracy'))
---> 43 model.fit( x ,epochs=100)
44 45
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/constant_op.py in convert_to_eager_tensor(value, ctx, dtype)
100 dtype = dtypes.as_dtype(dtype).as_datatype_enum
101 ctx.ensure_initialized()
--> 102 return ops.EagerTensor(value, ctx.device_name, dtype)
103 104

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).

A: The problem is that you are passing the images and labels to model.fit together, but fit expects two separate arguments: one for the images and one for the labels.
Try changing your last line of code to this:
model.fit(x[0], training_labels, epochs=100)


text:
Q: How to avoid code duplication for input variable declaration/instantiation in Terraform? I want to create a variable 'blueprint' and instantiate it several times. How do I achieve this?
Example :
my_project
|--main.tf
|--variables.tf
|--variables.tfvars

*

*In the main.tf I declare resources that use variables,

*In variables.tf module I want this sample variable

variable "project_info" {
  type = object({
    name = string
    id   = string
  })
}

*

*In variables.tfvars I want this (Kind of)

project_1_info = {
  name = "prj-1"
  id   = "prj-1-192388"
}

project_2_info = {
  name = "prj-2"
  id   = "prj-2-120917"
}

At the moment, what I declare in the variables.tf module is the following :
variable "project_1_info" {
  type = object({
    name = string
    id   = string
  })
}

variable "project_2_info" {
  type = object({
    name = string
    id   = string
  })
}

Which I find quite repetitive by duplicating declarations, makes maintenance and readability worse.
Any suggestions? Can this even be achieved with HCL?

A: Usually you would use map for that:
variable "project" {
  type = map(object({
    name = string
    id   = string
  }))
}

with a value:
project = {
  project1name = {
      name = "prj-1"
      id   = "prj-1-192388"
  },
  project2name = {
      name = "prj-2"
      id   = "prj-2-192388"
  },
  project3name = {
      name = "prj-3"
      id   = "prj-3-192388"
  }
}


text:
Q: How to run multiple services on a EC2 container instance and have Healthy Targets for Health Checks? I have an unusual problem (perhaps an easy solution but I tried a few ways without success).
I have 2 tasks running on a EC2 container instance in an ECS cluster.

Task 1 is a DAEMON exposing port X
Task 2 is an application exposing port Y

They both are running. When I check the Health check status for the EC2 instance, it shows 2 entries for it.

Entry 1 is Healthy for the DAEMON health check port at port X
Entry 2 is Draining for the Application health check port at port Y

I would like a single entry (for the application health check port Y) for the EC2 instance and a Healthy state for it.
How can I accomplish this with the 2 tasks running on it. Should I not be exposing the Health Check port for the DAEMON task ?
EDIT:
Load balancer and Target Group config -
resource "aws_alb" "alb" {
  name            = "${var.alb_name}"
  subnets         = flatten(["${var.public_subnet_ids}"])
  security_groups = ["${aws_security_group.alb.id}"]

  access_logs {
    bucket  = "${aws_s3_bucket.alb-logs.bucket}"
    prefix  = "load-balancer-logs"
    enabled = true
  }

  tags = {
    Environment = "${var.environment}"
  }
}

resource "aws_alb_target_group" "lb_target_group_app" {
  name                 = "${var.alb_name}-default"
  /* port                 = 5555 */  /* DAMEON health check port */
  port                 = 5000 .   /* Application health check port */
  protocol             = "HTTP"
  vpc_id               = "${var.vpc_id}"
  deregistration_delay = "${var.deregistration_delay}"

  health_check {
    path     = "${var.health_check_path}"
    port = "5000"        /* Is this needed here ?  */
    interval = "300"
    timeout = "120"
  }

  lifecycle {
    create_before_destroy = true
  }

  depends_on = ["aws_alb.alb"]
}

resource "aws_alb_listener" "https_listener" {
  load_balancer_arn = "${aws_alb.alb.id}"
  port              = "443"
  protocol          = "HTTPS"
  ssl_policy        = "ELBSecurityPolicy-2016-08"
  certificate_arn = "${aws_acm_certificate.ssl_cert.arn}"

  default_action {
    target_group_arn = "${aws_alb_target_group.lb_target_group_app.arn}"
    type             = "forward"
  }
}

Container definition for dameon -

  container_definitions = <<EOF
[
  {
    "name": "${var.environment}-${var.datadog-identifier}",
    "image": "datadog/agent:latest",
    "portMappings": [
      {
        "containerPort": 8126,
        "hostPort": 8126,
        "protocol": "TCP"
      },
      {
        "containerPort": 5555,
        "hostPort": 5555,
        "protocol": "TCP"
      },
      {
        "containerPort": 8125,
        "hostPort": 8125,
        "protocol": "UDP"
      }
    ],
    "environment": [
      { "name" : "DD_API_KEY", "value" : "xxxxxxxxx" },
      { "name" : "DD_APM_NON_LOCAL_TRAFFIC", "value" : "true" },
      { "name" : "DD_DOGSTATSD_NON_LOCAL_TRAFFIC", "value" : "true" },
      { "name": "DD_LOG_LEVEL", "value": "trace" },
      { "name": "DD_SITE", "value": "datadoghq.com" },
      { "name": "DD_HEALTH_PORT", "value": "5555" },
      { "name" : "DD_PROCESS_AGENT_ENABLED", "value" : "true" },
      { "name" : "DD_LOGS_ENABLED", "value" : "true" },
      { "name" : "DD_LOGS_CONFIG_CONTAINER_COLLECT_ALL", "value" : "true" },
      { "name" : "DD_APM_ENABLED", "value" : "true" }
    ],

Container definition for app -

    container_definitions = <<DEFINITION
[
  {
    "name": "app",
    "image": "quay.io/xxxxxxxx",
    "essential": true,
    "logConfiguration": {
      "logDriver": "awslogs",
      "options": {
        "awslogs-group": "/ec2/service/${var.cluster}",
        "awslogs-region": "us-west-2",
        "awslogs-stream-prefix": "ec2"
      }
    },
    "environment": [
      {
        "name": "APP_ENV",
        "value": "localhost"
      },
      {
        "name": "AUTH_JWT_SECRET",
        "value": "xxxxxxxx"
      }
    ],
    "portMappings": [
      {
        "containerPort": 5000,
        "hostPort": 5000,
        "protocol": "tcp"
      }
    ],

Service definition for dameon task -
resource "aws_ecs_service" "datadog" {
  name            = "${var.environment}-${var.datadog-identifier}-datadog-ecs-service"
  cluster         = "${var.cluster}"
  task_definition = "${aws_ecs_task_definition.datadog.arn}"

  load_balancer {
    target_group_arn = "${element(var.default_alb_target_group,0)}"
    container_name   = "${var.environment}-${var.datadog-identifier}"
    container_port   = 5555 .   /* datadog health check port */
  }
  # This allows running one for every instance
  scheduling_strategy = "DAEMON"
}

Service definition for app task -
resource "aws_ecs_service" "app-service" {
        name            = "app-service"
        cluster         = "${var.cluster}"
        task_definition = "${aws_ecs_task_definition.app.arn}"
        desired_count   = 2
        launch_type    = "EC2"

        load_balancer {
          target_group_arn  = "${element(var.default_alb_target_group,0)}"
          container_port    = 5000  /* app port exposed here */
          container_name    = "pared-somm"
        }

The way to reproduce this would be to -
1. Create ALB as below
2. Create 1 Target Group as below with a port to listen on. Add health check block to the Target Group (is port needed here or should I use Traffic port instead ?)
3. Create 2 tasks and service definitions (container definitions below) both pointing to the load balancer above. So when the tasks start running, they both run on the same targets in the above target group.
4. Check the Targets and their health and you should see 2 entries per target.


text:
Q: Как динамически проверять вводимые символы в input при использование маски Суть вопроса заключается в работе с плагином, и русском номере телефоне.
Я использую этот плагин: jQuery mask plugin
У меня настроена на инпут след. маска:
$('.PhoneNumber').mask('+7 (000) 000-00-00')

Тоесть маска настроена на международный формат. Бывают слепые пользователи, которые начинают вводить номер телефона с цифры 8, и не видят, что маска в инпуте автоматически подставляется и начинает писать значение с :
+7 (8..)

В результате история заканчивается тем, что слепой пользователь до конца вводит цифры, не смотря на экран, и получается последнюю цифру не вводит, так как маска ее не воспринимает, и мы получаем не верный номер телефона.
Вопрос заключается в том, как можно сделать так, что бы при первом вводе 8рки маска эту цифру не воспринимала, но если пользователь второй раз ввел 8 - то уже воспринимала. Если пользователь вводит любые цифры отличные от 8 то пропускать все символы.
Может кто то работал с плагином и сможет помочь решить вопрос?

A: $(...).one запускает функцию только один раз. А .slice() разрезает строку в указанных местах. В данном случае slice(0,1) — это первый символ.

$(document).one('input', '#PhoneNumber', function(){
  if( this.value.slice(0,1) == '8' ){
    this.value = this.value.replace(/^8/,'');
  }
});

$(document).on('click', '#send', function(){
  if( $('#PhoneNumber').val().length < 11 /*или какая там длина должна быть...*/){
    alert('Кажется введенный номер слишком короткий!');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input id="PhoneNumber">

<button id="send">Отправить</button>

Здесь есть минус - если сотрет и решит еще раз набрать - уже не сработает.
P.s. у меня там #id, а у вас .class, не перепутайте)


text:
Q: Push Notifications via PHP? So I'm working on an iPhone app and I'm looking for a Push Notification service which can send push notifications via PHP. Does anyone know about a service that offers that functionality ?

A: I think it is what you are looking for:
apple-push-notification-services

A: You should look at Easy APNS  It may help you
On this site you will find code snippets and instructions for:

*

*PHP Application Installation

*Installing MySQL Tables

*Configuring a Cron Job to Deliver Notifications

*Adding APNs to your Apple Delegate file


text:
Q: Project env vars (like GCP_PROJECT, CLOUDSDK_CORE_PROJECT) are no longer set when debugging cloud run locally I used to have a number of environment vars set when I tried to run my Cloud Run Dockerfile locally.

*

*GCP_PROJECT

*GCLOUD_PROJECT

*CLOUDSDK_CORE_PROJECT

*GOOGLE_CLOUD_PROJECT

They all were just the same value – my locally configured Google Cloud project.
Now they are all gone.
Am I doing something wrong with my configuration? Did something change recently?
Help!

A: Short-term work-around:
minikube delete --purge --all and run again.
Sounds like there might be a bug that Matthew will dig in on.


text:
Q: PWM Fan Controller, inverted duty cycle What I am trying to design is a 12 V DC controller for a PWM fan that uses a 100 Hz input signal and reversed duty cycle between 8 and 87 % to drive it. What I mean by reversed is that the fan is on full speed when at 8 % duty cycle and 87 % duty cycle yields minimum RPM (88 % will turn it off). I need to use a 0-5 VDC analog temperature sensor as an input signal and scale the duty cycle against it, 0 V being off, and 5 V full on, with a linear increase of speed in between. So a 0 V DC signal input to the controller would provide a 100 Hz 88 % (off) duty cycle signal from the controller and 5 V would provide an 8 % duty cycle (full speed) signal to the fan.
The controller doesn't handle the high current side of the fan at all, the fan has it's own wiring directly to the battery for that, so no relay or transistor would be required in the controller. If the controller is off, so is the fan.
Future plans for the controller would include a separate input that when triggered by a 12 V DC analog signal will cause the fan to go to max RPM (8 % duty cycle), and adjustable on/off points based on the 0-5 V DC input (narrowing the input voltage window [1-4 V DV, or 2-5 V DC, etc] to scale the PWM duty cycle against).
I'm not an electrical engineer by any means, but I do understand most concepts and parts involved in circuitry. I have been trying to build this device using off the shelf assembled PCB's but I couldn't find a pre-fabricated solution to scale the duty cycle in reverse based on the 0-5 V input.
I know it's a lot, but any help is greatly appreciated!


text:
Q: telegram with secret chats What is the best way to run telegram on linux with support for secret chats?
This is what I tried already:

*

*run telegram desktop - works very well but no secret chats feature

*pack android telegram apk as chrome app using ARC. Worked, have secret chats, unfortunately crashes sometimes, no easy to update

*compile telegram-cli and write some python wrapper (too much effort, not so user friendly, not easy for updates)

*install android telegram apk on android-x86 running on kvm or virtualbox (kind of heavy solution for chat application)

I will appreciate also another alternative open source  and trustworthy easy to use chat app with end-to-end encryption.
Thank you for your suggestions.

A: If you are a Pidgin user, there is a telegram-purple plugin:
https://github.com/majn/telegram-purple
It is provided for Ubuntu by the webupd8 repository:
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install telegram-purple

A: telegram-cli, although not the easiest to use, supports secret chats:
sudo snap install telegram-cli

but the pidgin plugin is easier from https://www.ubuntuupdates.org/ppa/webupd8?dist=bionic

A: If you can use another network, I'd suggest the Signal Desktop alternative. It's a similar Android app and now is more developed. Since April, end-to-end encryption was added.
SIGNAL DESKTOP
https://github.com/WhisperSystems/Signal-Desktop

A: If you want to stay with telegram you can use cutegram. I use 2.7.1 on w64. It has some issues (1) - prbably fixed in git already - but secret chats are working. HTH
(1) Sometimes attachments do not upload - cross check with phone.

A: There exist also an other method for telegram:
https://web.telegram.org/#/login
I don't know if you're able to use secret chats.With this options just try it :)
Try Tox, it's an open-source app with end-to-end encryption. Click on this  link for further informations:
official site Tox
It has a big community and the project is evolving fast


text:
Q: Spring data JPA and JdbcTemplate are not synchronous Im experiencing a problem with jdbcTemplate and JPA:
    public void test(){

     //assuming we have 3k users and use jdbcTemplate to perform batch update

     batchUpdateUsers(userList) ;
     //This list doesn't contain latest information of user after update
     List<User>updatedUsers = userRepository.findAll();
}

I guess after method batchUpdateUsers return, transaction was not committed or it has already been committed but there's delaying time to commit it to DB so the the fetched list later is not updated.
Is there any way to solve this problem? Thanks!

A: It looks like a transaction issue. If you declare a JpaTransactionManager and have a single Datasource, modifications made by batchUpdateUsers should be visible by userRepository.findAll
How do you manage transactions?  If you are using Spring Boot look at @EnableTransactionManagement and @Transactional annotations.


text:
Q: EPPlus Pivot table SubTotalFunctions produces spreadsheet error I am creating a pivot table to with data.  I create a RowField and attempt to add a SubTotalFunctions to that field.
When I open the .xlsx file, I get an error that says the file needs to be repaired.
Is this a bug or is there another option that I should be setting?

    using OfficeOpenXml;
    using OfficeOpenXml.Table.PivotTable;

    var data = Datas();

    var stream = new FileStream("Data.xlsx", FileMode.Create);
    // Create the spread sheet package
    var pkg = new ExcelPackage(stream);

    var wsData = pkg.Workbook.Worksheets.Add("Data");
    var wsPivot = pkg.Workbook.Worksheets.Add("Pivot Table");

    var dataRange = wsData.Cells["A1"].LoadFromCollection(data, true);

    // Create the pivot table
    var pivotTable = wsPivot.PivotTables.Add(wsPivot.Cells["A1"], wsData.Cells[1,1,dataRange.End.Row, 3], "Pivot Table");
    pivotTable.DataFields.Add(pivotTable.Fields[0]);  // FirstNumber
    var r = pivotTable.RowFields.Add(pivotTable.Fields[1]);    // SecondNumber
    pivotTable.ColumnFields.Add(pivotTable.Fields[2]);     // Text

    r.SubtotalTop = true;
    r.SubTotalFunctions = eSubTotalFunctions.Sum;
    r.Sort = eSortType.Ascending;
    r.Compact = true;

    r.Outline = true;
    pkg.Save();
    stream.Flush();
    stream.Close();

    IEnumerable<Data> Datas()
    {
        return new List<Data>
        {
            new()
            {
                Text = "red",
                FirstNumber = 0,
                SecondNumber = 10
            },
            new()
            {
                Text = "red",
                FirstNumber = 1,
                SecondNumber = 10
            },
            new()
            {
                Text = "blue",
                FirstNumber = 2,
                SecondNumber = 10
            },
            new()
            {
                Text = "blue",
                FirstNumber = 3,
                SecondNumber = 20
            },
            new()
            {
                Text = "green",
                FirstNumber = 4,
                SecondNumber = 20
            },
            new()
            {
                Text = "green",
                FirstNumber = 5,
                SecondNumber = 40
            }
        };
    }

    internal class Data
    {
        public int FirstNumber { get; set; }
        public int SecondNumber { get; set; }
        public string Text { get; set; }
    }


text:
Q: Probability: Third Draw from an urn having black and white balls
An urn contains 2 white and 2 black balls. A ball is drawn at random. If
  it is white, it is not replaced into the urn. Otherwise it is replaced
  with another ball of same colour. The process is repeated. Find the
  probability that the third ball drawn is black.

I am getting the final answer as $5/8$ from my tree diagram. But in my book the answer is $23/30$. I don't know where I am going wrong. Please help.

A: The question means to say that

If you draw a white ball, then don't put back. If you draw black ball, then put two black balls back.

Or put another way,

If it is white, it is not replaced (put back) into the urn. Otherwise it is replaced with alongside   another ball of same color. The process is repeated. Find the probability that the third ball drawn is black.

Let $B_i,W_i$ be the events that you drew a white or black ball in the $i$th draw. Then,
\begin{align*}
P(B_3) &=P(B_2B_3)+P(W_2B_3)\\
&=P(B_1B_2B_3)+P(W_1B_2B_3)+P(B_1W_2B_3)+P(W_1W_2B_3)\\
&=P(B_3|B_2B_1)P(B_2|B_1)P(B_1)+P(B_3|B_2W_1)P(B_2|W_1)P(W_1)\\
&\qquad+P(B_3|W_2B_1)P(W_2|B_1)P(B_1)+P(B_3|W_2W_1)P(W_2|W_1)P(W_1)\\
&=\frac46\frac35\frac24+\frac34\frac23\frac24+\frac34\frac25\frac24+\frac22\frac13\frac24\\
&=\frac{23}{30}.
\end{align*}

A:
I think this diagram shall help to understand the problem better. The final answer will be 23/30 and not 23/50.


text:
Q: Xcode Server "Build Service Warning An unexpected error occurred" "Without any reason" my Xcode build server showed "An unexpected error occurred" after integrating a bot. Additionally no build products were shown after integration.
Any ideas about that?

A: The error was my own fault. To give my after integration scripts access to the build products I had changed the file permissions of /Library/Developer/XcodeServer/Integrations and /Library/Developer/XcodeServer/IntegrationAssets to 755. Thus the server was not able to write the two directories anymore. By changing back the permissions to 775 the error went away.


text:
Q: What is the difference between 2x2 factorial design experiment and a 2-way ANOVA? What is/are the difference(s) between 2x2 factorial design and 2-way ANOVA? Do they have the same assumptions?

A: A 2x2 factorial design is a trial design meant to be able to more efficiently test two interventions in one sample. For instance, testing aspirin versus placebo and clonidine versus placebo in a randomized trial (the POISE-2 trial is doing this). Each patient is randomized to (clonidine or placebo) and (aspirin or placebo). The main effect of aspirin and the main effect of clonidine on the outcome of interest can be assessed using a two-way ANOVA.
This trial design is useful to detect an interaction (this is where the effect on the outcome of one factor (e.g. aspirin) depends on the level of the other factor (i.e. whether or not the person gets clonidine)), but one must be careful, as many factorial trials are not powered to detect an interaction. Therefore, one runs the risk of falsely declaring that there is no interaction, when in fact there is one (a type II error).
Therefore, I wouldn't say the two have the same assumptions, as one is a design and one is a statistical method. That being said, the two-way ANOVA is a great way of analyzing a 2x2 factorial design, since you will get results on the main effects as well as any interaction between the effects.
See http://udel.edu/~mcdonald/stattwoway.html for more information.


text:
Q: How can I use a text file as database in Python? I want to know what is the efficient way to insert several data to text file as database logic?
For instance I have set of cars, these cars have their id, name, and color variable.
id | name | color
1  | car1 | green
2  | car2 | red
3  | car3 | blue

I want to insert the data above to text file using python.
Later on I want to search a car, for instance based on its color.
Which method should I follow? An example with an explanation will really be appreciated!

A: In this simple case I would definitely recommend you to use tinyDB:

*

*it's really tiny

*written in pure Python

*works with Python 2.7 and 3.6 as well

*you can easily extend it

*fast installation with pip: pip install tinydb
It's definitely not for advance purposes (managing relationships or having ACID), but very flexible text file based storage, really easy to use. Check the link above.
For your case you can do something like this:
from tinydb import TinyDB
db = TinyDB('path_to_your_db_folder/db.json')
db.insert({'id': 1, 'name': 'car1', 'color': 'green'})
db.insert({'id': 2, 'name': 'car2', 'color': 'red'})
db.insert({'id': 3, 'name': 'car3', 'color': 'blue'})

You see, it's simple Python dict.
Querying is also simple:

*

*get all with db.all()

*query your data:
from tinydb import Query
Cars = Query()
db.search(Cars.color == 'green')


text:
Q: Call method in another class failure I've set up a little project and in this I would like to call a method in another controller. I've already set up like in this example. However, I tried to run the code but the method doesnt gets called!
Does anyone know what I'm doing wrong?
My Code:
Second.h:
#import <UIKit/UIKit.h>

@class First;

@interface Second : UIViewController {

}

@property (nonatomic, retain) First* vC;

@end

Second.m:
#import "Second.h"
#import "First.h"

@interface First ()

@end

@implementation First
@synthesize vC;

- (IBAction)dothis:(id)sender {

    NSLog(@"Hello World!");

    [self.vC getThis];

}

-(void)viewDidLoad {

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self
               action:@selector(dothis:)
     forControlEvents:UIControlEventTouchDown];
    [button setTitle:nil forState:UIControlStateNormal];
    button.frame = CGRectMake(5, 70, 270, 200);

[super viewDidLoad];

}

@end

First.h:
#import <UIKit/UIKit.h>
#import "Second.h"

@interface First: UIViewController {
//some Outlets and so on...

}

-(void)getThis;

@end

First.m:
#import "First.h"

@interface First ()
@end

@implementation First

-(void)getThis {
NSLog(@"You reached the end-zone!");
}

@end

Here you can see the parts of my controllers but if I run the app it works fine. However, just when I click the button on Second it displays just "Hello World!" and not "you reached the end-zone!". I tried this with alertviews as well. Could someone teach me how to solve this? I think that there is no connection bewteen the First and the Second but why?
Thanks in advance.

A: -(void)viewDidLoad {
self.vC  = [[First alloc] init]; //need this

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
           action:@selector(dothis:)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:nil forState:UIControlStateNormal];
button.frame = CGRectMake(5, 70, 270, 200);

[super viewDidLoad];

}