text:
Q: How to publish Cobertura coverage report from the VS coverage produced by dotnet test --collect "Code coverage"? So the process can be deduced from https://learn.microsoft.com/en-us/azure/devops/pipelines/ecosystems/dotnet-core?view=azure-devops#collect-code-coverage and contains of the following steps:

*

*Run the tests with coverage without publishing the test results, because we need to control the location of the generated binary coverage report (see How to set a custom coverage result file path when running dotnet test --collect "Code coverage"?)

*Convert the VS binary coverage result to XML

*Install the reportgenerator tool

*Convert the VS XML coverage to Cobertura using the reportgenerator tool

*Publish the Cobertura report using the Publish Code Coverage Azure DevOps task

*Publish the Test Results

These steps can be implemented with the following YAML template:
parameters:
  BuildConfiguration: Debug

steps:
- task: DotNetCoreCLI@2
  name: Test
  displayName: Test
  inputs:
    command: 'test'
    publishTestResults: false
    arguments: '-c ${{ parameters.BuildConfiguration }} --no-build -l trx -r $(Common.TestResultsDirectory)\tests --collect "Code coverage"'

- task: PublishTestResults@2
  displayName: Publish Test Results
  inputs:
    testResultsFormat: VSTest
    testResultsFiles: '*.trx'
    searchFolder: $(Common.TestResultsDirectory)\tests
    testRunTitle: $(Build.DefinitionName)-$(Build.BuildNumber)
  condition: succeededOrFailed()

- powershell: |
    $cc = "$(Get-ToolFolderFromNuGet Microsoft.CodeCoverage)\..\build\netstandard1.0\CodeCoverage\CodeCoverage.exe"
    $BinaryCoverageFile = (Get-Item "$(Common.TestResultsDirectory)\tests\*\*.coverage").FullName
    & $cc analyze /output:$(Common.TestResultsDirectory)\vstest-coverage.xml $BinaryCoverageFile
  displayName: Convert Coverage Result To Xml

- task: DotNetCoreCLI@2
  inputs:
    command: custom
    custom: tool
    arguments: install --tool-path . dotnet-reportgenerator-globaltool
  displayName: Install ReportGenerator tool

- script: .\reportgenerator.exe -reports:$(Common.TestResultsDirectory)\vstest-coverage.xml -targetdir:$(Common.TestResultsDirectory)\coverage\report -reporttypes:"Cobertura"
  displayName: Create Cobertura Coverage Report

- task: PublishCodeCoverageResults@1
  displayName: Publish Coverage Results
  inputs:
    codeCoverageTool: 'Cobertura'
    summaryFileLocation: '$(Common.TestResultsDirectory)/coverage/report/Cobertura.xml'
    failIfCoverageEmpty: true

It uses my powershell function Get-ToolFolderFromNuGet to download a package from NuGet, but other than that no custom code is used.
Anyway, the problem is that the Publish Test Results task publishes the binary coverage result as a hyperlink in the same tab where the coverage results are supposed to be:

This is useless. If I comment out the Publish Test Results, the coverage page shows the expected result:

But now I lost the Tests page, of course:

Does anyone know how to resolve this conundrum?
P.S.
I opened a bug here - https://github.com/microsoft/azure-pipelines-tasks/issues/12670
EDIT 1
I tried to Publish the Test Results at the end and even deleting the binary coverage result file. Nothing helps.

A: By inspecting the diag logs for the Publish Test Results task I managed to figure out how to resolve it. Indeed, from the logs:
2020-04-10T15:48:12.1799774Z ##[debug]pattern: '*.trx'
2020-04-10T15:48:12.1839752Z ##[debug]findPath: 'd:\_wf\06\13\TestResults\tests'
2020-04-10T15:48:12.1840795Z ##[debug]statOnly: 'false'
2020-04-10T15:48:12.1843783Z ##[debug]findPath: 'd:\_wf\06\13\TestResults\tests'
2020-04-10T15:48:12.1844681Z ##[debug]findOptions.allowBrokenSymbolicLinks: 'true'
2020-04-10T15:48:12.1845119Z ##[debug]findOptions.followSpecifiedSymbolicLink: 'true'
2020-04-10T15:48:12.1845244Z ##[debug]findOptions.followSymbolicLinks: 'true'
2020-04-10T15:48:12.1850467Z ##[debug]  d:\_wf\06\13\TestResults\tests (directory)
2020-04-10T15:48:12.1858807Z ##[debug]  d:\_wf\06\13\TestResults\tests\1f627391-dd45-48b3-af92-5213c471eb04 (directory)
2020-04-10T15:48:12.1864156Z ##[debug]  d:\_wf\06\13\TestResults\tests\tfsbuild_TDC5DFC1BLD24_2020-04-10_11_47_29 (directory)
2020-04-10T15:48:12.1868508Z ##[debug]  d:\_wf\06\13\TestResults\tests\tfsbuild_TDC5DFC1BLD24_2020-04-10_11_47_29\In (directory)
2020-04-10T15:48:12.1873069Z ##[debug]  d:\_wf\06\13\TestResults\tests\tfsbuild_TDC5DFC1BLD24_2020-04-10_11_47_29\In\TDC5DFC1BLD24 (directory)
2020-04-10T15:48:12.1880777Z ##[debug]  d:\_wf\06\13\TestResults\tests\tfsbuild_TDC5DFC1BLD24_2020-04-10_11_47_29\In\TDC5DFC1BLD24\tfsbuild_TDC5DFC1BLD24_2020-04-10.11_47_23.coverage (file)
2020-04-10T15:48:12.1884045Z ##[debug]  d:\_wf\06\13\TestResults\tests\tfsbuild_TDC5DFC1BLD24_2020-04-10_11_47_29.trx (file)
2020-04-10T15:48:12.1885576Z ##[debug]7 results

So the binary coverage file is found there. But its original location is different, we can see it from the regular build log of the test task itself:
2020-04-10T15:47:54.0912521Z M i c r o s o f t   ( R )   C o v e r a g e   C o l l e c t i o n   T o o l   V e r s i o n   1 6 . 0 . 3 0 3 1 9 . 3 0 0 2
2020-04-10T15:47:54.0913009Z
2020-04-10T15:47:54.0913107Z
2020-04-10T15:47:54.0913209Z  C o p y r i g h t   ( c )   M i c r o s o f t   C o r p o r a t i o n .     A l l   r i g h t s   r e s e r v e d .
2020-04-10T15:47:54.0913270Z
2020-04-10T15:47:54.0913307Z
2020-04-10T15:47:54.0913340Z
2020-04-10T15:47:54.0913400Z
2020-04-10T15:47:54.3182888Z  Results File: d:\_wf\06\13\TestResults\tests\tfsbuild_TDC5DFC1BLD24_2020-04-10_11_47_29.trx
2020-04-10T15:47:54.3183717Z
2020-04-10T15:47:54.3184201Z Attachments:
2020-04-10T15:47:54.3184419Z   d:\_wf\06\13\TestResults\tests\1f627391-dd45-48b3-af92-5213c471eb04\tfsbuild_TDC5DFC1BLD24_2020-04-10.11_47_23.coverage
2020-04-10T15:47:54.3196805Z Test Run Successful.
2020-04-10T15:47:54.3197219Z Total tests: 445
2020-04-10T15:47:54.3197713Z      Passed: 445
2020-04-10T15:47:54.3199584Z  Total time: 30.1160 Seconds

So, the original binary coverage file is in d:\_wf\06\13\TestResults\tests\1f627391-dd45-48b3-af92-5213c471eb04\tfsbuild_TDC5DFC1BLD24_2020-04-10.11_47_23.coverage, but it was copied over to d:\_wf\06\13\TestResults\tests\tfsbuild_TDC5DFC1BLD24_2020-04-10_11_47_29\In\TDC5DFC1BLD24\tfsbuild_TDC5DFC1BLD24_2020-04-10.11_47_23.coverage
My mistake was to only delete the original location. When deleted in both places, the Code Coverage page became as expected - no more useless hyperlink, yes to the actual coverage.
The corrected powershell task in the YAML looks like this:
- powershell: |
    $cc = "$(Get-NuGetPackageBaseFolder Microsoft.CodeCoverage)\build\netstandard1.0\CodeCoverage\CodeCoverage.exe"
    $BinaryCoverageFile = Get-Item "$(Common.TestResultsDirectory)\tests\*\*.coverage"
    & $cc analyze /output:$(Common.TestResultsDirectory)\vstest-coverage.xml $BinaryCoverageFile.FullName
    Remove-Item (Get-ChildItem -Path "$(Common.TestResultsDirectory)\tests" -Recurse -Filter $BinaryCoverageFile.Name).FullName
  displayName: Convert Coverage Result To Xml

And of course, the Publish Test Results task must be moved after this task.

A: I solved the problem by deleting the code coverage files after reportgenerator.
Here are the steps
steps:
  - task: DotNetCoreCLI@2
    displayName: dotnet test
    inputs:
      command: 'test'
      projects: '**/*.Tests.csproj'
      arguments: '--no-build --no-restore --configuration $(BuildConfiguration) --collect "XPlat Code Coverage" --settings CodeCoverage.runsettings --logger trx --results-directory $(Build.SourcesDirectory)/out/TestResults/'
      publishTestResults: false

  - script: |
        dotnet tool install -g dotnet-reportgenerator-globaltool
        reportgenerator -reports:$(Build.SourcesDirectory)/out/TestResults/**/coverage.cobertura.xml -targetdir:$(Build.SourcesDirectory)/out/CoverageResults "-reporttypes:HtmlInline_AzurePipelines;Cobertura"
    displayName: Create code coverage report

  - task: DeleteFiles@1
    displayName: 'Delete coverage files'
    inputs:
      sourceFolder: $(Build.SourcesDirectory)/out/TestResults
      contents: |
        \**\*.coverage

  - task: PublishTestResults@2
    displayName: 'Publish test results'
    inputs:
      testResultsFormat: VSTest
      testResultsFiles: '$(Build.SourcesDirectory)\out\TestResults\**\*.trx'
      failTaskOnFailedTests: true

  # Publish the combined code coverage to the pipeline
  - task: PublishCodeCoverageResults@1
    displayName: 'Publish code coverage report'
    inputs:
      codeCoverageTool: 'Cobertura'
      summaryFileLocation: '$(Build.SourcesDirectory)/out/CoverageResults/Cobertura.xml'
      reportDirectory: '$(Build.SourcesDirectory)/out/CoverageResults'


text:
Q: File to MultipartFile I know this question has been asked here before, for example here, however, most of the answers use MockMultipartFile to do the job. However, it seems that this class should be in the scope of test.
Another class that implements the interface MultipartFile, it is the CommonsMultipartFile.
However, using MockMultipartFile seems to be a lot easier to use than CommonsMultipartFile.
The question is: What is the correct way to transform a File to MultipartFile, since MockMultipartFile is on the package of mock and CommonsMultipartFile is not

redpajama_set_name: RedPajamaStackExchange


text:
Q: copy_to field referring parent field in elasticsearch Here is my mapping of Product document type. I have "copy_to" : "product_all" in mapping.
I am expecting value of label in brand should be copied in 'product_all' in product. Is it correct way of referring the field in outer object from inner object i.e. (product_all in type product from brand), below mapping doesn't work as I don't get results back for a query made on product_all field for the value of label in brand. Am I missing something?
{
  "product": {
    "_timestamp": {
      "enabled": true,
      "store": true
    },
    "_all": {
      "enabled": false
    },
    "dynamic": "strict",
    "properties": {
      "brand": {
        "properties": {
          "id": {
            "type": "long"
          },
          "label": {
            "type": "multi_field",
            "fields": {
              "label": {
                "type": "string",
                "index_analyzer": "productAnalyzer",
                "search_analyzer": "productAnalyzer"
              },
              "raw": {
                "type": "string",
                "index": "not_analyzed"
              }
            },
            "copy_to": "product_all"
          }
        }
      },
      "product_all": {
        "type": "string",
        "index_analyzer": "productAnalyzer",
        "search_analyzer": "productAnalyzer"
      }
    }
  }
}

A: I moved "copy_to":"product_all"  inside label.label of mutifield. Now it works

"label": {
            "type": "multi_field",
            "fields": {
              "label": {
                "type": "string",
                "copy_to": "product_all"
                "index_analyzer": "productAnalyzer",
                "search_analyzer": "productAnalyzer"
              },
              "raw": {
                "type": "string",
                "index": "not_analyzed"
              }
            }

          }


text:
Q: Why does the following code return an error when consuming multiple endpoints of a WCF service? I have created a multi-endpoint WCF service and consumed and it is working fine.
But when I am trying to close the service client then am getting error.
This is how I am creating the client object and disposing its working fine for single endpoint WCF service
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        ICardPrintingService Service = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Service = new CardPrintingServiceClient();
            var response = this.Service.GetCardData(new GetCardDataRequest { NIK = 6666620501740003 });
            try
            {
                ((CardPrintingServiceClient)Service).Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("error");
            }
        }
    }
}

This is going to the catch block when closing the connection with error message

The remote endpoint no longer recognizes this sequence. This is most
  likely due to an abort on the remote endpoint. The value of
  wsrm:Identifier is not a known Sequence identifier. The reliable
  session was faulted.

Can some one tell me why?
Thanks a ton in adv
Raghavendra

A: What is the need of casting overhere.
((CardPrintingServiceClient)Service).Close(); //pls explain this.

you can try this in finally block.
if (Service.State != System.ServiceModel.CommunicationState.Closed)
  {
     Service.Abort();
  }


text:
Q: Properties of the expected value rule & total expectation theorem I am going through some T/F questions that test my understanding of the expected value rule and total expectation theorem.
Assume that $X, Y, Z$ are continuous random variables and that all conditional PDFs and expectations are well-defined.

*

*$E[g(y)|X=x]=\int g(y)f_{Y|X}(y|x)dy$
The explanation to this problem says that "the quantity inside the expectation, $g(y)$, is a number (not a random variable). The left-hand side is a function of $y$, whereas on the right-hand side, $y$, is a dummy variable that gets integrated away. So, the formula is wrong on a purely syntactical basis.

*$E[g(X, Z)|Y=y]=\int g(x, z)f_{X,Z|Y}(x,z|y)dy$
The explanation says that "the left-hand side is a function of $y$, whereas the right-hand side (after $y$ is integrated out) is a function of $x$ and $z$. The correct form is:
$$E[g(X, Z)|Y=y]=\int\int g(x, z)f_{X,Z|Y}(x,z|y)dxdz."$$
What I don't understand
For question 1, how does the LHS depend on y while the RHS does not? The explanation says $g(y)$ on the LHS is a number (a constant), so we don't have any dependence on y and yet the explanation says LHS is dependent on y.
For question 2, how does the LHS depend on y? There's no $Y$ in $g(X,Z)$.

A: In standard notation in stochastics $X, Y$ and so on represent random variables. Random variables are actually functions from a probability space to a measurable space. $x, y$ and so on usually represent just (deterministic) variables, e.g. real numbers.
The expected value of a real number is just that real number, so $\mathrm E[f(x)] = f(x)$ for every real function $f$ and real variable $x$. Clearly this is a function of $x$. The term "constant" in this situation can be misleading because $f(x)$ is in general not constant with respect to changes in the input variable $x$, but it is constant with respect to what happens in our underlying probability space. Hence it is a constant random variable.
In an integral like $\int f(x) \mathrm dx$ the variable $x$ is bound by the integral operator. No matter the value of that integral, it can't depend on $x$. See here for a more thorough explanation.
As for problem 2: $\mathrm E[X|Y=y]$ is the conditional expected value of the random variable $X$ given that the random variable $Y$ takes the value $y$. This expression only makes sense if the event that $Y=y$ has positive probability, so $Y$ should be a discrete random varible. Then we have
$$\mathrm E[X|Y=y] = \int x \mathrm P(X=x|Y=y) \mathrm dx$$ which in the case that $X$ is also a discrete random variable (taking values in $\mathbb N$) is equal to
$$\sum_{x\in\mathbb N} x \frac{P(X=y,Y=y)}{\mathrm P(Y=y)} $$
which is clearly dependent on $y$ because $y$ is a free variable.


text:
Q: If $X\subset(\delta,\infty)$ and $ Y = \{ \sqrt x : x \in X \} $ then $ m^*Y \leq m^*X/(2\sqrt \delta) $
Problem:
  Let $\delta \in \mathbb{R}$ such that $\delta > 0$ and  $X \subset (\delta, \infty )$. Define the set $ Y = \{ \sqrt x : x \in X \} $. Show that $$ m^*Y \leq \frac{m^*X}{2\sqrt \delta} $$

Here's my approach but I'm stuck at one part.
Let $\{I_n\}_{n=1}^\infty \in \mathcal{C}(X)$ where $ \mathcal{C}(X)$ is the set of all open coverings of $X$ and $I_n$'s are open intervals. If I have proven that $\left\lbrace \frac{1}{2\sqrt \delta}I_n\right\rbrace_{n=1}^\infty \in \mathcal{C}(Y)$, then by taking the infimum over all open coverings of $Y$ yields (where $\mathcal{l}$ denotes the length of the open interval)
\begin{align*}
m^*Y &\leq \sum_{n=1}^\infty \mathcal{l}\left( \frac{1}{2\sqrt\delta} I_n \right) \\
&= \frac{1}{2\sqrt\delta} \sum_{n=1}^\infty \mathcal{l}\left( I_n \right) \\
&= \frac{m^*X}{2\sqrt\delta}
\end{align*} where the last inequality follows by taking the infimum over all open coverings of $X$.Thus, conclusion follows.
Can anyone provide hints to show that $\left\lbrace \frac{1}{2\sqrt \delta}I_n\right\rbrace_{n=1}^\infty \in \mathcal{C}(Y)$? Or maybe from the very start, my approach is wrong?

A: Start with a covering $\{I_n\}$ of $X$ by open intervals $I_n = (a_n,b_n)$. You can assume without loss of generality that $a_n > \delta$ for each $n$. Instead of scaling the intervals by a factor of $\frac{1}{2 \sqrt \delta}$, define new intervals $J_n$ as follows.
Let $J_n = (\sqrt{a_n},\sqrt{b_n})$.  If $y \in Y$, then $y^2 \in X$ so that $a_n < y^2 < b_n$ for some $n$. Thus $\sqrt{a_n} < y < \sqrt{b_n}$ for the same $n$ implying $y \in J_n$ for some $n$.  Thus $\{J_n\}$ is a covering of $Y$. Note
$$ \ell(J_n) = \sqrt{b_n} - \sqrt{a_n} = \frac{b_n - a_n}{\sqrt{b_n} + \sqrt{a_n}} \le \frac{b_n - a_n}{2 \sqrt{a_n}} \le \frac{\ell(I_n)}{2 \sqrt{\delta}}$$
since $\sqrt{b_n} > \sqrt{a_n} \ge \sqrt{\delta}$. Consequently $$m^*Y \le \sum_n \ell(J_n) \le \frac{1}{2\sqrt{\delta}} \sum_n \ell(I_n).$$


text: Q: Sorting alphanumeric characters I am new to QGIS. The version I am trying to get used to is v3.6. I have been trying to sort this table in map layout but still ending up as displayed in the table below. Need help to sort in ascending order.


text:
Q: Как изменить Content-Type в RabbitMQ (Spring JMS) Всем привет! Проблема в следующем:
У меня есть приложение, которое слушает определенную очередь в RabbitMQ. Когда в эту очередь поступает сообщение, то оно определенным образом обрабатывается. Проблема в том, что в эту очередь нельзя загружать обычные сообщения без заголовков и кодирования (например, в base64).
Если я помещу в очередь обычное сообщение (ниже есть пример), то в программе будет ошибка в виде Setup of JMS message listener invoker failed for destination 'queue' - trying to recover. Cause: invalid stream header: 304A2F52.
Причем само сообщение он получает: есть метод RMQMessage#fromMessage(byte[] b, List<String> trustedPackages) throws RMQJMSException и если там поставить точку остановки, то видно, что в переменную b приходит именно то, что я отправлял.

Опытным путём я выяснил, что его не устраивает вид, в котором приходит сообщение и понял, что вот такие сообщения программа разбирает правильно:

И как следствие вывод приложения нормальный:
2021-10-15 16:10:12.286  INFO 14264 --- [enerContainer-1] .m.m.w.CustomMessageListener :  [x] Received <<< queue Привет

Вопрос в том, как можно перенастроить RabbitMQ Client, чтобы он мог принимать обычные текстовые сообщения, а не закодированные с кучей заголовков.
Зависимость я использую следующую:
<dependency>
    <groupId>com.rabbitmq.jms</groupId>
    <artifactId>rabbitmq-jms</artifactId>
    <version>2.3.0</version>
</dependency>

Назначение слушателей происходит следующим образом (код немного видоизменен и в реальности происходит динамическое создания очередей + назначение им слушателей, но в любом случае это делается через JmsListenerEndpointRegistrar):
public class JmsListenerConfiguration implements JmsListenerConfigurer {

    private final CustomMessageListener messageListener;

    @Override
    public void configureJmsListeners(JmsListenerEndpointRegistrar registrar) {
        final String queue = "queue";

        final SimpleJmsListenerEndpoint endpoint = new SimpleJmsListenerEndpoint();
        endpoint.setId(queue);
        endpoint.setDestination(queue);
        endpoint.setMessageListener((message) -> messageListener.onMessage(message, queue));

        registrar.registerEndpoint(endpoint);
    }

}

A: У вас проблема не в самой очереди или настройке rabbitmq. У вас проблема в том, что ваше (?) приложение использует эту конкретную очередь для хранения JMS сообщений, т.е. сообщений для специфической задачи в специфическом формате.
Если вы туда отправляете сообщения в другом виде с другой целью, то ясно, что клиент, который читает из очереди и ожидает там увидеть JMS сообщение (а оно имеет особый формат и особые заголовки), их не понимает. Формат сообщения задается клиентом, т.е. библиотекой rabbitmq-jms, он строго определен и не настраивается. Тут можно посмотреть, как тело сообщения формируется из Message.
Чтоб решить вашу проблему, нужно понимать зачем вам это. Если вы хотите посылать сообщения, чтоб их мог обрабатывать существующий JMS клиент, то никуда не денетесь - нужно посылать в формате, который поддерживает rabbitmq JMS клиент.
Если же вы хотите посылать сообщения другим клиентам, то не нужно использовать эту же очередь - нужно создать новую очередь, конкретно под вашу задачу, и самое главное - не добавлять в нее сообщения JMS, а использовать классы из spring-rabbitmq: RabbitTemplate для посылки и SimpleMessageListenerContainer для получения сообщений:
// посылка без подтверждения
RabbitTemplate someExchangeTemplate = new RabbitTemplate(connectionFactory);
someExchangeTemplate.setExchange("exchange-name");

byte[] myData = ...;
someExchangeTemplate.send(new Message(myData, new MessageProperties()));

// получение
container = new SimpleMessageListenerContainer(connectionFactory);
container.setMessageListener((Message m) -> {
   byte[] myData = m.getBody();
});
container.setQueueNames(queue.getName());
container.start();


text:
Q: Custom jQuery accordion is acting weird on double click I am creating a simple accordion using jQuery, so far it looks good but it acts weird on double click or even if clicked more then twice. Instead of just closing itself it starts opening and closing depending how many times been clicked. Thought about implementing a variable, something like if(!hasbeenclicked) but not sure if that would work. So basically I wonder how to prevent it from double clicks an if clicked again on the same option, just close itself.
Here is a live demo http://jsfiddle.net/qBD5D/
My current code:
javascript
(function(){

    $('#accordion h3').click(function(e){

        e.preventDefault();
        $('#accordion div').slideUp();
        $(this).next('div').slideDown();

    });
})();

html

Accordion option text

hello world

Accordion option text

hello world

Accordion option text

hello world

Accordion option text

hello world

thank you.

A: You're looking for .stop() this will stop all jquery animation on the object. Fire this just before you start your animation:
(function(){

    $('#accordion h3').click(function(e){

        e.preventDefault();
        $('#accordion div').stop().slideUp();
        $(this).next('div').stop().slideDown();

    });
})();

Give that a try, should give you better feel.
If you don't like that solution though you can always have a waiting function, so you can't trigger any animation until they're done animating. They won't queue becuase they won't fire at all that way.
Update:
To have it wait before firing the next animation you've got to have a flag to say when so add a class when it begins animating, remove it when it stops. No events will queue up because you've stopped them firing at all:
(function(){
    $('#accordion h3').click(function(e){
        e.preventDefault();
        if ($('#accordian h3.sliding').length > 0)
            return false;

        var me = $(this);
        me.addClass('sliding');

        //slide up the currently shown div, no need to inefficiently
        //fire this on all  child divs
        $('#accordion div.shown').slideUp().removeClass('shown');

        //slide the corresponding div down and add and remove the
        //right classes when it's finished
        $(this).next('div').slideDown(500, function(){
             $(this).addClass('shown');
             me.removeClass('sliding');
        });

    });
})();

That aught to do it.

A: One of the solutions can be disabling sliding already visible div:
(function(){
    $('#accordion h3').click(function(e){
        e.stopImmediatePropagation();
        e.preventDefault();
        var div = $(this).next('div');
        if (div.is(":visible")) return;
        $('#accordion div').slideUp();
        div.slideDown();
    });
})();

DEMO: http://jsfiddle.net/JJsb4/
UPDATE: To make the section closing on the second click, you need to swap around two lines. So the final version will be:
(function(){
    $('#accordion h3').click(function(e){
        e.stopImmediatePropagation();
        e.preventDefault();
        var div = $(this).next('div');
        $('#accordion div').slideUp();  // these lines
        if (div.is(":visible")) return; // are swapped
        div.slideDown();
    });
})();

A: You might want to consider looking at the popular twitter bootstrap library.
It a time saver and has lots of feature including collapse/accordion
http://twitter.github.com/bootstrap/javascript.html#collapse

A: Hiya please see this working Demo http://jsfiddle.net/r9nw8/
Is this what you are looking for? Please let me know bruv!
Note: This sample will close the option on second click & further I am using slideToggle() API to do up and down.
Jquery Code
(function(){
    $('div#accordion > h3').click(function(e){

        e.preventDefault();
        if($(this).next('div').is(":hidden"))
           $("#accordion > div").slideUp();

         $(this).next('div').slideToggle();

    });
})();


text:
Q: Map tip display text in QGIS 2.16: pictures not showing up anymore! I've been using the great function of QGIS: "map tips". It allows to include html-formatted text (and pictures) in order to popup a window by hovering features.
I use map tips for a very convenient visualization of georeferenced pictures, as I presented once on digital-geography blog
But sadly I cannot make it woking anymore since (?) few weeks, I think since I updated QGIS to 2.16.1 (and later 2.16.2)!
I'm always using the same code as before:
[%CONCAT('')%]
(I know it can be written in an other way but this was working before...)
Now the frame popping up but there's just no picture

Is that a consequence of the map tips improvements of QGIS 2.16? Is there a new syntax I'm missing?
Or I might have something going wrong on my comp?
Anyone sharing the issue? Any ... tip?
Note that including an Iframe link works, I tried the code proposed by mbernasocchi answering to the question "How to view a video using map-tip QGIS 2.16" and it works great.
I'm working under Kubuntu 14.04
kdelibs: 4.13.3
Qt: 4.8.6
Core: 4.2.0-42-generic
System: 32 bit

A: This one worked for me:

[% "filename" %]

A: you need to add the file:// prefix.
The most portable way to use this (assuming you have the images in the same folder as the project) currently (tested on QGIS 3.2 - ubuntu) is:

you can also add width="300" and height="300" or so if needed
please note the @project_home this is a QGIS variable that is automatically set on each project thus allowing you to maintain relative paths


text:
Q: Append and write access to a Directory — FileIOPermission give not good result? I have one issue which is in fact solved, but I totally do not understand why it behaves like this.
So I have a network share and I would like simply to verify if I have access to create new files and directories in that share. I have used two approaches to solve that, but in both I get different result. My test case is that I can't create files and directories on that share:
Trying to create a new Directory — not a nice way
try
{
    var testPath = Path.Combine(path, testDirectory)
    Directory.CreateDirectory(testPath)
}
catch
{
    // No access
}

This is a way which I do not like at all, but it works... I have an exception here, so it says correctly that I do not have the permission on specific path.
Using FileIOPermission — nicer way
try
{
    var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, path)
    var appendPermission = new FileIOPermission(FileIOPermissionAccess.Append, path)
    writePermission.Demand()
    appendPermission.Demand()
}
catch
{
    // No access
}

With that approach I do not have any exception so it says to me that I have the permission to create new files — which is actually not true.
Anyone knows what is wrong with the second approach?

A: FileIOPermission doesn't check the actual permission on a file/directory.  It's more of a "if I didn't have to worry about ACLs, would I be able to access this?" check.
Look at this post to see what FileIOPermission is really doing under the covers.
Then, look at this post to see how to interrogate the actual file system ACLs to see whether you can read/write a file.

A: There is no safe alternative to doing file system operations than to try to do what you want and handle the exception(s) you are expecting such as the UnauthorizedAccessException if you want simple, easy to maintain and understandable code.
By explicitly handling UnauthorizedAccessException and ignoring the rest you can do your fallback logic for when that happen and the exception will bubble up and possibly be unhanded causing the application to stop (Your example 1). Your example 2 seems to break the .NET run-time contact on how to deal with run-time errors.
.NET and the managed run-time expect that you use and handle exceptions accordingly. See http://msdn.microsoft.com/en-us/library/8ey5ey87%28v=vs.91%29.aspx
I hope this helps you out somewhat at lest.


text:
Q: Highcharts master detail chart zooming in/out In Highcharts master details chart, every time we draw a brush both the ends get reset. I am trying to achieve something like in highstocks where we can adjust the left and right extremes independently.
Similarly I would like to add handles to brush as it is in Highstocks. So ideally I am trying to replicate Highstocks navigator just using highStocks. As we do not have HighStocks license.
Any suggestions please.


text:
Q: Getting nonsensical results from SQL query I've encountered a very, very strange situation in my application. I say strange because the errors are intermitent and I cannot find out why they occur.
I've pass a sqlcommand to the DB (Sql 2005) trying to get a bigint (column ID_Facultate) from a single table. The problem is that I've got a string (the name of some lecture) that has nothing to do with the table I've tried to access.
Also, when I get these errors, all my application is going crazy.
In the SQL Profiler everything seems fine (the last executing rows seem to be the ones sent by my application)
Here are some links to 3 captured screens during the errors and the code I've used. Please note the Watch1 with the very wrong string value where I expected some integer

*

*http://www.unitbv.ro/cata/errors/2.jpg

*http://www.unitbv.ro/cata/errors/3.jpg

*http://www.unitbv.ro/cata/errors/1.jpg
Updates:
I will consider using both the name of the column and/or ExecuteScalar.
Still, the problem is, as seen in the Watch1 that the query returns a value that has nothing to do with that table.
The code was expecting an integer (14) while the DB returned a string... (http://www.unitbv.ro/cata/errors/2.jpg)
The same in http://www.unitbv.ro/cata/errors/3.jpg : I was expecting a value from 1 to 20 while the DB/layer seems to return the value 305 which is not in that table...
In the following post (various forums) I asked the same or related questions (and no positive answer yet)

*

*http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/a9010d27-49ca-4cce-93a5-f3c4d62e4010

*http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/6191a59b-40cb-49f2-9f59-e9ee1bf2c683/

*https://stackoverflow.com/questions/843496/please-help-with-system-data-datarowview-does-not-contain-a-property-with-the-n

*http://forums.asp.net/t/1432140.aspx

*http://forums.asp.net/t/1426029.aspx

*http://forums.asp.net/t/1420133.aspx

A: From your code I could only think of getting the value using the field name.
rd["ID_Facultate"].ToString()

Although your code seems correct, I always prefer using field names to get the values instead of index position, that can be easily changed in a number of situations. Some of them, maybe like this one, you can't even figure it out.

A: Can you think of why the idr.FieldCount has a value of 4 in screens 1 and 2 but only 3 in screen 3. Could the problem be resolved by using the column name instead of the ordinal position?
id_faculate = long.Parse(idr["ColumnName"].ToString());

A: Since you're only getting 1 value back, you should consider using a SqlCommand.ExecuteScalar instead of getting a DataReader.

A: From everything you've told us, nothing seems wrong. It's probably something else for which you didn't give us the have info.
Some other things to try:

*

*Run DBCC CHECKDB

*Ensuring the query returns the correct result in SQL Server Management Studio

*Try the database on another machine/SQL instance and see if the same problems persist

A: This may be a blind avenue... but is your context a web application? Are you using an old EntLib version (4 or lower)?
There is a known bug in EntLib 4 (and earlier) versions that can strike under heavy load in the context of an ASP.NET app hosted on IIS. I don't remember all the details, but basically IIS has an optimization where, under heavy load, it might "park" a thread during the wait (to free it up so it can be used for something else), and then try to continue running the same LOGICAL thread on what is in fact another thread when the I/O wait is over.
If you have lots of data access going on this can produce the symptoms you are seeing - the results from one query ends up being received in a thread that ran a completely different query.
If you are not using EntLib, check if your own code might contain the same bug. Look for the [ThreadStatic] attribute - these are NOT handled by IIS when it decides to migrate logic to a different thread!
Googling "IIS thread agility" ought to turn up more info.
A few links that may be of use:
http://piers7.blogspot.no/2005/11/threadstatic-callcontext-and_02.html
and
http://blog.idm.fr/2010/03/aspnet-thread-agility-or-why-threadstatic-should-not-be-used.html


text:
Q: Creating model class through TS in angular 6 I am trying to create a model class in my angular app which goes like this:
export class BookModel {
  public _id:any;
  public authors:any[];
  public categories:any[];
  public isbn:any;
  public longDescription:any;
  public pageCount:any;
  public thumbnailUrl:any;
  public title:any;

  constructor(id,author, category, isbn, longDescription, pageCount, thumbnailUrl, title) {
    this._id = id;
    this.authors.push(author);
    this.categories.push(category);
    this.isbn = isbn;
    this.longDescription = longDescription;
    this.pageCount = pageCount;
    this.thumbnailUrl = thumbnailUrl;
    this.title = title;
  }
}

Now when i am instantiating this model class I am getting error that this.authors is undefined.
I am instantiating my class as
let newBook = new BookModel(formValues.id,formValues.AuthorName, formValues.category, formValues.isbn, formValues.description, formValues.pages, formValues.thumbnailUrl, formValues.bookName);

But it gives me error:

A: You need first to initialize your arrays and then use them. Initializing will allocate a space for them in the memory.
export class BookModel {
  public _id: any;
  public authors: any[] = []; // <- Initializing
  public categories: any[] = []; // <- Initializing
  public isbn: any;
  public longDescription: any;
  public pageCount: any;
  public thumbnailUrl: any;
  public title: any;

  constructor(id, author, category, isbn, longDescription, pageCount, thumbnailUrl, title) {
    this._id = id;
    this.authors.push(author);
    this.categories.push(category);
    this.isbn = isbn;
    this.longDescription = longDescription;
    this.pageCount = pageCount;
    this.thumbnailUrl = thumbnailUrl;
    this.title = title;
  }
}

A: change:
public authors:any[];
public categories:any[];

to:
public authors: Array<any>;
public categories: Array<any>;


text:
Q: Runtime error A PWM object already exists for this GPIO channel iam new to raspberry pi and i got an error while a running servo motor in my object detection script
Here is the part of the code all import functions are given on top of code
for i in range (classes.size):
    if(classes[0][i] == 2 and scores[0][i]>0.5):

      servoPIN = 22
      GPIO.setmode(GPIO.BCM)
      GPIO.setup(servoPIN, GPIO.OUT)
      p = GPIO.PWM(servoPIN, 50)  #line 150
      p.start(2.5) # Initialization
      try:

        p.ChangeDutyCycle(5)
        time.sleep(4)
        p.ChangeDutyCycle(10)
        time.sleep(4)
      except KeyboardInterrupt:
        p.stop()
      except:
          #print ("exception")

        GPIO.cleanup()

output:(motor turns on and immediately showing below error)
Traceback (most recent call last):
  File "Object_detection_picamera.py", line 150, in <module>
    p = GPIO.PWM(servoPIN, 50) # GPIO 17 for PWM with 50Hz
RuntimeError: A PWM object already exists for this GPIO channel

I dont know why this happening please help me

A:
p = GPIO.PWM(servoPIN, 50)  #line 150

this line should never be in a loop
PWM channel shold be initialized only on
So simply remove that line from the loop the put it before the loop


text:
Q: Solve Speed Difference in ktrain Predictor vs. Learner prediction? I am using ktrain huggingface library to build a language model. When implementing it for production, I noticed, there is a huge difference in speed for a "learner prediction" vs. a "predictor prediction".
How come and is there any way to speed up the predictor prediction?
%timeit test = learner.predict(val) # takes 10s
%timeit test = predictor.predict(x_val,return_proba = True) # takes 25s

A: The second call preprocesses the data (e.g., tokenization), whereas the first call is making a prediction on data that is already preprocessed.  So, the time difference is likely due to the time it is taking to preprocess the raw data:
%%time
tst = predictor.preproc.preprocess_test(x_test)
# Wall time: 5.65 s

%%time
preds = learner.predict(val)
# Wall time: 10.5 s

%%time
preds = predictor.predict(x_test)
# Wall time: 16.1 s

When supplying a list of texts to predict, you can also use a larger batch_size that may also help increase speed (default is 32):
predictor.batch_size = 128
preds = predictor.predict(x_test)

Finally, if you're looking to make faster predictions in a deployment scenario, you can look at the ktrain FAQ, where it shows how to make quantized predictions and predictions with ONNX.


text:
Q: A question concerning unipotent matrices and a basis choice Let $G$ be a subgroup of $\mathbb{GL}_n$, the group of all invertible $n\times n$ matrices over an algebraically closed field $k$, which consists of unipotent matrices.
I don't understand a step in a proof. We want to proof that there is an $x\in\mathbb{GL}_n$, such that $xGx^{-1}$ lies in the set of all upper triangular matrices with only $1$'s on the diagonal. The author of the proof states that it suffices to find a $v\in k^n\setminus 0$ such that $gv=v$ for all $g\in G$.
I don't understand why this is sufficient. Given such a $v$, how can I find $x$?
Thank you!

A: This is indeed a bit quick. Once you've got a fixed vector $v$ for the subgroup $G$, you can take this as first vector in a base, and after base change (which corresponds to a conjugation $g\mapsto xgx^{-1}$) all elements of $G$ will have the form
$$
  \begin{pmatrix}
 1&*&*&\cdots&*\\
 0&*&*&\cdots&*\\
 0&*&*&\cdots&*\\
\vdots&\vdots&\vdots&\ddots&\vdots\\
 0&*&*&\cdots&*\\
  \end{pmatrix}
$$
Now consider the subgroup (check it!) $G'$ of $\mathbb{GL}_{n-1}$ of all matrices that arise from elements of $G$ after dropping the first row and column (this amounts to considering the elements of $G$ as acting on the quotient space $k^n/\langle v\rangle$). Now $G'$ consists of unipotent matrices, so by induction on the dimension we can assume that there exists $y\in\mathbb{GL}_{n-1}$ such that $yG'y^{-1}$ consists of upper unitriangular matrices only. Now lifting $y$ to an element $\hat y\in\mathbb{GL}_n$ by adding a first row and column, with diagonal entry $1$ and all others $0$, one can check that $(\hat yx)G(\hat yx)^{-1}$ consists of upper unitriangular matrices in $\mathbb{GL}_n$ only.
A more geometric version of this argument says that after finding a fixed vector $v_1$ for $G$, we can continue to find a linearly independent vector $v_2$ that is fixed modulo $\langle v_1\rangle$ (meaning that $g(v_2)\in v_2+\langle v_1\rangle$ for all $g\in G$), which is obtained from a fixed vector in $k^n/\langle v_1\rangle$, then a linearly independent vector $v_3$ that is is fixed modulo $\langle v_1,v_2\rangle$ (obtained from a fixed vector in $k^n/\langle v_1,v_2\rangle$) and so on. In the end one obtains a basis $v_1,v_2,\ldots,v_n$ such that each subspace $\langle v_1,\ldots, v_k\rangle$ is $G$-stable (one says this is a $G$-stable flag of subspaces). Then a base change to this basis will make $G$ upper unitriangular.

A: Since $k$ is algebraically closed, we can assume $M$ has a Jordan decomposition. So it suffice to prove the Jordan blocks can be changed into the desired form. But this is not difficult given that the product of the determinant is 1.
The reason $v$ exists such that $$(g-I)v=0$$ would hold for any $g\in GL_{n}(k)$ follows from dimension consideration. If $v\not=0$, the solution space for $Av=0$ has dimension $n^{2}-1$ by the rank-nullity theorem. And the dimension for $GL_{n}(k)$ is $n^{2}$. Now proceed inductively to find a sequence of basis vectors for $V$ such that $gv_{i}=v_{i}+a_{1}v_{i-1}....+a_{i-1}v_{1}$. This should not be too difficult. Using this basis you get the desired transformation.


text:
Q: How do I get Cassandra to start when there is an error about "Connection refused"? I installed Cassandra on Ubuntu 16.04.  (I have gotten Cassandra to work on RedHat.  But now I want it to work on Ubuntu.)  The installation seemed to go smoothly.  I run this command to prove that Cassandra is active:
sudo service cassandra status

This command returns this output:
cassandra.service - LSB: distributed storage system for structured data
Loaded: loaded (/etc/init.d/cassandra; bad; vendor preset: enabled)
Active: active (exited) since Tue 2017-12-26 19:22:43 UTC; 8min ago
Docs: man:systemd-sysv-generator(8)   Process: 1252 ExecStart=/etc/init.d/cassandra start (code=exited, status=0/SUCCESS)
Tasks: 0    Memory: 0B         CPU: 0

The above "bad" concerns me.  But it does return "Active."  It seems like there is no major problem.
When I run "cqlsh" or "cqlsh 127.0.0.1" I get

Connection error: ('Unable to connect to any servers', {'127.0.0.1':
  error(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error:
  Connection refused")})

I used nmap to test port 9042.  The port is not blocked.  There is not firewall installed either.
I rebooted the server.  I tried modifying cassandra-env.sh.  I uncommented a stanza and set it to be 127.0.0.1:
JVM_OPTS="$JVM_OPTS -Djava.rmi.server.hostname=127.0.0.1"

Nothing I do works.  I expect to enter a different command prompt when I type in "cqlsh" or "cqlsh 127.0.0.1".  But this does not happen. What do I do to have "cqlsh" work on an Ubuntu server?

A: If you look at /var/log/cassandra/system.log you'll see:
Port already in use: 7199; nested exception is:java.net.BindException: Address already in use (Bind failed)
This is the default port in /etc/cassandra/cassandra-env.sh :
JMX_PORT="7199"
Changed it to another port: 7198.
This solution work for me.


text:
Q: Identifying chunks of outliers from a 1D and 2D data in Python Data: I have a data d in one column which varies as a function of two other variables, a and b, defined in other two columns. My objective is to identify chunks or outliers in d. Those chunks of outliers might not seem to be outliers, but for my case I want to identify those data that do not fall on a cloud of data that can be fitted with a linear line.
Problem:  Even though I have never done cluster analysis before, the name sounded like it could achieve what I am trying to do. In case I chose to do cluster analysis, I would like to do that for two cases as follow:

*

*with a and d

*with a, b and d
I did some search and found for #1, using KernelDensity module would be more appropriate whereas for #2 using MeahShift module would be a good option, both in Python.
Issue: I have never done cluster analysis before so I could not understand the examples for both KernelDensity and MeahShift given in their docs (here and here, respectively). Could someone please explain how can I use KernelDensity and MeahShift to identify "chunks" of outliers in d for case 1 and 2?

A: First of all, KernelDensity is for non-parametric method. Since you have strong belief that the relation is linear (that is parametric model), KernelDensity is not the most appropriate choice in this task.
Below is a sample code to identify the outliers.
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import RANSACRegressor

# data: 1000 obs, 100 of them are outliers
# =====================================================
np.random.seed(0)
a = np.random.randn(1000)
b = np.random.randn(1000)
d = 2 * a - b + np.random.randn(1000)
# the last 100 are outliers
d[-100:] = d[-100:] + 10 * np.abs(np.random.randn(100))

fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].scatter(a, d, c='g')
axes[0].set_xlabel('a')
axes[0].set_ylabel('d')
axes[1].scatter(b, d, c='g')
axes[1].set_xlabel('b')

# processing
# =====================================================
# robust regression
robust_estimator = RANSACRegressor(random_state=0)
robust_estimator.fit(np.vstack([a,b]).T, d)
d_pred = robust_estimator.predict(np.vstack([a,b]).T)

# calculate mse
mse = (d - d_pred.ravel()) ** 2

# get 50 largest mse, 50 is just an arbitrary choice and it doesn't assume that we already know there are 100 outliers
index = argsort(mse)
fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].scatter(a[index[:-50]], d[index[:-50]], c='b', label='inliers')
axes[0].scatter(a[index[-50:]], d[index[-50:]], c='r', label='outliers')
axes[0].set_xlabel('a')
axes[0].set_ylabel('d')
axes[0].legend(loc='best')
axes[1].scatter(b[index[:-50]], d[index[:-50]], c='b', label='inliers')
axes[1].scatter(b[index[-50:]], d[index[-50:]], c='r', label='outliers')
axes[1].legend(loc='best')
axes[1].set_xlabel('b')

for your sample data
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import RANSACRegressor

df = pd.read_excel('/home/Jian/Downloads/Data.xlsx').dropna()

a = df.a.values.reshape(len(df), 1)
d = df.d.values.reshape(len(df), 1)

fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].scatter(a, d, c='g')
axes[0].set_xlabel('a')
axes[0].set_ylabel('d')

robust_estimator = RANSACRegressor(random_state=0)
robust_estimator.fit(a, d)
d_pred = robust_estimator.predict(a)

# calculate mse
mse = (d - d_pred) ** 2

index = np.argsort(mse.ravel())

axes[1].scatter(a[index[:-50]], d[index[:-50]], c='b', label='inliers', alpha=0.2)
axes[1].scatter(a[index[-50:]], d[index[-50:]], c='r', label='outliers')
axes[1].set_xlabel('a')
axes[1].legend(loc=2)


text:
Q: JavaScript WebSocket non-null-terminated strings I have a very strange issue. I have an open WebSocket, the communication works perfectly. I also have onblur and onfocus events for the window, which notify the server via said connection. However, in that case, the strings I receive are non-null-terminated. The communication works absolutely impeccably otherwise, even when sending the same strings that are sent on those respective blur-/focus-events. Why is that, and how can it be fixed?
Here's some code:
$(document).ready(function(){

    initializeEverything();

    window.onblur = function(){ notifyFocusChange(false); };

    window.onfocus = function(){ notifyFocusChange(true); };

});

function notifyFocusChange(present){

    if(present){
        webSocket.send('presence:present');
    }else{
        webSocket.send('presence:absent');
    }

}

And here's an example of a non-null-terminated string I receive when the events fire:
presence:absentÏ┘ê÷/à°äJ÷ÝÿLÓ▓ùM÷Ýÿ[
EDIT: It's been suggested that it may be a server error, so here's the code for decoding incoming messages:
private function decode($payload) {

    $length = ord($payload[1]) & 127;

    if ($length == 126) {
        $masks = substr($payload, 4, 4);
        $data = substr($payload, 8);
    } elseif ($length == 127) {
        $masks = substr($payload, 10, 4);
        $data = substr($payload, 14);
    } else {
        $masks = substr($payload, 2, 4);
        $data = substr($payload, 6);
    }

    $text = '';
    for ($i = 0; $i < strlen($data); ++$i) {
        $text .= $data[$i] ^ $masks[$i % 4];
    }

    return $text;

}

EDIT: It only happens in Chrome. I checked it on Firefox, which uses the same WebSocket-protocol, and everything works perfectly fine there.

A: The onblur and onfocus events are probably happening several times in rapid succession. Meaning that the websocket.send call is also being called quickly multiple times in rapid succession.
If the multiple send calls happen close enough together then there is a high probability that you will receive multiple frames in a single read at the server and I believe that's what you are seeing. In other words, the "garbage" in your payload is actually one or more subsequent WebSocket frames.
You might be able to replicate the problem manually be doing two separate sends in the same Javascript context:
function do_test () {
    ws.send("data1");
    ws.send("data2");
}

That will send two WebSocket frames close enough together that the server will probably read them all at once from the socket.
In order to properly process frames you have to parse the payload length field and only read/unmask that specified amount of payload data. Anything remaining needs to be queued up as the beginning of a new frame.
Also, not only can multiple Websocket frames be returned from one read from the socket, but you can't rely on frames being read as whole frames: you might read half the frame in one read and the other half in the next frame. In other words, the first time you read from the socket you might get 3 whole websocket frames plus 1 byte of the 4th frame and then in the next read from the socket you get the rest of the 4th frame.
This can generally be summed up this way: WebSockets are a message based transport protocol, while TCP sockets are a streaming protocol. Since WebSockets are layered on TCP, this means that the WebSocket server (and client for that matter) must do the translation to present whole messages to the application even though the underlying transport is not message based.


text:
Q: Mouse handles are not in sync with the mouse I am trying to select a selection handle and then move it but the mouse handles are not in sync with the mouse pointer.
when you select the rectangle and then try to move the middle selection handle to create a gap in the rectangle the mouse pointer is positioned away from the handle is.
Fiddle is : http://jsfiddle.net/3PwWY/
                  case 8:
                if(mx > mySel.x + mySel.w/2)
                     mySel.windowWidth = mx - (mySel.x + mySel.w/2);
                else
                      mySel.windowWidth = (mySel.x + mySel.w/2) - mx;

                // Enforce limits on mx:
                //     Should not be closer than 5 pixels to this.x (left side of metric box)
                //     Should not be > this.x + width/2 (middle of metric box)
                  if(mySel.windowWidth < 2*  minGold)
                                           mySel.windowWidth = 2*  minGold;
                console.log(mySel.windowWidth);
                break;
            case 9:
                 if(mx > mySel.x + mySel.w/2)
                     mySel.windowWidth = mx - (mySel.x + mySel.w/2);
                else
                      mySel.windowWidth = (mySel.x + mySel.w/2) - mx;
                // Enforce limits on mx:
                //     Should not be closer than 5 pixels to this.x (left side of metric box)
                //     Should not be > this.x + width/2 (middle of metric box)
              //   mySel.windowWidth = mx - (mySel.x + mySel.w/2);

                console.log(mySel.windowWidth);
                break;


text:
Q: Hibernate filter not working with parent domain I have two domain in parent child structure.
First one is :-
class Client {

    String xyz
    static belongsTo = [site: Site]

 static hibernateFilters = {
        siteFilter(condition: ':siteId = site_id', types: 'long')
    }
}

And second one is.
class TicketDetail {

    Date date
    Client client
}

If I am directly accessing to Client domain like.
Client.searchByAlphabet(params).list(params)
Hibernate filter working fine.But when I am using criteria on TicketDetail like .
 client {
         site {
               eq('id', currentSiteId)
              }
        }
projections {
                distinct 'client'
            }

Then Hibernate filter on Client domain not working.How can i active hibernate filter when accessing child domain from parent domain.

A: Use createAlias... E.G.
class Customer {
   String name
   Account account
   BigDecimal minAccountBalance
   ...
}

class Account {
   BigDecimal currentBalance
   ...
}

Customer.createCriteria().list(){
      createAlias('account', 'acc')
      gtProperty('acc.currentBalance', 'minAccountBalance')
    }


text:
Q: How to delay not exist task by celery? I have two environments
1. webserver
2. celery worker
webserver add jobs to celery message queue. but those env are separated, so can not import task function.
how to call not exist task explicitly?
ex)
# A project (web) - view.py
def view(request):
    [X] task_a.delay()
    [O] add_jobs("task_a", *args)
    ...

# B project (worker) - tasks.py
@task
def task_a:
    ...

A: Use the send_task function to send a task to a decoupled celery project.
from celery.app import Celery
app = Celery(broker_url='the broker url of the celery instance')
app.send_task(name='myapp.mytaskname', kwargs={
  'arg1': 'value1',
  'arg2': 'value2',
})


text:
Q: Java Spring Boot response not converting whole response to JSON I am having an issue where my Spring Boot response Entity is mostly being converted to JSON but the body is staying as a string.
I have read many of the other questions on this site, but they all seem to point to the same thing.
pom.xml Dependencies
    <dependencies>
        <!--OpenAPI Generator Dependencies-->
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.0.2</version>
        </dependency>
        <!--Http Dependencies-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <!--Log4j Dependencies-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <!--Spring Framework Dependencies-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--Dotenv Dependencies-->
        <dependency>
            <groupId>io.github.cdimascio</groupId>
            <artifactId>java-dotenv</artifactId>
            <version>${dotenv.version}</version>
        </dependency>

        <!--JSON Object Dependencies-->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20220924</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.14.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.14.1</version>
        </dependency>

    </dependencies>

ApiResponse Class
public class ApiResponse {
    // class used to model api response data
    public Integer statusCode;
    public String statusReason;
    public String statusLine;
    public String url;
    public String body;
    public ProtocolVersion protocolVersion;

    public String getStatusLine() {
        return statusLine;
    }

    public void setStatusLine(String statusLine) {
        this.statusLine = statusLine;
    }

    public ProtocolVersion getProtocolVersion() {
        return protocolVersion;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public void setProtocolVersion(ProtocolVersion protocolVersion) {
        this.protocolVersion = protocolVersion;
    }

    public Integer getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(Integer statusCode) {
        this.statusCode = statusCode;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

}

processResponse method
    public ApiResponse processResponse(CloseableHttpResponse response) throws IOException {
        // process custom apache httpClient response
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.setProtocolVersion(response.getProtocolVersion());
        apiResponse.setStatusCode(response.getStatusLine().getStatusCode());
        apiResponse.setStatusReason(response.getStatusLine().getReasonPhrase());
        apiResponse.setStatusLine(response.getStatusLine().toString());

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // return it as a String
            String result = EntityUtils.toString(entity);
            apiResponse.setBody(result);
        }
        response.close();
        return apiResponse;
    }

getCall method
    @GetMapping(value = "/getHealth", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ApiResponse> getClientHealth() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {

        Client clientSetup = new Client(dotEnv.get("URL"), 80);

        try {
            ApiResponse response = clientSetup.getHealth();

            return new ResponseEntity<>(response, HttpStatusCode.valueOf(response.getStatusCode()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

The response
{
  "statusCode": 200,
  "statusReason": "OK",
  "statusLine": "HTTP/1.1 200 OK",
  "url": null,
  "body": "{\"status\":\"Healthy!\"}",
  "protocolVersion": {
    "protocol": "HTTP",
    "major": 1,
    "minor": 1
  }
}

The problem is with "body": "{\"status\":\"Healthy!\"}"
I have been unsuccessful in getting the body to be converted from a string to JSON when returned through my Spring Boot ResponseEntity.

A: You are getting exactly what you asked for with the definition of ApiResponse.
public String body;

If you want Jackson to serialize that as a part of the object. It needs to be defined as part of the object.
This may be as simple as changing it to JsonNode.
public JsonNode body;

And generating a JsonNode from the entity.
if (entity != null) {
  // return it as a JsonNode
  String stringResponse = EntityUtils.toString(entity);
  ObjectMapper mapper = new ObjectMapper();
  JsonNode jsonNode = mapper.readTree(stringResponse);
  apiResponse.setBody(jsonNode);
}

Although it would probably be better if your ApiResponse object more accurately modeled what it is holding.

A: As others have said, by declaring the type of ApiResponse.body as String, that's exactly what's being stored there; the JSON serializer doesn't have any knowledge of the content of the String, so it just serializes it out (with required escaping to make it a valid string value).
I can think of 2 options to make that a more useful object that can be serialized: A) transform the response HttpEntity you get from the downstream API into a simple DTO with just the properties you care about; or B) use HttpEntity<> directly and instruct the serializer to ignore properties you don't care about (such as the EofSensorInputStream from the exception you reported).
Option A seems fairly obvious so I won't show code for that. Here's how you can accomplish Option B:
public class ApiResponse {
    // ... other fields ...
    private HttpEntity<?> body;

    // ... other methods ...

    @JsonIncludeProperties({"body", "headers"})
    public HttpEntity<?> getBody() {
        return body;
    }

That instructs the serializer to only include body and headers when it serializes the body of ApiResponse, ignoring anything else in the HttpEntity.


text:
Q: Citation for an addendum in brackets, \citet vs \citep With natbib (and bibtex) I have the option of using either \citet{foo2019} or \citeb{bar2019} and I think I'm pretty clear on their use. I.e. "as Foo (2019) has shown, ducks tend to quack" vs "Previous experiments have shown that ducks tend to quack (Bar, 2019)"
But what do I use when I want to make a statement such as

According to various authors, quackiness is correlated with duckiness (see e.g. cite?{foo2019, bar2019}).

\citet{} appears to be to be the correct one, since I'm directly addressing the authors, but this will result in double brackets at the end, which feels off.

According to various authors, quackiness is correlated with duckiness (see e.g. Foo (2019) and Bar (2019)).

\citep{} solves this problem, but its use seems incorrect to me in this case:

According to various authors, quackiness is correlated with duckiness (see e.g. Foo, 2019 and Bar, 2019).

Is there any typographic rule on what to use?

A: \citep gives the more visually pleasing result here, so on that ground alone I'd argue that is what you should use
According to various authors, quackiness is correlated with duckiness \citep[see e.g.]{foo,bar}.

According to various authors, quackiness is correlated with duckiness (see e.g. Foo, 2019 and Bar, 2019).

Ultimately, there are no TeXnical reasons that would tell you whether to use \citet or \citep here. It comes down to stylistic (language) questions and will probably also depend on customs in your field. (As an aside, the question of how the output should look like is quite probably off-topic here and may be more suitable for https://writing.stackexchange.com/, https://academia.stackexchange.com/ or https://english.stackexchange.com/ depending on the spin you want to give the question)
The APA blog https://blog.apastyle.org/apastyle/2011/01/writing-in-text-citations-in-apa-style.html has two more examples

*

*After the intervention, children increased in the number of books read per week (Smith & Wexwood, 2010).

*Smith and Wexwood (2010) reported that after the intervention, children increased in the number of books read per week.

Just like your examples the \citep reference is a parenthetical reference tagged on at the end. It can be removed without impacting the structure of the sentence. The \citet example, on the other hand, can not be easily removed since a part of its output (the author names) is the subject of the sentence (note that only the authors are the subject, not the entire paper).
If we want to make a rule out of that we can say that \citep is used for parenthetical references whose removal does not affect the structure of the sentence. \citet is used when the author names are the subject or object of the sentence.
Note that this is a purely syntactical rule. The semantics are not that important. It does not matter whether you want to refer to people or their paper - what matters is the grammatical function of the citation.
This rule also suggests that \citep is right here, because "According to various authors, quackiness is correlated with duckiness" can stand on its own and the citations are not needed to complete the grammatical structure of the sentence. You may want to refer to the authors of those papers, but grammatically you don't need them as subjects or objects. And "As seen in [1]" is not all that different from "[see e.g. 1]".
I have ignored the case where you would want to refer to a particular paper as the object or subject of a sentence. I try to avoid that whenever possible because I find sentences such as

As shown in [1]

or

As shown in (Sigfridsson 1998)
As shown in Sigfridsson 1998

a bit awkward. But your mileage may vary. I have certainly seen "As shown in [1]" many times and generally people seem to be OK with it.


text:
Q: Why do ArcPy SQL expressions use three double quotes? I am using ArcGIS Pro 2.4 and I am trying to understand why ArcPy SQL expressions use three double quotes. ESRI's "Specifying a query in Python" page, https://pro.arcgis.com/en/pro-app/arcpy/get-started/specifying-a-query.htm,
gives two examples of using SQL statements (both of which seemingly have where clauses of "roadclass" = 2 wrapped in three double quotes):
Example without field delimiters:
import arcpy
fc = "D:/St_Johns/data.gdb/roads"

# Create a search cursor using an SQL expression
cursor = arcpy.da.SearchCursor(fc, ("roadclass", "name"), """"roadclass" = 2""")
for row in cursor:
    print(row[1])

Example with field field delimiters:
import arcpy
fc = "D:/St_Johns/data.gdb/roads"
fieldname = "roadclass"

# Create field name with the proper delimiters
whereclause = """{} = 2""".format(arcpy.AddFieldDelimiters(fc, fieldname))

# Create a search cursor using an SQL expression
cursor = arcpy.da.SearchCursor(fc, ("roadclass", "name"), whereclause)
for row in cursor:
    print(row[1])

It is my impression that SQL statements in a SearchCursor constructor in ArcGIS Pro should have string values enclosed in single quotes and that the overall expression should be in double quotes as in " PARCEL = 'A2003KSW' ". That syntax make sense, however I am not understanding the jump from one to three sets of double quotes.

A: It's a Python technique (string literal) that'll allow the tool or arcpy function to make use of quotations in the calculation or where clause. The triple quotes can span multiple lines and will 'escape' the quotes.
In your case:
""""roadclass" = 2""" when evalauted will be:  "roadclass" = 2 inside the tool.
Alternatively you could write "\"roadclass\" = 2"   (that is, \") to escape the quotes.


text:
Q: Как просмотреть все свойства определенной функции? Как просмотреть все свойства определенной функции?
function blah(){} alert(blah.name); // "blah"

Это пример одного из свойств, а как же просмотреть все свойства?

A: getOwnPropertyNames

function foo(a){}

// Список свойств:
console.log(Object.getOwnPropertyNames(foo));

// Со значениями:
console.log(Object.getOwnPropertyNames(foo)
  .reduce((r, f) => (r[f]=foo[f], r), {}));


text:
Q: Java permutations 2 I asked a question on helping me with this question about a week ago
Java permutations
, with a problem in the print permutation method. I have tidied up my code and have a working example that now works although if 5 is in the 5th position in the array it doesn't print it. Any help would be really appreciated.
 package permutation;

public class Permutation {

static int DEFAULT = 100;

public static void main(String[] args) {
    int n = DEFAULT;
    if (args.length > 0)
        n = Integer.parseInt(args[0]);
    int[] OA = new int[n];
    for (int i = 0; i < n; i++)
        OA[i] = i + 1;
    System.out.println("The original array is:");
    for (int i = 0; i < OA.length; i++)
        System.out.print(OA[i] + " ");
    System.out.println();
    System.out.println("A permutation of the original array is:");
    OA = generateRandomPermutation(n);
    printArray(OA);
    printPermutation(OA);
}

static int[] generateRandomPermutation(int n)// (a)
{
    int[] A = new int[n];
    for (int i = 0; i < n; i++)
        A[i] = i + 1;
    for (int i = 0; i < n; i++) {
        int r = (int) (Math.random() * (n));
        int swap = A[r];
        A[r] = A[i];
        A[i] = swap;
    }
    return A;
}

static void printArray(int A[]) {
    for (int i = 0; i < A.length; i++)
        System.out.print(A[i] + " ");
    System.out.println();
}

static void printPermutation(int[] p)

{
    int n = p.length-1;
    int j = 0;
    int m;
    int f = 0;

    System.out.print("(");
    while (f < n) {
        m = p[j];
        if (m == 0) {
            do
                f++;
            while (p[f] == 0 && f < n);
            j = f;
            if (f != n)
                System.out.print(")(");
        }
        else {
            System.out.print(" " + m);
            p[j] = 0;
            j = m - 1;
        }
    }
    System.out.print(" )");
}
}

A: I'm not too crazy about
int n = p.length-1;

followed by
while (f < n) {

So if p is 5 units long, and f starts at 0, then the loop will be from 0 to 3. That would seem to exclude the last element in the array.

A: You can use the shuffle method of the Collections class
Integer[] arr = new Integer[] { 1, 2, 3, 4, 5 };
List<Integer> arrList = Arrays.asList(arr);
Collections.shuffle(arrList);
System.out.println(arrList);

A: I don't think swapping each element with a random other element will give a uniform distribution of permutations.  Better to select uniformly from the remaining values:
Random rand = new Random();
ArrayList<Integer> remainingValues = new ArrayList<Integer>(n);
for(int i = 0; i < n; i++)
    remainingValues.add(i);
for(int i = 0; i < n; i++) {
    int next = rand.nextInt(remainingValues.size());
    result[i] = remainingValues.remove(next);
}

Note that if order of running-time is a concern, using an ArrayList in this capacity is n-squared time.  There are data-structures which could handle this task in n log n time but they are very non-trivial.

A: This does not answer the problem you have identified.
Rather i think it identifies a mistake with  your  generateRandomPermutation(int n) proc.
If you add a print out of the random numbers generated (as i did below) and run the proc a few times it allows us to check if all the elements in the ARRAY TO BE permed are being randomly selected.
static int[] generateRandomPermutation(int n)
{
    int[] A = new int[n];
    for (int i = 0; i < n; i++)
        A[i] = i + 1;
     System.out.println("random nums generated are: ");
    for (int i = 0; i < n; i++) {
        int r = (int) (Math.random() * (n));
         System.out.print(r + " ");

Run the proc several times.
Do you see what i see?
Jerry.


text:
Q: StatusStrip over form BackgroundImage I have a form with a background image as stretch layout mode. When I place a StatusStrip on my form, it covers the bottom of the form's background image.
How I can set the bottom of the form's background image stretch area to the top of the StatusStrip?

A: I think the only correct workaround is what Dmitry Bychenko mentioned:

Why don't you put a Panel (or some other container) with required background image instead of putting it on the form directly?

However I ended to edit the image and trim my form size (adequate for me), so that the StatusStrip covered the unused space below the image.


text:
Q: Inheritance vs Injection with Template-ish pattern and planned contributors I'm trying to develop an OSGi application to handle my game engine. This game engine will be making use of the Entity-Component-System pattern. Part of this pattern is the use of GameSystems.
I had initially planned on exposing the GameSystem interface as its own bundle; this way other contributors can create their own systems and add them to the game engine via OSGi bundles. When I wrote up the initial interface it looked like
public interface GameSystem {

    boolean isInterestedIn(GameEntity entity);

    void update(GameEntity entity);
}

Then I wrote an abstract implementation of this to add some precondition checking (returning false if the entity is null).
public abstract class AbstractGameSystem implements GameSystem {

    public boolean isInterestedIn(GameEntity entity) {
        if (entity == null) {
            return false;
        }
        // TODO
    }
}

At this point I realized I needed some sort of mechanism for allowing the subclass to add their own conditions, without being forced to call super.isInterestedIn(entity). I created a protected abstract method that subclasses could implement.
public abstract class AbstractGameSystem implements GameSystem {

    protected abstract boolean checkEntity(GameEntity entity);

    public final boolean isInterestedIn(GameEntity entity) {
        if (entity == null) {
            return false;
        }
        return checkEntity(entity);
    }
}

At this point I take a step back and wonder if maybe I should, instead of depending on inheritance, pass a predicate and consumer as constructor parameters, and not bother with an abstract class at all.
public final class InjectedGameSystem implements GameSystem {

    private final Predicate<GameEntity> predicate;
    private final Consumer<GameEntity> consumer;

    public InjectedGameSystem(Predicate<GameEntity> predicate, Consumer<GameEntity> consumer) {
        this.predicate = Objects.requireNonNull(predicate);
        this.consumer = Objects.requireNonNull(consumer);
    }

    public boolean isInterestedIn(GameEntity entity) {
        return predicate.test(entity);
    }

    public void update(GameEntity entity) {
        consumer.accept(entity);
    }
}

The expected execution of this code would be in the game engine, something like
public void run() {
    while (shouldRun()) {
        for (GameEntity entity : entities) {
            for (GameSystem system : systems) {
                if (system.isInterestedIn(entity)) {
                    system.update(entity);
                }
            }
        }
    }
}

This revealed an interesting question in my head. If I always expect a piece of code to be run in a certain way (call isInterestedIn followed by update if it returns true), and if I provide a way of delegating all functionality to other objects (the predicate and consumer), is there any reason to provide the interface at all, instead of just the delegating class?

A: A class like InjectedGameSystem that just delegates all it's methods essentially is an interface. The difference is that you can assemble the implementation at runtime, by providing appropriate delegate functions.
Whether it makes sense for such a class to implement an interface depends on the usage. I can think of three potential reasons for having a separate interface:

*

*You have to comply with an existing interface, because that is required by a consumer of the class.
For example, I often apply your approach to dynamically create objects that implement the ICommand interface in .NET. Clearly, this is not the case for you.

*You have implementations that act as GameSystem, but also need to do other things, and possibly inherit from other classes.
Again, from what you've written, it doesn't seem like you need that. Also, you can always get around that, by having that class provide a InjectedGameSystem AsGameSystem() method.

*You want to hide the fact that the method calls are delegated, because this is an implementation detail. This is more relevant if creating and consuming the objects happens in different modules.
Personally, I would probably keep the interface, but I think it would be hard to make a case that one approach is significantly better or worse than the other.


text:
Q: using grunt-browserify in Gruntfile.js I'm having some trouble finding an explanation for how to use grunt-browserify.  Looking in their examples folder, I'm looking under the browserify node under their basic example and I see the following:
module.exports = function (grunt) {
  grunt.initConfig({
    browserify: {
      vendor: {
        src: [],
        dest: 'public/vendor.js',
        options: {
          require: ['jquery'],
          alias: [
            './lib/moments.js:momentWrapper', //can alias file names
            'events:evt' //can alias modules
          ]
        }
      },
      client: {
        src: ['client/**/*.js'],
        dest: 'public/app.js',
        options: {
          external: ['jquery', 'momentWrapper'],
        }
      }
    },
    concat: {
      'public/main.js': ['public/vendor.js', 'public/app.js']
    }
  });
  grunt.loadTasks('../../tasks');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.registerTask('default', ['browserify', 'concat']);
};

What are "vendor" and "client" and where are they documented?  In the README file, they mention "preBundleCB", "dist" and I've seen quite a few others, and most have their own data structures.  Are these options enumerated and explained anywhere?

A: According to the convention of Grunt configuration, "vendor" and "client" are targets. Their names are not defined by grunt or grunt-browserify. You can create as many targets as you want and give them the names you like. Each target has files configuration, which is common in most of Grunt tasks, such as src and dest, and options configuration, which is plugin specific. "dist" is another example of targets and "preBundleCB" is a property of grunt-browserify's options.
You can individually invoke the targets with grunt browserify:vendor and grunt browserify:client. And grunt browserify invokes all targets of browserify task, which are "vendor" and "client" in this example.
Each target of grunt-browserify creates a bundled script file. In this example, "vendor" target creates vendor.js that contains jquery, moment.js named momentWrapper and events named evt. "client" target creates app.js that contains client/**/*.js and their dependencies excluding jquery and momentWrapper.


text:
Q: How can I examine the whole source tree with an annotation processor? I have a lot of handler classes that handle specific message types.  To register all these handlers, I need to know which ones exist.  Currently, they're all annotated with a specific annotation, and I use a Java 6 annotation processor to get all of them, and make a Register class that holds an instance of each of the annotated types.
This works great if the whole tree is being built at once, but if just one of the annotated classes is being built (when I save the file in Eclipse, for example), the processor only sees that type, and builds an incomplete Register.  How can I examine the other types in this scenario?

A: I've solved this well enough for now.  What I did is a little hackey, but basically for every annotated class I see, I add its name to a HashSet.  Then I use Filer.getResource() to get open a file where I've recorded all the previously-seen annotated classes, and add those to the HashSet too.  Then I generate the register class, and write the whole HashSet out to the same resource with Filer.createResource().  This will cause problems if I delete an annotated type, since it will still be recorded in that file, but I can just clean the project or delete that file to solve it.
EDIT: Also, I believe that passing the appropriate "originating elements" to Filer.createSource() should allow Eclipse to track those dependencies properly, but it doesn't.  Perhaps that's an Eclipse bug.

A: Unsurprisingly, compile-time annotation processors only process the files being compiled.  Eclipse uses incremental compilation to save time, so the short answer is that you cannot expect your annotation processor to see all types in one pass.
One solution is to change your architecture to support incremental compilation.  For example, for each annotated HandlerClass, generate a RegisterHandlerClass class that registers that handler class.
That said, sounds like what you are doing would be better done at runtime, perhaps with the help of a tool like Reflections.


text:
Q: Limit textarea inner text width but not scrollbar I have a textarea. It's limited by its container and stretched out to fit it perfectly. The problem I have is that I want to set a max-width to the text inside it, without affecting the scrollbar position.
If I set max-width to the textarea itself, the scrollbar moves from the right and more to the left.
The working code, except for inner text limit

* {
  margin: 0;
  padding: 0;
}

html,
body {
  height: 200px;
  overflow: hidden;
}

textarea {
  height: 100%;
  width: 100%;
  border: none;
  outline: none;
  resize: none;
  padding: 4rem;
  box-sizing: border-box;
}
<textarea spellcheck="false">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur est lectus, ornare eget purus in, lacinia eleifend lectus. Duis eu libero id sapien congue ultrices. Suspendisse eu quam sed risus congue placerat vel quis mi. Donec iaculis lorem sem, ac auctor nibh tempor et. Donec at facilisis eros. Proin semper tincidunt orci, vel eleifend nisl blandit ut. Suspendisse cursus posuere erat, et convallis mauris varius id. Suspendisse orci nulla, tempor a lorem non, ullamcorper condimentum ante. Aenean suscipit tortor in vehicula vehicula. Donec tincidunt, orci non scelerisque ornare, leo sem finibus sapien, ac faucibus sem tellus nec orci. In eu mi lacus. Ut mollis felis vitae sem molestie lobortis. Maecenas viverra, enim vel tempus vulputate, diam est vehicula nisi, non suscipit massa justo ac lacus. Nunc non laoreet quam.

Phasellus eget lacinia quam. Vivamus malesuada turpis a arcu hendrerit euismod. Fusce mattis purus ac ultrices aliquet. Donec ut tellus elit. Fusce eu imperdiet est. Duis feugiat enim massa, ut suscipit erat ornare a. Aliquam in viverra nunc, eget sagittis risus. Aenean vitae blandit neque. Donec consectetur nisi metus, quis vehicula dolor vestibulum vel. Nam sit amet ullamcorper dolor. Aliquam tincidunt velit imperdiet urna mattis, rutrum hendrerit tellus sollicitudin. Nulla blandit sem sed interdum sagittis. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

Nullam pellentesque aliquam sollicitudin. Vestibulum nec molestie arcu, finibus cursus nisi. Sed efficitur vitae turpis sed volutpat. Aenean blandit tortor lectus. Suspendisse potenti. In mattis at risus vel varius. Praesent convallis arcu quis diam eleifend, vitae faucibus tellus dictum. Mauris volutpat finibus risus eget placerat. Proin ante elit, venenatis quis dapibus et, viverra eget velit. Duis consectetur dignissim magna, a pellentesque mi sagittis in. Phasellus sollicitudin, tellus ut mattis aliquam, eros nulla finibus arcu, ac ornare eros sem sit amet mauris. Praesent laoreet efficitur dolor, ut ultricies dui iaculis sed.

Maecenas consectetur, ligula a suscipit rhoncus, turpis lacus ornare turpis, at efficitur sapien metus vitae arcu. Ut et augue nulla. Phasellus a mauris bibendum velit lobortis venenatis. Sed laoreet aliquet velit at posuere. Nulla fringilla neque at velit tempor, eu fringilla eros vehicula. Suspendisse tellus elit, tincidunt a condimentum feugiat, ultricies rhoncus lectus. Curabitur ut purus eu nunc porta volutpat. Maecenas dignissim dui sed mi dapibus vehicula. Praesent porttitor bibendum velit, vel accumsan turpis consectetur vel. Donec dignissim nisl accumsan lectus posuere aliquam. Phasellus laoreet mauris non tellus vulputate pellentesque.

Donec sed aliquam metus, at malesuada tellus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nullam hendrerit quis ex sed efficitur. Quisque ornare consequat condimentum. Aliquam dapibus leo urna, a vehicula orci luctus et. Ut eget velit viverra, consectetur quam ac, pellentesque erat. Fusce dictum est ligula. Suspendisse tellus odio, imperdiet consequat aliquam vitae, elementum eu metus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</textarea>

Tried with padding
I tried to solve it with padding. This code works, as long as the container is larger than 900px. Else the padding has no effect.
padding-right: calc(100% - 900px - 4rem);

In the real code I have more elements at the sides of the textarea which means that I can't solve it with media queries or vw.

A: Maybe a dumb question, but why dont you use:
width:100%;
padding-right:4em;

just like that?


text:
Q: WPF OnApplyTemplate on derived class of ItemsControl isn't called The title basically points it out. I've read other blogs and posts related to the same issue, but none of the provided solutions did work for me.
Here's a simplification of my code:
<!-- CustomItemsControl.xaml -->
<ItemsControl x:Class="myNamespace.CustomItemsControl"
              xmlns:local="clr-namespace:myNamespace">

    <ItemsControl.Resources>
        <Style TargetType="{x:Type local:CustomItemsControl}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:CustomItemsControl}">
                        <Grid x:Name="MyItemsHost" Background="{TemplateBinding Background}" IsItemsHost="True"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ItemsControl.Resources>
</ItemsControl>

// CustomItemsControl.xaml.cs
namespace myNamespace
{
    public partial class CustomItemsControl : ItemsControl
    {
        public CustomItemsControl()
        {
            this.DefaultStyleKey = typeof(CustomItemsControl);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            var MyItemsHost = (Grid)base.GetTemplateChild("MyItemsHost");
        }
    }
}

What I'm doing wrong?

A: I haven't seen it done that way before, I define the template in Generic.xaml as that is what Visual Studio generates when you go Project->Add Custom Control (WPF).
You can make the code you posted work by calling InitializeComponent(); in your constructor.
Also the documentation says you should use Template.FindName("MyItemsHost",this) instead of GetTemplateChild. If your control may need a different layout other than the grid you may want to use an ItemsPresenter and set the ItemsPanelTemplate instead.

A: Depending on what your Custom Control derives from, you may not be able to call InitializeComponent() on it.  For example, a ContentControl doesn't provide InitializeComponent.
If you check this thread, you'll see that the reason OnApplyTemplate never gets called, is because you defined the project as a Class Library, not a Custom Control Library.  Visual Studio adds extra information to AssemblyInfo.cs to tell the runtime where to find the template for your control.
If you add the following code to your AssemblyInfo.cs file, it should start behaving correctly:
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)

)]


text:
Q: Why R system is not able to execute hdfs commands? I am trying to merge some .csv files with the
hdfs dfs -getmerge /path/folderfile filename.csv command.
If I run this command from a terminal or from rstudio's internal terminal, it works fine. If I execute the same command using system("hdfs dfs -getmerge /path/folderfile /destinationpath/filename.csv") it returns the following error:
sh: hdfs: command not found
Warning message:
In system("hdfs dfs -getmerge /path/folderfile /destinationpath/filename.csv") :
  error in running command

Thanks for suggestions


text:
Q: Adding modules to a google cloud function I am follwing documentation to write a simple trigger for my bucket insertion , I am doing this in Python and then deployed the function using gcloud,
my python function is the same as documentation, but I wonder how If i wanna use this function within a project for example I need this function to read the file and publish them to kafka, can I add any external module to this function or using other classes in the python project containing my function?
def gcs_object_insert(data, context):
    print('Event ID: {}'.format(context.event_id))
    print('Event type: {}'.format(context.event_type))
    print('Bucket: {}'.format(data['bucket']))
    print('File: {}'.format(data['name']))
    print('Metageneration: {}'.format(data['metageneration']))
    print('Created: {}'.format(data['timeCreated']))
    print('Updated: {}'.format(data['updated']))

A: Yes, the documentation is clear about how to include dependencies.

A function is allowed to use other third-party libraries as well as
  other local data. Dependencies in Python are managed with pip and
  expressed in a metadata file called requirements.txt shipped
  alongside your function. This file must be in the same directory as
  the main.py file that contains your function code.


text:
Q: Download Highchart image in Phonegap application We are developing a mobile application using Phonegap + Ionic. We are using Highcarts in our application. We want to give a feature to share the highchart in facebook, Whatsapp or Twitter. Sharing is not a issue with phonegap as there is a plugin available for that.
Issue is that when we want to share any image using the phonegap plugin we need to give a path of the Image and Highchart uses SVG to display the chart.
I have tried converting SVG into Canvas and then exporting that canvas using org.devgeeks.Canvas2ImagePlugin of phonegap but nothing works.
Can somebody please help or share some code if they have achieved something like this.
Thanks in advance.

A: After spending hours we have the solution. Hope this will help others also.
(1) Install Cordova plugin "org.devgeeks.Canvas2ImagePlugin".
(2) Get the SVG html of the highchart.
var svg = document.getElementById('chart1').children[0].innerHTML;

(3)Create a Canvas html element and append that canvas element inside the div in your page.
 var canvas = document.createElement('canvas');
 canvas.width = $window.innerWidth;
 canvas.height = 500;

 document.getElementById('divID').innerHTML = '';
 document.getElementById('divID').appendChild(canvas);

(4) Canvg will add the Image to the canvas.
canvg(canvas, svg, { log: true, ignoreMouse: true, ignoreAnimation: true });

(5) With the help of Cordova plugin you can download the image like this
window.canvas2ImagePlugin.saveImageDataToLibrary(
    function(path) {
        console.log(path);
    },
    function(err) {
        console.log(err);
    },
    document.getElementById('canvas').getElementsByTagName("canvas")[0]
);


text:
Q: Jprobe doesn't monitor all `do_execve` calls I know there has been a question about this in the past, but I didn't find a solution.
I'm writing the next kernel module to trace do_exec calls. AFAIK every new process image (not creation) should be loaded like this, so I figure I can trace down all executions with this jprobe.
Unfortunately, the only outputs from this jprobe are these:
execve called /usr/lib/systemd/systemd-cgroups-agent by kworker/u8:3
My module code is as follow:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/kprobes.h>
#include <linux/fs.h>

static long jdo_execve(struct filename *filename,
        const char __user *const __user __argv,
        const char __user *const __user __envp)
{
    const char *name = filename->name;
    printk("execve called %s by %s\n", name, current->comm);
    jprobe_return();
    return 0;
}

static struct jprobe execve_jprobe = {
    .entry          = jdo_execve,
    .kp = {
        .symbol_name    = "do_execve",
    },
};

static int __init jprobe_init(void)
{
    int ret;

    ret = register_jprobe(&execve_jprobe);
    if (ret < 0) {
        printk(KERN_INFO "register_jprobe failed, returned %d\n", ret);
        return -1;
    }
    return 0;
}

static void __exit jprobe_exit(void)
{
    unregister_jprobe(&execve_jprobe);
    printk(KERN_INFO "jprobe at %p unregistered\n", write_jprobe.kp.addr);
}

module_init(jprobe_init)
module_exit(jprobe_exit)
MODULE_LICENSE("GPL");

I'm using CentOS 7, kernel version 3.10.0-514.el7.x86_64
Any help is appreciated!

A: The code at hand is:
SYSCALL_DEFINE3(execve,
                const char __user *, filename,
                const char __user *const __user *, argv,
                const char __user *const __user *, envp)
{
        return do_execve(getname(filename), argv, envp);
}

and:
int do_execve(struct filename *filename,
        const char __user *const __user *__argv,
        const char __user *const __user *__envp)
{
        struct user_arg_ptr argv = { .ptr.native = __argv };
        struct user_arg_ptr envp = { .ptr.native = __envp };
        return do_execve_common(filename, argv, envp);
}

Given how short the function is the first obvious suspicion is that it got inlined in the execve entry point. Disassembling confirms the suspicion:
0xffffffff811e6e20 <sys_execve>:        nopl   0x0(%rax,%rax,1) [FTRACE NOP]
0xffffffff811e6e25 <sys_execve+0x5>:    push   %rbp
0xffffffff811e6e26 <sys_execve+0x6>:    mov    %rsp,%rbp
0xffffffff811e6e29 <sys_execve+0x9>:    push   %r12
0xffffffff811e6e2b <sys_execve+0xb>:    mov    %rdx,%r12
0xffffffff811e6e2e <sys_execve+0xe>:    push   %rbx
0xffffffff811e6e2f <sys_execve+0xf>:    mov    %rsi,%rbx
0xffffffff811e6e32 <sys_execve+0x12>:   callq  0xffffffff811ef380 <getname>
0xffffffff811e6e37 <sys_execve+0x17>:   mov    %r12,%r8
0xffffffff811e6e3a <sys_execve+0x1a>:   mov    %rbx,%rdx
0xffffffff811e6e3d <sys_execve+0x1d>:   xor    %ecx,%ecx
0xffffffff811e6e3f <sys_execve+0x1f>:   xor    %esi,%esi
0xffffffff811e6e41 <sys_execve+0x21>:   mov    %rax,%rdi
0xffffffff811e6e44 <sys_execve+0x24>:   callq  0xffffffff811e6520 <do_execve_common>
0xffffffff811e6e49 <sys_execve+0x29>:   pop    %rbx
0xffffffff811e6e4a <sys_execve+0x2a>:   pop    %r12
0xffffffff811e6e4c <sys_execve+0x2c>:   cltq
0xffffffff811e6e4e <sys_execve+0x2e>:   pop    %rbp
0xffffffff811e6e4f <sys_execve+0x2f>:   retq

Thus, you are not seeing most "calls" to do_execve because the are not any in the code path you are interested in.
Another approach to debug this would be try to put a probe on something deeper or higher in the stack.
I have to ask why are you playing with jprobes or the kernel in general. So far it seems you are a beginner programmer and should not play with it just yet. In particular it is unlikely you will be able to write kernel code (and this includes jprobes) which obeys all the rules and be able to explain why it does. It is too easy to create code which in insufficient testing appears to work, but is broken.