text:
Q: DatePicker Renderer to change textcolor if not selecting the datepicker field I  changed the datepicker textcolor white to red when the datepicker field is not selected by the user.But after that when user select the datepicker field i want to change the textcolor to white.But the text color remains the red color.
By default my xmal page datepicker textcolor is white.How to change the color to white after the red color.
how to add datepicker to placeholder property?
I want to remove the default value of date picker control when the  page is loading.How to solve this problem.
when loading the page current date is in the date picker field.i don't want to set the default date.
how to set blank date on datepicker control in xamarin forms
dtpDate.Format = DateTimePickerFormat.Custom;

dtpDate.CustomFormat = " ";
i found a solution like the above code.But its not working


text:
Q: How to set ASP.net dropdownlist index to 0 from the front-end I have the following code in ASP.net page:
<asp:DropDownList ClientIDMode="Static" ID="ddl1" CssClass="chosen-select le" runat="server" AppendDataBoundItems="true"></asp:DropDownList>
<asp:DropDownList ClientIDMode="Static" ID="ddl2" CssClass="chosen-select le" runat="server" AppendDataBoundItems="true"></asp:DropDownList>
<asp:DropDownList ClientIDMode="Static" ID="ddl3" CssClass="chosen-select le" runat="server" AppendDataBoundItems="true"></asp:DropDownList>

<input type="button" id="ClearForm" value="Clear" class="btn1" />

JQuery to set the index to 0 for all three dropdownlist:
$(function () {
    $("body").on("click", "#ClearForm", function (e) {
        e.preventDefault();
        $("select#ddl1, select#ddl2, select#ddl3").prop('selectedIndex', 0); //does not set the selected index to 0
        alert($("select#ddl1").text()); //displays all the options from #ddl1
    });
});

How can I modify so the dropdownlist index is set to 0.
HTML render of the first dropdownlist:
<select name="ctl00$BodyPlaceHolder$ddl1" id="ddl1" class="le">
    <option value="Select a State">Select a State</option>
    <option value="Alabama">AL</option>
    <option value="Alaska">AK</option>
    <option value="Arizona">AZ</option>
</select>

I tried the following JQuery and it returns null:
alert($("select#ddl1").val());

Also tried the following and it didn't work:
$('select').each(function () {
    $(this).find('option:first').prop('selected', 'selected');
});

Added the following JavaScript:
function setSelectedIndex(dropdownlist, selVal) {
    var ddl1 = document.getElementById(dropdownlist);
    alert(ddl1.selectedIndex);
    if (ddl1.length >= selVal) { //if the selected value is greater then 0, the alert is shown but the value is not set back to 0.
        ddl1.selectedIndex = selVal;
        alert("greater or equal");
    }
    else {
        alert("not greater or equal");
    }
}

It seems like, if I remove the chosen Jquery it works fine: http://jsfiddle.net/bpbvhsay/

A: There are many ways to do this but here is the solution with JavaScript:
function setSelectedIndex(dropdownlist, selVal)
    var ddl1 = document.getElementById(dropdownlist);
    //alert(ddl1.selectedIndex); //displays the proper index...
    if(ddl1.length >= selVal)
    {
       ddl1.selectedIndex = selVal;
    }
}

Call the above function as per you required as below:
setSelectedIndex('<%=ddl1.ClientID %>', 2);

UPDATE As you said you have already set ClientIDMode, try the following updated function:
function setSelectedIndex(selVal){
    var ddl1 = document.getElementById('ddl1');
    if(ddl1.length >= selVal)
    {
       ddl1.selectedIndex = selVal;
    }
}

and call it as:
setSelectedIndex(0);

A: I was using the Chosen Jquery which caused the dropdownlist to not update.
This is the HTML:
<select name="ctl00$BodyPlaceHolder$ddl1" id="ddl1" class="chose-select le">
    <option value="Select a State">Select a State</option>
    <option value="Alabama">AL</option>
    <option value="Alaska">AK</option>
    <option value="Arizona">AZ</option>
</select>

JavaScript which sets the selected index to 0:
function setSelectedIndex(dropdownlist, selVal) {
    var ddl1 = document.getElementById(dropdownlist);
    if (selVal < ddl1.selectedIndex) {
        ddl1.selectedIndex = selVal;

        $(ddl1).val(0).trigger('chosen:updated');
    }
}

That does the trick.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write a JavaScript condition that reports if git commands succeed or fail in the terminal? I am a begginer
I am trying to create a VS Code extension that will do 4 git commands for me (checkout, pull, merge and push). My problem is in my condition... I want the extension to stop if one of the git command fail in the terminal so I am trying to make an if/else JavaScript condition that will tell if the git command succeeds or fails in the terminal so the extension will stop if the git commands fails and will continue if not.
I have look everywhere on Google and I don't find anything that help me. In my code, I have write a condition for now that is terminal.error() == true even if I know that this command doesn't make any sense. Can someone help me or if you know another way to do this, please tell me.
context.subscriptions.push(vscode.commands.registerCommand('terminalTest.TS', () => {
    const terminal = vscode.window.createTerminal(`TS Terminal #${NEXT_TERM_ID++}`);
    vscode.window.showInformationMessage('Terminal is now open');

    terminal.sendText("git checkout master");
    if (terminal.error() == true) {
        vscode.window.showInformationMessage('Failed to checkout');
    }
    else {
        terminal.sendText('git pull');

A: You would want to look at the response code for that git checkout master shell command.
Within the VS Code terminal API, I cannot find a way to do that (although I'm not certain it's not possible).
So instead, as far as I can tell from searching, within a VSCode extension, you would have access to Node.js libraries.
This means you can execute the command using the child_process library. This library can use the response codes for commands, as required.
const child_process = require("child_process")
child_process.exec("git checkout master", (error, stdout, stderr) => {
    if (error == 0) {
        // Sucess, now onto 'git pull'
    } else {
        // Failure, abort
    }
});

Hopely a different library would be possible for your project.
And note, if you want more information about why the git checkout master failed, the command uses different response codes for different things (e.g. 128 for no git repo), or you can look at stdout/stderr.


text:
Q: OpencvSharp LbgrtoLab Does anyone know what is "L" means in conversion code LbgrtoLab? I searched in web and cannot find any description on this conversion code, currently I tried to use both BgrtoLab / LbgrtoLab, I found that values are different in A and B channels with using same image source. Seems that LBgr can get a better result.
Currently I am using OpenCvSharp 2.4.10.

A: Even though the meaning of this colour conversion code doesn't appear to be documented, there's no need to despair -- OpenCV is an open source library, so let's consult the source code.
case COLOR_BGR2Lab: case COLOR_RGB2Lab: case COLOR_LBGR2Lab: case COLOR_LRGB2Lab:
case COLOR_BGR2Luv: case COLOR_RGB2Luv: case COLOR_LBGR2Luv: case COLOR_LRGB2Luv:

    // ....

    bool srgb = code == COLOR_BGR2Lab || code == COLOR_RGB2Lab
        || code == COLOR_RGB2Luv || code == COLOR_BGR2Luv;

    // ....

        if (srgb && usRGBGammaTab.empty())
            Mat(1, 256, CV_16UC1, sRGBGammaTab_b).copyTo(usRGBGammaTab);
        else if (ulinearGammaTab.empty())
            Mat(1, 256, CV_16UC1, linearGammaTab_b).copyTo(ulinearGammaTab);

    // ....

This suggests that the prefix L is meant to distinguish between non-linear (sRGB) and linear RGB colour spaces. More details about what this means can be found in this answer.


text:
Q: AWS::Errors::MissingCredentialsError using paperclip and aws-s3 in rails 3.1 I am trying to upload image at aws.
class Asset < ActiveRecord::Base
  belongs_to :post
  attr_accessible :image
  has_attached_file :image, :styles => { :medium => "640x480>",
                                     :thumb => "100x100#"},
  :storage => :s3,
   :s3_credentials => "#{Rails.root}/config/s3.yml",
  :path => ":attachment/:id/:style.:extension",
  :bucket => 'yourbucket'
end

s3.yml
development:
  access_key_id: xxxxxxxx

   secret_code: xxxxx

I am getting a message
 AWS::Errors::MissingCredentialsError in PostsController#create

Missing Credentials.

 Unable to find AWS credentials.  You can configure your AWS credentials
 a few different ways:

 * Call AWS.config with :access_key_id and :secret_access_key

 * Export AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to ENV

* On EC2 you can run instances with an IAM instance profile and credentials
 will be auto loaded from the instance metadata service on those
  instances.

* Call AWS.config with :credential_provider.  A credential provider should
either include AWS::Core::CredentialProviders::Provider or respond to
the same public methods.

= Ruby on Rails

In a Ruby on Rails application you may also specify your credentials in
   the following ways:

*

*Via a config initializer script using any of the methods mentioned above
(e.g. RAILS_ROOT/config/initializers/aws-sdk.rb).

*Via a yaml configuration file located at RAILS_ROOT/config/aws.yml.
This file should be formated like the default RAILS_ROOT/config/database.yml
file.
I believe I am doing the last step.
Gemfile
gem 'rails', '3.1.3'
gem 'mysql'
gem 'koala'
gem 'paperclip'
gem 'aws-s3'
gem 'aws-sdk'

A: The following worked for me:

*

*Create a file in your initializers called aws.rb

*Put in the following in your aws.rb file:
AWS.config(
access_key_id: 'your_access_key',
secret_access_key: 'your_secret_access_key')

*Then my paperclip options looks like this:
has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "100x100>" },
:default_url => "missing_:style.png", :default_url => 'missing_:style.png', :storage =>
:s3, :bucket => "<my_bucket>"


text:
Q: Adding brackets to json ajax I'm working with a plugin called (http://michaeleisenbraun.com/columns/) that converts json to tables.
I use the following code:
<script>
$.ajax({
      url:'/large-data.json',
      dataType: 'json',
      success: function(json) {
          example2 = $('#example2').columns({
              data:json,
          });
      }
  });
</script>

It works well when the json is in brackets, like below:
[
  {
    "id": 9998,
    "isActive": false,
    "balance": "$5",
    "age": 38,
    "eyeColor": "blue",
    "name": "Lola Townsend",
    "gender": "female",
    "company": "...",
    "email": "asdf@asdf.com,
    "phone": "..."
  }
]

But, does not work if the json is not in brackets, like below:
  {
    "id": 9998,
    "isActive": false,
    "balance": "$5",
    "age": 38,
    "eyeColor": "blue",
    "name": "Lola Townsend",
    "gender": "female",
    "company": "...",
    "email": "asdf@asdf.com,
    "phone": "..."
  }

The json response is from other sites, so I will not be able to control whether it does / does not have brackets.
Is there a way to ensure the json returned has brackets each time and if not, that brackets are added?
I tried JSON.parse() and it did not work.

A: The first one mean it's an array object, the second one is only an object. I don't really get what you are trying to do right now but you can simply ass the object into in array if it's not allready one. something like :
if(!Arrays.isArray(yourObject)) {
    var temp = [] ;
    temp.push(yourObject);
    yourObject= temp;
}

I haven't test it since i don't know what you want to do, but this is the main idea.
Hope it helps !

*

*Nic

A: You can use regex to check if the code is correct with ^\[|\n*\]$. You should have 2 matches if the first character of the string is [ and the last is ].
You can test here : https://regex101.com/r/Cukwog/1


text:
Q: Jquery UI autocomplete results from JSON file I am having great difficulty in successfully parsing a JSON file to use within JQuery UI autocomplete
Please see my dev page: http://www.zyredesign.com/autocomplete
The JSON isn't organised as well as I would have hoped as the items keys are ID's eg:
{"140":"Abarth",
"375":"Acura"
}
Etc....
Here is my javascript attempt:
$(document).ready(function() {

    $('#cars').autocomplete({
        source: function()
        {

            $.getJSON('json.json', function(data)
            {
                cars_array = new Array();

                $.each(data, function(k, v) {

                    cars_array.push(v);

                 })

                alert( cars_array);

                return cars_array;
            })

        },
        minLength: 3,
        focus: function( event, ui ) {},
        select: function( event, ui ) {
            $('#suggestions').html(ui);

            return false;
        }
    });

});

/*
function get_json()
{
var items = new Array();

$.getJSON('json.json', function(data) {
  var items = [];

  alert(  eval ("(" + data + ")") );

 // $.each(data, function(key, val) {
    //items.push('
' + val + '
');

 // });

  $('
', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

return items;
}
*/

Any help would be greatly appreciated, thanks!

A: The function you've supplied for the source: attribute doesn't return a value. The $.get() function does, but that won't reach the source attribute.
    source: function()
    {
        $.getJSON('json.json', function(data)
        {
            cars_array = new Array();
            $.each(data, function(k, v) {
               cars_array.push(v);
            })
            return cars_array;
        })
        //You need to return something here
    }

Also, it may be an issue that you're using an asynchronous call to the json file in a synchronous pattern. In other words, consider this:
    $.getJSON('json.json', function(data)
    {
        cars_array = new Array();
        $.each(data, function(k, v) {
           cars_array.push(v);
        })

        //Now you definitely have the cars so you can do the autocomplete
        $('#cars').autocomplete({
            source:cars_array,
            minLength: 3,
            focus: function( event, ui ) {},
            select: function( event, ui ) {
            $('#suggestions').html(ui);
            return false;
        }
    });


text:
Q: LSTM VAD сеть плохо обучается Здравствуйте!
Решил попробовать обучить LSTM сеть с помощью caffe, до этого имел дело только с CNN.
В качестве решаемой задачи выбрал детектор речи (VAD).
Имеется небольшая размеченная выборка. Записи различной длительности.
Вектор признаков формируется следующим образом: беру окно в 25мс и вычисляю 13 MFCC + их производную, так для всей записи,
при этом шаг 20мс.
Полученные данные сохраняю в hdf5.
В сеть данные подаю следующим образом:
за одну итерацию в сеть подается один вектор MFCC, и label для него который принимает значение 0-шум или 1-речь.
Так же подаю одно значение cont_sentence, которое сбрасывается каждые 40 векторов (обнуляет внутренние регистры lstm),
таким образом сеть все время работает с сигналом длительностью 40 кадров.
Подскажите правильный ли подход для подачи данных я выбрал?
В данный момент конфигурация сети такая:
input -> LSTM(50) -> sigmoid -> LSTM(25) -> IP(256) -> dropOut -> IP(1) -> sigmoid
К сожалению сеть плохо обучается...
P.S. И еще вопрос, как в дальнейшем в рабочем проекте подавать данные, интересует именно cont_sentence, нужно ли его сбрасывать каждые 40 кадров?


text:
Q: finding min S such that integral is greater than some value I have this function $R(r)$, and $r*R^2$ is a probability density function.
R[n_, l_, r_] :=
  Sqrt[(n - l - 1)!/(2*n*((l + 1)!)^3)]*(2/(n*a))^(l + 1/2)*
   D[LaguerreL[n + l, (2*r)/(n*a)], {r, 2*l + 1}]*r^l*Exp[-r/(n*a)]

I am basically trying to find the value of $s$ such that the integral of the function $R(r)$ as $r$ goes from $0$ to $s$ is $95\%$ probability.
In the function below, I need the argmin $s$ such that the integral value is at least $0.95$. Solve didn't work for an exact number. How do I set it up to solve for "at least" 0.95?
Solve[Integrate[(r*R[1, 0, r])^2, {r, 0, s}] == 0.95, s]

A: Integrate[(r*R[1, 0, r])^2, {r, 0, s}] /. s -> σ*a // FullSimplify
(*    1 + E^(-2σ) (-1 - 2σ (1 + σ))    *)

FindRoot[% == 0.95, {σ, 3}]
(*    {σ -> 3.1479}    *)

In one line:
FindRoot[Integrate[(r*R[1, 0, r])^2, {r, 0, σ*a}] == 0.95, {σ, 3}]
(*    {σ -> 3.1479}    *)


text:
Q: Rails Tutorial ch. 10 Test 10.20 failure I have problem with test 10.20 in Rails Tutorial.
After using command:

bundle exec rake test:mailers

I've received error:
Run options: --seed 6131

# Running:

F

Finished in 0.559132s, 1.7885 runs/s, 5.3655 assertions/s.

  1) Failure:
UserMailerTest#test_account_activation [/home/adam/workspace/sample_app    /test/mailers/user_mailer_test.rb:11]:
Expected: ["noreply@example.com"]
Actual: nil

1 runs, 3 assertions, 1 failures, 0 errors, 0 skips

I've thoroughly checked my code and can't find the impropriety but I'm obviously doing it wrong.
Here's my user_mailer:
class UserMailer < ActionMailer::Base

  def account_activation(user)
    @user = user
    mail to: user.email, subject: "Account activation"
  end

  def password_reset
    @greeting = "Hi"

    mail to: "to@example.org"
  end
end

user_mailer_test:
require 'test_helper'

class UserMailerTest < ActionMailer::TestCase

  test "account_activation" do
    user = users(:michael)
    user.activation_token = User.new_token
    mail = UserMailer.account_activation(user)
    assert_equal "Account activation", mail.subject
    assert_equal [user.email], mail.to
    assert_equal ["noreply@example.com"], mail.from
    assert_match user.name,               mail.body.encoded
    assert_match user.activation_token,   mail.body.encoded
    assert_match CGI::escape(user.email), mail.body.encoded
  end
end

I've added this line to config/environments/test.rb:
config.action_mailer.default_url_options = { host: 'example.com' }

Can I have some advise?

A: All references to the User mailer should start with
class UserMailer < ApplicationMailer

This is due to recent changes in Rails 4.2. I missed a couple of references when I updated the tutorial last week, but these have now been corrected. Be sure you also include the Application mailer as shown in Listing 10.8. In fact, it's probably a good idea to remove the mailers and regenerate them from scratch to make sure your code conforms to the structure expected by Rails 4.2.

A: You need to add :from to this line
mail to: user.email, subject: "Account activation"

like this
mail to: user.email, from: "noreply@example.com", subject: "Account activation"

A: Simply edit the user_mailer.rb file from this:
class UserMailer < ActionMailer::Base

to this:
class UserMailer < ApplicationMailer

The reason being is that the default from: address is in the application_mailer.rb file and it pulls from ActionMailer::Base


text:
Q: Getting line input from a AllocConsole C++ A team member added the following code to our GUI Ogre project to add a console (so that we are able to see cout as we are debugging...
We are now running way behind time, and we need text interaction with the game, I was going to make a console, but it is plausibly a big time hole... So I thought hey! Why not use the console he attached!! unfortunatly, I was inable to type into it when I attempted, thus I wouldn't be able to send a command to the console :\
Is there any way to enable writing into the console (atm the way he's done it if you hit any key (as such as 'a') nothing goes into the console, therefore I can't wait for enter and then phase the string typed into the win32 console)
Here's his code (I also added the link encase somone has a rough idea, but they want to read about it again, I don't know the exact guide he followed, but it was very simular)
void showWin32Console()
{
    static const WORD MAX_CONSOLE_LINES = 1000;
    int hConHandle;
    long lStdHandle;
    CONSOLE_SCREEN_BUFFER_INFO coninfo;
    FILE *fp;

    // allocate a console for this app
    AllocConsole();

    // set the screen buffer to be big enough to let us scroll text
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
    coninfo.dwSize.Y = MAX_CONSOLE_LINES;
    SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);

    // redirect unbuffered STDOUT to the console
    lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    fp = _fdopen( hConHandle, "w" );
    *stdout = *fp;
    setvbuf( stdout, NULL, _IONBF, 0 );

    // redirect unbuffered STDIN to the console
    lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    fp = _fdopen( hConHandle, "r" );
    *stdin = *fp;
    setvbuf( stdin, NULL, _IONBF, 0 );

    // redirect unbuffered STDERR to the console
    lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    fp = _fdopen( hConHandle, "w" );
    *stderr = *fp;
    setvbuf( stderr, NULL, _IONBF, 0 );

    // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
    // point to console as well
    std::ios::sync_with_stdio();
}

A: AllocConsole() just gives you a new console, it doesn't change existing stdin/stdout - so the handles you get back from GetStdHandle will still be their former values. Instead you have to open the special devices "CONIN$"/"CONOUT$". Turns out that reassigning stdin/stdout to this new console is actually fairly simple, using freopen:
BOOL f = AllocConsole();
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);

...and presto, all further access to standard input or output will now go to your new console.
(This doesn't change what the Win32's view of your standard input/output handles are, by the way, so if there happens to be other code in the process that calls GetStdHandle(STD_INPUT_HANDLE) etc instead of using the CRT's stdio, those will still return the original values that are not related to your new console. If you need to change those too, then you may need to play around with opening CONIN$/CONOUT$ manually and using SetStdHandle to fix up those.)


text:
Q: Symfony Impossible to access an attribute ("nameArticle") on a null variable I created a blog and there is a comment system. I have a little problem to post my comments. When comments exist the articles are correctly displayed with their comments, but the problem when an article does not have a comment, it shows me an error like this

Impossible to access an attribute ("nameArticle") on a null variable.

I tried to add a if but it does not work it does not show me the article!
my controller:
/**
 * @Route("/{slug}")
 * @param string $slug
 * @param Request $request
 * @return Response
 * @throws \Exception
 */
 public function detail(Request $request, string $slug): Response {

     $article = $this->getDoctrine()
         ->getRepository(Articles::class)
         ->findOneWithCategorySlug($slug);

     $info = $this->getDoctrine()
         ->getRepository(InfoMore::class)
         ->findByInfo(2);

     // $comments = $this->getDoctrine()->getRepository(Comments::class)->findAll();

     $comment = new Comments();
     $form = $this->createForm(CommentsType::class, $comment);
     $form->handleRequest($request);

     if($form->isSubmitted() && $form->isValid()) {

         $comments = $form->getData();
         $manager = $this->getDoctrine()->getManager();
         $user = $this->getUser();
         $comments->setUserComments($user);
         $comments->setArticleComments($article);
         $manager->persist($comments);
         $manager->flush();
         $this->addFlash('notice', 'Le commentaire a bien été ajouté ');
         return $this->redirectToRoute('app_home_detail', [
             'slug' => $slug
         ]);
     }

     return $this->render('front/detail_article.html.twig', [
         'title' => $article,
         'article' => $article,
         'info' => $info,
         'description' => '',
         'keywords' => '',
         'addComments' => $form->createView()
    ]);
}

my view:
{% extends 'base.html.twig' %}

{% set active = '' %}
{% set active2 = '' %}
{% set active3 = '' %}
{% set active4 = '' %}
{% set active5 = '' %}
{% set active6 = '' %}

{% if title %}
{% set title = article.nameArticle %}
{% else %}
    {% set title = 'Erreur article non trouver !' %}
{% endif %}

{% block body %}

{{ article.nameArticle }}

Article publié le : {{ article.createdAt | date('d/m/Y à H:i') }} dans {{ article.category }}

            {{ article.introduction | raw }}

            ×

            {{ article.articleContent |raw }}

{% for comment in article.comments %}

{{ comment.commentsContent }} de la part {{ comment.userComments }}

{% endfor %}

 {% if is_granted("IS_AUTHENTICATED_REMEMBERED") %}

     {% for message in app.flashes('notice') %}

             {{ message }}
             <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                 ×
             </button>

     {% endfor %}

   {{ form_start(addComments) }}

                    {{ form_widget(addComments) }}
                    {{ form_errors(addComments) }}
                <input type="submit" class="btn btn-primary" value="Ajouter un commentaire">

   {{ form_end(addComments) }}
        {% endif %}

{% endblock %}

and my repository:
 /**
  * @param string $slug
  * @return Articles|null
  * @throws \Exception
  */
  public function findOneWithCategorySlug(string $slug): ?Articles {

      $query = $this->createQueryBuilder('a')
          ->join('a.category', 'c')
          ->addSelect('c')
          ->where('a.slug = :slug')
          ->setParameter(':slug', $slug)
          ->innerJoin('a.comments', 'com')
          ->getQuery()
      ;

      try {
          return $query->getOneOrNullResult();
      } catch (\Exception $e) {
          throw new \Exception('Problème dans ArticlesRepository::findOneWithCategory' . $e->getMessage() . var_dump($e));
      }

  }

A: That's normal, in your query you use innerJoin.

The INNER JOIN keyword selects records that have matching values in both tables.

So your query will only select records that have matching values in both Articles and Comments tables. If there are no comments, the record with the Article found won't be selected.
If you want to get rid of

Impossible to access an attribute ("nameArticle") on a null variable.

Just fix your twig by using not null and you can add defined to enforce your verification:
{% if article is defined and article is not null %}
    {% set title = article.nameArticle %}
{% else %}
    {% set title = 'Erreur article non trouver !' %}
{% endif %}

If you want to display Articles even if they don't have comments use leftJoin instead of innerJoin:
/**
 * @param string $slug
 * @return Articles|null
 * @throws \Exception
 */
public function findOneWithCategorySlug(string $slug): ?Articles {

    $query = $this->createQueryBuilder('a')
        ->join('a.category', 'c')
        ->addSelect('c')
        ->where('a.slug = :slug')
        ->setParameter(':slug', $slug)
        ->leftJoin('a.comments', 'com')
        ->getQuery()
    ;

    try {
        return $query->getOneOrNullResult();
    } catch (\Exception $e) {
        throw new \Exception('Problème dans ArticlesRepository::findOneWithCategory' . $e->getMessage() . var_dump($e));
    }

}


text:
Q: making unobtrusive validation work when using Select2 ASP.NET MVC Select boxes converted to Select2, do not automatically  integrate with unobtrusive validation mechanism in ASP.NET MVC framework.
For example, on a form which contains a regular select box (marked as required in model definition), submitting the form while no options have been selected in the select box, will cause the border and background of the select box to take a reddish color, and by using @Html.ValidationMessageFor, error messages, if any, can be displayed beside the box. However if the select box is converted to a Select2 component, then none of the mentioned features work any more. Even the validation error message will not show up.
It seems that the reason for even the validation error message not showing, is because Select2 changes the display CSS property of the original select box to none (display:none), and I guess the unobtrusive validation script does not bother generating error messages for invisible fields.
Any ideas / solutions?

A: This issue isn't really specific to Select2, but rather to the jQuery unobtrusive validator.
You can turn on validation for hidden fields as highlighted in this answer.
$.validator.setDefaults({
    ignore: ''
});

As the comments noted, it didn't work inside an anonymous callback function within $(document).ready(). I had to put it at the top level.

A: I've run into similar issues with the select2 plugin.  I don't know exactly which features you're using specifically, but in my experience, when you set an element as a select2 in the document.ready event, the plugin will change some of the element's attributes on the fly (inspect one of the elements after your page has finished loading - oftentimes you'll see the id and class properties are different than what you're seeing when you view source).
It's difficult to offer more without actually seeing the code, but here's a few ideas to get you started:
First off, obviously make sure you have the a link to your select2.css stylesheet in the header.
Then, since you're talking about form submissions, I'd recommend you examine whether or not you're getting a full postback or submitting via AJAX (if you're using jQueryMobile, you're using AJAX unless you override it in the jquerymobile.js file or set a data-ajax="false" in your form attributes).  You can just look at the value returned by Request.IsAjaxRequest() for this.  Obviously if you're submitting via ajax, you won't hit the document.ready event and the select2 won't initialize properly and you'd need to figure out a way around that.  Try refreshing the page after the submit and see if it renders the select2 component.
Then I'd suggest examining the elements and see if they're not behaving like you'd expect because you're actually trying to work with classes that the plugin has reassigned at runtime.  You can either just adjust your logic, or you can dig into the select2 code itself and change the behavior - it's actually fairly well-documented what the code is doing, and if you hop on the Google group for select2, Igor is usually pretty quick to follow up with questions.

A: $('body').on('change', 'select.m-select2', function () {
$(this).blur();

})

A: like this
$('select').on('select2:select', function (evt){
        $(this).blur();
});


text:
Q: python input function doesnt show actual input window I just started to learn python and I am reading "automate the boring stuff" book. I wrote my first program suggested in the book that is:
print('Hello world!')
print('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')

however, when I click f5, the program doesnt ask for input in the shell, it only prints this:
===================== RESTART: /home/user/Downloads/1.py =====================
Hello world!
What is your name?

I am using qubes os right now. Could it be something related to it?

A: You are almost there, I made some small changes so it might be a little bit more obvious when/where you should input.
print('Hello world!')
myName = input('What is your name? ')
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
myAge = input('What is your age? ')
print('You will be ' + str(int(myAge) + 1) + ' in a year.')

You can start typing when you see the "what is your name" query.

A: You can add a string in input(). You do not have to have separate lines of code for this. Also if you do not enter something in the console your program will block there because it expects an input from the user. As long as you do not type anything it will stay there. Your code works as is btw, but if you want to use less prints:
print('Hello world!')
myName = input('What is your name?')
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
myAge = input('What is your age?')
print('You will be ' + str(int(myAge) + 1) + ' in a year.')


text:
Q: Vagrant not listening to my port and using default port I'm using Vagrant for multiple projects now with a per-project-installation, meaning I have multiple boxes. One for each project (or for production enviroment)
When I want to access my first Vagrantbox I access it via http://sitea.com:8080. My second Vagrantbox should listen to 1337 (I tried multiple ports here) but when I call http://siteb.com:1337 I'm getting an error in all browsers (ERR_CONNECTION_REFUSED in Chrome).
However, when I'm calling my second site like http://siteb.com it works without any problems. It seems that my second Vagrantbox just doesn't listen to the ports and uses the default port. But why is that?
First box (Which works with port only)
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config|
  config.vm.box   = "puppetlabs/debian-7.8-64-puppet"
  config.vm.provision :shell, path: "vagrant_ressources/bootstrap.sh"
  config.vm.network :forwarded_port, guest: 80, host: 8080
  config.vm.network "private_network", ip: "192.168.50.4"
  config.vm.synced_folder ".", "/var/www", type: "nfs"
end

Second box (Which works without port only)
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config|
  config.vm.box   = "puppetlabs/debian-7.8-64-puppet"
  config.vm.provision :shell, path: "vagrant_ressources/bootstrap.sh"
  config.vm.network :forwarded_port, guest: 80, host: 1337
  config.vm.network "private_network", ip: "192.168.50.5"
  config.vm.synced_folder ".", "/var/www", type: "nfs"
end

Both have the same vhost configuration, and my hosts file looks like this
# Vagrant
192.168.50.4    sitea.com
192.168.50.5    siteb.com

A: When using port forwarding with Vagrant you'll usually access localhost since the forwarded port is available at your host machine. Like this:
http://localhost:8080 -> should deliver the website siteA.com
http://localhost:1337 -> should deliver the website siteB.com

If you are able to access http://siteB[:80] it means that the DNS entry of siteB points to 192.168.50.5, which is the private network ip of that box.
Check:
getent hosts | grep siteB\.com

I bet it will give you 192.168.50.5.


text:
Q: Handlebar-helpers built-in blocks. Complex sum Without creating a new helper and just use the existing one's from "handlebar-helpers"
So I am actually trying to add the values in the below specified payload.
{
  "products": [
    {
      "product": [
        {
          "price": 10
        },
        {
          "price": 20
        },
        {
          "price": 30
        }
      ]
    },
    {
      "product": [
        {
          "price": 10
        },
        {
          "price": 20
        },
        {
          "price": 30
        }
      ]
    }
  ]
}

From the above payload. I am trying to compute the sum of products array based upon the index position of product array.
The output for this payload is 20 , 40 ,60 respectively.
I tried with pluck block as,
{{pluck products "products.price"}} but it simply didn't work.
Is there any workaround for this ?
Current logic that doesn't works.
{{#each products}}
    {{#each product}}
        {{sum (pluck products "product.price")}}
    {{/each}}
{{/each}}


text:
Q: Spring cloud config match profile I have a hierarchy structure of applications files in my git repository as follows:
uri: https://bitbucket.org/repositorios-company/configuration-files
Directory:
-authorization-service
----application.yml
----application-development.yml
----application-uat.yml
----application-production.yml
-cpo-executor
----application.yml
----application-development.yml
----application-uat.yml
----application-production.yml

In config project yml file:
server:
    port: 8888
spring:
    application:
        name: config-server
    cloud:
        config:
            server:
                git:
                    username: ######
                    ....
                    uri: https://bitbucket.org/repositorios-company/cup-configuration-files
                    searchPaths: '{application}'

Problems:

*

*When I try to access the file of development by url http://localhost:8888/authorization-service/development spring load two files and not only one as I expected:

2021-01-13 10:34:40.549  INFO 141562 --- [nio-8888-exec-1] o.s.c.c.s.e.NativeEnvironmentRepository  : Adding property source: file:/tmp/config-repo-3531515016986363333/authorization-service/application.yml
2021-01-13 10:34:48.950  INFO 141562 --- [nio-8888-exec-2] o.s.c.c.s.e.NativeEnvironmentRepository  : Adding property source: file:/tmp/config-repo-3531515016986363333/authorization-service/application-development.yml

*When a client application, using the following configuration, tries to access the corresponding config file, spring only brings the application.yml file and not the file corresponding to the profile:

Client yml:
spring.application.name=authorization-service
spring.profiles.active=development
spring.cloud.config.uri=http://localhost:8888

After application starts, spring cloud config log shows the default application.yml:
2021-01-13 11:09:11.346  INFO 144899 --- [nio-8888-exec-2] o.s.c.c.s.e.NativeEnvironmentRepository  : Adding property source: file:/tmp/config-repo-1131390371944673193/authorization-service/application.yml

Edited: I've checked if the value changed in runtime and if it has taken the values from application-development.yml, but not.
Does anybody know how can I bring only one config file to the two situations?

A: When you access directly to your config server, it will show these 2 files, that is normal, the base config file and the second that override the base config file, that is a normal behaviour.
And when your client connects to your config server, it will fetch only one file which will have the mix of two property files configurations allocated in your config server.
The following post describes the use of a bootstrap.yml file that is located into the resources folder, this file allows to activate the profile when fetching the data from the config server.
What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

A: Three things to consider:

*

*Even though I utilized profile as "spring.profiles.active=development" Spring looks for application-dev.properties and not application-development.properties file. I utilized Spring actuator to see which profile Spring was looking for.

How to use Spring actuator
http://localhost:8080/actuator/env

{"activeProfiles":["dev"],....}

*Even thought two files were loaded in Spring Cloud Config, only the corresponding profile file was utilized by application client:

INFO 373818 ...NativeEnvironmentRepository  : Adding property source: file:/tmp/config-repo/authorization-service/application-dev.properties
INFO 373818 ...NativeEnvironmentRepository  : Adding property source: file:/tmp/config-repo/authorization-service/application.properties

But if you need an application only to consume the file corresponding to it profile, when access http://localhost:8888/authorization-service/dev, just remove the default application.yml from git repository.

*When using Spring Cloud Config utilize bootstrap.{yml|properties} and not application.{yml|properties} in your application client.

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

A: you must tell spring what the specific file yml you need to use :
for example :
in the main class you must be added:
@PropertySource("classpath:foo.yml")

this annotation says at run main class use foo.yml
for more details Visit :
https://www.baeldung.com/properties-with-spring?
I hope the solution helpful.


text:
Q: @ViewScoped is recreated after button action on WebLogic First of all I know some other similar questions about my title, but My issue is a little bit different... When I try to initialize LazyDataModel in my @ViewScoped Bean it works fine until I click the actionButton on my page. When My Bean is created, its @PostConstruct method works as expected and LazyDataModel filled up in that method then datatable populated well. But when ajax called by actionButton in my page then entire bean recreated and @PostConstruct method called again, with that LazyDataModel value changing to null. Because of that, my page is crashing. In another scenario I was using rowSelect event in my datatable instead of actionButton with method which has a SelectEvent parameter. In SelectEvent parameter object field of it was null and I was getting NullPointerException. These are the scenarios... As result I guess when I use LazyDataModel in my @ViewScoped bean It calls PostConstruct again and my datamodel returns null for my SelectEvent method.
This is my ViewScoped PostConstruct method
@ManagedBean (name = "myEctrInboxBB")
@ViewScoped
public class MyEContractInboxBackingBean implements Serializable {

private static final long serialVersionUID = 2399679621562918360L;

private static final Logger logger = LogManager.getLogger(MyEContractInboxBackingBean.class);

@ManagedProperty("#{ectrDomainService}")
EContractDomainService ectrDomainService;

@ManagedProperty("#{eContractUtil}")
EContractUtilBean eContractUtil;

@ManagedProperty("#{ectrApproveController}")
EContractApproveControllerBean ectrApproveController;

private EContractInboxItem selectedInboxRow;
private LazyEContractInboxItemModel lazyEcontractInboxItem;

private List<EContractInboxItem> inboxItems = new ArrayList<EContractInboxItem>();
private List<EContractInboxItem> filteredInboxItems = new ArrayList<EContractInboxItem>();

@PostConstruct
public void init() {

    User portalUser = getUser();
    List<String> userRoles = fetchUserRoles(portalUser);
    List<String> userSmCodes = fetchUserSmCodes(userRoles, portalUser);

    lazyEcontractInboxItem = new LazyEContractInboxItemModel(ectrDomainService, eContractUtil, userRoles, userSmCodes);

}

public void onRowSelect(SelectEvent selectEvent) {
    logger.info("**************************" + selectEvent);
}

public void openSelectedJob(EContractInboxItem item) {
ectrApproveController.openEContractInfoPage(item.getProcessInstanceId());
}

LazyDataModel
public class LazyEContractInboxItemModel extends LazyDataModel<EContractInboxItem>{

List<EContractInboxItem> inboxItems = new ArrayList<EContractInboxItem>();
List<Task> taskList = new ArrayList<Task>();

EContractDomainService ectrDomainService;
EContractUtilBean ectrUtilBean;

List<String> userRoles = new ArrayList<String>();
List<String> userSmCodes = new ArrayList<String>();

public LazyEContractInboxItemModel(EContractDomainService ectrDomainService, EContractUtilBean utilBean, List<String> roles,
        List<String> smCodes) {

    userRoles.addAll(roles);
    userSmCodes.addAll(smCodes);
    ectrUtilBean = utilBean;

    this.ectrDomainService = ectrDomainService;
}

public List<EContractInboxItem> getInboxItems() {
    return inboxItems;
}

public void setInboxItems(List<EContractInboxItem> inboxItems) {
    this.inboxItems = inboxItems;
}

@Override
public List<EContractInboxItem> load(int first, int pageSize, String sortField, SortOrder sortOrder,
        Map<String, Object> filters) {
    taskList = ectrDomainService.findTaskListAssignedToUserByUser(userRoles, userSmCodes);

    inboxItems.clear();

    inboxItems.addAll(ectrUtilBean.retrieveInboxItems(taskList));

    setRowCount(inboxItems.size());

    return inboxItems;
}

@Override
public List<EContractInboxItem> load(int first, int pageSize, List<SortMeta> multiSortMeta,
    Map<String, Object> filters) {
    taskList = ectrDomainService.findTaskListAssignedToUserByUser(userRoles, userSmCodes);

    inboxItems.clear();

    inboxItems.addAll(ectrUtilBean.retrieveInboxItems(taskList));

    setRowCount(inboxItems.size());

    return inboxItems;
}

@Override
public Object getRowKey(EContractInboxItem object) {
    return object.getProcessInstanceId();
}

@Override
public EContractInboxItem getRowData() {
    return super.getRowData();
}

@Override
public EContractInboxItem getRowData(String rowKey) {

    for (EContractInboxItem eContractInboxItem : inboxItems) {
        if (rowKey.equals(eContractInboxItem.getProcessInstanceId()))
            return eContractInboxItem;

    }
    return null;

}
getters and setters

xhtml page with actionButton
<?xml version="1.0"?>
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:pe="http://primefaces.org/ui/extensions">

<h:form
    id="eContractWaitingApprovalForm"
    prependId="false"
    enctype="multipart/form-data">

            <p:dataTable
                id="waitingEcontracts"
                widgetVar="waitingEcontracts"
                styleClass="grid-sm-bottom"
                rows="20"
                resizableColumns="true"
                resizeMode="expand"
                paginator="true"
                lazy="true"
                paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                rowsPerPageTemplate="5,10,15,50,100,200"
                value="#{myEctrInboxBB.lazyEcontractInboxItem}"
                var="item">

                    <h:outputText value="#{item.eContract.eContractCode}" />

                    <h:outputText value="#{item.eContract.eContractSubject}" />

                    <h:outputText value="#{item.eContract.eContractDate}">
                        <f:convertDateTime
                            type="date"
                            pattern="dd-MM-yyyy" />
                    </h:outputText>

                    <h:outputText value="#{item.agencyName}" />

                    <h:outputText value="#{item.agencyType}" />

                    <h:outputText
                        value="#{myEctrInboxBB.findSalesOfficeBySmCode(item.agencySM)}" />

                    <h:outputText
                        value="#{item.eContract.eContractStatus eq 'INPROGRESS' ? i18n['e-contract.dt.waiting.inprogress'] : item.eContract.eContractStatus}" />

</h:form>

xhtml page with rowSelect
<?xml version="1.0"?>
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:pe="http://primefaces.org/ui/extensions">

<h:form
    id="eContractWaitingApprovalForm"
    prependId="false"
    enctype="multipart/form-data">

            <p:dataTable
                id="waitingEcontracts"
                widgetVar="waitingEcontracts"
                styleClass="grid-sm-bottom"
                rows="20"
                resizableColumns="true"
                resizeMode="expand"
                paginator="true"
                lazy="true"
                paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                rowsPerPageTemplate="5,10,15,50,100,200"
                value="#{myEctrInboxBB.lazyEcontractInboxItem}"
                var="item"
                selection="#{myEctrInboxBB.selectedInboxRow}"
                selectionMode="single"
                rowKey="#{item.processInstanceId}">

                    <h:outputText value="#{item.eContract.eContractCode}" />

                    <h:outputText value="#{item.eContract.eContractSubject}" />

                    <h:outputText value="#{item.eContract.eContractDate}">
                        <f:convertDateTime
                            type="date"
                            pattern="dd-MM-yyyy" />
                    </h:outputText>

                    <h:outputText value="#{item.agencyName}" />

                    <h:outputText value="#{item.agencyType}" />

                    <h:outputText
                        value="#{myEctrInboxBB.findSalesOfficeBySmCode(item.agencySM)}" />

                    <h:outputText
                        value="#{item.eContract.eContractStatus eq 'INPROGRESS' ? i18n['e-contract.dt.waiting.inprogress'] : item.eContract.eContractStatus}" />

</h:form>

When I clicked a row of Datatable selectEvent.getObject() --> NULL always with LazyDataModel.
A big important information: These all situations happens in WebLogic 10.3.6.0 and works on TomCat like charm (even with LazyDataModel).
My Development environment: JSF 2.0, Primefaces 5.2, Liferay 6.2.3 ga4 with TomCat 7.04.
Testing environment: Same all except WebLogic 10.3.6.0 (Problem only occurs on here)
I really appreciate if someone could help me... Thanks in advance!!!
EDIT:
@ManagedBean (name = "myEctrInboxBB")
@ViewScoped
public class MyEContractInboxBackingBean implements Serializable {

private static final long serialVersionUID = 2399679621562918360L;

private static final Logger logger = LogManager.getLogger(MyEContractInboxBackingBean.class);

@ManagedProperty("#{ectrDomainService}")
private transient EContractDomainService ectrDomainService;

@ManagedProperty("#{eContractUtil}")
private EContractUtilBean eContractUtil;

@ManagedProperty("#{ectrApproveController}")
private EContractApproveControllerBean ectrApproveController;

private EContractInboxItem selectedInboxRow;
private LazyEContractInboxItemModel lazyEcontractInboxItem;

@PostConstruct
public void init() {

    User portalUser = getUser();
    List<String> userRoles = fetchUserRoles(portalUser);
    List<String> userSmCodes = fetchUserSmCodes(userRoles, portalUser);

    lazyEcontractInboxItem = new LazyEContractInboxItemModel(userRoles, userSmCodes);
}

We can access Spring Beans like that:
    public EContractProcessService geteContractProcessService() {
    ELContext elContext = FacesContext.getCurrentInstance().getELContext();
    return (EContractProcessService) FacesContext.getCurrentInstance().getApplication()
        .getELResolver().getValue(elContext, null, "eContractProcessService");
}


text:
Q: Move Magento 2 Area code is not set problem I am trying to move magento 2 to another server but when I am trying to flush cache I am getting this error:
php bin/magento cache:flush

[Magento\Framework\Exception\SessionException]
Area code not set: Area code must be set before starting a session.

[Magento\Framework\Exception\LocalizedException]
Area code is not set

cache:flush [--bootstrap="..."] [types1] ... [typesN]

I already updated database with the new directory.
What should I do ?


text:
Q: Python - get process names,CPU,Mem Usage and Peak Mem Usage in windows I am wanting to get a list of all the process names, CPU, Mem Usage and Peak Mem Usage. I was hoping I could use ctypes. but I am happy to hear any other options. Thanks for your time.

A: You can use psutil.
For example, to obtain the list of process names:
process_names = [proc.name() for proc in psutil.process_iter()]

For info about the CPU use psutil.cpu_percent or psutil.cpu_times.
For info about memory usage use psutil.virtual_memory.
Note that psutil works with Linux, OS X, Windows, Solaris and FreeBSD and with python 2.4 through 3.3.

A: I like using wmic on Windows.  You can run it from the command-line, so you can run it from Python.
from subprocess import Popen,PIPE
proc = Popen('wmic cpu',stdout=PIPE, stderr=PIPE)
print str(proc.communicate())

With wmic you can get processes, cpu, and memory info easily. Just use wmic cpu, wmic process, and wmic memphysical.  You can also filter out certain attributes by using wmic <alias> get <attribute>. And you can get a list of all commands with wmic /?.  Hope that helps!
You can check out the official documentation for WMIC here: http://technet.microsoft.com/en-us/library/bb742610.aspx

A: This Python 3.3 code works for Windows 7 with UAC all the way down.
import psutil
import time

def processcheck(seekitem):
    plist = psutil.get_process_list()
    str1=" ".join(str(x) for x in plist)
    if seekitem in str1:
        print ("Requested process is running")

processcheck("System")


text:
Q: Typescript & Mongoose - "this" not available in instance methods I am currently converting my API from JS to TS. However, I'm having some difficulties with mongoose & typescript. Specifically, this is not available inside my instance methods.
My code:
AccountSchema.methods.comparePassword = async function (candidatePassword: string) {
  const isMatch = await bcrypt.compare(candidatePassword, this.password);
  return isMatch;
};

Which generates the following error as this refers to the function rather than the actual document:

Argument of type 'Function' is not assignable to parameter of type 'string'.

However, according to Mongoose's documentation, there shouldn't be an error as this should refer to the actual document.
What this actually refers to:
this: {
    [name: string]: Function;
}

How I defined my schema:
const AccountSchema = new mongoose.Schema<IAccount>({...})

My approach worked just fine with JS, so I know it has something to do with TypeScript. Mongoose documentation confirms that my implementation is the right way to define instance methods, so I'm quite confused why it doesn't work.
Is there a specific TS way of declaring & using instance methods in mongoose that I don't know of?
Any help would be greatly appreciated!

A: All I needed was a this parameter on that function. That's special in TS, and specifies the type of this within the function.
Like so:
async function (this: IAccount, candidatePassword: string) { ... }

this parameters are not passed explicitly, so the new parameter doesn't change how the function is called.


text:
Q: Is the zero vector in $\mathbb{R}^n$ by itself a subspace of $\mathbb{R}^n$? W is a subspace of $\mathbb{R}^n$ iff

*

*The zero vector ∈ W.

*X + Y ∈ W for any X, Y ∈ W.

*aX ∈ W for any X ∈ W and a ∈ R.

So, given W = { X : X = [x1...], x1 = 0, x2 = 0, ... xn = 0 } ∈ Rn

*

*The zero vector ∈ W because each X in W is the zero vector by definition,

*X + Y ∈ W because [0...] + [0...] = [0...]

*aX ∈ W because a[0...] = [0...]

So if I understand this correctly, the zero vector is itself a subspace of $\mathbb{R}^n$. Is this correct?
In addition, can this be extended to say that for any W = { X : X = [$x_1$...] } ∈ $\mathbb{R}^n$, assuming W is a subspace of $\mathbb{R}^n$, $x_i$ (an arbitrary component of W) can only be a constant if it is 0? (I.e., $x_i$ can't be 1 or 2, but can be 0)

A: Yes the set containing only the zero vector is a subspace of $\Bbb R^n$. It can arise in many ways by operations that always produce subspaces, like taking intersections of subspaces or the kernel of a linear map. It has dimension$~0$: one cannot find a linearly independent set containing any vectors at all, since $\{\vec0\}$ is already linearly dependent (taking $1$ times that vector is a nontrivial linear combination that gives the zero vector). The subspace is isomorphic to $\Bbb R^0$. Like any vector space of dimension$~k$, and hence like $\Bbb R^k$, it has a basis consisting of $k$ vectors; since $k=0$ such a basis is the empty set. Indeed, rather exceptionally, this is the unique basis for $\{\vec0\}$. That $\vec0$ is in the span of the empty set might seem strange, but the unique linear combination one can form of the empty set is the linear combination with no terms at all, and the value of such an empty sum (computed in a vector space) is by convention the zero vector.
In the comments to your question you chose the wrong one of the two available subsets $\emptyset$ and $\{0\}$ to be candidate for the basis; the latter has $1$ element which is too much for dimension$~0$, so naturally you find that it is linearly dependent.

A: Indeed, $\{0\}$ is a subspace. In fact, for any vector space $V$ and any $x\in V$, we have that $\{x\}$ is a subspace of $V$ if and only if $x$ is the zero vector of $V$, since any subspace of $V$ must contain the zero vector of $V$, and the subset of $V$ containing only the zero vector of $V$ is necessarily closed under addition and scalar multiplication (as you've shown).

A: Yes. Took me sometime to get this.

*

*Zero is a member of ${0}$.

*${0}$ is closed under addition. Let u and v be members of ${0}$. $u=v=0$ hence $u+v=0$.

*${0}$ is closed under scalar multiplication.


text:
Q: How to bind map with salesforce page Here is my controller
public with sharing class Search
{
    public String strTag {get;set;}
    public String strlocation {get;set;}
    public String result {get;set;}
    public ResultSet data {get;set;}

    public PageReference find() {

    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();

    req.setEndpoint('http://test.3spire.net/index.php?ins='+strTag+'&loc='+strlocation);
    req.setMethod('GET');

    //these parts of the POST you may want to customize
    req.setCompressed(false);
    req.setBody('key1=value1&key2=value2');
    req.setHeader('Content-Type', 'application/x-www-form-urlencoded');

    try {
        res = http.send(req);
    } catch(System.CalloutException e) {
        system.debug('Callout error: '+ e);
        result = ''+e;
    }

    data= JSON.deserialize(res.getBody(),ResultSet.class);

//    result = res.getBody();
        return null;
    }

    public class ResultSet{
        public Map<String, Result> resultSet;
    }

    public class Result
    {
        public String ins;
        public String loc;
    }
}

And this is my visulforce page
 <apex:pageBlock >
    <apex:pageBlockTable value="" var="var" id="table">
     <apex:column value="" />
     <apex:column value="" />
    </apex:pageBlockTable>
 </apex:pageBlock>

Now how can i bind the data with the interface
Thanks in advance

A: Use like below
Few changes use get set
Class
public with sharing class Search
{
    public String strTag {get;set;}
    public String strlocation {get;set;}
    public String result {get;set;}
    public Map<String, Result> data {get;set;}

    public PageReference find() {

    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();

    req.setEndpoint('http://test.3spire.net/index.php?ins='+strTag+'&loc='+strlocation);
    req.setMethod('GET');

    //these parts of the POST you may want to customize
    req.setCompressed(false);
    req.setBody('key1=value1&key2=value2');
    req.setHeader('Content-Type', 'application/x-www-form-urlencoded');

    try {
        res = http.send(req);
    } catch(System.CalloutException e) {
        system.debug('Callout error: '+ e);
        result = ''+e;
    }
    data= (Map<String, Result>)JSON.deserialize(res.getBody(),Map<String, Result>.class);

    result = res.getBody();
        return null;
    }
    public class Result
    {
        public String ins {get;set;}
        public String loc {get;set;}
    }
}

VF page
<apex:page controller="Search">
    <apex:form>
            <apex:pageBlock >
                <apex:pageBlockSection >
                    Industry
                    <apex:inputText value="{!strTag}"/>
                    Location
                    <apex:inputText value="{!strlocation}"/>
                </apex:pageBlockSection>
                <apex:pageBlockButtons >
                    <apex:commandButton value="Search" action="{!find}" reRender="tableId,tableId2"/>
                </apex:pageBlockButtons>
            </apex:pageBlock>

        <apex:PageBlock id="tableId2">
            <apex:outputText value="{!result}"></apex:outputText>
        </apex:PageBlock>
        <apex:pageBlock id="tableId">
            <apex:pageBlockTable value="{!data}" var="var" id="table">
                <apex:column headerValue="Location">
                    <apex:outputText value="{!data[var].ins}"/>
                </apex:column>
                <apex:column headerValue="Insudtry">
                    <apex:outputText value="{!data[var].loc}"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
</apex:form>
</apex:page>

A: Assuming data to be the wrapper list
<apex:page controller="TestClass1">
<apex:form>
    <apex:pageBlock >
        <apex:pageBlockTable value="{!data.resultSet1.values}" var="var" id="table">
            <apex:column  > {var[0]}</apex:column>
            <apex:column  > {var[1]}</apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>


text:
Q: Unable to use page data in nextjs i am new in nextjs,created "Blog.js" page (inside "page" folder) for fetch data via api,Whenever i open page in browser then data is displaying but whenever i call that page in index.js then displaying following error
"TypeError: Cannot read property 'map' of undefined"

Here is my code in "Data.js" (inside page folder)
import react from "react";

function Data(props)
{
    console.warn("data",props);
    return

    {
    props.data.map(data=>(

                {data.title}
                {props.title}

        ))
 }

}
Data.getInitialProps=async function()
{
    const res= await fetch('https://jsonplaceholder.typicode.com/users')
    const data =await res.json();
    return {
        data
    }
}
export default Data

And after import, i am using following code for use "Data",Where i am wrong ?
<Data />


text:
Q: How to append data from an excel file to an ODBC with Access VBA? I'm trying to append records to an ODBC, but there is an error, here is the vba :
Set rs = CurrentDb.OpenRecordset("accesstable", dbOpenDynaset, dbSeeChanges)
i = wb.Sheets(1).Cells(wb.Sheets(1).Rows.Count, 1).End(-4162).Row
For n = 2 To i
    With rs
        .AddNew
            .Fields(0).Value = wb.Sheets(1).Cells(n, 1).Value
        .Update
    End With
    i = i + 1
Next n

And at the .Update line :
Run-time error '3155':
ODBC--insert on a linked table 'accesstable' failed

Do you know where this might come from please ?
Thank you.

A: you can use below ways:
Sub DAOCopyFromRecordSet(DBFullName As String, TableName As String, _
    FieldName As String, TargetRange As Range)
' Example: DAOCopyFromRecordSet "C:\FolderName\DataBaseName.mdb", _
    "TableName", "FieldName", Range("C1")
Dim db As Database, rs As Recordset
Dim intColIndex As Integer
    Set TargetRange = TargetRange.Cells(1, 1)
    Set db = OpenDatabase(DBFullName)
    Set rs = db.OpenRecordset(TableName, dbOpenTable) ' all records
    'Set rs = db.OpenRecordset("SELECT * FROM " & TableName & _
        " WHERE " & FieldName & _
        " = 'MyCriteria'", dbReadOnly) ' filter records
    ' write field names
    For intColIndex = 0 To rs.Fields.Count - 1
        TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
    Next
    ' write recordset
    TargetRange.Offset(1, 0).CopyFromRecordset rs
    Set rs = Nothing
    db.Close
    Set db = Nothing
End Sub

More info about above code
and you can find a good information in Stack over flow


text:
Q: Is it practical to port code from Flash to C#? My goal is to gain a better understanding of the characteristics of C#, and become more comfortable creating simple apps. I am fairly competent with Flash (Actionscript 3), and found an old Tic-Tac-Toe game I'd written. I started wondering about porting this code into a C# application. Not knowing much about C#, I'm wondering how difficult the migration would be.
On the one hand, the underlying game logic is syntactically similar, and therefore would be easy to port.
However, as far as the graphics are concerned, I don't even know where to begin. So far, I've only exposed myself to Windows Forms and Console apps in C#.
I'm wondering if these Flash concepts have similar analogs in C#, or if the procedures and syntax are radically different:

*

*Placing graphic elements on a stage

*Rendering lines from start/end coordinates

*Event listeners on movie clips

*Swapping the image inside a graphic element (or, in my Flash version, nextFrame() in a movie clip)

A: You may want to try developping your little game using Silverlight. Silverlight applications, coded using C# and Xaml, are pretty similar in form with flash applications, and you should find everything you need without trouble.
So I suggest you download the Silverlight SDK (free) and give it a try.

A: Firstly, Flash is to WPF (close enough) as ActionScript is to C#.
The WPF/Silverlight model is much more similar to Flex that it is to Flash. Everything is added to the UI tree as a object, even lines.
Likewise, adding event handlers to controls (like a button click) can be done in the "code behind" (the code that lives with the view), but the recommendation is to use the MVVM pattern. If you are new to the concepts of separation of concerns and unit testing, feel free to start with the simpler "code behind" method.
While WPF and Silverlight are very similar, I'd recommend starting with Silverlight as the SDK and available samples are richer. You can easily move onto WPF later on (though porting an application from Silverlight to WPF is not automatic).
Swapping images, as you mentioned, would be done via "Visual States" in Silverlight (or possibly changing the image reference, which is more "hacky").
Have a look at the following links to get started:

*

*Learn @ Silverlight.net

*Silverlight on MSDN

*Shapes and Drawing (Silverlight)

A: If you're looking specifically to do games and the like, you may wish to look into the free XNA framework.  However, there will be differences as Flash gives you far more ability to "set up" things beforehand and modify them.

*

*Placing graphic elements on a stage

If you go the XNA route, you will be drawing sprites using the spritebatch, you tell them where and how to draw and that's where they will go

*Rendering lines from start/end coordinates

In windows forms you can do this via a simple System.Drawing call, however if you wish to do this in XNA, you will either have to make a 1 pixel square and stretch/rotate it to what you want, or use 3d primitives (Though this will limit you to a 1 pixel line)

*Event listeners on movie clips

Look into delegates, but there isn't really an equivalent for movie clips to my knowledge

*Swapping the image inside a graphic element (or, in my Flash version, nextFrame() in a movie clip)

This is fairly simple, depending on what you mean.  If you want to, say, animate a sprite.  You can do this by moving the source rectangle or changing the texture of the spritesheet.  If you mean the screen as a whole, this is mostly handled for you provided you use the spritebatch.  In windows forms you'll have to do more of it yourself, but the base concepts are the same.

Overall it's not that bad, but if that doesn't sound appealing check out Silverlight.  It's basically C# styled flash so you may find the transition easier.
Good luck and hope this helps.


text:
Q: Python: Read multiple files and move them to a directory according to their content I am quite new to python, but I would like to use it for the following tasks:

*

*read all files in a directory

*look for a specific character in all lines of the files

*if this character is present only once in the file copy the file in a specific directory.

I tried the following code:
#! /usr/bin/python

import glob
import shutil

path = '/xxxx/Dir/*.txt'
files=glob.glob(path)
for file in files:
    f=open(file)
    f.read()
    total = 0
    for line in f:
        if "*TPR_4*" in line:
            total_line = total + 1
            if total_line == 1:
                shutil.copy(f, 'xxxx/Test/')
f.close()

However, it is not working.
Any suggestion?

A: shutil.copy() takes file names as arguments not open files. You should change your call:
shutil.copy(file, 'xxxx/Test/')

Also: file is a poor name choice. It's a built-in function's name.

A: The logic is not quite correct, also you are mixing up total and total_line and shutil.copy takes the name, not the object as an argument. And note that the if .. in line does not use globbing syntax, i.e. to search for TPR_4, use 'TPR_4', not '*TPR_4*'. Try the following:
#! /usr/bin/python
import glob
import shutil

path = '/xxxx/Dir/*.txt'
files=glob.glob(path)
for file in files:
    f=open(file)
    total = 0
    for line in f:
        if "TPR_4" in line:
            total += 1
            if total > 1:
                break  # no need to go through the file any further
    f.close()
    if total == 1:
        shutil.copy(file, 'xxxx/Test/')

A: I wrote some code for your question, maybe it's good for you.
import os, shutil

dir_path = '/Users/Bob/Projects/Demo'
some_char = 'abc'
dest_dir = "/Users/Bob/tmp"
for root, dirs, files in os.walk(dir_path):
    for _file in files:
        file_path = os.path.join(root, _file)
        copy = False
        with open(file_path, 'r') as f:
            while True:
                line = f.readline()
                if not line:
                    break
                if str(line).find(some_char) > -1:
                    copy = True
                    break
            if copy:
                shutil.copy(file_path, dest_dir)
                print file_path, ' copy...'


text:
Q: How to calculate coordinate map I'll create polygon coordinate on google map,
but i dont know how to get coordinate from degree
360/5 = 72 and I get degree [0,72,144,216,288,360,0] to draw polygon
how to getting cordinate from center.
example center coordinate lat: -6.213689, lng: 106.560494 and radius: 1km
expectation
/**
0deg => longitude: ? , latitude: ?
72deg => longitude: ? , latitude: ?
144deg => longitude: ? , latitude: ?
216deg => longitude: ? , latitude: ?
288deg => longitude: ? , latitude: ?
360deg => longitude: ? , latitude: ?
**/

A: Trigonometrical circle

You have done well so far, you will need to acquire some theoretical knowledge going forward. Don't worry, it's not difficult. Let's first understand what a trigonometrical circle is.
The trigonometrical circle is a circle in the OXY plane, whose center is located on O(0, 0) and radius is equal to 1.
Points on the trigonometrical circle

From the figure you can see that a point located at a given degree, let's say, it's 72 degree (0.0174533 radians). The coordinates of P, where A is the degree are (cos(A), sin(A)). If A = 72, then the coordinates are (cos(72), sin(72)) = (0.99984769502, 0.0174533)
How to compute it
In many cases, degrees are calculated in radians. You might have to convert degrees into radians in order to get the correct result.
Scaling
If the radius is not 1, but r, then the coordinates on the trigonometric circle are (r * cos(A), r * sin(A))
Translation
If your polygon is not centered on O(0, 0), but C(Xc, Yc), then the formula modifies to (Xc + r * cos(A), Yc + r * sin(A))


text:
Q: Pointer in C only updates once when method is called I am doing a program to mimic the hare and turtle race. I dont understand why my pointer for the turtle movement only updates once when the condition is met multiple times.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define SIZE 70

void turtleMove(char raceTrack[SIZE], char *tPtr);

int main()
{
    char raceTrack[SIZE];
    for(int i = 0; i<SIZE; i++)
    {
        raceTrack[i] = ' ';
    }

    char *tPtr = raceTrack;

    for(int i = 0; i <=10; i++)
    {
        turtleMove(raceTrack, tPtr);
    }

}
void turtleMove(char raceTrack[SIZE], char *tPtr)
{
    srand(time(0));

    int num = rand() % 10 + 1;
    printf("%d\n", num);

    if(num >= 1 && num <= 5)
    {
        printf("Fast plod\n");
        *tPtr = ' ';
        tPtr += 3;
        *tPtr = 'T';

        for(int i = 0; i <SIZE; i++)
        {
            printf("%c,", raceTrack[i]);

        }
        printf("\n");

    }
}

I want it to do this for example:
2
Fast plod
 , , ,T, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
5
Fast plod
 , , , , , , ,T, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
etc...
Instead it's doing:
2
Fast plod
 , , ,T, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
5
Fast plod
 , , ,T, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

A: You are only updating the local value of tPtr.
Your function is defined as:
void turtleMove(char raceTrack[SIZE], char *tPtr);

This takes a pointer to a char as the second argument, so anything at the address pointed to by tPtr can be modified and retained, but the value of tPtr (the address itself), cannot.
To be able to modify the address, you need to pass a pointer to a pointer to char:
void turtleMove(char raceTrack[SIZE], char **tPtr);

Then in the function, when you want to modify the character, you dereference twice:
**tPtr = ' ';

And when you want to modify the address, you dereference once:
*tPtr += 3;

Lastly, of course, you have to fix how you are calling turtleMove() so that you are passing a char**. Fortunately, you can do this by just grabbing the address of tPtr as defined in main():
turtleMove(raceTrack, &tPtr);


text:
Q: change radcombobox button color I use VS2010, C# in my ASP.NET web app, I'm using RadCombobox (telerik), how can I change its button (the part that contains downside arrow), also I want to change the button hover color

A: Assuming you are using Telerik ASP.NET AJAX toolkit you are able to change appearance of Rad controls by changing their skins.
You can select skin from the list of existing skins:
http://www.telerik.com/help/aspnet-ajax/combobox-appearance-skins.html
You can also create your own skin using steps under followin link:
http://www.telerik.com/help/aspnet-ajax/combobox-appearance-creating-custom-skins.html
Similar changes may be done to other Telerik controls.


text:
Q: Prevent svg paths from overflowing I have a simple SVG image with a line in it:
<svg class="icon icon-person" width="25rem" height="25rem" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <style>
    path {
      stroke-width: 5 !important;
    }
  </style>
  <path d="M2.5 0 V 200"></path>
</svg>

It draws a simple vertical line along the left border of the SVG image. My stroke-width is constant and is equal to 5.
In order for the path not to overflow the SVG image area, I had to set the path starting point x coordianate to 2.5 which is 50% of its width. However, it feels confusing to mind those overflow every time I draw something near the edge of the SVG image.
So what I thought is to wrap all my paths into some g element or something, set its size to 195 x 195 and offset it by 2.5 units from the edge of the SVG image, then specify the position of all paths inside it relative to the g element without having to deduct that 50% of the border width.
The problem is that g elements cannot be positioned so I am stuck Any help would be appreciated.

A: You can transform a group 's contents.

<svg class="icon icon-person" width="25rem" height="25rem" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <style>
    path {
      stroke: black;
      stroke-width: 5 !important;
    }
  </style>
  <g transform="translate(2.5, 0)">
    <path d="M0 0 V 200"></path>
  </g>
</svg>


text:
Q: PDF columtext shrink to fit using iText or iTextSharp I have a function to relay a stamp on top of a field in PDF to serve as filling richtext field.
    public void FillRichTextField(AcroFields pdfForm, PdfStamper pdfStamper, string fieldName, string value)
{
    System.Collections.Generic.IList<AcroFields.FieldPosition> pos = pdfForm.GetFieldPositions(fieldName);
    //tell itextSharp to overlay this content
    PdfContentByte contentByte = pdfStamper.GetOverContent(pos[0].page);
    //create a new paragraph
    Paragraph par = new Paragraph();
    //parse html
    var mh = new SampleHandler();
    //Bind a reader to our text
    using (TextReader sr = new StringReader(value))
    {
        //Parse
        XMLWorkerHelper.GetInstance().ParseXHtml(mh, sr);
    }
    for (int k = 0; k < mh.elements.Count; k++)
    {
        par.Add((IElement)mh.elements[k]);
    }

    //create a ColumnText to hold the paragraph and set position to the position of                   the field
    ColumnText ct = new ColumnText(contentByte);

    ct.SetSimpleColumn(pos[0].position.Left, pos[0].position.Bottom, pos[0].position.Right, pos[0].position.Top);
    ct.AddElement(par);
    int status = ct.Go();
    bool fits = !ColumnText.HasMoreText(status);

}

The paragraph got cut off so I'd like to resize/rescale the paragraph to fit in the ColumnText, there does not seem to be a way of doing that. I can't initiate a new font as the paragraph contains richtext data that has it's own font. I guess my best bet is to convert the paragraph into a scalable image then resize to fit?
Or if there is a better way of filling richtext field so that all text fit in with the style maintained please let me know.

A: If you change your method FillRichTextField like this, it scales down the content it draws to fit the form field rectangle. Furthermore it removes the form field as it would hide the drawn text.
public void FillRichTextField(AcroFields pdfForm, PdfStamper pdfStamper, string fieldName, string value)
{
    System.Collections.Generic.IList<AcroFields.FieldPosition> pos = pdfForm.GetFieldPositions(fieldName);
    PdfContentByte contentByte = pdfStamper.GetOverContent(pos[0].page);
    Rectangle fieldRectangle = pos[0].position;

    PdfTemplate template = contentByte.CreateTemplate(fieldRectangle.Width, fieldRectangle.Height);

    ColumnText ct = new ColumnText(template);
    XMLWorkerHelper.GetInstance().ParseXHtml(new ColumnTextElementHandler(ct), new StringReader(value));

    for (float factor = 1; ; factor *= 1.5f)
    {
        ct.SetSimpleColumn(0, 0, factor * fieldRectangle.Width, factor * fieldRectangle.Height);

        if (!ColumnText.HasMoreText(ct.Go(false)))
        {
            ct.Go();
            template.Width = factor * fieldRectangle.Width;
            template.Height = factor * fieldRectangle.Height;
            contentByte.AddTemplate(template, 1 / factor, 0, 0, 1 / factor, fieldRectangle.Left, fieldRectangle.Bottom);

            pdfForm.RemoveField(fieldName);

            contentByte.Rectangle(fieldRectangle.Left, fieldRectangle.Bottom, fieldRectangle.Width, fieldRectangle.Height);
            contentByte.Stroke();

            return;
        }
    }
}

in combination with this handler class
public class ColumnTextElementHandler : IElementHandler
{
    public ColumnTextElementHandler(ColumnText ct)
    {
        this.ct = ct;
    }

    ColumnText ct = null;

    public void Add(IWritable w)
    {
        if (w is WritableElement)
        {
            foreach (IElement e in ((WritableElement)w).Elements())
            {
                ct.AddElement(e);
            }
        }
    }
}

The result is not yet satisfying though:

As you see there is some overlapping text.
The code above renders what it receives from the XMLWorker. Thus, either my XMLWorker usage is incorrect or the input is bad. The scaling code as such (i.e. the for loop) should be correct, though.


text:
Q: Use CloudWatch with VPC Endpoints (PrivateLink) I have read the AWS documentation on the connection between the resources of a VPC and CloudWatch but I have not really understood what the objective is.
Does this secure the data transport between the VPC and CloudWatch?
Or is it because the internet is required for communication between one instance of a VPC and CloudWatch?
Is a VPC with an Internet connection required to send data to CloudWatch?

A: Normally, to communicate with CloudWatch (CW), for example when using cloudwatch agent, your instance must be able to connect to CW public endpoint. For CW, the endpoints are here.
These are regular HTTP/HTTPS public endpoints, which means that your instance generally requires internet connection. Without it will not be able to reach the internet and the endpoints. However, this requires your instance be in a public subnet or use a NAT gateway.
Internet access often can be not desired due to enhance security requirements. This is where VPC endpoints come into play. They enable resources in private VPC or subnet (i.e. without any internet access) to connect privately to the CW, or there services (e.g., S3, Lambda).

Is a VPC with an Internet connection required to send data to CloudWatch?

Yes, unless you will use VPC interface endpoint in your VPC.


text:
Q: How to "intersperse" two lists by a key value? I have two lists of maps and I want to form a list that would contain values from both lists basing on some common values.
list1 = [
  %{email: "email1", name: "name1"},
  %{email: "email2", name: "name2"}
]

list2 = [
  %{"email" => "email3", "name" => "new name3"},
  %{"email" => "email2", "name" => "new name2"}
]

The lists may be different size, one of them may even be empty.
The desired output would be:
[
  {%{email: "email1", name: "name1"}, nil},
  {%{email: "email2", name: "name2"},
   %{"email" => "email2", "name" => "new name2"}},
  {nil, %{"email" => "email3", "name" => "new name3"}}
]

Here is an implementation I came up with:
  # to produce the output above, call it with
  # list_intersperse(list1, list2, :email, "email")
  def list_intersperse(list1, list2, key1, key2) do
    map2 = Enum.map(list2, fn elem -> {elem[key2], elem} end) |> Map.new()

    result =
      Enum.map(list1, fn elem ->
        common_value = Map.get(elem, key1)
        {elem, map2[common_value]}
      end)

    keys1 = Enum.map(list1, fn elem -> Map.get(elem, key1) end) |> MapSet.new()

    result ++
      (list2
       |> Enum.reject(&MapSet.member?(keys1, &1[key2]))
       |> Enum.map(&{nil, &1}))
  end

The implementation feels sub-optimal to me and it's hard to read. Am I missing something, could it be done in a more concise and more readable way?

A: How about this?
def pair(list1, list2) do
  map1 = Map.new(list1, fn item -> {item.email, item} end)
  map2 = Map.new(list2, fn item -> {item["email"], item} end)

  all_emails = MapSet.new(Map.keys(map1) ++ Map.keys(map2))
  for email <- all_emails, do: {map1[email], map2[email]}
end

Usage:
iex(1)> Example.pair(list1, list2)
[
  {%{email: "email1", name: "name1"}, nil},
  {%{email: "email2", name: "name2"},
   %{"email" => "email2", "name" => "new name2"}},
  {nil, %{"email" => "email3", "name" => "new name3"}}
]

A: The accepted answer works perfectly for the data set I've posted in the question, but it turned out that my data set has some duplicated data on both sides.
For example:
list1 = [
  %{email: nil, name: "nil1"},
  %{email: nil, name: "nil2"},
  %{email: "email1", name: "name1"},
  %{email: "email2", name: "name2"}
]

list2 = [
  %{"email" => "email3", "name" => "new name3"},
  %{"email" => "email2", "name" => "new name2"},
  %{"email" => "email2", "name" => "new name2"}
]

In the first list there are two items with duplicated keys and both of them nil, and in the second list there are two keys with the same values equals to email2.
I need to keep all these values in the resulting data set, so mapping by key won't work.
What I ended up doing is using List.myers_difference function and transforming its results into the list I want to see:
def list_intersperse(list1, list2, key1, key2) do
  list1 = Enum.sort_by(list1, &Map.get(&1, key1))
  list2 = Enum.sort_by(list2, &Map.get(&1, key2))

  List.myers_difference(list1, list2, fn elem1, elem2 ->
    if Map.get(elem1, key1) == Map.get(elem2, key2), do: {elem1, elem2}
  end)
  |> Enum.map(&myers_to_intersperse/1)
  |> List.flatten()
end

defp myers_to_intersperse({:del, list}), do: Enum.map(list, &{&1, nil})
defp myers_to_intersperse({:ins, list}), do: Enum.map(list, &{nil, &1})
defp myers_to_intersperse({:diff, tuple}), do: tuple

The code above gives the result I wanted:
[
  {%{email: nil, name: "nil1"}, nil},
  {%{email: nil, name: "nil2"}, nil},
  {%{email: "email1", name: "name1"}, nil},
  {%{email: "email2", name: "name2"}, %{"email" => "email2", "name" => "new name2"}},
  {nil, %{"email" => "email2", "name" => "new name2"}},
  {nil, %{"email" => "email3", "name" => "new name3"}}
]


text:
Q: Every Time I create a new angular project it gives me 5k commits I haven't initialized git yet in this project but everytime I create a new angular
project through angular cli , it gives me 5k commits on vscode.I want there to be no commits so
I can initialize a new git repository and push all the data there.I have created a new repo and I
want to attach that with my code.


text:
Q: Insert aggregation results into an index The goal is to build an Elasticsearch index with only the most recent documents in groups of related documents to track the current state of some monitoring counters and states.
I have crafted a simple Elasticsearch aggregation query:
{
  "size": 0,
  "aggs": {
    "group_by_monitor": {
      "terms": {
        "field": "monitor_name"
      },
      "aggs": {
        "get_latest": {
          "top_hits": {
            "size": 1,
            "sort": [
              {
                "timestamp": {
                  "order": "desc"
                }
              }
            ]
          }
        }
      }
    }
  }
}

It groups related documents into buckets and select the most recent document for each bucket.
Here are the different ideas I had to get the job done:

*

*directly use the aggregation query to push the results into the index, but it does not seem possible : Is it possible to put the results of an ElasticSearch aggregation back into the index?

*use the Logstash Elasticsearch input plugin to execute the aggregation query and the Elasticsearch output plugin to push into the index, but seems like the input plugin only looks at the hits field and is unable to handle aggregation results: Aggregation Query possible input ES plugin !

*use the Logstash http_poller plugin to get a JSON document, but it does not seem to allow specifying a body for the HTTP request !

*use the Logstash exec plugin to execute cURL commands to get the JSON but this seems quite cumbersome and my last resort.

*use the NEST API to build a basic application that will do polling, extract results, clean them and inject the resulting documents into the target index, but I'd like to avoid adding a new tool to maintain.

Is there a reasonably complex way of accomplishing this?

A: Edit the logstash.conf file as follow
input {
  elasticsearch {
    hosts => "localhost"
    index => "source_index_name"
    type =>"index_type"
    query => '{Query}'
    size => 500
    scroll => "5m"
    docinfo => true
  }
}

output {
  elasticsearch {
    index => "target_index_name"
    document_id => "%{[@metadata][_id]}"
  }
}


text:
Q: Flatten column values into a string Although I've been using Sql Server on an occasional basis for yonks, I didn't realise until I stumbled across it the other day that you could do something like this:
declare @result varchar(8000)

select @result = ''

select @result = @result + acolumn+ ' '

from atable

Nothing I'd read in the Transact-Sql docs led me to think of using a construct like that rather than e.g. a cursor.  My question: Is this construct supported by other versions of Sql or is it Sql Server-specific?

A: This is Sql server specific. The statements you mentioned are T-SQL statements and they are only available for Sql Server.

A: Do not do this, because it depends on the physical implementation and internal access paths. Please read the article on Concatenating Row Values in Transact-SQL for several correct approaches such as the FOR XML PATH('') approach.


text:
Q: Java Batch (JSR-352) - How to set a Job Parameter from a batchlet? I have a batchlet that gets a file from a FTP server and stores it in a temporary folder. I would like to set the path of that folder as a batch job parameter, so that other steps can access the file. Is this possible and if so, how? My JSR 352 implementation is spring batch.
Edit: I am using Spring Batch 3.0 Milestone 3.

A: You can pass in the location of the file as a job parameter using JSR-352's facilities as follows:
<step id="step1">
    <batchlet ref="fooBatchlet">
        <properties>
            <property name="fileName" value="#{jobParameters['testParam']}"/>
        </properties>
    </batchlet>
</step>

The above assumes you're using either the batch.xml or Spring DI to define fooBatchlet.  Otherwise, fooBatchlet would need to be the fully qualified class name.

A: What version of Spring are you using?
Assuming v3, you can store information to pass to other job steps either in the StepContext or the JobExecutionContext. You can retrieve the StepContext from the ChunkContext which is passed into the BatchletAdapter RepeatStatus method.
Or you could set a JVM parameter, but that feels a bit clunky given that Spring offers the above methods.

A: Thanks to Michael Minella I found out I could inject the JobContext in my Batchlet.
@Inject
private JobContext jobContext;

Now I can use this jobContext to set properties.
jobContext.setTransientUserData(myData);


text:
Q: has_many through association | NameError: uninitialized constant Organization::Organizationsuser I have two models joined with a has_many through association:
Here are the tables:
  create_table "organizations", force: :cascade do |t|
    t.string   "name"
    t.string   "description"
    t.string   "mission"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "organizations_users", force: :cascade do |t|
    t.integer  "user_id"
    t.integer  "organization_id"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "first_name"
    t.string   "last_name"
  end

Here are the models:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :organizationsusers
  has_many :organizations, :through => :organizationsusers

end

class Organization < ActiveRecord::Base
  has_many :organizationsusers
  has_many :users, :through => :organizationsusers
  has_many :categories, as: :categorizable

end

class OrganizationsUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :organization
end

When I create a new organization via my form it creates adequately. However I keep getting:
NameError: uninitialized constant Organization::Organizationsuser

If I do something like this for example:
o = Organization.last

  Organization Load (0.4ms)  SELECT  "organizations".* FROM "organizations"  ORDER BY "organizations"."id" DESC LIMIT 1
 => #<Organization id: 1, name: "HOU", description: "fkjndskj", mission: "fnskjdfs", created_at: "2015-09-16 07:35:42", updated_at: "2015-09-16 07:35:42">

o.users
NameError: uninitialized constant Organization::Organizationsuser

Why is this happening? Am I misunderstanding something here?

A:
NameError: uninitialized constant Organization::Organizationsuser

Changing organizationsusers to organizations_users in your code should fix the error.
#user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :organizations_users
  has_many :organizations, :through => :organizations_users
end

#organization.rb
class Organization < ActiveRecord::Base
  has_many :organizations_users
  has_many :users, :through => :organizations_users
  has_many :categories, as: :categorizable
end

A: I have read you code. You have typo to write your associations.
Please change :organizationsusers into :organizations_users. I hope this help you


text:
Q: SSL_CTX_new() hangs on ARM architecture I am working on a cross-compile project, implementing an HTTPS connection. My code builds and runs fine in the qemu-arm emulator, but when running on the actual hardware, it hangs on SSL_CTX_new.
This is the code I use to initialise my SSL context:
SSL_CTX *_https_initialise_context() {
    const SSL_METHOD *method;
    SSL_CTX *_ctx;
    OpenSSL_add_all_algorithms();
    SSL_load_error_strings();

    method = TLS_client_method();
    // This is where the program hangs
    _ctx = SSL_CTX_new(method);

    if (_ctx == NULL) {
        ERR_print_errors_fp(stderr);
        abort();
    }

    return _ctx;
}

The device the code is running on is old, and does not have a lot of resources (32M RAM, running on a 192MHz ARM processor), but when checking top, the process does not seem to be CPU bound. (it stays at 0% CPU and 13% RAM)
Is TLS too much for this device, or could I update my code to get this running?


text:
Q: How to select multiple, relative cells in VBA A
Range("O16:P19").Select
This code will select a single, grid-locked area
B
Range("Q19:R22,T19:U22").Select

This code is able to select multiple, grid-locked areas
C
Range(ActiveCell.Offset(0,0), ActiveCell.Offset(1,1)).Select

This code is able to select a single, relative area
D
?????
How do you write code to select multiple, relative areas in VBA
If 'A' is to 'B' as 'C' is to 'D', then how do I write 'D'?

A: You can use Union to join a bunch of different ranges.
Here you can see I'm mixing relative ranges and absolute references:
Sub Teste()
    Dim RG As Range
    Set RG = Union( _
        ActiveCell.Offset(0, 0).Resize(3, 3), _
        ActiveCell.Offset(5, 5).Resize(2, 2), _
        ActiveCell.Offset(10, 2).Resize(1, 5), _
        Range("A2:B3"))
    RG.Select
    ActiveCell.Activate
End Sub

A: Relative Ranges
Offset
Sub Test1()

    Dim ColumnOffset As Long
    ColumnOffset = Columns("D").Column - Columns("A").Column

    Dim rg As Range: Set rg = Columns("F").Offset(, ColumnOffset)

    Debug.Print rg.Address ' Result: '$I:$I'

End Sub

Resize
Sub Test2()

    Dim srg As Range: Set srg = Columns("A:D")
    Dim drg As Range: Set drg = Columns("F").Resize(, srg.Columns.Count)

    Debug.Print drg.Address ' Result: '$F:$I'

End Sub

Sub Test3()

    Dim srg As Range: Set srg = Range("A1:E5")
    Dim dfCell As Range: Set dfCell = Range("C10")
    Dim drg As Range: Set drg = dfCell.Resize(srg.Rows.Count, srg.Columns.Count)

    Debug.Print drg.Address ' Result: '$C$10:$G$14'

End Sub

Sub Test4()

    Dim srg As Range: Set srg = Range("A1:E5")
    Dim dfCell As Range: Set dfCell = Range("C10")
    Dim drg As Range: Set drg = dfCell.Resize(srg.Rows.Count, srg.Columns.Count)
    Dim urg As Range: Set urg = Union(srg, drg)

    Debug.Print urg.Address ' Result: '$A$1:$E$5,$C$10:$G$14'

End Sub


text:
Q: Venn diagram for conditional probability property of Independent Events In my maths schoolbook there is this property for independent events:

p(A|B) = p(A)
p(B|A) = p(B)

But I can't imagine how this is possible. How would you draw a Venn diagram that follows this property?

A: Here is a diagram that illustrates independence, where probability means "area".
 Here $P(A)$ is the proportion of the square that is colored yellow, while $P(A\mid B)$ is the proportion of the green stripe that is colored yellow. These two proportions are the same (approximately 1/3).

A: The events $A$ and $B$ are independent if
$$
P(A\cap B)=P(A)P(B).
$$
The conditional probability of the event $A$ given the event $B$ is defined by
$$
P(A\mid B)=\frac{P(A\cap B)}{P(B)}
$$
provided that $P(B)>0$. So we have that
$$
P(A\mid B)=\frac{P(A\cap B)}{P(B)}=\frac{P(A)P(B)}{P(B)}=P(A)
$$
if $A$ and $B$ are independent. Analogously, $P(B\mid A)=P(B)$. So we see that this property holds if and only if the events $A$ and $B$ are independent. This property can be taken as a definition of the independence.