Q: Scala Spray Templated Custom Routing Directive Okay so.... I have this:
  def convertPost  = extract {
    _.request.entity.asString.parseJson.convertTo[CustomClass]
  }

  private def myRoute: Route =
    (post & terminalPath("routeness")) {
      convertPost { req =>
        detach() {
           ThingHandler.getMyResults( req )
        }
      }
    }

but I want to template it, like this:
  def convertPost[T] = extract {
    _.request.entity.asString.parseJson.convertTo[T]
  }

  private def myRoute: Route =
    (post & terminalPath("routeness")) {
      convertPost[CustomClass] { req =>
        detach() {
           ThingHandler.getMyResults( req )
        }
      }
    }

But that doesn't work.  I am using spray-json-shapeless.  My error is
Error:(28, 50) Cannot find JsonReader or JsonFormat type class for T
    _.request.entity.asString.parseJson.convertTo[T]
                                                 ^

when I try:
  def getStuff[T] = extract {
    _.request.entity.asInstanceOf[T] // .convertTo[T]
  }

it gives:
spray.http.HttpEntity$NonEmpty cannot be cast to com.stuff.CustomClass


Q: How to open my jupyter notebook on docker after starting a docker? I wanna start my container and run the jupyternotebook on it. The image is from jupyter/scipy.
First, I start my contianer. Then I try to command 'jupyter notebook' to open it but seems like the port is not 8888, it turns to 8889. I dont know how to deal with this.
enter image description here


Q: I was mocking an independent class method using the jest.spyOn but instead of mocked implementation, the actual method is called Class File
//Consumer class
class Consumer {
constructor(){
}
getConsumerData(){
//does something and does not return anything
}
}

Inside react component button click this method is being called
//ReactComponent.tsx
handleButtonClick() {
Consumer.getConsumerData();
}

Test File
  const methodSpy = jest.spyOn(Consumer.prototype, "getConsumer").mockImplementation(()=>{});
  expect(methodSpy).toHaveBeenCalled();

A: You can mock the whole Consumer

*

*Make sure Consumer is the default export of its file

import Consumer from './consumer';
///...
jest.mock('./consumer'); // SoundPlayer is now a mock constructor

beforeEach(() => {
  // Clear all instances and calls to the constructor and all methods:
  Consumer.mockClear();
});

/// Your tests

More details:
https://jestjs.io/docs/es6-class-mocks


Q: Connect/Authenticate SPO with VBA (excel) I am trying to connect to Sharepoint Online with Excel VBA script to create or delete items in a list. The problem is how to authenticate properly to SPO.
I have checked the site with instruction:

*

*http://www.sharepoint-insight.com/2016/03/21/step-by-step-sharepoint-online-authentiaction-process-via-http-protocol/
When trying to follow the sequence of the instruction via a Chrome app (ARC) to test the webservices it works properly however when I build the same to complete it fails on the last step:
I am able to get a BinarySecurityToken
After that there should be authed via https://XXXXX.sharepoint.com/_vti_bin/idcrl.svc to gain the SPOIDCRL cookie which can be used in every next webservice (fe REST call to create list items). however in vba I get an 401 Unauthorized error. But when I do the same in ARC it works properly. I even can use the returned Cookie in my VBA Excel to create/delete list items (after gaining context)
Dim objXMLHTTP As Object
Dim url As String

url = "https://XXXXXXX.sharepoint.com/_vti_bin/idcrl.svc"

Set objXMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")

With objXMLHTTP
    .Open "GET", url, False
    .setRequestHeader "Authorization", "BPOSIDCRL <LONG BASE64 STRING>"
    .setRequestHeader "X-IDCRL_ACCEPTED", "t"
    .send
End With


Q: How to get WebView Content Size I am looking to find WebView content size to scale data to fit into small size of WebView Frame.
WebView is continuous loading data as getting images from IP Camera so -(void)webViewDidFinishLoad delegate method is not called, otherwise [webview sizeThatFits:CGSizeZero] would give receiver content size.
How to get WebView content size which is continuous loading data ?
Thanks,

A: See my answer to a similar question. Instead of -webViewDidFinishLoad you should consider calling this using a timer (and checking whether something has been loaded, first).
If the HTML is under your control, you might wanna call it using a JavaScipt onLoad handler that tries to fetch a custom URL that you can intercept in -webView:shouldStartLoadWithRequest:navigationType:.


Q: Calculating a windowed weighted moving average where each observation has its own weight I'm trying to calculate a windowed weighted moving average, with a window value of n. I essentially have a set of products, a price for each id, and a reference. I then calculate the ratio of the price with respect to the reference. (price = 45, reference = 45, distance = 1)
From this calculation I then obtain a weight for each observation. I would like to compare results when doing a simple moving average of all the prices and a weighted moving average.
library(tidyverse)
df <- tibble(id = c(1:15),
       price = c(40,50,34,56,78,35,23,40,50,34,56,78,35,23,12),
       product = c(sample(c("A","B"), 15, replace = TRUE)),
       reference = 45,
       distance = price / reference)

max_weight = 1
min_weight = 0

max_distance = 1
min_distance = 0

df <- df %>%
  mutate(weight = case_when(
    distance < 1 ~ (min_weight * (min_distance - distance) + max_weight * (distance - max_distance)) / (min_distance - max_distance) ,
    TRUE ~ 1
  )
  )

> df %>%
+   head()
# A tibble: 6 x 6
     id price product reference distance weight
  <int> <dbl> <chr>       <dbl>    <dbl>  <dbl>
1     1    40 B              45    0.889  0.111
2     2    50 B              45    1.11   1
3     3    34 B              45    0.756  0.244
4     4    56 A              45    1.24   1
5     5    78 B              45    1.73   1
6     6    35 A              45    0.778  0.222

Moving Average calculation:
moving_average <- function(x,n){stats::filter(x, c(0, rep(1/n,n)), sides=1) }

df <- df %>%
  group_by(product) %>%
  mutate(moving_average = moving_average(price, n =3))

> df %>%
+   head()
# A tibble: 6 x 7
# Groups:   product [2]
     id price product reference distance weight moving_average
  <int> <dbl> <chr>       <dbl>    <dbl>  <dbl>          <dbl>
1     1    40 B              45    0.889  0.111           NA
2     2    50 B              45    1.11   1               NA
3     3    34 B              45    0.756  0.244           NA
4     4    56 A              45    1.24   1               NA
5     5    78 B              45    1.73   1               41.3
6     6    35 A              45    0.778  0.222           NA

Essentially, the last step would be to calculate a moving average such that:
sum(price_i * weight_i) / sum(weight_i)
And this calculation would only take place in the given window. I can already create a column that calculates sum(price_i * weight_i), but I'm stuck when it comes to correctly adding those values n times, and then dividing them by the corresponding n weights, where n is the moving average window. Any ideas?

A: I think zoo::rollapplyr should work here. Here's a simple n=2 window,
MA <- function(X) {
  if (!is.matrix(X)) X <- matrix(X, nrow = 1)
  Hmisc::wtd.mean(X[,1], X[,2])
}
df %>%
  group_by(product) %>%
  mutate(n2 = zoo::rollapplyr(
    cbind(price, weight), 2, MA,
          by.column = FALSE, partial = TRUE)
  ) %>%
  ungroup()
# # A tibble: 15 x 7
#       id price product reference distance weight    n2
#    <int> <dbl> <chr>       <dbl>    <dbl>  <dbl> <dbl>
#  1     1    40 B              45    0.889  0.111  40
#  2     2    50 B              45    1.11   1      49
#  3     3    34 A              45    0.756  0.244  34
#  4     4    56 B              45    1.24   1      53
#  5     5    78 B              45    1.73   1      67
#  6     6    35 B              45    0.778  0.222  70.2
#  7     7    23 B              45    0.511  0.489  26.8
#  8     8    40 B              45    0.889  0.111  26.1
#  9     9    50 A              45    1.11   1      46.9
# 10    10    34 B              45    0.756  0.244  35.9
# 11    11    56 B              45    1.24   1      51.7
# 12    12    78 A              45    1.73   1      64
# 13    13    35 B              45    0.778  0.222  52.2
# 14    14    23 B              45    0.511  0.489  26.8
# 15    15    12 A              45    0.267  0.733  50.1

And here's a method demonstrating multiple windows in one call:
df %>%
  group_by(product) %>%
  mutate(
    data.frame(lapply(
      setNames(2:4, paste0("n", 2:4)),
      function(n) zoo::rollapplyr(
        cbind(price, weight), n, MA,
        by.column = FALSE, partial = TRUE)
    ))
  ) %>%
  ungroup()
# # A tibble: 15 x 9
#       id price product reference distance weight    n2    n3    n4
#    <int> <dbl> <chr>       <dbl>    <dbl>  <dbl> <dbl> <dbl> <dbl>
#  1     1    40 B              45    0.889  0.111  40    40    40
#  2     2    50 B              45    1.11   1      49    49    49
#  3     3    34 A              45    0.756  0.244  34    34    34
#  4     4    56 B              45    1.24   1      53    52.3  52.3
#  5     5    78 B              45    1.73   1      67    61.3  60.6
#  6     6    35 B              45    0.778  0.222  70.2  63.8  59.5
#  7     7    23 B              45    0.511  0.489  26.8  56.7  56.4
#  8     8    40 B              45    0.889  0.111  26.1  28.5  55.7
#  9     9    50 A              45    1.11   1      46.9  46.9  46.9
# 10    10    34 B              45    0.756  0.244  35.9  28.4  29.8
# 11    11    56 B              45    1.24   1      51.7  50.7  43.4
# 12    12    78 A              45    1.73   1      64    60.7  60.7
# 13    13    35 B              45    0.778  0.222  52.2  49.2  48.5
# 14    14    23 B              45    0.511  0.489  26.8  43.8  42.6
# 15    15    12 A              45    0.267  0.733  50.1  50.0  48.7

This method takes advantage of the not-well-known behavior of mutate with an unname argument that returns a data.frame. The use of setNames is so that the column names are meaningfully named, there are likely other ways one might approach that.
There's not a particular reason I'm using Hmisc::wtd.mean over a custom function other than I know it works well. The use of the MA function is because within zoo::rollapply*, the FUN= argument is passed a single matrix, so we need to handle it specially, even more so because due to partial=TRUE, the first time MA is called for each group, it is passed a vector instead of a matrix.


Q: Azure Devops: Approval for several Service Endpoints as a whole I´m configuring a YAML deployment pipeline for a certain app which includes several service endpoints (of different types). Deployment of this app must have an approbal from the owner of all these resources. Problem comes from the fact that you can configure an approval for each service endpoint, but not for the whole set. Due to this, the resource owner receives 5 approval requests every time the app is being deployed (and every of these has to be approbed individually).
Any way of grouping the approval of several service endpoints in only one approval step? (Looking for something like Environments, where an "Environment level" approval can be set giving acces to the whole set of resources of that Environment. Sadly, I can not put a service endpoint there, only VM´s o Kubernetes).
Remark: I think this can be achieved with classic pipelines setting a stage approval, but my requirement is using YAML.
Regards.

A: I am afraid that there is no such a feature in azure devops to group the approval requests of service endppoints currently.
Actually, the resource owner doesnot need to click multiple times to approve each individual approval request for a pipeline run.  He can simply click Approval All to approve at once
In my test yaml pipeline, I included several service endpoints in my yaml pipeline. When i run the pipeline. The resource owner will receive the approval requests. He can click the Approval All button to approve all the requests in a single click, he can also choose to approve each specific approval request. See below screenshot.

If above approval all feature in azure devops can not achieve what you expect with grouping the approval requests of service endpoints. You can suggest a feature to microsoft development team. Hope they will consider implementing this feature in the future sprint.


Q: Как построить систему уведомлений в распределенном проекте? Я знаю что для уведомлений с сервера на клиент нужно использовать WebSockets или Long pooling или еще что-то похожее. Но как уведомить одного пользователя о новом сообщении когда ему совсем другой пользователь прислал сообщение. А, другой пользователь может находиться на другом сервере или же даже в другом дата центре.
Допустим сценарий:
Пользователь Петя открыл  WebSocket соединение с сервером в Европейском дата центре.
Пользователь Джордж открыл  WebSocket соединение с сервером в Американском дата центре.

Петя отправляет Джорджу новое сообщение, и Джордж с не большой задержкой получает его.

Как правильно это реализовать?
У меня есть несколько идей, но я не уверен какое из них нужно выбрать. Возможно это делаться вообще по другому. Куда копать нужно?

Идея №1
Когда любой пользователь открывает connection, то мы записываем в распределенную базу данных информацию. Типа: user_id → server_address. server_address – это адрес сервера где он открыл WebSocket.
Так как информация не велика то, всю эту информацию можно держать в RAM. Допустим, можно сделать Redis или Memcached кластер с репликациями и twemproxy который будет работать с кластером. Или использовать готовый кластер от Redis. Также можно заодно еще дополнительную информацию держать там. Допустим пользователь online или offline.
Когда Петя будет отправлять Джорджу сообщение, то мы будем лезть в Redis, смотреть ip сервера Джорджа и на прямую отправлять это сообщение на сервер Джорджа. Сервер Джорджа будет принимать сообщение и отправлять Джорджу через WebSocket.
При этом можно сделать кеш кешей. Логично что к одному серверу будут подключены одни пользователи, которые будут отправлять сообщения своим друзьям и еще кому-то. При отправке сообщений можно будет кешировать адреса тех пользователей, а в случае неудачи инвалидировать кеш. Но это уже преждевременная оптимизация, наверное.
Идея №2
Я пока не понял как именно данные будут распределяться и обрабатываться. Но, там можно создать подписчиков и продюсеров и поставить фильтры которые будут фильтровать сообщения и отправлять нужным продюсерам. Не понял я из-за фильтров. Непонятно как они будут это все проверять и как правильно их писать.
Как я понимаю этот вариант лучше, если в нем разобраться, так как можно хранить также данные в RAM и на прямую с Apache Ignite отправлять сообщения на нужный нам сервер (наверное, но не факт). При этом количество коннекшенов API серверов будет на много меньше. В первом случае у нас будет N * (N-1) коннекшенов, а во втором N, где N это количество серверов.

Идея №3
Такая же, как идея №1, но вместо того чтобы на прямую отправлять сообщение мы будет отправлять его в очередь. В каждом дата центре будет свой локальный RabbitMQ кластер. При том  каждый сервер создаст в RabbitMQ кластере свою очередь и подпишется на неё. Когда мы захотим передать сообщение от Пети к Джорджу, мы посмотрим к какому дата центру принадлежит данный IP. Если к локальному то в зависимости от сервера отправим сообщение в соответствующую очередь. Если в другом дата центре, то отправим сообщение в тот дата центр и там любой сервер сможет отправить это сообщение в локальный кластер RabbitMQ. В таком случае у нас будет N*2 + N*(M-1) конекшенов где N – количество серверов, M – количество дата центров.

Как правильно создать данную систему уведомлений? Возможно все мои идеи не правильны и есть более проработанные схемы.


Q: Magento 2: why we use cache mechanism at a block level? I have a doubt that I see some cache codes in layout xml like below
 <referenceContainer name="store.menu">
            <block class="Vendor\Megamenu\Block\Megamenu"
                name="megamenu"
                template="Vendor_Megamenu::Vendor/Megamenu/megamenu.phtml"
                before="-" ttl="3600">
                 <arguments>
                    <argument name="cache_lifetime" xsi:type="number">3600</argument>
                </arguments>
             </block>
        </referenceContainer>

So I do not define cache at block level so Magento 2 Full page mechanism will get that block in cache automatically ,so My question is if Magento 2 already do full page in cache blocks so why we define block level cache ?

A: FPC
By default in Magento 2 cache lifetime fo public content is set to 86400 seconds (1 day). This means all public cache content will be invalidated after this period. It is called as Time To Live (TTL).
However, FPC also allows to set a different TTL for a block if required. This can be done in the layout XML by setting a ttl attribute (value in seconds).
TTL
Whenever FPC detects a TTL value for the block, it wraps it inside an Edge Side Include (ESI) tag and requests this block in a separate request. This will work only if the caching application is set to Varnish.
e.g. In DOM it will appear something as below
<esi:include src="http://domain.com/rb-ee/page_cache/block/esi/blocks/%5B%22catalog.topnav%22%5D/handles/WyJkZWZhdWx0IiwiY21zX2luZGV4X2luZGV4IiwiY21zX3BhZ2VfdmlldyJd/"></esi:include>

The esi wrapping occurs in below Observer
vendor/magento/module-page-cache/Observer/ProcessLayoutRenderElement.php
Drawback:

*

*Varnish does not support ESI over HTTPS. So ESI will work only for pages served over HTTP only.

*Usage of too many ESIs is discouraged as it may lead to performance issues

e.g. Refer file vendor/magento/module-theme/view/frontend/layout/default.xml
<block class="Magento\Theme\Block\Html\Topmenu" name="catalog.topnav" template="Magento_Theme::html/topmenu.phtml" ttl="3600" before="-"/>

So here the entire page will be cached for the default TTL time of 86400 seconds (1 day), but as the top menu has a shorter TTL of 3600 seconds it will expire many times during the day and will be requested again.
Cache Lifetime
You can set a different cache lifetime for a particular block using cache_lifetime in layout XML.
<block class="your_block">
    <arguments>
        <argument name="cache_lifetime" xsi:type="number">3600</argument>
    </arguments>
</block>

For this to work, your block class needs to implement the IdentityInterface and a getIdentities method, which must return a unique identifier.
e.g. Below is the example of how it is handled for CMS static blocks
<?php

namespace Magento\Cms\Block;

use Magento\Framework\View\Element\AbstractBlock;

/**
 * Cms block content block
 */
class Block extends AbstractBlock implements \Magento\Framework\DataObject\IdentityInterface
{
    ...
    public function getIdentities()
    {
        return [\Magento\Cms\Model\Block::CACHE_TAG . '_' . $this->getBlockId()];
    }
    ...
}

The \Magento\Cms\Model\Block::CACHE_TAG constant is defined as 'cms_b'. So a CMS static block having entity id of 3, the generated cache tag will be 'cms_b_3'.
The getIdentities method can return as many tags as required, for e.g. on category page it will return a tag for the category (e.g. 'catalog_category_6'), and also return several tags for child products (e.g. 'catalog_product_1').
For a particular page, FPC combines all the block tags from the layout, and then adds them to the response in a custom HTTP header: X-Magento-Tags
With the FPC pages now associated with one or several cache tags, the cache invalidation becomes a process of identifying the necessary tags and purging the associated content using observer events.
For the built-in cache these are configured in the Magento_PageCache module.
For the Varnish cache the configuration and observers are in Magento_CacheInvalidate module.

A: According to Wikipedia, the cache is a component that stores data, so future requests for that data can be served faster.
In Magento 2, a full-page cache module stores the entire HTML code of a generated page in the cache storage. As storage, Magento by default uses File cache or Varnish cache.
When your store visitor opens any page in the browser, his or her request goes to the Magento 2 cache system:

*

*If the requested page is inside cache storage, it is quickly returned to the visitor. The speed of such an operation is very high.

*If the requested page is not present in the cache storage yet, Magento will generate this page, add it to the cache storage, and return it to a customer. The speed of such an operation is much lower.
We can see that if a page is served from the cache, Magento sends a response very fast. If a page is not in the cache - the response is slow.
The correct work of the cache system directly affects the store speed. As you know, the speed influences the store's performance in Google search results and the conversion of store visitors into buyers.
Magento 2 Page Cache greatly improves the speed of the store. Your store should be correctly developed and use ‘cache-friendly’ extensions to use all the potential of the Magento cache system. Don’t forget that the store speed may affect your Google search results.
The cache system is extremely relevant and necessary, and Magento 2 speed optimization is a very important task.
Note: Varnish cache is ultra-fast and recommended for any size store, but it requires additional steps to instal and configure.
UPDATE
In the layout XML file we do not get all the blocks from the cache. There are some blocks in which the data shows. So that changes when you change the data block is shown. This type of block is essential which is why magento determines the cache at the block level.
let's assume we have created one block and this block is cacheable. When the first time page loads this html is shown and stored in cache. when next time reload this page block comes from cache. so your any updates or changes are not reflected. That's why Magento uses cache at the block level because some blocks are always shown correctly and update information on the frontend.


Q: Fetch event .focusout from input field in table cell First, I have a Google visualisation dataTable.
After that I create a for loop to get table cell values and put then in input fields:
for (var y = 0, maxrows = data.getNumberOfRows(); y < maxrows; y++) {
    for (var x = 1, maxcols = data.getNumberOfColumns(); x < maxcols; x++) {

      data.setValue(y, x, '<input id="costRedovi" vr="'+ data.getValue(y,0) + '" kol="'+ data.getColumnLabel(x) +'" class="form-control" value="'+data.getValue(y,x)+'">');
    }
}

Now every value is into table cell into input field. Now I can change those values when table is ready, but how to get those values now because  my script produce this HTML code now. Also I need to get value on event .focusout on an input field:

   <input id="costRedovi" vr="2013-04-01" kol="John Deer n7" class="form-control" value="0">
   <input id="costRedovi" vr="2013-04-01" kol="Laza Lazic" class="form-control" value="0">

I tried to do this:
new google.visualization.events.addListener(table, 'ready', function () {

    $("#costRedovi").focusout(function() {
        console.log($('#costRedovi').attr('value'));
    });

});

The problem is that every input has the same ID now.

A: If you were to use a class instead of an ID, that is:

  <input vr="2013-04-01" kol="John Deer n7" class="form-control costRedovi" value="0">
  <input vr="2013-04-01" kol="Laza Lazic" class="form-control costRedovi" value="0">

You could then retrieve the unfocused-input like so:
$(".costRedovi").focusout(function() {
  var origval = $(this).attr('value');
  var editedval = $(this).val();

  console.log("before: " + origval + ", after:" + editedval);
});


Q: Write a Python script named ten-sum-even.py which outputs the sum of only the even integers encountered My Attempt:
n = 10

total = 0

i = 0
while i < n:
    if i % 2 == 0:
    print(total)

else:
print(i)

total = total + int(input())
i = i + 1

Terminal is still counting every number

A: Mistake:
You are on right track but just printing in case its even wont help. You actually need to add that number to the total sum so far as:
n = 10
total = 0
i = 0
while i < n:
    if i % 2 == 0:
        total+=i
    else:
        print(i)
    i+=2
print(total)

Or simply:
print(sum([i for i in range(n) if i%2==0]))

A: n = 10
sum = 0

for i in range(0, n):
    if i % 2 == 0:
        sum += i
print (sum)

A: n = 10
total = 0

for i in range(10):
    if i % 2 == 0:
        total = total + i
print("Total of even numbers is " + total)


Q: Rate limiting with lua We have implemented redis based rate limiting for our web service which has been taken from here. I am duplicating the relevant code here.
local limits = cjson.decode(ARGV[1])
local now = tonumber(ARGV[2])
local weight = tonumber(ARGV[3] or '1')
local longest_duration = limits[1][1] or 0
local saved_keys = {}
-- handle cleanup and limit checks
for i, limit in ipairs(limits) do

local duration = limit[1]
longest_duration = math.max(longest_duration, duration)
local precision = limit[3] or duration
precision = math.min(precision, duration)
local blocks = math.ceil(duration / precision)
local saved = {}
table.insert(saved_keys, saved)
saved.block_id = math.floor(now / precision)
saved.trim_before = saved.block_id - blocks + 1
saved.count_key = duration .. ':' .. precision .. ':'
saved.ts_key = saved.count_key .. 'o'
for j, key in ipairs(KEYS) do

    local old_ts = redis.call('HGET', key, saved.ts_key)
    old_ts = old_ts and tonumber(old_ts) or saved.trim_before
    if old_ts > now then
        -- don't write in the past
        return 1
    end

    -- discover what needs to be cleaned up
    local decr = 0
    local dele = {}
    local trim = math.min(saved.trim_before, old_ts + blocks)
    for old_block = old_ts, trim - 1 do
        local bkey = saved.count_key .. old_block
        local bcount = redis.call('HGET', key, bkey)
        if bcount then
            decr = decr + tonumber(bcount)
            table.insert(dele, bkey)
        end
    end

    -- handle cleanup
    local cur
    if #dele > 0 then
        redis.call('HDEL', key, unpack(dele))
        cur = redis.call('HINCRBY', key, saved.count_key, -decr)
    else
        cur = redis.call('HGET', key, saved.count_key)
    end

    -- check our limits
    if tonumber(cur or '0') + weight > limit[2] then
        return 1
    end
  end
end

I am trying to figure out the meaning of the comment -- don't write in the past
I don't see how a case would be possible where old_ts is greater than now
I have put logs all over the lua code but without any success.
At maximum old_ts can be equal to saved.trim_before which in turn can be equal to now if precision is 1 and blocks is 1. But not greater .
It would be helpful if someone has insights on it.

A: If you look at the gist provided in the article
https://gist.github.com/josiahcarlson/80584b49da41549a7d5c
There is comment which asks
In over_limit_sliding_window_lua_, should

if old_ts > now then

at here be

if old_ts > saved.block_id then

And I agree to this, the old_ts is supposed to have the bucket and when the bucket jumps to the next slot, that is when old_ts will be greater then than the block_id


Q: How can I add remote repositories in Mercurial? I am working with Git repositories in the following way:

*

*I have the master repository and several remotes on the different production machines.

*I am pushing the production code to the remotes and restart the services for the changes to take effect.

I am about to switch from Git to Mercurial and I would like to know ahead how I can achieve something like that.

A: You could have a look at hg-git GitHub plugin:

adding the ability to push to and pull from a Git server repository from Mercurial.
This means you can collaborate on Git based projects from Mercurial, or use a Git server as a collaboration point for a team with developers using both Git and Mercurial.

Note: I haven't tested that tool with the latest versions of Mercurial.

A: You add entries to the [paths] section of your local clone's .hg/hgrc file.  Here's an example of a section that would go in the .hg/hgrc file:
[paths]
remote1 = http://path/to/remote1
remote2 = http://path/to/remote2

You can then use commands like hg push remote1 to send changesets to that repo.  If you want that remote repo to update is working directory you'd need to put a changegroup hook in place at that remote location that does an update.  That would look something like:
[hooks]
changegroup = hg update 2>&1 > /dev/null && path/to/script/restart-server.sh

Not everyone is a big fan of having remote repos automatically update their working directories on push, and it's certainly not the default.

A: if you want to add default path, you have to work with default in your ~project/.hg/hgrc file.  As Follows:
[paths]
default = https://path/to/your/repo

Good Luck.

A: If you're on Unix and you have Git installed, you can use this bash function to readily add a path to the remotes without a text editor:
add-hg-path() {
    git config -f $(hg root)/.hg/hgrc --add paths.$1 $2
    awk '{$1=$1}1' $(hg root)/.hg/hgrc > /tmp/hgrc.tmp
    mv /tmp/hgrc.tmp $(hg root)/.hg/hgrc
}

Then invoke it with:
$ add-hg-path remote1 https://path.to/remote1

If someone would like to build a Powershell equivalent, I'd like to include that as well. Other potentials improvements include error checking on the parameters and factoring out the call to $(hg root).


Q: How to enable HTTP Pipelining with Spray-Can I read on the spray-can docs that it supports HTTP Pipelining. But there is no method or example specified anywhere on how to do it.

A: This is a config setting. See this or this doc for all available settings in Spay config.
This setting turns it on:
spray.can.host-connector.pipelining = off

And this one has to be > 1 to effectively enable it:
spray.can.server.pipelining-limit = 1

By default pipelining is off.
Relevant description of each setting:

# The maximum number of requests that are accepted (and dispatched to
# the application) on one single connection before the first request
# has to be completed.
# Incoming requests that would cause the pipelining limit to be exceeded
# are not read from the connections socket so as to build up "back-pressure"
# to the client via TCP flow control.
# A setting of 1 disables HTTP pipelining, since only one request per
# connection can be "open" (i.e. being processed by the application) at any
# time. Set to higher values to enable HTTP pipelining.
# Set to 'disabled' for completely disabling pipelining limits
# (not recommended on public-facing servers due to risk of DoS attacks).
# This value must be > 0 and <= 128.
pipelining-limit = 1

# If this setting is enabled, the `HttpHostConnector` pipelines requests
# across connections, otherwise only one single request can be "open"
# on a particular HTTP connection.
pipelining = off


Q: Access to OctoberCMS page in code? I have a Static Page in OctoberCMS named General that has a bunch of site-wide settings including phone number and address. Is it possible to access this page in code to read these settings from its ViewBag?
UPDATE: a plugin was created with the following, where properties like twitter_username for example can now be accessed in templates with {{ general('twitter_username') }}:
use System\Classes\PluginBase;
use RainLab\Pages\Classes\Page;
use Cms\Classes\Theme;

class Plugin extends PluginBase
{
    private static $generalViewBag = null;

    public function registerMarkupTags()
    {
        return [
            'functions' => [
                'general' => function($var) {
                    if (self::$generalViewBag === null) {
                        self::$generalViewBag = Page::load(Theme::getActiveTheme(), 'general')
                            ->getViewBag();
                    }

                    return self::$generalViewBag->$var;
                },
            ],
        ];
    }
}

The twitter_username form field was added to the General page in the backend using a separate plugin:
use System\Classes\PluginBase;
use Event;

class Plugin extends PluginBase
{
    public function boot()
    {
        Event::listen('backend.form.extendFields', function($widget) {
            if (! $widget->getController() instanceof \RainLab\Pages\Controllers\Index) {
                return;
            }
            if (! $widget->model instanceof \RainLab\Pages\Classes\Page) {
                return;
            }

            switch ($widget->model->fileName) {
                case 'general.htm':
                    $widget->addFields([
                        'viewBag[twitter_username]' => [
                            'label' => 'Twitter username',
                            'type' => 'text',
                            'tab' => 'Social Media',
                        ],
                    ], 'primary');
                    break;
            }
        });
    }
}

A: yes you can do it actually you need to use this code in page life-cycle method

In page code block you can use something like this OR anywhere else

use RainLab\Pages\Classes\Page as StaticPage;

function onStart() {
    $pageName = 'static-test';
    $staticPage = StaticPage::load($this->controller->getTheme(), $pageName);
    dd($staticPage->viewBag);
}

let me know if it you find any issues


Q: Style html table when saving as csv file I have the below table

Name	Age	Country

Geronimo	26	France

Natalia	19	Spain

Silvia	32	Russia

Pet	Breed	Type

Roscoe	Pug	Dog

Polly	Parrot	Bird

Whiskers	Calico	Cat

Pet	Breed	Type

Roscoe	Pug	Dog

Polly	Parrot	Bird

Whiskers	Calico	Cat

<button>Export HTML table to CSV file</button>

and I have the below JS code
function download_csv(csv, filename) {
    var csvFile;
    var downloadLink;

    // CSV FILE
    csvFile = new Blob([csv], {type: "text/csv"});

    // Download link
    downloadLink = document.createElement("a");

    // File name
    downloadLink.download = filename;

    // We have to create a link to the file
    downloadLink.href = window.URL.createObjectURL(csvFile);

    // Make sure that the link is not displayed
    downloadLink.style.display = "none";

    // Add the link to your DOM
    document.body.appendChild(downloadLink);

    // Lanzamos
    downloadLink.click();
}

function export_table_to_csv(html, filename) {
    var csv = [];
    var rows = document.querySelectorAll("table tr");

    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th");

        for (var j = 0; j < cols.length; j++)
            row.push(cols[j].innerText);

        csv.push(row.join(","));
    }

    // Download CSV
    download_csv(csv.join("\n"), filename);
}

document.querySelector("button").addEventListener("click", function () {
    var html = document.querySelector("table").outerHTML;
    export_table_to_csv(html, "table.csv");
});

This code converts the html tables into an csv file for download. I was wondering if it's possible to somehow add some styling to it so when the csv is open in Excel it display table header with some color to it.
Here's the fiddle Fiddle
Thanks

A: Unfortunately no! CSV files are basically raw cell data, with no formatting at all.
If you would like to have some styling you would need to learn one of the following formats. But that would be much more complicated.

*

*Office Open XML — for Excel 2007 and above

*Excel 2003 XML — for Excel 2003 and above

*Open Document Format (.ods) — can be read by Excel 2010.


Q: Can and should Stack Overflow automatically rewrite bit.ly links? Quite a few people paste in bit.ly links into comments or answers, sometimes even for linking to other pages (or answers within the same page) on Stack Overflow.
This way, you do not see where the link is pointing to.
Assuming that there is an API to do this, should the site automatically rewrite the links to point at the original URL?
Are there any benefits to leave them at bit.ly?
Why are people pasting them through bit.ly in the first place?
Stack Overflow displays shortened URL anyway, so formatting should not be a concern.

A: First, I agree with Joel C. in that shortened links are occasionally a necessary evil:

There are a few cases where the shortened links are necessary. For example, try linking to anything in the Internet Archive's wayback machine or a screenshot on browsershots.org. The markdown chokes and it just won't work without an intermediary. This makes an outright ban problematic.

Second, this is a fairly challenging technical problem, in that it requires us to go through all posts and follow all links -- how do we know which ones are "url shorteners"? The ones on a whitelist? And when do we do this? On a scheduled task or cron job? Every time a post is saved?
I think it might make sense in the short term to just do this the old-fashioned way, with tiny slivers of fractional human effort -- if you see a shortened link that has no reason to be shortened, then un-shorten it.

A: Eschew obfuscation.
I would not be opposed to an outright ban on obfuscated and shortened URLs. If one is entered into a question, answer, or comment, the system should simply reject the post with a link to the FAQ.  There's no reason to shorten a URL that doesn't need to be typed out, and some people do care about the destination of a URL before clicking on it (for example, I have no wish to test my company's proxy or URL logging by visiting a NSFW site).
One other situation, which the site operators should care about: using an URL shortener allows using amazon.com URLs that are not rewritten by the system to insert SO referral information.
Another case is lmgtfy links, which are banned from the site but I have seen users using URL shorteners to get around this restriction.

A: I changed my mind about url shortening services, they indeed do more harm than good in SO ecosystem. I still think it doesn't make sense to call someone as a spammer just by using it, but I do believe it's bad for "link health" in long term.
So, I would like to do a suggestion in this answer: SO could just rewrite these links, maybe using an API from longurlplease.
(I don't know if SO team are really going to depend in a third party service like this, but since url shorteners are a problem from every site that supports user generated content with links, I still think this is a valid and useful concept)

A: If you have the rep to do so, rewrite those links out into the actual.
Unless the problem comes from some quirk with colons, other punctuation marks or something else like too many characters to escape for.
Though the encoding continues to be improved on the links, so even that argument is falling away.
The problem with URL shorteners is that if the service fails you have no idea where that link went to and don't have an idea as to where to find the replacement. If the site just changes how it does its URLs, then you at least have the domain and the old URL slug to work off of.

A: There are actually some legitimate uses for shortening services.
The examples in my answer here would not have been possible without a shortening service.  SO was misinterpreting the URL because it contained a regular expression as part of the query string:
http://www.strfriend.com/vis?re=<([A-Z][A-Z0-9]*)\b[^>]*>(.*%3F)</\1

However in the answer I explicitly stated the reason for the shortened URLs.

A: Yes, this should be done automatically in the background, all the shortened links will rot long term and become useless.

A: Yeah!
When it comes to the internet, one of my fears is reliance on technologies that can't sustain themselves. URL shorteners can't sustain themselves by themself. By definition, they can't show ads (If it's not silent, nobody would use it), and if it dies (like tr.im almost did), the links are worse than useless, even if the original pages remain.
Google's service gives me hope (If google go down, we have bigger worries than their URLs not working), but they still have no place on M?S[OFU] (If we're going to regex-refer to the trilogy, we have to include meta!), and if at all possible, automatic de-shortification should occur.
More to the point, who the hell is shortening links here? Surely that takes more effort for no gain at all?
(On a side note, I entirely blame twitter for all of this. If they'd simply not counted URLs in character limits, this entire scary system would never have been created)

A: There are a few cases where the shortened links are necessary.  For example, try linking to anything in the Internet Archive's wayback machine or a screenshot on browsershots.org.  The markdown chokes and it just won't work without an intermediary.  This makes an outright ban problematic.  I can't find the link now, but in the bug reports from one of those Jeff himself suggested a url shortener as a work-around.
That said, unless it's one of those rare exceptions you probably shouldn't do it, and if you have the rep go ahead and clean it up.

A: If you are that concerned about shorten urls you should be using a tool on your browser to expand them on all sites. Both Google Chrome and Firefox have tools that let you expand short URLs. As Jeff pointed out they are sometimes a necessary evil, and I don't think it is work fixing when there are browser based workarounds.

A: People use bit.ly because using it you can track how many clicks, twitter and other social media mentions. It's not just about shortening links, is about trying to measure it's impact. You have a panel in bit.ly for link statistics.
I don't mind having bit.ly links. They try to prevent spam from their links, so to me it's even safer than have a http://codertutorials.example.com link for example - I can read the link, but have no idea what's waiting for me there. In bit.ly at least they are providing a layer of protection.
Seriously, I want a good answer. And url shorteners are here to stay. Even google has its own.

A: I would rather vote to infer the title from the posted link


Q: Fatal Error: Call to a member function write() on a non-object occurs when memory usage is very high I've been working on a web-based application to export database information through PHP. The original version of the application originally generated a single OpenXML worksheet, but ran into the issue that beyond a certain number of rows (approximately 9500), the worksheet generated was too large to import into Excel or OpenOffice.
I subsequently reworked the app to use the php_excel wrapper for libxl, which worked adequately in test, but when deployed to the live server (which had a larger amount of data in comparison to the testing server), the memory usage of the process would hit just a little bit under 2GB and then fail, giving this error:
Call to a member function write() on a non-object in...etc etc.

Now, the interesting thing is that the code works for smaller sets of data, and if I restrict the amount of data being requested, I can collect partial data dumps from the database. From all investigation, this error occurs when the code attempts to reference an object that is not assigned. Here's the code below:
$objPHPExcel = new ExcelBook($rcn, $rcl, true);
for ($i=0;$i<$myCCount;$i++){
    $myPCount = count($mySelection[$i])
    for ($j=1;$j<$myPCount;$j++){
        $myWorkSheet = $myAccountSelection[$i][0] . ' - ' . $myAccountSelection[$i][$j];
        $thisSheet = $objPHPExcel->addSheet($myWorkSheet);
        for ($k=0;$k<count($myQueryArray);$k++){
            $thisSheet->write(0, $k, $titleList[$myQueryArray[$k]]); //Error on this line
        }
    //The rest is database queries and spreadsheet generation.

Again, I'd like to reiterate that this works for smaller sets of data (same number of rows with fewer columns, or same number of columns, but fewer rows) and will run for approximately fifteen minutes before it errors out.
According to the requirements, a full data dump will generate up to a maximum of 924 workbooks (minus workbooks where there would be no actual entries), with ~360 columns in each workbook containing a combined total of 10,000+ rows.
Can anyone help me identify what the problem actually is in this case?
Edit Update:
After some logging and digging through the php_excel wrapper's error handling (such as it is), I have determined that the problem is indeed a memory allocation limit being hit - within the wrapper itself. The amount of free memory available to PHP or FastCGI or on the rest of the machine doesn't matter in this case, because once it hits a certain amount (I'm in the process of currently trying to pin down exactly what the limits are). Unless anyone can educate me as to a way to improve the amount of cells that the phpexcel wrapper can handle, I think this is closed as a "unsolvable but known problem".

A: Under some conditions, the code in this line:
$thisSheet = $objPHPExcel->addSheet($myWorkSheet);

$thisSheet will be null,
change the following code to:
if ($thisSheet) {
    for ($k=0;$k<count($myQueryArray);$k++){
        $thisSheet->write(0, $k, $titleList[$myQueryArray[$k]]); //Error on this line
    }
}

to avoid the error.
The reason why $objPHPExcel->addSheet reutuns null may be that the memory usage is reach limit, you can use ini_set("memory_limit", -1); to set memory usage to unlimited.


Q: Is there a way to make an SSRS cell display either a sub-report or an expression? I have an SSRS report that has a cell which I need to show the value of a Dataset item unless a parameter is selected, in which case I need to display a sub-report in that cell.
I tried setting the sub-report's visibility but then it never displays the expression since it takes over the entire cell. It's like it is either one way or the other.

A: If you put a subreport in a cell then you can't optionally display something else in that cell.
However from your comment you're trying to display values from two different datasets based on a condition, and you should be able to do this with an expression. Assuming there is some field in the table that can be used to relate to either dataset, then you might be able to use the lookup() function to get the relevant value, e.g. a code outline for this:
Iif(some_condition, lookup(value1 in datasetA), lookup(value1 in datasetB))


Q: How to use VBA to clear content? I would like to have all cells empty after opening my spreadsheet on "ThisWorkbook".
Code:
Sheets("1 - Feuille de Suivi").Range("C19") = ""

and
Sheets("1 - Feuille de Suivi").Liste_cible.Clear
Sheets("1 - Feuille de Suivi").Liste_cible.Value = ""

But it takes a little time before deleting, so I can see the data after opening (1-2 seconds) and it is deleted after.
Maybe you know some efficient function VBA that deletes the data while opening the spreadsheet ?
Thank you very much for your help !


Q: How to hide a solution in xsim for the student book and display all solutions for the teacher book In my books there are two types of exercises. The first type has public solutions, those solutions should appear in the student's book and teacher's book. The second type has solutions that should only appear in the teacher's book and not in the student's book.
My first approach was to define a boolean "teacherbook" to mark the exercises for the teacher's book.
I also probably need a global variable in the preamble to indicate whether my book should now be printed in student or teacher form.
How do you achieve that?
\documentclass{scrbook}
\usepackage[utf8]{inputenc}

\usepackage{hyperref}

%Rahmenumgebung
\usepackage{tcolorbox}
\usepackage[english]{babel}
\usepackage{blindtext}
\tcbuselibrary{skins,breakable,xparse}

\usepackage[blank]{xsim}
\xsimsetup{
    print-solutions/headings=false,%no headings before solutions
}
\DeclareExerciseProperty{level}
\DeclareExerciseProperty{symbole}
\DeclareExerciseProperty{notenstufe}
\DeclareExerciseProperty{title}
\DeclareExerciseProperty*{teacherbook}%*=boolean, wenn teacherbook ohne Zuweisung oder wenn teacherbook=true ist, dann soll diese Lösung nur im Teacherbook erscheinen.
\DeclareExerciseEnvironmentTemplate{aufgabe-template}{%
    \IfExistSolutionT{%
        \IfInsideSolutionTF
            {%True
                \label{sol:\ExerciseID}
            }
            {%False
                \label{ex:\ExerciseID}
            }
    }%
    \tcolorbox[
        parbox=false,%wenn dieser Befehl deaktiviert ist, dann sollte unten setlength{\parskip}{0.5\baselineskip plus2pt minus2pt} aktiviert sein.
        enhanced jigsaw,
        breakable,%auskommentieren, wenn die Aufgaben in einer einzigen Box zusammenhängen sollen
        left=1mm,%Abstand links zum Rahmen
        right=1mm,%Abstand rechts zum Rahmen
        %colframe=blue!30!white,%Rahmenfarbe
        colframe=black,%Rahmenfarbe
        coltext=black,%Schriftfarbe
        colback=white,%Hintergrundfarbe
        colbacktitle=white,%Hintergrundfarbe im Titel
        coltitle=black,%Schriftfarbe im Titel
        %underlay={%Hintergrund
            %\begin{tcbclipinterior}
            %\shade[inner color=green!80!yellow,outer color=white]
            %(interior.north west) circle (2cm);
            %\draw[help lines,step=5mm,white!80!black,shift={(interior.north west)}]
            %(interior.south west) grid (interior.north east);
            %\end{tcbclipinterior}
        %},
        %drop shadow,%mit Schatten
        beforeafter skip = .5\baselineskip,
        title ={
            \textbf{\GetExerciseName~\GetExerciseProperty{counter}}%Aufgabe mit Nummer ausgeben
            \GetExercisePropertyT{level}{ \SymAnforderungen{\PropertyValue}}%evtl. Level mit Knödeln anzeigen
            \GetExercisePropertyT{symbole}{ \PropertyValue}%evtl. Symbole anzeigen
            \GetExercisePropertyT{notenstufe}{ (N:~\PropertyValue)}%evtl. Notenstufe anzeigen
            \GetExercisePropertyT{points}{ % notice the space, evtl. Punkte anzeigen
                \mbox{(%
                \printgoal{\PropertyValue}
                \IfExerciseGoalSingularTF{points}
                    {\XSIMtranslate{point}}
                    {\XSIMtranslate{points}}%
                )}%
            }%
            \IfExistSolutionTF%
                {%True bedeutet: Lösung existiert
                    \IfInsideSolutionTF%
                        {%True bedeutet wir sind in der Lösung
                            {\hfill A:~\pageref{ex:\ExerciseID}}%Querverweis zur Aufgabe (A)
                        }
                        {%False
                            {\hfill L:~\pageref{sol:\ExerciseID}}%Querverweis zur Lösung (L)
                        }%
                }%
                {}%False bedeutet Lösung existiert nicht
            \GetExercisePropertyT{title}{\\\PropertyValue}%evtl title in neuer Zeile (\\) ausgeben
        },%
        pad at break*=0mm,%sollte immer letzte Option sein, weil diverse Anpassungen dadurch ausgelöst werden.
    ]
    %nachfolgender Befehl wird nicht gebraucht, wenn mit parbox=false oben gearbeitet wird.
    %\setlength{\parskip}{0.5\baselineskip plus5pt minus5pt}%
    \IfInsideSolutionT{
        \IfExerciseBooleanPropertyT{teacherbook}{\textcolor{red}{This solution only appears in the student book.}}
    }
}
{%end-Bereich für aufgabe-template
    \endtcolorbox
}
\DeclareExerciseType{Aufgabe}{
    exercise-env = exercise,
    solution-env = solution,
    exercise-name = Aufgabe,
    exercises-name = Aufgaben,
    solution-name = Lösung von Aufgabe,
    solutions-name = Lösungen,
    exercise-template = aufgabe-template,
    solution-template = aufgabe-template,
    within=section,
    %the-counter = \thesection.\arabic{counter-aufgabe}
}

\begin{document}

\setcounter{chapter}{2}

\chapter{Chapter Title 3}
\section{Section 3.1}
\begin{exercise}[%
    points=1,%
    teacherbook=true%
]
This solution should only visible in the teacher book.
\blindtext[1]
\end{exercise}
\begin{solution}
\blindtext[1]
\end{solution}

\begin{exercise}[%
    points=2%
]
\blindtext[1]
\end{exercise}
\begin{solution}
\blindtext[1]
\end{solution}

\section{Section limited solutions for students}
\printsolutions[chapter=true]

\chapter{Chapter Title 4}
\section{Section 4.1}
\begin{exercise}[%
    points=1%
]
\blindtext[1]
\end{exercise}
\begin{solution}
\blindtext[1]
\end{solution}

\begin{exercise}[%
    points=1,%
    teacherbook=true%
]
This solution should only visible in the teacher book.
\blindtext[1]
\end{exercise}
\begin{solution}
\blindtext[1]
\end{solution}

\section{Section all solutions for teachers}
\printsolutions[chapter=true]

\end{document}


Q: Maximum of $\int_a^b \frac{f(x)}{x}\,\mathrm dx$
Let $b>a>0$ and $M>0$ be fixed. Let $F$ be the set of all functions $f:[a,b]\to[-M,M]$ such that $$\int_a^bf(x)\,\mathrm dx=0.$$Find$$\max_{f\in F}\int_a^b\frac{f(x)}x\,\mathrm dx.$$

I tried to use the CBS inequality for integrals for the functions $(f(x))^2$ and $\dfrac{1}{x^2}$, but when I tried to find the equality case, the function $f(x)=\dfrac{k}{x}$ I got did not satisfy $\displaystyle\int_a^bf(x)\,\mathrm dx=0$. So the maximum must be lower than what I found. But I do not know anything about the continuity of $f$ and I don't know how to continue.

A: While this answer I cant claim is complete proof, I will share it, maybe others can complete it or find the ideas useful.
I would approach this using calculus of variations. However, if $f(x)$ must be continuous, I think the calculus of variations would dictate $f(x) \equiv 0$ (and the functional won't be a maximum). So, let us assume that $f$ is discontinuous at a point $ a < c < b$, such that:
$$
f(x) = \begin{cases}
f_1(x), & a \leq x \leq c \\
f_2(x), & c < x \leq b\end{cases}.
$$
Our functional reads: $$ I_{f_1,f_2} = \int_a^b \dfrac{f(x)}{x} dx = \int_a^c \frac{f_1(x)}{x} dx + \int_c^b\frac{f_2(x)}{x} dx$$
and when we write the stationary (extremum) condition of $I$ with respect to independent variations of $f_1, f_2$ we get $\delta f_1 = \delta f_2 = 0$ (so they are constant functions). Let us assume now:
$$
f(x)/M = \begin{cases}
k_1 , & a \leq x \leq c \\
-k_2, & c < x \leq b\end{cases}.
$$
From the constraint $\int_a^b f(x) dx=0$, we get:
$c = \dfrac{k_1 a + k_2 b}{k_1+k_2}$. We ask that $a < c < b$, so $0 < k_{1,2} \leq 1$ (because $\vert f(x) \vert \leq M$). Not all pairs $(k_1,k_2)$ need to be studied (see the scaling relation in the following, to keep in mind).
All that is left to do is to compute the functional and maximize it with respect to $k_1, k_2$. We have:
$$I(k_1,k_2)/M = k_1 \ln \frac{c}{a} + k_2 \ln \frac{c}{b} = \ln \left[ \left(\frac{c}{a}\right)^{k_1} \left(\frac{c}{b}\right)^{k_2} \right],$$
with $c=c(k_1,k_2)$ given above.
Note that $I(\lambda k_1, \lambda k_2) = I^\lambda(k_1,k_2)$. This allows us to simplify the search for $k_1, k_2$ to obtain maximum value. Namely, we only could look for $0 < t < 1$ at $I(1,t)$, $I(t,1)$, and $I(1,1)$ to understand the behavior for all values $(k_1,k_2)$ (using the scaling relation above, we can scale the arguments down by the one that is the biggest). Turns out (I did plotting only) that the maximum is attained for $k_1=k_2=1$.  This is a bit of a hand-waving proof, maybe somebody else can complete this point.
With the above in mind, the maximum value of the functional is the same as one obtained by Saad above: $$ \text{max } I_{f_1,f_2} = M \ln\dfrac{(a + b)^2}{4ab}.$$

A: $\def\d{\mathrm{d}}\def\peq{\mathrel{\phantom{=}}{}}$For any fixed $f \in F$, define$$
g(x) = \int_a^x f(u) \,\d u, \quad \forall x \in [a, b]
$$
then $g' = f$ almost everywhere and $g(a) = g(b) = 0$. Since $|f(x)| \leqslant M$, then for any $a \leqslant x \leqslant \dfrac{a + b}{2}$,$$
g(x) = \int_a^x f(u) \,\d u \leqslant M (x - a),
$$
and for any $\dfrac{a + b}{2} < x \leqslant b$,$$
g(x) = g(b) - \int_x^b f(u) \,\d u \leqslant M(b - x).
$$
Therefore by integration by parts,$$
\int_a^b \frac{f(x)}{x} \,\d x = \int_a^b \frac{g'(x)}{x} \,\d x = \left. \frac{g(x)}{x} \right|_a^b + \int_a^b \frac{g(x)}{x^2} \,\d x = \int_a^b \frac{g(x)}{x^2} \,\d x\\
= \int_a^{\tfrac{a + b}{2}} \frac{g(x)}{x^2} \,\d x + \int_{\tfrac{a + b}{2}}^b \frac{g(x)}{x^2} \,\d x \leqslant M \int_a^{\tfrac{a + b}{2}} \frac{x - a}{x^2} \,\d x + M \int_{\tfrac{a + b}{2}}^b \frac{b - x}{x^2} \,\d x = M \ln\frac{(a + b)^2}{4ab}.
$$
Note that the above inequality becomes equality for$$
f(x) = \begin{cases}M;& a \leqslant x \leqslant \dfrac{a + b}{2}\\-M;& \dfrac{a + b}{2} < x \leqslant b\end{cases},
$$
thus the maximum is $M \ln\dfrac{(a + b)^2}{4ab}$.


Q: I am failing to run Mule 3 on the command line This is what I get on a pristine Mule distribution:
$ ./mule
MULE_HOME is set to /home/wena/src/mule-standalone-3.1.2
Running in console (foreground) mode by default, use Ctrl-C to exit...
MULE_HOME is set to /home/wena/src/mule-standalone-3.1.2
Running Mule...
--> Wrapper Started as Console
Launching a JVM...
Starting the Mule Container...
Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
  Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.

INFO  2011-07-02 05:00:33,164 [WrapperListener_start_runner] org.mule.module.launcher.MuleContainer:
**********************************************************************
* Mule ESB and Integration Platform                                  *
* Version: 3.1.2 Build: 21975                                        *
* MuleSoft, Inc.                                                     *
* For more information go to http://www.mulesoft.org                 *
*                                                                    *
* Server started: 2011/07/02 5:00 AM                                 *
* JDK: 1.6.0_18 (mixed mode)                                         *
* OS: Linux (2.6.39-2-686-pae, i386)                                 *
* Host: debian (127.0.1.1)                                           *
**********************************************************************
INFO  2011-07-02 05:00:33,247 [WrapperListener_start_runner] org.mule.module.launcher.application.DefaultMuleApplication:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ New app 'default'                                        +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ERROR 2011-07-02 05:00:33,250 [WrapperListener_start_runner] org.mule.module.launcher.DeploymentService:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Failed to deploy app 'default', see below                +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ERROR 2011-07-02 05:00:33,250 [WrapperListener_start_runner] org.mule.module.launcher.DeploymentService: org.mule.module.launcher.DeploymentException: Failed to deploy application [default]
INFO  2011-07-02 05:00:33,254 [WrapperListener_start_runner] org.mule.module.launcher.StartupSummaryDeploymentListener:

**********************************************************************
*            - - + APPLICATION + - -            * - - + STATUS + - - *
**********************************************************************
* default                                       * FAILED             *
**********************************************************************

INFO  2011-07-02 05:00:33,279 [WrapperListener_start_runner] org.mule.module.launcher.DeploymentService:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Mule is up and kicking (every 5000ms)                    +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

I am however able to run Mule from Eclipse.
Note that a recent development snapshot leading to 3.2 release didn't have any such problem.

A: Mule is failing probably because an empty directory (lib/shared/default) is missing.
Hg doesn't version empty directories.

A: There is something weird that Mercurial (Debian's 1.8.3-1+b1 in Unstable) does: whenever I run hg clean, even if there is nothing to clean (hg status output is null), trying to run ./mule fails with the stated error.
Solution: stay away from that clean command for now.


Q: Django: Put multiple widgets/fields into one field I'm making a form to let users edit their photo gallery. So when I show the form I need 2 fields/widget per photo.
For each photo there will be one
CheckBox(label='Delete photo', value=<Id of photo>)
and one RadioSelect(label='Set as cover image', value=<Id of photo>)
In the form class I guess I should put something like this in the __init__:
for image in images:
    #make a checkbox widget
    #make a radio select
    #store the url of the image
    self.fields[..] = gallery_field_widget

I would prefer to put as much code in the form class instead of the template. I've played around with MultpleSelect widget but I can't figure out how to iterate through it together with the rest of the widgets.. and help on this?

A: This isn't two widgets per field, this is two fields per form and one form per instance. For that we have formsets.


Q: Google map con estilo no marca el sitio indicado Mi mapa de Google Maps no señala al sitio que le indico con su típica flecha roja. ¿Qué puedo hacer para que aparezca?

<!DOCTYPE html>

    <title>Styled Maps - Night Mode</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

A: Debes crear un marker, como lo explica la documentacion de google maps
con el comando :
new google.maps.Marker({
            position: location, //debes elegir las coordenadas
            map: map  // en que mapa lo quieres ver

En ejemplo lo que quieres realizar, se realizo en base al ejemplo de google map para que puedas crear un archivo js con las funcionalidades comunes:

function initMap() {
        // Styles a map in night mode.
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 40.4610378, lng: -3.6926671},
          zoom: 12,
          styles: [
              {
                "elementType": "geometry",
                "stylers": [
                  {
                    "color": "#212121"
                  }
                ]
              },
              {
                "elementType": "labels.icon",
                "stylers": [
                  {
                    "visibility": "off"
                  }
                ]
              },
              {
                "elementType": "labels.text.fill",
                "stylers": [
                  {
                    "color": "#7a7a7a"
                  }
                ]
              },
              {
                "elementType": "labels.text.stroke",
                "stylers": [
                  {
                    "color": "#212121"
                  }
                ]
              },
              {
                "featureType": "administrative",
                "elementType": "geometry",
                "stylers": [
                  {
                    "color": "#757575"
                  },
                  {
                    "visibility": "off"
                  }
                ]
              },
              {
                "featureType": "administrative.country",
                "elementType": "labels.text.fill",
                "stylers": [
                  {
                    "color": "#9e9e9e"
                  }
                ]
              },
              {
                "featureType": "administrative.land_parcel",
                "stylers": [
                  {
                    "visibility": "off"
                  }
                ]
              },
              {
                "featureType": "administrative.locality",
                "elementType": "labels.text.fill",
                "stylers": [
                  {
                    "color": "#bdbdbd"
                  }
                ]
              },
              {
                "featureType": "poi",
                "elementType": "labels.text.fill",
                "stylers": [
                  {
                    "color": "#757575"
                  }
                ]
              },
              {
                "featureType": "poi.park",
                "elementType": "geometry",
                "stylers": [
                  {
                    "color": "#181818"
                  }
                ]
              },
              {
                "featureType": "poi.park",
                "elementType": "labels.text.fill",
                "stylers": [
                  {
                    "color": "#616161"
                  }
                ]
              },
              {
                "featureType": "poi.park",
                "elementType": "labels.text.stroke",
                "stylers": [
                  {
                    "color": "#1b1b1b"
                  }
                ]
              },
              {
                "featureType": "road",
                "elementType": "geometry.fill",
                "stylers": [
                  {
                    "color": "#2c2c2c"
                  }
                ]
              },
              {
                "featureType": "road",
                "elementType": "labels.text.fill",
                "stylers": [
                  {
                    "color": "#8a8a8a"
                  }
                ]
              },
              {
                "featureType": "road.arterial",
                "elementType": "geometry",
                "stylers": [
                  {
                    "color": "#373737"
                  }
                ]
              },
              {
                "featureType": "road.highway",
                "elementType": "geometry",
                "stylers": [
                  {
                    "color": "#3c3c3c"
                  }
                ]
              },
              {
                "featureType": "road.highway.controlled_access",
                "elementType": "geometry",
                "stylers": [
                  {
                    "color": "#4e4e4e"
                  }
                ]
              },
              {
                "featureType": "road.local",
                "elementType": "labels.text.fill",
                "stylers": [
                  {
                    "color": "#616161"
                  }
                ]
              },
              {
                "featureType": "transit",
                "elementType": "labels.text.fill",
                "stylers": [
                  {
                    "color": "#757575"
                  }
                ]
              },
              {
                "featureType": "water",
                "elementType": "geometry",
                "stylers": [
                  {
                    "color": "#171717"
                  }
                ]
              },
              {
                "featureType": "water",
                "elementType": "labels.text.fill",
                "stylers": [
                  {
                    "color": "#3d3d3d"
                  }
                ]
              }
            ]
        });
        function addMarker(location, map) {
          var marker = new google.maps.Marker({
            position: location,
            map: map
        });
      }
        addMarker({lat: 40.4610378, lng: -3.6926671}, map);
      }
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>


Q: Mapping 2 columns in pandas to third one I want to create pandas column 'Link' based on other 2 columns (URL and Title) in order to create column which will hold HTML link tag with title in form:
{}'.format(df['Ad_URL'],df['Title'])
I'm using:
def Ad_Link(df):
    return ('{}'.format(df['Ad_URL'],df['Title']))

df['Link'] = df[['Ad_URL','Title']].apply(lambda x:Ad_Link(x), axis=1)

but it doesn't work as expected.
It gives:
List of all Titles for all items in  df['Link']
It suppose iterate and give:
Title[0]
Title[1]

EDIT
Actually my solution worked, had a problem with data frame initially.

A: This works fine for me.
df = pd.DataFrame({'Ad_URL':['u1', 'u2', 'u3'], 'Title':['t1', 't2', 't3']})

def Ad_Link(df):
    return ('{}'.format(df['Ad_URL'],df['Title']))

df['Link'] = df[['Ad_URL','Title']].apply(lambda x:Ad_Link(x), axis=1)

print(df)

Output:
  Ad_URL Title                 Link
0     u1    t1  t1
1     u2    t2  t2
2     u3    t3  t3

A: First your code working for me nice. But added multiple solutions with same output:
df = pd.DataFrame({'Ad_URL':['u1', 'u2', 'u3'], 'Title':['t1', 't2', 't3']})

def Ad_Link(df):
    return ('{}'.format(df['Ad_URL'],df['Title']))

df['Link'] = df[['Ad_URL','Title']].apply(lambda x:Ad_Link(x), axis=1)

#change variable in function to x
def Ad_Link1(x):
    return ('{}'.format(x['Ad_URL'],x['Title']))

df['Link1'] = df[['Ad_URL','Title']].apply(lambda x:Ad_Link1(x), axis=1)

#removed lambda function
def Ad_Link2(x):
    return ('{}'.format(x['Ad_URL'],x['Title']))

df['Link2'] = df.apply(Ad_Link2, axis=1)

#pass columns names to lambda function, changed function
def Ad_Link3(url, link):
    return ('{}'.format(url, link))

df['Link3'] = df.apply(lambda x: Ad_Link3(x['Ad_URL'],x['Title']), axis=1)

#only lambda function solution
df['Link4'] = df.apply(lambda x: '{}'.format(x['Ad_URL'], x['Title']), axis=1)

print (df)
  Ad_URL Title                 Link                Link1                Link2  \
0     u1    t1  t1  t1  t1
1     u2    t2  t2  t2  t2
2     u3    t3  t3  t3  t3

                 Link3                Link4
0  t1  t1
1  t2  t2
2  t3  t3


Q: How to integrate key vault with Bot composer I want to make an http request from bot composer but one thing to pass while making http request needs to be kept a secret. So I want to fetch that value from key vault. Can someone tell how to integrate bot composer with key vault.

A: I'll assume you are using Azure to run the bot, so I'll answer with that in mind. Otherwise let me know and I can expand the answer.
Take the secret from the settings of the bot. It's just like how you access turn.activity.text, but using settings scope instead of the turn scope. So: settings.apiSecret.
Local Env
Now in development, local environment, you can just put the secret in the settings file.
In Azure
When you deploy to your azure app service, you can use Key Vault References in the Configuration blade. Remember you need to give the app service Secret Get permission to that Key Vault.
This is the easiest way since you don't need to write code to query KeyVault via the API.
From DevOps to Azure
There's a way to get the secret in the pipeline, but I believe this is not something you need in this scenario, you just want to set the variable in the App Service. So in the App Service Deployment task, under Application and Configuration settings -> App Settings: you can add the same thing you'd put in the Configuration blade in the azure portal.
So you can add to the textbox: -apiSecret @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/) or click on the button with the elipsis on the right and enter it on the form


Q: Javascript multiple countdown timers on the same page using dates from django models this is my first ever post so please let me know if I need to clarify anything thanks.
I don't have any Javascript experience and I'm trying to write a countdown timer that runs through a django model's data and displays a countdown timer based on each individual object date in my database.
My django models work correctly and loops correctly etc.
I place the below script within my django models for loop but the script only pulls the first objects target date and then populates the countdown timer(correctly) for my first django model object's targetdate but it uses the date of only this first model.
My guess is that I need to put the targetdate (the folowing piece of code) :
let targetdate  = new Date({{ datemodel.dateinmodel|date:"U" }} * 1000);

also in some sort of for loop within javascript itself. I've tried to do this but I really still struggle a lot with javascript at the moment so I don't have any idea.
Do I need to put the target date also in some sort of loop within my javascript script to be able to make it loop through the rest of the object dates in my django model?
Please find the script that I've got so far below :

    Countdown until target date-
    D
    H
    M
    S

Any guidance on how I should approach this will be appreciated many thanks.

A: This is not an answer though but I'm facing similar challenge.. I don't know if you've sorted it out.   I tried converting the data to JSON using JSON dump with that the whole params comes out for each of the timers. And I see that in my console.log so next challenge is to be able to pass all to the table through a loop I was thinking although it's not conventional but might work. Creating another table close to the main table to move this timer out of the for loop entirely and work from there with it..
This is the link to a solution that worked for me https://stackoverflow.com/a/65218112/16174649

A: Thanks for the suggestion.
I was unable to get it to work within the Django loop itself so my solution was to seperate and load each date object seperately within the views file in django and then to just build a counter for each date by itself.
Its probably not the most effective solution but it worked as I only had 11 plus dates to build countdowns for.
In the code example below I would simply update/+1 number for the "countDownDate", "date" and "demo" fields until I created 11 scripts for my 11 items so each item/section has its own countdown script.
Below is the first and second script as an example.


Q: parsing error while parsing document using ow3c.dom.Document object, (Unicode: 0x1a) was found in the element content of the document I am getting error : org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 14515; An invalid XML character (Unicode: 0x1a) was found in the element content of the document.
my xml file content in which I getting error:
 <Product>
          <Description>672577000 3M 4540 DISPOSABLE COVERALL → XL</Description>
 </Product>

I got this error while I am parsing document using org.w3c.dom.Document object, error is occurred due to → in input file. so how can I fix this issue ?

A: No all characters are allowed in a xml files. Here is a link for you to find which one is allowed or is discouraged and the reset is not allowed:
http://en.wikipedia.org/wiki/Valid_characters_in_XML
Yours (→) is not allowed.

A: I resolved this by using below code
String removedUnicodeChar  = "DISPOSABLE COVERALL → XXL</Description></Order> ↔ ↕ ↑ ↓ → ABC";
Pattern pattern = Pattern.compile("[\\p{Cntrl}|\\uFFFD]");
Matcher m = pattern.matcher(removedUnicodeChar);
if(m.find()){
    System.out.println("Control Characters found");
    removedUnicodeChar = m.replaceAll("");
}


Q: How to Format TextBox While Typing? When the user types in the textbox i want it to format itself with decimals.
For example, if the user types 10000 I want it to show up like 10,000 while he types it.

A: Here you go.  Handing backspace/delete made it especially challenging.  That was fun! :-)
I have added this to my online portfolio of scripts at rack.pub.

function toast(a,b){b||(b=2750);var c={message:a,timeout:b};snackbarContainer.MaterialSnackbar.showSnackbar(c)}var doc=document,textArea=doc.getElementById("area"),numArray=[],backArray=[],num="",numF="",regx="",thisChar="",lastChar="",str="",index=0;window.snackbarContainer=doc.querySelector("#toast"),textArea.addEventListener("keydown",function(){var a=event.keyCode;if(str=this.value,(8==a||46==a)&&(backArray=[],index=str.length-1,lastChar=str.charAt(index),!isNaN(lastChar)||","==lastChar))for(var b=str.length-1;b>=0;b--){if(" "==str.charAt(b))return;if(isNaN(str.charAt(b))&&","!=str.charAt(b))return;backArray.push(str.charAt(b))}if(32==a&&backArray[1]){var c=backArray.reverse().slice(0,-1).join(""),d=c.replace(/\,/g,""),e=Number(d).toLocaleString().toString(),f=str.lastIndexOf(c);f>=0&&f+c.length>=str.length&&(str=str.substring(0,f)+e),this.value=str}}),textArea.addEventListener("keypress",function(){if(thisChar=this.value.slice(-1),isNaN(thisChar)){num=numArray.join(""),numArray=[],numF=Number(num).toLocaleString().toString(),regx=num+"(?!.*"+num+")",regx=new RegExp(regx);var a=this.value.replace(regx,numF);this.value=a}else{if(" "==thisChar){num=numArray.join(""),numArray=[],numF=Number(num).toLocaleString().toString(),regx=num+"(?!.*"+num+")",regx=new RegExp(regx);var a=this.value.replace(regx,numF);return void(this.value=a)}numArray.push(thisChar)}});
        html body {
            font-family: 'Roboto', sans-serif;
            background: #f5f5f5;
        }
        .text-right{
            text-align:right;
        }
        .text-center{
            text-align:center;
        }
        .text-left{
            text-align:left;
        }
        .thin{
            font-weight: 100;
        }
        .heading{
            font-size:3em;
        }
        .subtitle{
            margin-top: -16px;
        }
        #submit{
            margin-top:10px;
        }
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.2.0/material.indigo-pink.min.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,400" rel="stylesheet">

commas.js demo

                        JavaScript to automatically add commas to numbers in a text area

                        Basically it auto formats numbers as you type in the text area.  Give it a try.

                    <textarea class="mdl-textfield__input" type="text" rows= "3" id="area" ></textarea>
                    Type Here...

A: use replace and a regex then just Queue that up on keyup.
$(selector).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//will replace with commas

A: That problem proved to be more challenging than I expected (I should have known better). Here is what I got, using vanilla Javascript.
You can set event handler for the onkeyup event of the TextBox:
<asp:TextBox ID="txtAutoFormat" runat="server" onkeyup="processKeyUp(this, event)" />

And here is the Javascript code:

Credits:
CMS's solution to extract digits from string in Regex using javascript to return just numbers.
Alan Moore's regular expression to insert thousand separators in How do I add thousand separators with reg ex?.
Note: Ron Royston's idea of using toLocaleString is also very interesting. It could provide a more universal solution. You could replace this line of processKeyUp:
txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");

with the following:
txt.value = Number(extractNumber(value)).toLocaleString();

A: Try an input mask, here is an example:
http://digitalbush.com/projects/masked-input-plugin/

A: You can use jquery masking framework
references:
Jquery Masking
Source at git


Q: What is the name of the chemical Sulfur or Sulphur? Is the chemical Sulfur or Sulphur?

A: Sulfur vs. sulphur; the spelling difference is mainly a question of AmE vs other English speaking countries  as suggested by the Grammarist:

*

*For the pale yellow nonmetallic element found especially in volcanic deposits, sulfur is the usual spelling in American English.

*Sulphur is generally the preferred spelling in nonscientific texts from outside North America, but sulfur is gaining ground in scientific writing throughout the English-speaking world

*The spelling distinction extends to derivative words such as sulfuric/sulphuric, sulfate/sulphate, and sulfide/sulphide.

Etymology:

*

*Usually English words spelled with 'ph' are derived from Greek, where the 'ph' represents the Greek letter ‘phi’, but in this case the ultimate source of the word is Arabic.

*The word, from the French soufre, entered English around the end of the 14th century. Both modern spellings have been in use for many centuries, but sulphur prevailed by a wide margin until the Americans adopted sulfur around the start of the 20th century as shown in Ngram.

It is interesting to note that:

*

*The International Union of Pure and Applied Chemistry did indeed officially adopt the sulfur spelling in 1990; in 1992 the Royal Society of Chemistry followed suit, issuing a press release adopting sulfur as the official international nomenclature for atomic element 16.

*But while this might seem to settle the case once and for all, it’s clear that not all practising scientists have adopted the spelling change.  This is a good example of the difficulties of reforming established spellings, even in a relatively defined group of users.

(spellingtrouble.blogspot.it)


Q: How to debug application as root in Geany on Raspbian Jessie Having installed Geany on a Raspberry Pi and added the Debugger plugin, I need the debugger to run the application as root as I am accessing the GPIO libraries and pins on the Raspberry Pi.
I usually run the program using sudo ./programName
I cannot find an option in the debug settings to prefix the debug target with sudo.

A: Try running geany with sudo geany.


Q: MS Teams - TaskModule close the window I display a third party web page(client page) in the task module

*

*using Deeplink
https://teams.microsoft.com/l/task/botid?url=https:test.com/test.html&height=450&width=510&title=Custom+Form&completionBotId=botid

*new AdaptiveOpenUrlAction() { Title = "Enable MS Team access", Url = new Uri(DeeplinkHelper.DeepLink }

Here the web page is opening in Task module, I need to close this task module by clicking the button available on the web page(URL) and send the result to completionBotId.
Any sample pls that need to implement in client-side code.

A: There are two steps to make this work:

*

*you need to reference the Teams Javascript SDK in your web page

*When your user clicks the button, you would call microsoftTeams.tasks.submitTask  in your 'click' event handler. There are a few parameter options for this method, depending on whether you want it to send anything back to your bot. To simply close the window, call microsoftTeams.tasks.submitTask(null);, or if you want to send an object back, call microsoftTeams.tasks.submitTask(whateverObjectYouWantToSendBack);


Q: DialogWhenLarge adjustResize not working The activity theme is Theme.AppCompat.Light.DialogWhenLarge. I can not get the activity to resize when keyboard is up. Configuring android:windowSoftInputMode="adjustResize" or getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
 has no effect, all I'm getting is adjustPan behaviour. However, I can confirm that adjustNothing works. Any ideas how to make an activity with DialogWhenLarge theme to resize with keyboard?
Result with adjustResize:

Result with adjustNothing:

A: I've found a workaround, but would still like to hear if anyone had a similar problem.
Workaround:

*

*Replaced Activity's theme DialogWhenLarge with Theme.AppCompat.Light.Dialog. This allows the adjustResize to behave as expected with ActionBarActivity

*Added toolbar.xml layout as android.support.v7.widget.Toolbar

*Assigned the toolbar as action bar in my Activity

*Set activity's height for 10' tablets layout-sw720dp to 500dp for better presentation

Configure toolbar as action bar:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout...);

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);
}

More on toolbar at android developer blog and stackoverflow


Q: Interpretation of regression coefficients as percent change when the outcome is log-scaled? $X$ is democracy level
$Y$ is infant mortality rate (IMR)
In my model, 1 unit increase in $X$ predicts a $20\%$ decrease in $Y$
Does this mean 5 unit increase in $X$ will eradicate IMR? In other words, can I conclude that 5 unit increase in democracy predicts $100\%$ decrease in IMR?

A: The regression models of positive outcomes usually consider multiplicative decrease in outcome and additive change in predictor. Assuming model $\log Y=\beta X+\epsilon$. Then an additive change in $X$ by one unit changes $Y$ by a multiplicative factor $e^\beta$, which can be translated into percent change with $(e^\beta-1)\cdot 100$.
Increasing $X$ by five units i.e. $X=x_0+5$ gives us $Y=y_0 \cdot \exp(\beta)^5$ with $y_0=\epsilon \exp(\beta x_0)$. Assuming that

1 unit increase in X predicts a 20% decrease in Y

then $\exp(\beta)= 1-20/100=.8$ and for 5 units increase in $X$, $Y$ decreases by a factor $\exp(\beta)^5=0.8^5=0.33$. That is approx. $67\%$ decrease.
It is sometimes recommended to approximate the logarithm with $\log(z)=z-1$ which is what You implicitly do when You claim that the percantage change is equal to $\beta$. The approximation is only valid for small changes in $Y$. Thus, with a change in $X$ by one unit, the approximation gives $-19.5$ for a true value of $(e^\beta-1)\cdot 100=-17.71\%$ which is reasonably accurate. However, when $X$ changes by five units, the approximation fails. Approximation suggests a change by $-97.5\%$ while the true value is $(e^{5\beta}-1)\cdot 100=-62.28\%$. When in doubt avoid the approximation and perform the exact calculation.


Q: When drilling down, how to retrieve the parent? In a dimension I have
1st layer > 2nd layer
I display a chart with values from 1st layer and drilling down to 2nd layer when clicked on.
Once clicked, the graph displays value for the children, so 2nd layer only.
How do I retrieve and display the 1st layer that was clicked on ?

A: Charts can generate iccube-events for a couple of js events (I guess here on row click).
Check the image below :

Edit:
For a bar chart, use "On Navigate" event.


Q: How to add an image to be returned by a map in REACT (JS) I'm building a chatbox, on a card I have a messageList that I made with useState:

I'm trying to add images to the initMessageList to be displayed on the card with preview using useRef but it does not show the image (I'm changing the 'messageList' func):

function ConvBoard({ name }) {
const [initMessageList, setMessageList] = useState([])

const messageList = initMessageList.map((now, key) => {
    if (now.Image) {
        return
    }
    return <Message text={now.text} key={key} />
});

let newText = useRef(null);

const addMessage = () => {
    if (newText.current.value != "") {
        setMessageList([...initMessageList, {
            text: newText.current.value,
            key: initMessageList.length
        }])
        newText.current.value = ""
    }
}

const onKeyFunc = function onKeyEnter(e) {
    if (e.key === "Enter" && newText.current.value != "") {
        { addMessage() };
    }
}

const [image, setImage] = useState();
const [preview, setPreview] = useState();

const pressRef = useRef();

useEffect(() => {
    if (image) {
        const reader = new FileReader()
        reader.onloadend = () => {
            setPreview(reader.result)
        };
        reader.readAsDataURL(image)
        setMessageList([...initMessageList, {
            text: preview,
            key: initMessageList.length
        }])
    } else {
        setPreview(null)
    }
}, [image]);

return (
    <Tab.Pane eventKey={name}>
        <Card className='card'>
            <extraWarper className="extra">
                {messageList}
            </extraWarper>
        </Card>
        <InputGroup>
            <FormControl className='inputLine' ref={newText}
                placeholder="your text" onKeyPress={onKeyFunc}
            />
            <Button variant="outline-secondary">record</Button>
            <DropdownButton title="upload" variant="outline-secondary">
                <button onClick={(event) =>
                    pressRef.current.click()
                }>
                    Send image
                </button>
                <input ref={pressRef} id="filePicker" style={{ display: "none" }} type={"file"}
                    onChange={(event) => {
                        const file = event.target.files[0]
                        if (file) {
                            setImage(file)
                        } else {
                            setImage(null)
                        }
                    }
                    } />
            </DropdownButton>
            <Button variant="outline-secondary" onClick={addMessage}>send</Button>
        </InputGroup>

    </Tab.Pane>
);

export default ConvBoard
}
now the site looks like this:

but when i try to add an Image its blank.
Any ideas?
(Sorry for the mess, and thank you!)

A: There is no now.Image in this code.
    if (now.Image) {
        return
    }
    return <Message text={now.text} key={key} />
});

there may be now.Text which represents now.Image and preview in your code
because you set it in this part of code
 setMessageList([...initMessageList, {
            text: preview,
            key: initMessageList.length
        }])


Q: Should I migrate data using detach/copy/attach or through backup-restore-replay? I am about to embark on migrating database files to a new SAN (from an old SAN) abd I have a couple of options to implement this. (1) It was suggested that I look into the level of effort of restoring a full backup to a new database on the server. However, (2) my original plan was to copy the files from the old SAN to the new SAN by detaching and then reattaching the database.
My gut tells me that I'd rather detach, copy, and attach since it seems more fail-safe, but that may just be my naïvety. I don't want to miss a transaction or somehow "break something" in the process of renaming databases.
I guess my question is whether or not I am justified in my skepticism of the BACKUP-RESTORE-Replay option and what are other merits or risks of that option?

A: I used to move databases almost constantly, due to SAN reconfiguration and migrations.
Assuming that you are moving a whole server at a time, I would go with something like your path #2. (If you are moving one database at a time, and eventually doing every database on a server, that would be more problematic since you would have to be changing paths to the files.)
Note that "single_user" doesn't necessarily mean YOU. You could go to DBCC CHECKDB a database and not be able to get in because someone is already in there. Prepare a script that you can run to boot "everyone but you" out of a database and keep it in a handy place. Note that SQL 2000 doesn't have the same "keep everyone out" features as the more modern versions.
One old trick is to pause the SQL Server service. This will prevent new logins, but anyone who is already connected can continue as usual. So: connect via an SSMS window so you can do work, then pause the service, then kick out the undesirable connections, do your thing via SSMS command window (not the GUI, it makes and breaks lots of connections) and then un-pause the service. Warning: I'm not sure how that would play out on a cluster. It might want to failover.
It is handy to have a way to keep all app users out of a server until you are done your work. Otherwise, connections can start popping up while you are trying to do things, that can lead to resource contention and/or slowness. I have used the following ways in the past, depending on the exact situation:
Turning off the app server(s)
Use of ALTER DATABASE .. SET RESTRICTED_USER (If app accounts are members of db_owner, sysadmin or dbcreator roles, that's a problem.)
Telling the users that the system will be offline at some specific time, like a Sunday morning. (This won't work in a "for real" 24x7 environment.)
Unplugging the NIC that faces the app servers or users. (In this case, I could get in via another NIC connected to an admin-only network or through ILO.)
Detaching a large number of databases and reattaching them can be a lot of work. If you do that, make sure you have your "attach" script written ahead of time.
I've had plenty of success stopping the SQL Server, copying everything, changing the drive letters and starting SQL Server. No detach/attach. As long as SQL Server is off and you are copying (not MOVING) files, you can't get into too much trouble, even if you are moving the system databases. Since the paths are the same, SQL Server won't realize anything has changed while the service was off. Just make sure that you get the drive letters pointed back to the correct volumes or things will go badly for you.
My most frequent problem was not getting the ACLs on the file directories correct. More modern versions of SQL Server are better at setting just the permissions that the service account needs while older versions seem less fussy. If you forget to set the ACLs, and the service account isn't a local administrator (not that I'd recommend that), one or more databases may not open when the instance starts. Don't panic, just change the ACLs and attach the database.
I generally use ROBOCOPY to do this sort of work. There is a command line switch to preserve ACLs.
Using a CRC calculation/verification isn't a bad idea, but I've never done that. When the databases come back up, I do run CHECKDB() on all of them. I will usually prepare a script for this ahead of time, rather than relying on manually kicking off a maintenance job. That way, I can check a couple of smaller databases first before checking a large database which could take many minutes or hours to run. I doubt that a CRC check (or a Redgate Data Compare tool) would find something that CHECKDB() would miss, and if it did SQL Server wouldn't be able to fix it.
After I copy the files, but before I restart the instance, I will go and slightly change the filepath of the OLD folders by renaming one of the folders. This is an extra check against the "oops, the server is still pointing to the old files" problem.
Don't be in a hurry to drop the old files and recover space on the old storage and make double sure that your full backups have run successfully. Test restore a couple of those backups to somewhere else. Once you have good checkdb() runs and good full backups, then you can think about dropping that old storage and shutting down the Lefthand.
The worst problems I've had with these migrations have happened after I thought I was done. That would be the SAN admin telling me that something had happened and my file systems were scrambled. (Repartioned, reformatted, copied again.)
Another fun problem is the SAN being slow for no apparent reason. If you think that it will take 10 hours to copy your data and you are 30% copied at hour number 9, you have a problem. Watch the transfer times (robocopy shows % copied and gives time estimates, or you can use Perfmon) and have a fallback plan if something goes wierd.
Also, I am not sure if your volumes will be partitioned for you, but you might want to be sure that they are using a 1 MB offset. On Windows Server 2008 and better, this should not be a problem. On older OS, it is. There is a ton of googlable stuff on this, and your storage guys should know about it, but I'd ask.

A: First I would look at the option of simply using the feature of the storage array to handle the data moving.  If those aren't available because the vendor doesn't support it, you didn't purchase it, or the SAN admin doesn't know how to do it...
Then I'd simply use the following steps.

*

*Present the new storage to the SQL Server.

*Stop the SQL Services

*COPY all the data from the old drive to the new drive (don't forget to include the permissions if using robocopy)

*Remove the drive letters from the old drives.

*Change the drive letters on the new drives to match the old drive letters

*Start the SQL Services

That's it.
There's no detach / attach needed as, as far as SQL Server knows nothing has changed.  And if something does go horribly wrong, you've got the old copy of the databases sitting on the old LUN on the old storage array.  Failing back is just a matter of changing the drive letters around.

A: Personally, I would avoid the detach/attach mechanisms. Especially in SQL Server 2000, I just don't trust that you will always bring the server back up and be able to attach those files. I've heard plenty of stories where this didn't happen cleanly - just because you have a Plan B doesn't automatically make Plan A sensible.
With backup / restore, you don't risk having to go to Plan B. If the backup fails, your database is still up. If restore fails, your old database is still up. In both cases you can restore the operation of the original database and revisit the plan later. In addition to the extra security here over stopping SQL Server and/or detaching, this also means you can test the hoo-has out of the backup/restore methodology (assuming you currently have the space to perform the backups and another instance to test the restore). You can't really test the detach approach without detaching the databases or stopping SQL Server, and that's tough to do outside of a proper maintenance window. And finally, with the other approaches you can't even start copying the files until you've detached or brought SQL Server down. With backup/restore you can have the .bak file waiting on the new storage long before you take the last log backup and start your maintenance window.
One other benefit over the pull-the-drive-out-from-under-SQL-Server method: with backup/restore you can move various files to different drive letters than they were before. For example when we migrated to a new SAN, we were able to have more volumes, so we could move tempdb to T:\ (which didn't exist before), some of the data and log files to new drive letters, etc. to better utilize all the new I/O capacity we had. If you simply shut down SQL Server and then swap out the disks, you need to have the same drive letters and the same number of volumes.


Q: Mysql SELECT query returns false when ran in PHP I'm trying:
$mysqli = new mysqli(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$usernames_results = $mysqli->query("SELECT username FROM users WHERE user_id = $member_id") or trigger_error($mysqli->error);
while($user_row = $username_results->fetch_object()) {
// do stuff with$user_row
}

This always returns FALSE. I'm certain $member_id is not null and that it does exist in the database. I ran the SQL query directly on the database and it returns the correct result. The error I get is

Fatal error: Call to a member function fetch_object() on a non-object`

when calling fetch_object() on $usernames_results.
$mysqli is also defined correctly because this works:
$conversations_results = $mysqli->query("SELECT UserID, ConversationID FROM Conversation_Members WHERE UserID = $user_id");

I have tried looking at $mysqli->error but it's empty.
What am I doing wrong in the first query?
This question has been wrongly marked duplicate before. Please do not mark this as a duplicate unless you're certain the suggested duplicate answers my problem.