text:
Q: If $\alpha=(a_1a_2...a_k)$ is a $k$-cycle, then $\alpha^i(a_j)=a_{(j+i)\text{ mod }k}$. I am trying to show that if $\alpha=(a_1a_2...a_k)$ is a $k$-cycle, then for all $i\in\{1,2,...,k\}$ we have $\alpha^i(a_j)=a_{(j+i)\text{ mod }k}$. I was hoping folks could check my proof and perhaps comment on if it's more natural to use simple induction or strong induction.
Proof: (strong)
When $i=1$, if $j<k$ then by definition of the cycle $\alpha=(a_1a_2...a_k)$ we have $\alpha(a_j)=a_{(j+1)}=a_{(j+1)\text{ mod }k}$ since $j+1\leq k$ if $j<k$ and $a_{0 \text{ mod } k}= a_{k\text{ mod } k}$. If $j=k$, then again by definition of the cycle $\alpha=(a_1a_2...a_k)$ we have $\alpha(a_j)=\alpha(a_k)=a_1=a_{(k+1)\text{ mod }k}$.
Now assume by induction that for all $i$ less than $k$ and greater than $1$ that $\alpha^i(a_j)=a_{(j+i)\text{ mod }k}$ holds. Let $i=k$. Then $$\alpha^i(a_j)=\alpha^k(a_j)=\alpha(\alpha^{k-1}(a_j))$$ but by the induction hypothesis $\alpha^{k-1}(a_j)=a_{(j+k-1)\text{ mod }k}$ so $$\alpha^i(a_j)=\alpha^k(a_j)=\alpha(\alpha^{k-1}(a_j))=\alpha(a_{(j+k-1)\text{ mod }k}).$$

Now, since $(j+k-1)\text{ mod }k +1 =(j+k-1)\text{ mod }k+(1)\text{ mod }k=(j+k)\text{ mod }k$ and $(j+k-1)\text{ mod }k\leq k $ we have

again by definition of the cycle $\alpha=(a_1a_2...a_k)$ that:
$$\alpha(a_{(j+k-1)\text{ mod }k})=a_{(j+k)\text{ mod }k}=a_{(j+i)\text{ mod }k}$$
so $\alpha^i(a_j)=a_{(j+i)\text{ mod }k}$. Thus the claim holds for $i=k$, and by induction $\alpha^i(a_j)=a_{(j+i)\text{ mod }k}$ holds for any $k$-cycle where $k\in\mathbb{Z^+}$. $\blacksquare$
Proof: (simple)
When $i=1$, if $j<k$ then by definition of the cycle $\alpha=(a_1a_2...a_k)$ we have $\alpha(a_j)=a_{(j+1)}=a_{(j+1)\text{ mod }k}$ since $j+1\leq k$ if $j<k$ and $a_{0 \text{ mod } k}= a_{k\text{ mod } k}$. If $j=k$, then again by definition of the cycle $\alpha=(a_1a_2...a_k)$ we have $\alpha(a_j)=\alpha(a_k)=a_1=a_{(k+1)\text{ mod }k}$.
Now assume by induction that $\alpha^i(a_j)=a_{(j+i)\text{ mod }k}$ holds for some $i\in\{1,2,...,k\}$. Then by the induction hypothesis: $$\alpha^{i+1}(a_j)=\alpha(\alpha^i(a_j)=\alpha(a_{(j+i)\text{ mod }k})$$

so by definition of the cycle $\alpha=(a_1a_2...a_k)$ and that $(j+i)\text{ mod }k\leq k$ we have

$$\alpha(a_{(j+i)\text{ mod }k})=a_{(j+i+1)\text{ mod }k}.$$
Hence the claim holds for all $i$ in $\{1,2,...k\}$ and for all integers $k$. $\blacksquare$
Are there any gaps, specifically in the induction step(s) highlighted? I'm concerned I'm not properly accounting for the cases when the element is the last in the cycle $(=k)$. Thanks in advance!

A: As for your main focus (expressed in a comment), let's start from the definition of $k$-cycle:
$\alpha(a_i)=a_{i+1}$, for $i=1,\dots,k-1$
$\alpha(a_k)=a_1$

Step to get insight on the formula to be proven by induction:
$\alpha^2(a_i)=\alpha(a_{i+1})=a_{i+2}$, for $i=1,\dots,k-2$
$\alpha^2(a_{k-1})=\alpha(\alpha(a_{k-1}))=\alpha(a_k)=a_1$
$\alpha^2(a_{k})=\alpha(\alpha(a_{k}))=\alpha(a_1)=a_2$
So, the proper definition of the $j$-th power of $\alpha$, $1\le j\le k$, relies on the splitting of the set $\{1,\dots, k\}$ into $\{1,\dots, k-j\}$ and $\{k-j+1,\dots, k\}$, which must be part of the induction process.

Induction:
Inductive hypothesis ("i.h."):

*

*$\alpha^j(a_i)=a_{i+j}$, for $i=1,\dots,k-j$

*$\alpha^j(a_{k-j+l})=a_l$, for $l=1,\dots,j$
For $j=1$ we retrieve the definition of $k$-cycle. Now the case $j+1$:

*

*for $i=1,\dots,k-(j+1)$, we get: $\alpha^{j+1}(a_i)=$ $\alpha(\alpha^j(a_i))\stackrel{(i.h.)}{=}$ $\alpha(a_{i+j})\stackrel{(j+1\le i+j\le k-1)}{=}a_{i+(j+1)}$;

*for $l=1,\dots,j+1$, we get: $\alpha^{j+1}(a_{k-(j+1)+l})=$ $\alpha(\alpha^j(a_{k-(j+1)+l}))=$ $\alpha(\alpha^j(a_{k-j+(l-1)}))$; now:

*

*for $l=1$, we get: $\alpha(\alpha^j(a_{k-j+(l-1)}))=$ $\alpha(\alpha^j(a_{k-j}))\stackrel{(i.h.,\text{ part 1})}{=}$ $\alpha(a_k)=a_1$;

*for $l=2,\dots,j+1$, we get: $\alpha(\alpha^j(a_{k-j+(l-1)}))\stackrel{(i.h.,\text{ part 2})}{=}$ $\alpha(a_{l-1})=$ $a_l$,

and hence $\alpha^{j+1}(a_{k-(j+1)+l})=a_l$ for every $l=1,\dots,j+1$. $\space\Box$

For $j<k$, from the part 1 follows $\alpha^j(a_1)=a_{j+1}\ne a_1$, and hence $\alpha^j\ne Id$.
On the other hand, for $j=k$, part 2 tells the whole story, which is: $\alpha^k(a_l)=a_l$, for $l=1,\dots,k$, namely $\alpha^k=Id$.
Therefore, $\left|\alpha\right|=k$.


text:
Q: Using For loop Int in DataGridView.Rows[] In my WFA project (C#) i need to read all DataGridView values to arrays.I want to use for loop.
For example, for first row i have tried to use i = 0 value and tried to read values to arrays.
Like;
string[] Array1 = new string[2];
for (int i = 0; i < NumOfRow; i +=1)
  {
    string [0] = dgv1.Rows[i].Cells["Total1"].Value.ToString();
    string [1] = dgv1.Rows[i].Cells["Total2"].Value.ToString();
    string [2] = dgv1.Rows[i].Cells["Total3"].Value.ToString();
  }

And i am getting error, no value for "i". I am trying to use it in Print action. I give value in BeginPrint event too.

A: your code is correct but it seems there are some error like you did not use correct pocket size for array and 2nd you missed array name while assigning values to array.
following are the example for your help.
string[] Array1 = new string[3];

                for (int i = 0; i < dataGridView1.Rows.Count; i +=1)
                {
                    Array1 [0] = dataGridView1.Rows[i].Cells[0].Value.ToString();
                    Array1 [1] = dataGridView1.Rows[i].Cells[1].Value.ToString();
                    Array1 [2] = dataGridView1.Rows[i].Cells[2].Value.ToString();
                }

A: i think you want something more like this:
List<string[]> allValues = new List<string[]>();
foreach(var row in dvg1.Rows)
{
    string[] arr = new string[3];
    arr[0] = row.Cells["Total1"].Value.ToString();
    arr[1] = row.Cells["Total2"].Value.ToString();
    arr[2] = row.Cells["Total3"].Value.ToString();

    allValues.add(arr);
}

I'm not sure why I've been downvoted. Aside from your compiler errors, I'm trying to address your issue of overwriting yourself with each iteration through the loop.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prevent Mono from being cancelled? I am trying to implement something as a "race condition". This race condition must follow these situations:

*

*Fire two simultaneous HTTP calls.

*Return the response from the first call that was completed successfully.

*Handle the last call. (The most important thing here is that I can not discard the last call, I do need to handle the result of it: whatever its status, success or fail).

This sample of code is the most close of the solution that I have achieved:
    Mono<StatusMock> monoA = webClient.get()
      .uri("https://some.url.a")
      .retrieve()
      .bodyToMono(StatusMock.class)
      .subscribeOn(Schedulers.boundedElastic());

    Mono<StatusMock> monoB = webClient.get()
      .uri("https://some.url.b")
      .retrieve()
      .bodyToMono(StatusMock.class)
      .doOnSuccess(this::verifyBody)
      .onErrorStop()
      .subscribeOn(Schedulers.boundedElastic());

    StatusMock statusMock = Flux.first(monoA, monoB)
      .blockFirst();

    if (statusMock != null) {
      return statusMock.getStatus();
    }

    return "empty";
  }

  private void verifyBody(StatusMock statusMock) {
    if (statusMock.getStatus().contains("error")) {
      log.error("throwing an exception");
      throw new RuntimeException("error");
    }
  }

public class StatusMock {

  private String status; // getters and setters implicit
}

In this example I used the Flux.first method, and it helps me a lot returning the first call, but it discards (cancel) the second one which is a problem since I need the result of the last call as well.
Is there any solution to this logic? Here I am using Spring Project Reactor, but I accept any library or framework that could help me with this situation.

A: You can use cache operator on the Monos to prevent them from being cancelled:
    Mono<StatusMock> monoA = webClient.get()
      // ...
      .cache();

    Mono<StatusMock> monoB = webClient.get()
      // ...
      .cache();

    Mono.firstWithSignal(monoA, monoB);


text:
Q: Express.js or angular routes for serving pug templates in a MEAN application? I'm a bit new to Mean Stack development and cant figure out how to approach the issue of serving my pug templates. Option One is having it confgured through angular and compile html with gulp. The other option is having it rendered through Express.  In last case I ran into an issue that express does not register angular ui route change hence the template is not being rendered. It only runs if I manully run the url.
Just in case here are my files so far
express routes
const express = require('express');
const router = express.Router();
const mid = require('../middleware');

// GET /

router.get('/', function(req, res, next) {
    // return res.render('index', { title: 'Home' });
});

// GET /about
router.get('/tutorials', function(req, res, next) {
    // return res.render('tutorials', { title: 'Tutorials' });;
});

// GET /contact
router.get('/contact', function(req, res, next) {
    // return res.render('contact', { title: 'Contact' });
});

module.exports = router;

Angular App.js
'use strict';

var app = angular.module('myApp', ['ui.router']);

app.config(['$locationProvider','$stateProvider', '$urlRouterProvider',
    function($locationProvider, $stateProvider, $urlRouterProvider) {

  $locationProvider.html5Mode({
    enabled: true,
    requireBase: false
  });

  $stateProvider
    .state('home',{
      url: "/",
      templateUrl: "views/index"
    })
    .state('tutorials',{
        url: "/tutorials",
      templateUrl: "views/tutorials"
    })
    .state('contact',{
      url: "/contact",
      templateUrl: "views/contact"
    });

    $urlRouterProvider.when('', '/');
    $urlRouterProvider.otherwise("/");

}]);

Express App.js (Configuration File)
'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const app = express();

const stFolder = '/src';

// parse incoming requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// serve static files from /public
app.use(express.static(__dirname + `${stFolder}/public`));

// view engine setup
app.set('view engine', 'pug');
app.set('views', __dirname + `${stFolder}/views`);

app.get('/partials/:filename', routes.partials);
app.use(routes.index);

// include routes
var routes = require(`.${stFolder}/routes/index`);

app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('File Not Found');
  err.status = 404;
  next(err);
});

// error handler
// define as the last app.use callback
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

// listen on port 3000
const port = 3000;
app.listen(port, function () {
  console.log(`App is running on localhost:${port}`);
});


text:
Q: Конвертирование строки char* в байт код. Превратить hexdump "89 C2" в байты {0x89, 0xC2} Добрый день, подскажите, как преобразовать строку вида:
UCHAR bytes[] = "89 C2 48 89 F9 E8 CE 55";

В массив байт:
UCHAR bytes[] = {0x89,0xC2,0x48,0x89,0xF9,0xE8,0xCE,0x55}
/*UCHAR bytes[] = "\x89\xC2\x48\x89\xF9\xE8\xCE\x55";*/

пояснение:
т.е мне нужна функция, на входе которой подается строка (массив символов) - сигнатура массива байт и она преобразуется в массив байт , т.е. 89 это не символы 8 и 9, а HEX код символа '‰' , (HEX)C2 = (INT)62 ='В' и т.д.

A: В одну строчку :)
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>

int main()
{
  const char str[] = "89 C2 48 89 F9 E8 CE 55";
  unsigned char bytes[256];

  unsigned char *e = std::copy(std::istream_iterator<unsigned>(std::istringstream(str) >> std::hex), std::istream_iterator<unsigned>(), bytes);

  std::copy(bytes, e, std::ostream_iterator<unsigned>(std::cout << std::hex, " "));
  std::cout << std::endl;
}

или, с std::vector в качестве получателя
const char str[] = "89 C2 48 89 F9 E8 CE 55";
std::vector<unsigned char> bytes;

std::copy(std::istream_iterator<unsigned>(std::istringstream(str) >> std::hex), std::istream_iterator<unsigned>(), std::back_inserter(bytes));

В качестве побочного замечания можно обратить внимание на то, что
std::istream_iterator<unsigned>(std::istringstream(str))

является некорректным выражением (из-за того, что конструктор std::istream_iterator принимает неконстантную ссылку), а вот
std::istream_iterator<unsigned>(std::istringstream(str) >> std::hex)

уже вполне корректно. Некоторые правила языка С++ временами приводят к внешне нелогичным результатам...

A: Ну например так:
char s[] = "89 C2 48 89 F9 E8 CE 55";
std::vector<UCHAR> result;
std::istringstream iss(s);
unsigned b;
while (iss >> std::hex >> b)
    result.push_back(b);

Если нужен именно массив, то придётся подсчитать длину вручную:
char s[] = "89 C2 48 89 F9 E8 CE 55";
size_t len = (std::strlen(s) + 1) / 3; // или sizeof(s) / sizeof(*s), если это таки массив,
UCHAR* result = new UCHAR[len];        // а не указатель
std::istringstream iss(s);
unsigned b;
UCHAR* p = result;
while (iss >> std::hex >> b)
    *p++ = b;

A: Сделал вот такое чудо ^_^, но работает как часы
byte* CharToByte(char* str_sign_WithSpace, int& sizeOfByteArray)
{
printf("strlen_do = %llu\n",strlen(str_sign_WithSpace));

//Прогоняем строку на пробелы, вырезаем все спеймы (trim all space)
char str_sign[256];
int ij = 0;
do
{
    if (*str_sign_WithSpace != ' ')
    {
        str_sign[ij] = *str_sign_WithSpace;
        ij++;
    }
} while (*str_sign_WithSpace++);

printf("strlen_posle = %llu\n", strlen(str_sign));

unsigned char* ret_ByteArray = new unsigned char[strlen(str_sign)/2];
char** mass_char = new char*[strlen(str_sign)/2];
for (int i(0); i < strlen(str_sign) / 2; i++)
    mass_char[i] = new char[3]{0};

for (int i(0), j(0); i < strlen(str_sign) / 2; i++, j += 2)
{
    if(*(str_sign + j) !='x' || *(str_sign + j) != 'X')
    strncpy(mass_char[i], str_sign + j, 2);
    else
    strncpy(mass_char[i], "00", 2);
    mass_char[i] += '\0';
}

for (int i(0); i < strlen(str_sign) / 2; i++)
{
    printf("mass_CHAR[%i] = %s\n", i, mass_char[i]);
    ret_ByteArray[i] = strtol(mass_char[i],&mass_char[i],16);
    printf("mass_byte[%i]=%X\n", i, ret_ByteArray[i]);
}
sizeOfByteArray = strlen(str_sign)/2;
delete[] mass_char;
return ret_ByteArray;
}

Ну и для проверочки:
char* str_sign_Space = "48xxxxxxxxxxxx48xxxxxxxxxxxx75xx48xxxxxxxxxxxxF6xxxxxxxxxxxx74xxF3xxxxxxxxxxxxxxxx83xxxxxxxxxxxx76xxF3xxxxxxxxxx80xxxxxxxxxxxx74xx80xxxxxxxxxxxx74xxF3xxxxxxxxxxF3xxxxxxxx"; //Строка
int size;
byte* MyByteArray = CharToByte(str_sign_Space, size);

for (int i(0); i < size; i++)
    printf("%X", MyByteArray[i]);

delete[] MyByteArray;
system("pause");
return 0;

В функции присутствует удаление пробелов и замена xx || XX в сигнатуре на 0.

A: unhexlify можно реализовать через std::strtol() (пренебрегая обработкой ошибок):
#include <cstdlib>
#include <iostream>

int main()
{
  char hexstr[] = "68 65 6C 6C 6F", bytes[(sizeof hexstr) / 3 + 1] = {};
  char *p = hexstr, *end = nullptr, *pbyte = bytes;
  for (long byte = std::strtol(p, &end, 16); p != end;
            byte = std::strtol(p, &end, 16)) {
    *pbyte++ = byte;
    p = end;
  }
  std::cout << bytes << std::endl;
}

Пример:
$ c++ -std=c++11 *.cc && ./a.out
hello


text:
Q: SQL View From a View Running Slow I created a view that pulls data from another view and it is running extremely slow.  The original view runs fine so I'm not sure what the hold up would be.  Is this typically an issue when querying off a view?

A: I did some brief research and can conclude that you'll have a hard time maintaining efficient nested views. In short, your SQL Server query optimizer is going to have a near-impossible time figuring out how to quickly execute your query. At best it has to execute three statements: Source statement, View 1, View 2 (Nested). Without indexes on the tables and views performance is going to continually be slow because it's running so many operations.
You'd be much better off by searching for an alternate solution to your nested view, such as replicating your SELECT statement from your first view within your nested view. The duplication is also less than ideal, but it means that your optimizer won't have to work so hard. You can also look into applying indexes to your views. When done properly, you will improve SELECT performance while sacrificing speed when you perform INSERT operations. This should be done if you don't expect your source table to change too often, but is probably the best solution available if you can't restructure view layout.

A: Probably you use some filters on both internal (fast) and external (slow) views.
Make sure that filters used on the external view are best 'linked' to the internal view. Best 'linked' means that if e.g. at the external view you use some more tables and join the internal view, try to join with filter columns as well or with the lower detail base table.


text:
Q: Codeigniter Multi Insert Query I couldn't find any proper example how to execute multiple insert query in codeigniter. I already tried make a function in models, containing more than 1 insert query. What I get always first query success, and others not executed at all.
I've already try use transaction: $this->db->trans_start();
In my case below: $db->trans_start();  and off course $db->trans_complete();
But that didn't help. Always only first insert query that executed. What should I do to execute all insert/update/delete queries in one fuction?
Example:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Deposit_model extends CI_Model
{
     function __construct()
     {
          // Call the Model constructor
          parent::__construct();

     }

     public function inputdeh()
     {
            $this->load->helper('url');
            $CI =& get_instance();
            $db = $CI->load->database( 'local', TRUE );

            $id_member = $this->input->post('id_member');
            $jumlah = $this->input->post('jumlah');
            $ket1 = $this->input->post('ket');
            $ket = 'WEB/'.$ket1;

        $saldoawal = $db->query("select saldo from member where id_member='$id_member'");
        $saldoawa['saldo'] = $saldoawal->row('saldo');
        $saldoaw = $saldoawa['saldo'];

        $saldoak = $saldoaw + $jumlah;
        //$_POST[jumlah]=number_format($_POST['jumlah'],".");
        //$saldoak = number_format($saldoak);
        //$dep = number_format(floatval($jumlah));

        $result = $db->query("select nama from member where id_member='$id_member'");
        $namar['nama'] = $result->row('nama');
        $nama = $namar['nama'];

        $resulthp = $db->query("select hp from member_hp where id_member='$id_member' LIMIT 1 OFFSET 0");
        $hpr['hp'] = $resulthp->row('hp');
        $nohp = $hpr['hp'];

        //$now = 'NOW()';
        $user = 'adminweb';

        $data = array(
        'id_member' => $this->input->post('id_member'),
        'nama' => $nama,
        'jml' => $this->input->post('jumlah'),
        'saldo_awal' => $saldoaw,
        'saldo_akhir' => $saldoak,
        'kode_trx' => '1',
        'status' => '1',
        'ket' => $ket,
        'user_input' => $user,
        );
        $db->set('tgl_transaksi', 'NOW()', FALSE);
        $db->set('tgl_input', 'NOW()', FALSE);

        return $db->insert('transaksi', $data);

        $logsaldodata = array(
        'id_member' => $this->input->post('id_member'),
        'saldo' => $saldoaw,
        'act' => $this->input->post('jumlah'),
        'ket' => 'Deposit Tambah~True#',
        );
        $db->set('tgl', 'NOW()', FALSE);
        $db->set('ref', 'last_insert_id()', FALSE);
        return $db->insert('log_saldo', $logsaldodata);
}
}

A: Of course, you're returning before executing the rest of the code!
$db->set('tgl_input', 'NOW()', FALSE);
return $db->insert('transaksi', $data); // <-- remove the keyword here
$logsaldodata = array(

Remove that intermediate return statement, just leave $db->insert('transaksi', $data). return stops the function and returns the result, the rest of the function code won't be executed.


text:
Q: Does Duplication also re-roll Modifiers? When equipment drops it generally has a Modifier on it giving it some extra stats and a prefix.
With the latest update to Terraria adding Journey Mode and the ability to Research and Duplicate items and blocks. while playing around in Journey Mode i saw that i only had to give up 1 Shackle to allow it for duplication, though i didn't give it up because i was more playing around with blocks.
So i am wondering if Journey Mode's Duplication for Equipment also rerolls Modifiers, ie. if i gave up a Demonic Shackles, would i get a different Modifier when i duplicate it? the same? or just regular Shackles?

A: Duplicated accessories and weapons have no modifier at all. This is pretty easy to test with any of the starting equipment, as it only takes one weapon or accessory to fully research them.


text:
Q: Need guidance on drawing PNGs into a Delphi XE6 TDrawGrid I'm using a drawgrid to display a "dungeon" map. I have an array filled with data describing what types of physical features are located in each cell. The basic layout of rooms and corridors, etc. There's a PNG for each permutation.
I'm trying to "draw" the map by drawing the appropriate PNG into each cell of the drawgrid. I can do it more or less directly using DrawGrid1.Canvas.Draw(x,y,pngImage), but figuring out the exact x,y in pixels is frustrating because of the gridlines (at least, I'm finding it frustrating), and I'm not sure what other issues I'll run into down the road.
I also tried pngImage.Draw(DrawGrid1.Canvas,Rect), but once again, I have to calculate the Rect, which really seems unnecessary as the cells and PNGs are all 40x40 pixels.
Reading related articles and examples, OnDrawCell seems to be a better way, because given ARow and ACol, the Rect for the given cell is apparently precalculated (unless I'm misinterpreting what I've read in several places). But none of the examples I've found actually show how OnDrawCell is triggered. The easy answer "when something gets drawn into a cell" doesn't really explain it much better. That's what I'm trying to do.
(I've often found this to be the case with Delphi's documentation: How is explained (not always exactly for your given use case), but when or why is left shrouded in mystery..)
Of course, there are a few other things to figure out as well, like controlling the drawgrid so it doesn't erase the PNG when a cell is clicked..
Any relevant suggestions will be greatly appreciated. TFRM

A: Why is figuring out exact X and Y in pixels so hard? It is actually pretty simple.
In order to get left border of your rectangle you simply multiply width of you column plus width of your gridline by number of the column. And if you have gridline on the very left of the first column then add the width of your gridline.
And in order to get right border of your rectangle simply add width of the column to the previous result.
And for calculating Y you just use height instead of width
So the code would look something like this (written from my mind and untested)
const
  CellWidth = 40;
  CellHeight = 40;
  GridLineThickness = 1;

procedure DrawCell(Row, Column: Integer; Image: Bitmap);
var Rect: TRect;
begin
  Rect.Left := ((CellWidth + GridLineThickness) * Column) + GridLineThickness;
  Rect.Right := Rect.Left + CellWidth;
  Rect.Top := ((CellHeight + GridLineThickness) * Row) + GridLineThickness;
  Rect.Bottom := Rect.Top + CellHeight;
  PaintBox1.Canvas.StretchDraw(Rect, Image);
end;

And if you want an ability to zoom in or zoom out just multiply the CellWidth and CellHeight by a zoom factor. And when being zoomed out a lot just omit rendering grid lines.


text:
Q: How to unit test just one function, without browser, on Angular Let's say I have a function that performs a very long calculation:
export const veryLongCalculation = () => 1 + 1;

How can I unit test this function in Angular without opening Karma and without configuring anything else?
I would like to write a test like this one:
describe('Difficult Calculations', () => {
  it('should calculate', () => {
    const calcul = veryLongCalculation();
    expect(calcul).toBe(2);
  });
})

If I run ng test it starts Karma and the browser (and takes ages).
Can I run just that test without opening a browser and initializing everything? I guess there should be a command to do it, already configured. How?

A: I suggest trying Chrome in headless mode. This way Karma and Chrome remain, but the browser window won't be opened and the process will be quicker.
To test it add a script to package.json:
"test-headless": "ng test --watch=false --browsers=ChromeHeadless"

And run it using npm run test-headless.
Note that an Angular-based code runs in a browser, so it is highly recommended to run the test suits in a browser. Otherwise, the tests could have false positive/negative results.


text:
Q: Php Local Host and server are different result I have created script for lk domain search.
this is the code
<form action="" method="GET">
    <input type="text" name="dm" placeholder="tx">
</form>

<?php

if (isset($_GET["dm"])) {

    $domain = $_GET["dm"];

    $res = file_get_contents("https://www.domains.lk/domainsearch/doDomainSearch?domainname=$domain");

    echo $domain;
}

?>

<script type="text/javascript">

    var data = '<?php echo $res ?>';

    document.write(data);

</script>

var data will show in local host. but i have hosted it in my server then result will not show.
this is server hosted file http://vishmaloke.com/dm/ser.php

A:
SOLUTION #1

There is PHP setting by name allow_url_fopen. This must be enable to get content from remote url. You can do it via .htaccess file.
Put following line in an .htaccess file in the directory you want the setting to be enabled:
php_value allow_url_fopen On

Note: This above setting will apply only into same directory where .htaccess file placed.

SOLUTION #2

Alternatively you can update php.ini
PHP.INI UPDATE
add following line to php.ini
allow_url_fopen = On;

SOLUTION 3

It is recommended to use curl instead of file_get_contents
CURL UPDATE
if (isset($_GET["dm"]))
{

    $domain = $_GET["dm"];

    // curl
    $curl_handle=curl_init();
    curl_setopt($curl_handle, CURLOPT_URL,"https://www.domains.lk/domainsearch/doDomainSearch?domainname=$domain");
    curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($curl_handle);
    curl_close($curl_handle);

    echo $domain;
}


text:
Q: How to inject servletcontext for junit test cases which are autowired in source controller I have a controller class in which, servletContext is autowired.
@Controller
public class BaseController {
    @Autowired
    private ServletContext servletContext;

protected ServletContext getServletContext() {
        return servletContext;
    }

    public Object getBean(String beanName) {

        ApplicationContext appContext =    WebApplicationContextUtils.getWebApplicationContext(this.servletContext);
        return appContext.getBean(beanName);
    }
}

The getBean() in BaseController is used by many methods in subclasses extending it.
When I tried to execute jUnit test cases for the methods in subclasses (which were invoking getBean()), I was getting the below error.
java.lang.IllegalArgumentException: ServletContext must not be null

I am unable to load web.xml while running junit.
Can someone please help in explaining , on how to set servlet context from JUnit ? If MockServletContext is the solution, please provide a code snippet on how to inject MockServletContext, to the autowired servletContext in the controller.
Note : There is no setServletContext() in BaseController

A: You could set the servletContext with PowerMock's WhiteBox.
WhiteBox.setInternalState(controller, "servletContext", yourServletContext);


text:
Q: MYSQL: #1525 - Incorrect DATE value: '', Error when selecting a blank date I am migrating my project from php 5.6 to 7 but here mysql is also updated when i try to select a data and check if date is empty or not i have applied check in where clause that WHERE date is '' means empty not NULL. but when i execute this query on php 7 dates it says  #1525 - Incorrect DATE value: ''. Anyone please help me. I have applied this on multiple sides of a complete project.

A: You can try to play with the sql-mode of mysql.
https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html
There are options, like ALLOW_INVALID_DATES.
Check the changed default behaivior of mysql in newer versions. MySQL8 runs with enabled sql-mode-options:
ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, and NO_ENGINE_SUBSTITUTION
The first one is quite interessting, because it requires all columns of "GROUP BY"-Statements in the SELECT-output. It costs me lots of time, to find out this problem. I still can not understand the added value of this change.


text:
Q: Jquery date difference I have this code for calculating date difference (without weekends) between two input fields, and printing the difference in days in a third text box. The date format is yy-mm-dd (because of mysql).
<script type="text/javascript">

    $("#vazi_od, #vazi_do").change(function() {

    var d1 = $("#vazi_od").val();
    var d2 = $("#vazi_do").val();

            var minutes = 1000*60;
            var hours = minutes*60;
            var day = hours*24;

            var vazi_od1 = getDateFromFormat(d1, "yy-mm-dd");
            var vazi_do1 = getDateFromFormat(d2, "yy-mm-dd");

            var newvazi_od=new Date();
            newvazi_od.setFullYear(vazi_od1.getYear(),vazi_od1.getMonth(),vazi_od1.getDay());
            var newvazi_do=new Date();
            newvazi_do.setFullYear(vazi_do1.getYear(),vazi_do1.getMonth(),vazi_do1.getDay());
            var days = calcBusinessDays(newvazi_od,newvazi_do);
      if(days>0)
    { $("#razlika").val(days);}
    else
    { $("#razlika").val(0);}
 });
 </script>

But, when i pick the start and the end date, nothing happens in the field that should show the difference in days... Any help?

A: You are using setFullYear to pass all the date params...
setFullYear is just for setting the year part of the date..
Use
var newvazi_od=new Date(vazi_od1.getYear(),vazi_od1.getMonth(),vazi_od1.getDay());
var var newvazi_do=new Date(vazi_do1.getYear(),vazi_do1.getMonth(),vazi_do1.getDay());

Also to use getDateFromFormat and calcBusinessDays you need to include the date library from the javascript toolbox


text:
Q: Run a target from a custom target in CMake I have the following file structure:
├── Generator/
│   ├── output/
│   └── script.py
│
└── FinalProgram/
    ├── build/
    ├── src/
    │   └── main.cpp
    ├── include/
    │   └── MyClass.h
    └── CMakeLists.txt

The Generator/script.py file is a script that generates c++ files in the Generator/output folder. That script can be launched with two different arguments (SimA and SimB), each one generating a different set of files.
On the other hand, the FinalProgram needs to use that set of generated files, so every time I want to compile the FinalProgram with the SimA set of files, I have to
cd Generator
./script.py SimA
cp output/*.cpp ../FinalProgram/src
cp output/*.h   ../FinalProgram/include
cd ../FinalProgram/build && cmake ..
make

What I want is to be able to type
make SimA

Or
make SimB

So everything happens automatically. In both cases the executable must be the same, so obviously I cannot have two different add_executable blocks. I guess I should create two add_custom_target blocks, one for each possible value, do all the work there and finally call the target that compiles everything. Hence, the real question is, how can I run another target from within an add_custom_target block? Of course, I guess I could use
COMMAND make

But that... that makes me cry. Isn't there a better way?

A: As MadScienceDreams mentioned, you can use add_custom_command to generate the c++ file, then you can use generated file in add_executable command.
add_custom_command(OUTPUT ${CMAKE_SOURCE_DIR}/../Generator/output/SimA.cpp
                   COMMAND ${PYTHON_EXECUTABLE} script.py SimA
                   DEPENDS ${CMAKE_SOURCE_DIR}/../Generator/script.py
                   WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/../Generator)

set_property(SOURCE ${CMAKE_SOURCE_DIR}/../Generator/output/SimA.cpp PROPERTY GENERATED TRUE)

add_executable(SimA ${CMAKE_SOURCE_DIR}/../Generator/output/SimA.cpp ...)

add_custom_command(OUTPUT ${CMAKE_SOURCE_DIR}/../Generator/output/SimB.cpp
                   COMMAND ${PYTHON_EXECUTABLE} script.py SimB
                   DEPENDS ${CMAKE_SOURCE_DIR}/../Generator/script.py
                   WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/../Generator)

set_property(SOURCE ${CMAKE_SOURCE_DIR}/../Generator/output/SimB.cpp PROPERTY GENERATED TRUE)

add_executable(SimB ${CMAKE_SOURCE_DIR}/../Generator/output/SimB.cpp ...)

For more information see

*

*http://www.cmake.org/cmake/help/v3.0/command/add_custom_command.html

*http://www.cmake.org/cmake/help/v3.0/prop_sf/GENERATED.html


text:
Q: How can I create a grid overlay that accounts for feature density instead of map unit area? I am working with the below spatial data (each point does contain relevant attribute information). I need to be able to audit these data for completeness and accuracy against the associated data from a CRM system. To this point, I have performed several attribute and spatial analyses to identify and add or eliminate a large portion duplicate or inaccurate records. However, I am still finding several areas that points or attributes are missing or inaccurate. From here, my only option left, given the poor structure of the data, is to individually verify points and clean up data.
WHAT I AM HOPING TO ACCOMPLISH:

I would like to create a grid for this data set that will break down the spatial data into blocks of 100-200 points to help systematically review the the existing data and the surrounding area for any points that may be missing.

SOFTWARE:

I am currently working in ArcGIS Pro 3.0.3 with a basic license. I do have access to QGIS as well if needed, however I would like to find a way within Pro to complete this task.


text:
Q: Font not rendering properly in Godot I am trying to use a font in Godot, and it is posing problems. The font is Karmatic Arcade.
Here are the font settings in my theme:

Here is how it looks in the editor:

And here is how it looks in-game. Notice how there are more lines, and a few transparent pixels as if antialiasing or filter is turned on.

Does anyone know what is going on here?? I have similar results with other fonts, but not all of them.


text:
Q: Configure High Availability conditionally based on variable for `azurerm_postgresql_flexible_server` I'm configuring my servers with terraform. For non-prod environments, our sku doesn't allow for high availability, but in prod our sku does.
For some reason high_availability.mode only accepts the value of "ZoneRedundant" for high availability, but doesn't accept any other value (according to the documentation). Depending on whether or not var.isProd is true, I want to turn high availability on and off, but how would I do that?
resource "azurerm_postgresql_flexible_server" "default" {
  name                   = "example-${var.env}-postgresql-server"
  location               = azurerm_resource_group.default.location
  resource_group_name    = azurerm_resource_group.default.name
  version                = "14"
  administrator_login    = "sqladmin"
  administrator_password = random_password.postgresql_server.result

  geo_redundant_backup_enabled = var.isProd
  backup_retention_days        = var.isProd ? 60 : 7

  storage_mb = 32768

  high_availability {
    mode = "ZoneRedundant"
  }

  sku_name = var.isProd ? "B_Standard_B2s" : "B_Standard_B1ms"
}

A: I believe the default assignment for this resource would be disabled HA, and therefore it is not the argument mode which manages the HA, but rather the existence of the high_availability block. Therefore, you could manage the HA by excluding the block to accept the default "disabled", or including the block to manage the HA as enabled with a value of ZoneRedundant:
dynamic "high_availability" {
  for_each = var.isProd ? ["this"] : []

  content {
    mode = "ZoneRedundant"
  }
}

I am hypothesizing somewhat on the API endpoint parameter defaults, so this would need to be acceptance tested with an Azure account. However, the documentation for the Azure Postgres Flexible Server in general claims HA is in fact disabled by default, so this should function as desired.

A: If you deploy flexible server using azurerm provider in terraform it will accept only ZoneRedundant value for highavailability.mode and also using this provider you can deploy sql server versions [11 12 13] only.
Using Azapi provider in terraform you can use highavailability values with any one of these "Disabled, ZoneRedundant or SameZone"
Based on your requirement I have created the below sample terraform script which has a environment variable accepts only prod or non-prod values using this value further flexible server will get deployed with respective properties.

*

*If the environment value is prod script will deploy flexible server with high availability as zone redundant and also backup retention with 35 days with geo redundant backup enabled.

*If the environment value is non-prod script will deploy flexible server with high availability as disabled and also backup retention with 7 days with geo redundant backup disabled
Here is the Terraform Script:
terraform {
  required_providers {
    azapi = {
      source = "azure/azapi"
    }
  }
}

provider "azapi" {
}

variable "environment" {
    type = string

    validation {
      condition = anytrue([var.environment == "prod",var.environment=="non-prod"])
      error_message = "you havent defined any of allowed values"
    }
}

resource "azapi_resource" "rg" {
  type = "Microsoft.Resources/resourceGroups@2021-04-01"
  name     = "teststackhub"
  location = "eastus"
  parent_id = "/subscriptions/<subscriptionId>"
}

resource "azapi_resource" "test" {
  type = "Microsoft.DBforPostgreSQL/flexibleServers@2022-01-20-preview"
  name                   = "example-${var.environment}-postgresql-server"
  location               = azapi_resource.rg.location
  parent_id = azapi_resource.rg.id
  body = jsonencode({
    properties= {
      administratorLogin="azureuser"
      administratorLoginPassword="<password>"
    backup = {
        backupRetentionDays = var.environment=="prod"?35:7
        geoRedundantBackup = var.environment=="prod"?"Enabled":"Disabled"
      }
      storage={
        storageSizeGB=32
      }
      highAvailability={
        mode= var.environment=="prod"?"ZoneRedundant":"Disabled"
      }
      version = "14"
    }
    sku={
        name = var.environment=="prod" ? "Standard_B2s" : "Standard_B1ms"
        tier = "GeneralPurpose"
      }
  })
}

NOTE: The above terraform sample script is for your reference please do make the changes based on your business requirement.


text:
Q: MYSQL I am trying to return a value where I need to compare one value against the minimum value for the same field when grouped against another field Basically I am trying to calculate shots received in golf for various four balls, here is my data:-
DatePlayed  PlayerID    HCap    Groups  Hole01  Hole02  Hole03  Shots
----------------------------------------------------------------------
2018-11-10  001          15       2       7        3    6
2018-11-10  004          20       1       7        4    6
2018-11-10  025          20       2       7        4    5
2018-11-10  047          17       1       8        3    6
2018-11-10  048          20       2       8        4    6
2018-11-10  056          17       1       6        3    5
2018-11-10  087          18       1       7        3    5

I want to retrieve the above lines with an additional column which is to be calculated depending on the value in the group column, which is the players (Handicap - (the lowest handicap in the group)) x .75
I can achieve it in a group by but need to aggregate everything, is there a way I can return the value as above?, here is query that returns the value:
SELECT
    PlayerID,
    MIN(Handicap),
    MIN(Hole01) AS Hole01,
    MIN(Hole02) AS Hole02,
    MIN(Hole03) AS Hole03,
    MIN(CourseID) AS CourseID,
    Groups,
    ROUND(
        MIN((Handicap -
            (SELECT MIN(Handicap) FROM Results AS t
            WHERE DatePlayed='2018-11-10 00:00:00' AND t.Groups=Results.Groups)) *.75))
        AS Shots
FROM
    Results
WHERE
    Results.DatePlayed='2018=11=10 00:00:00'
GROUP BY
    DatePlayed, Groups, PlayerID

.
  PlayerID MIN(Handicap)Hole01 Hole02 Hole03 CourseID Groups Shots
  -----------------------------------------------------------------
      4        20         7       4     6       1        1    2
     47        17         8       3     6       1        1    0
     56        17         6       3     5       1        1    0
     87        18         7       3     5       1        1    1
      1        15         7       3     6       1        2    0
     25        20         7       4     5       1        2    4
     48        20         8       4     6       1        2    4

Sorry about any formatting really couldn't see how to get my table in here, any help will be much appreciated, I am using the latest mysql from ubuntu 18.04

A: Not an answer; too long for a comment...
First off, I happily know nothing about golf, so what follows might not be optimal, but it must, at least, be a step in the right direction...
A normalized schema might look something like this...
rounds
round_id DatePlayed  PlayerID HCap Groups
       1 2018-11-10         1   15      2
       2 2018-11-10         4   20      1

round_detail
round_id hole shots
       1    1     7
       1    2     3
       1    3     6
       2    1     7
       2    2     4
       2    3     6

A: Hi Guys I have found the solution, basically I need to drop the MIN immediately after the ROUND of the equation and therefore it does not need a Group By.

SELECT
PlayerID,

Handicap,

Hole01,

Hole02,

Hole03,

CourseID,

Groups,

ROUND((Handicap -

      (SELECT MIN(Handicap) FROM Results AS t

       WHERE DatePlayed='2018-11-10 00:00:00'

       AND t.Groups=Results.Groups))

       *.75) AS Shots

FROM
Results

WHERE
Results.DatePlayed='2018=11=10 00:00:00'


text:
Q: RuntimeException occured : java.lang.RuntimeException: java.lang.ClassCastException: java.lang.String cannot be cast to com.mongodb.DBRef I have been using play for a few months now on ubuntu servers and also on Google App Engine using the Siena module. Now I have an application on an Ubuntu server with the following versions:
Play Framework - 1.1
Morphia - morphia-1.2beta3
My code is throwing a very strange error:
RuntimeException occured : java.lang.RuntimeException: java.lang.ClassCastException: java.lang.String cannot be cast to com.mongodb.DBRef
for this line inside app/models/Playlist.java:
List items = PlaylistItem.filter("playlist", this).asList();
"playlist" is a field in PlaylistItem and it's defined as:
@Required
@Reference
public Playlist playlist;
The weird thing is that this same application (I have the code in source control and pull to both machines) works on my laptop but does not work on my Ubuntu server. Does anyone know why this may be happening?

A: you may want to check this bug report. It seems to be your issue.


text:
Q: Java Module module-info.java duplicate I have created a project, Inside the Project, there One source folder, have taken name as feeding, created packages, classes, module-info.java file into it. After Then, Another source folder created,  have taken name as care, created packages, classes, But while creating module-info.java into care folder facing issue duplicate module-info.java
I am sharing a screenshot of the project, Here, If I am trying to add module-info.java file then the project getting elapsed means project even not opening, trying to open in type hierarchy then showing Duplicate module-info.java. Please have a concern.


text:
Q: Minimize cost of purchasing $N$ widgets among $S$ stores I recently encountered this puzzle that seems like a standard combinatorial optimization or dynamic programming problem, but I wasn't able to crack it. I'm happy to receive answers, hints, references, or suggestions about related problems that I can map this one to.
Problem: You're out shopping for $N$ widgets. There are $S$ stores that carry the widgets, each having a stock of $N$ of them. However, each store has a different pricing scheme. For example, one store could charge \$1 for the first widget you order, but then the second widget could cost \$10 and the third only \$1. The cumulative order cost $f$ for this store has values $f(1) =1, f(2)=11, f(3)=12.$ The only restriction is that the cumulative order cost functions is positive on positive integers and strictly monotonically increasing. Having the $S$ stores' cumulative cost functions, (you can write capture all the relevant information in an $N\times S$ matrix, where each entry is positive and along each column the values strictly increase), you want to buy the $N$ widgets for the lowest possible price.
I imagine there's something better than the exhaustive search over all ${\tbinom  {N+S-1}{N}}$ possible ways. I tried looking at marginal costs and then doing a greedy approach but this doesn't work.
As a possible extension: what happens if you decide you want more than $N$ widgets?

A: I think dynamic programming works.  For $n=1,2,3,\dots,N$ determine the cheapest way to buy $n$ widgets from stores $1$ and $2$, and store the results.  With this in hand, it's straightforward to determine the cheapest way to buy $n$ widgets from stores $1,2$,and $3$.  For $k=1,\dots,n$ compute the cost of buying $k$ widgets from store $3$ and $n-k$ widgets from stores $1$ and $2$, and store the least expensive method and its cost.
Then add stores $4,5,\dots,S$ in the same manner.
While this will be better than trying every possible combination, it still seems very computationally demanding.
I think one might be able to make some performance gain if it were true, in contrast to your example, that the $n+1$st widget was never more expensive than the $n$th widget, from any given store. That's just a guess though.  I haven't really thought about it, since you say the assumption doesn't hold.


text:
Q: Getting a runtime exception -(BOOL)createTimer
{
    stRs232Timer*   pEvent = malloc(sizeof(stRs232Timer));

    pEvent->bPersistent = YES;                              // setup timer structure
    pEvent->wAppTimerId = 95;
    pEvent->uPeriod     = 50;
    pEvent->bStopped    = NO;
    pEvent->uExpirationTime = 10;

    NSLog(@"bPersistent:%d",pEvent->bPersistent);
    NSLog(@"wAppTimerId:%d",pEvent->wAppTimerId);
    NSLog(@"uPeriod:%d",pEvent->uPeriod);
    NSLog(@"bStopped:%d",pEvent->bStopped);

    NSData* myData = [NSData dataWithBytes:(stRs232Timer*)pEvent length:sizeof(stRs232Timer*)];

    wTimerId = 99;
    pEvent->uPeriod = 51;
    myData = [NSData dataWithBytes:(stRs232Timer*)pEvent length:sizeof(stRs232Timer*)];
         [m_cAppIdMap setObject:myData forKey:[NSNumber numberWithUnsignedShort:wTimerId]];
    wTimerId = 96;
    pEvent->uPeriod = 52;
    myData = [NSData dataWithBytes:(stRs232Timer*)pEvent length:sizeof(stRs232Timer*)];
    [m_cAppIdMap setObject:myData forKey:[NSNumber numberWithUnsignedShort:wTimerId]];
    wTimerId = 97;
    pEvent->uPeriod = 53;
    myData = [NSData dataWithBytes:(stRs232Timer*)pEvent length:sizeof(stRs232Timer*)];
    [m_cAppIdMap setObject:myData forKey:[NSNumber numberWithUnsignedShort:wTimerId]];
    wTimerId = 98;
    pEvent->uPeriod = 54;
    myData = [NSData dataWithBytes:(stRs232Timer*)pEvent length:sizeof(stRs232Timer*)];
    [m_cAppIdMap setObject:myData forKey:[NSNumber numberWithUnsignedShort:wTimerId]];
    wTimerId = 95;
    pEvent->uPeriod = 55;
    myData = [NSData dataWithBytes:(stRs232Timer*)pEvent length:sizeof(stRs232Timer*)];
    [m_cAppIdMap setObject:myData forKey:[NSNumber numberWithUnsignedShort:wTimerId]];

    NSLog(@"The dictionary count now is:%d",[m_cAppIdMap count]);
    NSLog(@"The dictionary values now is:");
    NSLog(@"%@",m_cAppIdMap);

    [m_cPendingEventList addObject:myData];
    NSLog(@"EventList:%@",m_cPendingEventList);

    [self ChangeTimer:95 withPeriod:10];

    free(pEvent);
    return YES;
}

-(BOOL)ChangeTimer:(unsigned short)wTimerIds withPeriod:(uint8_t)uPeriod
{
 stRs232Timer*   pEvent;
    NSLog(@"Into the changeTimer");
    pEvent = (stRs232Timer*)[m_cAppIdMap objectForKey:[NSNumber numberWithUnsignedShort:wTimerIds]];
    NSLog(@"The val is:%@",pEvent);
    if(pEvent!=nil){
        pEvent->bStopped = NO;
        pEvent->uPeriod = uPeriod;
        NSLog(@"completed");
        }

    return YES;
}

main.m
----------
int main (int argc, const char * argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSArray1* arr = [[NSArray1 alloc]init];
    [arr createTimer];
    [pool drain];
    return 0;
}

I am getting EXC_BAD_ACCESs runtime exception.Why is it so.I am not accessing any released memory.
EDITED:
2011-05-30 11:21:45.191 NSArray[1091:a0f] bPersistent:1
2011-05-30 11:21:45.194 NSArray[1091:a0f] wAppTimerId:95
2011-05-30 11:21:45.195 NSArray[1091:a0f] uPeriod:50
2011-05-30 11:21:45.195 NSArray[1091:a0f] bStopped:0
2011-05-30 11:21:45.196 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x100110180 of class NSConcreteData autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.196 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x1001102f0 of class NSConcreteData autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.197 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x100110410 of class NSCFNumber autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.197 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x100110a70 of class NSConcreteData autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.198 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x100110ab0 of class NSCFNumber autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.198 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x100110ad0 of class NSConcreteData autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.199 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x100110b10 of class NSCFNumber autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.199 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x100110b30 of class NSConcreteData autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.200 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x100110b70 of class NSCFNumber autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.201 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x1001109e0 of class NSConcreteData autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.201 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x1001105d0 of class NSCFNumber autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.202 NSArray[1091:a0f] The dictionary count now is:5
2011-05-30 11:21:45.202 NSArray[1091:a0f] The dictionary values now is:
2011-05-30 11:21:45.203 NSArray[1091:a0f] {
    98 = <5f000136 000a0000>;
    97 = <5f000135 000a0000>;
    96 = <5f000134 000a0000>;
    99 = <5f000133 000a0000>;
    95 = <5f000137 000a0000>;
}
2011-05-30 11:21:45.203 NSArray[1091:a0f] EventList:(
    <5f000137 000a0000>
)
2011-05-30 11:21:45.204 NSArray[1091:a0f] Into the changeTimer
2011-05-30 11:21:45.204 NSArray[1091:a0f] *** __NSAutoreleaseNoPool(): Object 0x100111130 of class NSCFNumber autoreleased with no pool in place - just leaking
2011-05-30 11:21:45.205 NSArray[1091:a0f] The val is:<5f000137 000a0000>
2011-05-30 11:21:45.205 NSArray[1091:a0f] completed

This is the output i'm getting when removed the NSAutoreleasePool and [pool drain].
If i'm not removing both of this i'm getting EXC_BAD_ACCESS as the run time exception.When i debugged i got exception(EXC_BAD_ACCESS) coming when it comes to [pool drain]; statement.
I could not find out why this happens.

A: look at this line (and similar):
NSData* myData = [NSData dataWithBytes:(stRs232Timer*)pEvent length:sizeof(stRs232Timer*)];

the amount of bytes is equal to the size of a pointer to stRs232Timer data, which for exmaple for a 32-bit system would be 4 bytes, for 64-bit system 8 bytes - but not the size of stRs232Timer structure. So you are copying not enough bytes.
The cast is also not necessary, so it should be like that:
NSData* myData = [NSData dataWithBytes: pEvent length: sizeof(stRs232Timer)];

BTW this very first instance will be overwritten before it gets saved into the dictionary.
LATER
In ChangeTimer you should use NSData bytes method instead of casting directly to stRs232Timer:
pEvent = (stRs232Timer*)[[m_cAppIdMap objectForKey:[NSNumber numberWithUnsignedShort:wTimerIds]] bytes];

This will give you the pointer to the data, casting NSData directly to stRs232Timer is wrong.


text:
Q: Does `TransferUtility` from the android Amazon AWS Mobile SDK run in its own `Service`? I am using TransferUtility to upload big files to S3.
(https://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/s3-integration-transferutility.html)
Can anyone confirm that TransferUtility creates its own Android Service for this?
Files are big, and I need to perform the upload in an Android Service to avoid the app to be killed.
TransferUtility exposes an asynchronous API, but it's not clear if it creates an Android Service or not.

A: In the past when I used to use AWS, I always wrapped my calls in a JobScheduler. But you should probably wrap it in a WorkManager.
public class UploadWorker extends Worker {

    public UploadWorker(
        @NonNull Context context,
        @NonNull WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Result doWork() {
      // Do the work here.

      transferLargeFilesToAws()

      // Indicate whether the task finished successfully with the Result
      return Result.success()
    }
}


text:
Q: Vue js loop for I'm trying to add an a action to my data, this's code=
this.array = res.data.data;
        for( i in this.array){
            this.$set(this.array[i], 'action',
            "<a href='/users/ope/array[i].id'> <v-icon> mdi-account-details-outline </v-icon> </a>"
            );
        }

but I'm having this error=
ReferenceError: i is not defined

what I'm doing wrong??

A: You missed to define the i variable using let or const :
for(let i in this.array){
      ...

the i represents the index, if you want to loop through the values you could use for(let val of this.array){


text:
Q: Reverse for 'likes' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['datasecurity/likes/'] Like buttton error in django registration and login page is working properly but mine like button is not working .. I don't know why...
Can somebody help me to solve this issue …
it will be great help
please help
Thank you!

*

*views.py`
 from django.shortcuts import render, get_object_or_404
 from datasecurity.models import Post
 from django.urls import reverse
 from django.http import HttpResponseRedirect
 from django.contrib.auth.decorators import login required

 # Create your views here.
 def datasecurity(request):
      allPosts= Post.objects.all()
      context={'allPosts': allPosts}
       return render(request, 'datasecurity/data.html',context=context)

 def blogHome(request, slug):
      post=Post.objects.filter(slug=slug).first()
      context={"post":post}
      return render(request, "datasecurity/blogHome.html", context)

 @login_required
 def likes(request, pk):
      post=get_object_or_404(Post, id=request.POST.get('post_id'))
      post.likes.add(request.user)
      return HttpResponseRedirect(reverse('datasecurity:blogHome', args=str(pk)))

*urls.py
from django.conf.urls import url

from . import views

app_name = 'datasecurity'

urlpatterns = [
        url(r'^$', views.datasecurity, name="datasecurity"),
        url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'),
        url(r'^likes/<int:pk>', views.likes, name = "likes"),

]

*data.html
 {% extends 'careforallapp/navbar.html' %}
 {% block body_block %}
  {% load static %}

Welcome to Data Security
    {% for post in allPosts  %}

     This is a Bootstrap v4.2.1 CSS Template for you. Edit and use
       this layout for your site. Updated on 21 May 2019 for repeated main menu HTML code.

           {% if post.img %}

           {% endif %}

{{post.title}}

Article  by {{post.author}}

{{post.datetime}}

             {{post.content|safe | truncatechars:280}}

           <from action = "{% url 'datasecurity:likes' pk=post.pk %}" method = "POST">
             {% csrf_token %}
             <button type="submit" name="post_id" value = "{{ post_id }}" class="btn"> Like
           </button>
           </form>

             Read More

            {% endfor %}

*error msg <from action = "{% url 'datasecurity:likes' pk=post.pk %}" method = "POST">

*

*Reverse for 'likes' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['datasecurity/likes/int:pk']

this msg was highlighted when I debug the the code. So can someone tell me please what i missed in my code...
Thank You!

A: You are not taking the pk argument from view. Change your view to:
@login_required
 def likes(request, pk):
      post=get_object_or_404(Post, id=pk)

and the url to:
url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"),

notice the used regular expression in the url.


text:
Q: how to input two route parameters one of which is in between the URL for navigation while using children routes in Angular CLI 8+ using Angular Router I am trying to navigate to a page providing two route parameters as follows:
author/journals/:journal_Id/draftArticles/:articleId
I know that two parameters can be given when route parameter is at the end of the route like author/journals/draftArticles/:journal_Id/:articleId, journal_Id, articleId and this will probably solve my issue. But I wanted to maintain the structure I am trying.
path: 'author',
        canActivate: [AuthGuardService],
        canActivateChild: [AuthorGuard],
        component: AuthorNavComponent,
        children: [
          {
            path: '',
            component: AuthorDashboardComponent,
            pathMatch: 'full'
          },
          {
            path: 'profile',
            component: AuthorProfileComponent,
            pathMatch: 'full'
          },
          {
            path: 'journals/:journal_Id',
            component: JournalPublicPageComponent,
            pathMatch: 'full',
            children: [
              {
                path: 'draftArticles', children: [
                  {
                    path: ':articleId',
                    component: DraftArticleComponent,
                    pathMatch: 'full'
                  },
                  {
                    path: '',
                    component: DraftArticlesComponent,
                    pathMatch: 'full'
                  }
                ]
              },
              {
                path: 'articles', children: [
                  {
                    path: '',
                    component: ArticlesComponent,
                    pathMatch: 'full'
                  },
                  {
                    path: ':articleId',
                    component: ArticleComponent,
                    pathMatch: 'full'
                  }
                ]
              }
            ]
          }

Above is the structure my routes.
AuthorNavComponent is my Sidenav within which I am also using another router-outlet for showing children routes. The button that I am clicking is inside the Sidenav which ultimately calls a method in serviceA which will, after making a call to server, redirect to the above specified URL i.e. https://localhost:4200/author/journals/:journal_Id/draftArticles/:articleId
Please let me know if any more information is required
Update
I tried using service in the middle named journalService and created a BehaviorSubject<any[]> to pass in the route of to navigate to. In the component whose route is author/journals/3, I subscribed to this BehaviorSubject<any[]> and navigated upon changing the value of this BehaviorSubject passing along relative ActivatedRoute as follows:
Journal Component
this.js.navigateAgain.subscribe(data => {
      if (data) {
        this.router.navigate(data, {relativeTo: this.activatedRoute});
      }
    });

Other Component From where I am changing the value of BehaviorSubject<any[]>
this.js.navigateAgain.next(['draftArticles', articleId]);

Update 2
Route could also be generated using this -> this.router.navigate(['author/journals', journalId, 'draftArticles', articleId]); but still the below error persists :(
Above technique generated the URL perfectly. But I still get the following error:

It seems like, there is something wrong with the routing described far above.

A: Answer to the above question is partially mentioned within the question at:

Update 2 Route could also be generated using this -> this.router.navigate(['author/journals', journalId, 'draftArticles', articleId]); but still the below error persists

Using this, we can pass two parameters. However, I used router-outlet for displaying child component. Such that, parent is shown in the main router-outlet while the children are shown in the subsequent router-outlets mentioned within the HTML templates of parent. The routing hierarchy defined above is like: author (parent) then journals/:journal_Id (child to author, parent to onward children) then draftArticles/:articleId (child to journals/:journal_Id) which will be shown in its parent for which I had to mention router-outlet tag in journals/:journal_Id component.
Also, I learned that pathMatch: 'full' should not be mentioned in children routes. Now that parent component will also be showing along with the child component, I could simply if-else statement.


text:
Q: Physicality of claims regarding AC ice energy storage units Many of us may remember the problems from thermodynamics where we had to determine if a pretend air conditioning unit supplier's claims violated the 2nd law.  I want to pose a similar question regarding a new "green" Air Conditioning (AC) technology.
An ice energy storage unit for AC works by making ice during the night and using the latent heat (mostly) to cool the building during the day.  The major motive for doing this is to move the energy demand from the peak energy use times to the low-demand times at night when it is cheaper.  The cost of electricity is not relevant to this question.  The claims of a vendor of this technology, Ice Bear Energy Storage System, include the following:

Bottom line: The Ice Bear system reduces total net energy consumption for most buildings under virtually all operating conditions and installations.

Question: Is this claim physically plausible, given reasonable assumptions about climate?  There are some example cities below, I imagine that considering an average location or just the extremes would be sufficient.
Here are a few things to note, but these are certainly not comprehensive.  Creativity may be important for identifying all the factors at play.

*

*The temperature of ice is $0^{\circ} C$ ($32^{\circ} F$)

*Room temperature is $22.2^{\circ} C$ ($72^{\circ} F$)

*The outside ambient temperature is lower at night than during the day.  Exactly how much depends on the location and humidity particularly.  Locations mentioned on their website include Glendale, CA; Howell, NJ; Las Vegas, NV; Fort Collins, CO; Orange County, CA; and Redding, CA.

*The ice storage duration is 6 hours and since these are multiple MW products, I'll say it's fair to assume almost perfect insulation unless someone wants to challenge this.

*You can obtain useful work while exchanging the heat from the office building to the ice.  I believe this would be important considering the wording of "total net energy consumption".

Temperatures
I have looked up the temperatures for most of the mentioned cities.  For some I couldn't get data for I used a nearby city instead.

*

*(City/State) (night-day difference) (seasonal difference) (hottest month high)

*Redding CA, 27.4, 44, 99

*Las Vegas NV, 26.5, 48, 104

*Denver CO, 27.8, 45, 88

*Lakehurts NJ, 27.8, 45, 88

*Santa Anna CA, 20.5, 18, 83

These seem to be fairly consistent for the night-day difference in particular.  I hope that simplifies the problem.  It seems clear that running at night "buys" you about 27.5 degrees F.  Now, the absolute temperatures as well as the seasonal variation will affect the efficiency, but to a much smaller degree.
My conflict: Can a $27.5$ degree difference really make up for a $72-32=40$ degree penalty on the thermal cycle?  Really?  It's not a trivial problem, but I am skeptical.  I will certainly send them an email letting them know they violated the 2nd law depending on the outcome here.

A: The technology you describe can actually save some energy using the fact that the night temperature can be much lower than the day temperature. When you cool the ice using a refrigerator-like unit it's very important how cold the air you use to cool the refrigerator radiator is.
Since you can place the radiator in such way that it is intensely cooled with outside air and use much colder air available during the night you can cool the ice more efficiently than you would cool the inside air during the day with a usual AC system. So not only you shift to cheaper electricity but you could also use less electricity because with colder outside air cooling can be more efficient during the night.
One point to illustrate this: my own electricity usage pattern is mostly constant during the year. Now the electricity bill is about 30% larger in the hottest summer months because of the refrigerator that constitutes the most of my electricity consumption. Of course the refrigerator also heats up faster with warmer room air, but it also cools less efficiently and these two factors noticeably boost energy consumption.


text:
Q: Add a page break at different levels in a group in report builder I have 5 different groups within  the Row Groups in Report Builder. I need help  to add pagebreak only after the 2nd group ( in this case at the residentName level and not at the facility level).
Row Groups

*

*facility

*residentName

*room

*abbrevdesc

*type

Edit: To make things more clear:
Say I have facility = chicagoApartment within which I have various residents say sam, john and sean . Each resident than have their room numbers and multiple description which then has its types.
I want to be able to page break at the resident level so that all the information related to sam stays on the same page instead of expanding to the next.
When I do "page break" inside "group properties" and choose "between each instance of a group".. it cuts off at the facility level but i want the facility to stay chicago and pagebreak at the residentName level.
I hope its more clear now!!
Row groups


text:
Q: Origin and etymology of "travel" Yesterday I was asking about the origin of the word trabajo ("work") in Spanish, that most etymologists think that comes from Latin tripalium (or trepalium according to other sources), an instrument of torture, and its verb tripaliare, "to torture". An English cognate is travail, that according to the Merriam-Webster it still conveys the meaning of "agony, torment", while the Oxford dictionary says it means a "painful or laborious effort".
Both dictionaries agree with its origin, but a note in the M-W also says:

From trepalium sprang the Anglo-French verb travailler, which originally meant "to torment" but eventually acquired the milder senses "to trouble" and "to journey." The Anglo-French noun travail was borrowed into English in the 13th century, followed about a century later by travel, another descendant of travailler.

The Oxford dictionary seems to confirm that travel is a variant of travail. So it seems that the English verb to travel also derives from that original torment. The similarity of travail and travel is obvious, but how did a word that meant torment evolve its meaning into journey? Are there any texts that can confirm this and in which we can see this evolution?

A: TRAVEL
I have found a text that uses "travell" to mean "work", dating from 1576.
In the introduction to "The Rocke of Regard" by George Whetstone, he uses the following passage:

and further, for that I know the most part of youth (to whome I chiefly dedicate the fruite of my travell) are so carelesse of their commoditie, as they set light of sound advice, unless such persuasions be sauced (in some respect) with their owne desires...And yet, least they lighting on some discourse of worth, shoulde by and by be led away with the sight of some wanton devise, I have published my travell under these foure following titles.

At some point between 1579 and 1587 (these dates being the period when Sir Thomas Bromley was Lord Chancellor), "travel" is used for "journey", in the Journals of the House of Lords (see 2nd snippet view).

Sir Thomas Bromley, Knight, Lord Chancellor of England, is at this Time so visited with Sickness, that he is not able to travel to the Upper House of this Our present Parliament, holden at Westm., nor there to supply the Room and Place in the said Upper House, among the Lords Spiritual and Temporal there assembled, as to the Office of the Lord Chancellor, or Lord Keeper of the Great Seal of England, hath been accustomed

TRAVAIL
If 1560 is early enough, one book alone contains several uses of "travail" meaning "work", and at least one where it means "make a journey".
The Calendar of State Papers, Foreign Series, of the Reign of Elizabeth, 1559-1560 contains this passage, dated Feb 12 1560, in which "travail" appears to cross the border from "work" to "journey":

As for his keeping watch, he thinks the French in Leith and Inchkeith would not deny but that the fleet had kept them waking.  There has been never night since he came hither, being possible for men to travail upon the water, but that he has had 300 or 400 men armed in boats to guard the haven's mouth, that no succours should come in to them between the shore and the ships; and that they might not be able to put more men or victuals into Inchkieth.

A further example, from Feb 19, 1560, blurs the lines a little between the two meanings:

Cecil considered that Sir James Croftes was the meetest for that purpose, from his experience amongst the Scots, and his travail taken in the discourse of the said journey;

There are several (over 30) other uses of "travail" to mean "work" in the same publication, an example of which is below, from Feb 25, 1560:

Most heartily thanks him for his earnest travail about the said payment, and is right glad that it is so well ended.

Hence, it can be seen that travail was certainly used in the mid-late 16th Century to mean both work and journey, and that the same was also the case for "travel" a decade or two later.
Also, the hardship and difficulty of making any lengthy journey seems to be pertinent to the evolution from one meaning to the other.

A: According to the OED the etymology of travel it is derived from the same word as travail v.

2a. intr. To make a journey; to go from one place to another; to
  journey. Also fig.
α.
c1290   S. Eng. Leg. I. 25/61   For ȝe þus i-trauailede beoth fram
  so ferre londe..Ich eov nelle greui nouȝt.
c1330   R. Mannyng Chron. (1810) 3   He was of grete elde, & myght not
  trauaile.
1413   Pilgr. Sowle (1859) i. i. 1   I had longe tyme trauayled toward
  the holy Cyte of Ierusalem.
1544   Letanie in Exhort. vnto Prayer sig. Bviii   To preserue all
  that trauaile by lande or by water.
1590   Spenser Faerie Queene i. ii. sig. B7   Long time they thus
  together traueiled.
a1616   Shakespeare Measure for Measure (1623) i. iii. 14   He
  supposes me trauaild to Poland.    1691   J. Norris Pract. Disc.
  Divine Subj. 94   Why should we..quit the Road they have taken, if we
  may safely travail in it?
1714   J. Gay Shepherd's Week Proeme sig. A3   Other Poet travailing
  in this plain High-way of Pastoral.
β.
c1410   Sir Cleges 16   To men, that traveld in londe of ware.
c1480  (▸a1400)    St. Eugenia 326 in W. M. Metcalfe Legends Saints
  Sc. Dial. (1896) II. 133   Sen scho mycht nocht trawel hym til.
1483   Cath. Angl. 391/2   To Travelle, itinerare.
1568  (▸a1500)    Freiris Berwik 39 in W. T. Ritchie Bannatyne MS
  (1930) IV. 262   For he wes awld and micht not wele travell.
1594   T. Nashe Vnfortunate Traveller sig. L3   He is no body that
  hath not traueld.
a1616   Shakespeare As you like It (1623) i. iii. 108   What danger
  will it be to vs,..to trauell forth so farre?    1697   Dryden tr.
  Virgil Georgics iv, in tr. Virgil Wks. 126   A thirsty train That long
  have travel'd through a desart plain.    1768   L. Sterne Sentimental
  Journey I. 34   An English man does not travel to see English men.
1855   F. A. Paley Æschylus (1861) Pref. 28   They have..pointed out
  the path in which succeeding editors should travel.
1901   W. R. H. Trowbridge Lett. Mother to Elizabeth iv. 13   [They]
  travelled down from London in a special Pullman attached to the
  Bristol express.


text:
Q: Searchview not showing the correct results I"m using Recycle view adtper to populate my framgment class iwht json file from online and using searchview, user can search for Title by typing inside searchbox and it will show the filtered results which matches text entered and title from json.
But instead whenever I type any text it show different results. Here is the screenshot

as you can notice when I type con, It filter different results. Also when I type la it still show results which don't have any word containing "la".
Here is my adapter class

public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> implements
        Filterable {
    private Context mContext;
    private ArrayList<ExampleItem> mExampleList = new ArrayList<ExampleItem>();
    private ArrayList<ExampleItem> contactListFiltered = new ArrayList<ExampleItem>();
    private OnItemClickListener mListener;
    private ExampleAdapterListener listener;

    public ExampleAdapter(Context context, ArrayList<ExampleItem> bookslist, ExampleAdapterListener listener) {
        this.mContext = context;
        this.listener = listener;
        this.mExampleList = bookslist;
        this.contactListFiltered = bookslist;
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                String charString = charSequence.toString();
                if (charString.isEmpty()) {
                    contactListFiltered = mExampleList;
                } else {
                    ArrayList<ExampleItem> filteredList = new ArrayList<>();
                    for (ExampleItem row : mExampleList) {

                        // name match condition. this might differ depending on your requirement
                        // here we are looking for name or phone number match
                        if (row.getTitle().toLowerCase().contains(charString.toLowerCase())) {
                            filteredList.add(row);
                        }
                    }

                    contactListFiltered = filteredList;
                }

                FilterResults filterResults = new FilterResults();
                filterResults.values = contactListFiltered;
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                contactListFiltered = (ArrayList<ExampleItem>) filterResults.values;
                notifyDataSetChanged();
            }
        };
    }

    public interface OnItemClickListener {
        void onItemClick(int position);

        void onClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

    // Here I added the update list function
    public void updateList(ArrayList<ExampleItem> exampleList) {
        mExampleList = exampleList;
        contactListFiltered = exampleList; // Add the exampleList here as well
    }

    @Override
    public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.example_item, parent, false);
        return new ExampleViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ExampleViewHolder holder, int position) {
        ExampleItem currentItem = mExampleList.get(position);

         String title = currentItem.getTitle();
//        int likeCount = currentItem.getLikeCount();
//        String imageUrl = currentItem.getImageUrl();

          holder.mTextViewCreator.setText(title);
//        holder.mTextViewLikes.setText("Likes: " + likeCount);
//        Glide.with(mContext).load(imageUrl).apply(RequestOptions.circleCropTransform()).into(holder.mImageView);

    }

    @Override
    public int getItemCount() {
        return contactListFiltered.size();
    }

    public class ExampleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        public TextView mTextViewCreator;
//        public TextView mTextViewLikes;
//        public ImageView mImageView;

        public ExampleViewHolder(View itemView) {
            super(itemView);
//            mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
//            mImageView = itemView.findViewById(R.id.image_view);
            mTextViewCreator = itemView.findViewById(R.id.text_title);
            itemView.setOnClickListener(this);

        }

        @Override
        public void onClick(View view) {

            if (mListener != null) {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    mListener.onItemClick(position);
                }
            }

        }
    }
    public interface ExampleAdapterListener {
        void onContactSelected(ExampleItem contact);
    }
}

and my fragment class is

public class Mynotes extends Fragment implements ExampleAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener, ExampleAdapter.ExampleAdapterListener {
    public static final String PDF_LINK = "link";
    private ProgressBar myProgressBar;
    private RecyclerView mRecyclerView;
    private ExampleAdapter mExampleAdapter;
    private ArrayList<ExampleItem> mExampleList;
    private RequestQueue mRequestQueue;
    SwipeRefreshLayout mSwipeRefreshLayout;
    String url="https://api.myjson.com/bins/16mecx";
    private SearchView searchView;

    public Mynotes() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.activity_jsonfeed, container, false);

        Bundle bundle = getArguments();
        if(bundle!=null){
            url = bundle.getString("key_one");
        }

        mRecyclerView = view.findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new MyDividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL, 36));

        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.colorBackground);

        myProgressBar = view.findViewById(R.id.myProgressBar);
        myProgressBar.setIndeterminate(true);
        myProgressBar.setVisibility(View.VISIBLE);
        mRequestQueue = Volley.newRequestQueue(getActivity());

        // SearchBox
        searchView = (SearchView) view.findViewById(R.id.search);
        searchView.setIconifiedByDefault(false);
        searchView.setFocusable(true);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String queryString) {
                mExampleAdapter.getFilter().filter(queryString);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String queryString) {
                mExampleAdapter.getFilter().filter(queryString);
                return false;
            }
        });

        updateListContent();
        mExampleList = new ArrayList<>();
        mExampleAdapter = new ExampleAdapter(getActivity(), mExampleList,this);
        mExampleAdapter.setOnItemClickListener(this);

        mRecyclerView.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(llm);
        mRecyclerView.setAdapter(mExampleAdapter);

        mExampleAdapter.setOnItemClickListener(this);

 mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    updateListContent();
                }
            });

        return view;
    }

    public void updateListContent() {
        mSwipeRefreshLayout.setRefreshing(true);
        if (mExampleList != null)
            mExampleList.clear();
        parseJSON();
    }

    private void parseJSON() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        myProgressBar.setVisibility(View.GONE);

                        try {
                            JSONArray jsonArray = response.getJSONArray("hits");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject hit = jsonArray.getJSONObject(i);
                                String videoTitle = hit.getString("title");
                                String link = hit.getString("link");
                                String doc = hit.getString("doc");

                                mExampleList.add(new ExampleItem(videoTitle, link,doc));
                                // Move this outside of the for loop
                                // mExampleAdapter.notifyDataSetChanged();
                            }

                            // Update the list here and then call notifyDataSetChanged
                            mExampleAdapter.updateList(mExampleList);
                            mExampleAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });

        mRequestQueue.add(request);
    }

    @Override
    public void onItemClick(int position) {
        Intent ytdIntent = new Intent(getActivity(), Pdfviewer.class);
        ExampleItem clickedItem = mExampleList.get(position);
        ytdIntent.putExtra(PDF_LINK, clickedItem.getmDocs());
        startActivity(ytdIntent);

    }

    @Override
    public void onClick(int position) {

    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onContactSelected(ExampleItem contact) {

    }
}

and my json url is
enter link description here.  If any more information is required. I'll add. Thanks in advance.

A: Make two list for filter
       List<ProdectModel> prodectModels ;
         List<ProdectModel> productFilterList;

     public BookAdapter(Context context, List<ProdectModel> bookModels, String title,String Cat_id) {
            this.context = context;
            this.prodectModels = bookModels;
            this.title = title;
            this.Cat_id = Cat_id;
            this.productFilterList = new ArrayList<>();
            this.productFilterList.addAll(this.prodectModels);
        }

 private static String removeAccent(String text) {
        String result = Normalizer.normalize(text, Normalizer.Form.NFD);
        return result.replaceAll("[^\\p{ASCII}]", "");
    }

  public void searchCompanyes(CharSequence charText) {

        charText = removeAccent((String) charText).toLowerCase(Locale.getDefault());

        prodectModels.clear();
        if (charText.length() == 0) {
            prodectModels.addAll(productFilterList);
        } else {
            for (ProdectModel Company : productFilterList) {
                String name = removeAccent(Company.getName());
                if (name.toLowerCase(Locale.getDefault()).contains(charText)) {
                    prodectModels.add(Company);
                }
            }
        }

        notifyDataSetChanged();
    }

And finally call the method in activity and pass your text in that


text:
Q: Get text from  element? I would like to get the school name, "Perkins College..." from this link using beautifulSoup.
The code I use returns nothing.
school = soup.find('a','profiles-show-school-name-sm-link')
print 'school: ', school
print 'school.text: ', school.text

output:
school:

school.text:

Suggestions for a BeautifulSoup implementation to extract school name (not URL)? Thx!

A: school = soup.find('a','profiles-show-school-name-sm-link')
url = school['href']

Assuming the school is always in the same spot in the url:
for i in range(5):
   url = url[url.find("/")+1:]
schoolname = url[:url.find("/")]
print " ".join(schoolname.split("-")).title()

Yields:
Perkins College Of Education Undergraduate

Getting the University
for i in range(4):
   url = url[url.find("/")+1:]
university= url[:url.find("/")]
print " ".join(university.split("-")).title()

Yields:
Stephen F Austin State University


text:
Q: AVD in Eclipse not working in Emulator? I am in the process of putting together an android application for a client using Eclipse Classic with the Android SDK.
The problem I have is the AVD is not running when I start it, just showing this message.

invalid command-line parameter: Files. Hint: use '@foo' to launch a
  virtual device named 'foo'. please use -help for more information*

Any help would be much appreciated.

A: Just take a look where you have installed the android SDK. This means where is your SDKManager.exe file.
The path up to that file should not have more then 2 folder.
In my computer the path for SDKMAnager.exe is " C:\Android\android-sdk-windows".
In android-sdk-windows folder everything is there like addons, docs, tools, SDKManager.exe etc.
If you have installed anywhere like " C:\Programe Files\MyFolder\Android\android-sdk-windows" then it will not run.
Remove all folder and remain with 2 folder like I have described above.

A: Ya it is happen when you had not installed SDK properly or see this Running first Android application - error message .

A: Please remove space on android sdk path.


text: Q: How to add pages of images to horizontalscrollview android? I need a help in doing a task in my app. I want to load images in gridview from server. On swiping left the next set of images has to be loaded in the gridview. On swiping right again it has to show the previous set of images which is already loaded in the gridview. On clicking one image in gridview it has to show the details of that image. Please help me if anybody knows.


text:
Q: How to restrict output bandwidth of each stream in RTMP I have a digital ocean server for serving RTMP and hls live streaming.Is there any way I can restrict output bandwith for each stream to 1mbps Or 1.5mpbs.
I already tried wondershaper but it is limiting the entire server bandwidth but I need some way to restrict bandwidth only for rtmp and hls streams.

A: Personaly,I would use either cgroups + tc or iptables for that.
On my servers I have used a tool named wondersharper
https://github.com/magnific0/wondershaper/blob/master/wondershaper
This can limit the bandwith / throughput on a given network-interface. My NGINX server is listing on a virtual network interface that is limited in its bandwith.
ip link add br0 type bridge
ip link set br0 up

Another way of doing it (but not tested) are iptables and the hashlimit extension.
https://ipset.netfilter.org/iptables-extensions.man.html

hashlimit uses hash buckets to express a rate limiting match (like the limit match) for a group of connections using a single iptables rule. Grouping can be done per-hostgroup (source and/or destination address) and/or per-port. It gives you the ability to express "N packets per time quantum per group" or "N bytes per seconds" (see below for some examples).

#matching bytes per second flows exceeding 512kbyte/s

--hashlimit-mode srcip,dstip,srcport,dstport --hashlimit-above 512kb/s

#matching bytes per second hosts that exceed 512kbyte/s, but permit up to 1Megabytes without matching

--hashlimit-mode dstip --hashlimit-above 512kb/s --hashlimit-burst 1mb

While researching the ipbtables part I found this
http://info.iet.unipi.it/~luigi/dummynet/
Documentation can be found here:\
https://www.freebsd.org/cgi/man.cgi?query=ipfw&manpath=FreeBSD+9-current&format=html
That one looks pretty interessting though.


text:
Q: How can I set a value for a LinkedItem? I want to do the following:
electronicSignatureModel.createdBy.Id = DbContext.CurrentUser.CreatedById;

where electronicSignatureModel.createdBy.Id = DbContext.CurrentUser.CreatedById; is a long? and DbContext.CurrentUser.CreatedById is a long?. When I try to do this I get a NullReferenceException. DbContext.CurrentUser.CreatedById has a value, so I think it has to do with electronicSignatureModel.createdBy.Id. electronicSignatureModel.createdBy is a LinkedItem and is null. How can I fill this LinkedItem, so that it is not null?
The LinkedItem looks as follows:
#if SCRIPTSHARP
    [Imported]
    [IgnoreNamespace]
    [ScriptName("Object")]
#endif
    public class LinkedItem : BaseModel
    {
        /// <summary>
        /// entity that represents the item
        /// </summary>

#if SCRIPTSHARP
        [PreserveCase]
#endif
        public string Entity;

        /// <summary>
        /// name of the item
        /// </summary>
#if SCRIPTSHARP
        [PreserveCase]
#endif
        public string Name;

        /// <summary>
        /// id of the item
        /// </summary>
#if SCRIPTSHARP
        [PreserveCase]
#endif
        public long? Id;

    }
}

A: If something is null, it means it has no value. And you can't modify properties of nothing. If you want to set the Id of createdBy, you first have to set createdBy to some non-null value.
How to do that depends on how does the type of electronicSignatureModel, but assuming it's a property with accessible setter (or a public field, but you should avoid those), you can do for example something like:
var createdBy = new LinkedItem();
createdBy.Id = DbContext.CurrentUser.CreatedById;
electronicSignatureModel.createdBy = createdBy;

Or alternatively, using object initializer syntax:
electronicSignatureModel.createdBy =
    new LinkedItem { Id = DbContext.CurrentUser.CreatedById };


text:
Q: How to find output_node_name to build frozen graph? I am referring   https://github.com/dennybritz/cnn-text-classification-tf as a reference. My goal is to build frozen graph from model files. I want to know input and output node in the signature to effectively build the frozen graph. I am printing the proto file from the graph definition using the following code.
saver=tf.train.import_meta_graph('some_path/model.ckpt.meta')
imported_graph = tf.get_default_graph()
graph_op = imported_graph.get_operations() with open('output.txt', 'w') as f:
        for i in graph_op:
            f.write(str(i))

The output I am getting is as follows: https://drive.google.com/drive/folders/1iZQqohx8jAWbSw7XV3vFJuLkaUp0Dt2s?usp=sharing
How do I know which is the output node and which is the input node there are plathora of input and outputs in this file?

A: I recommend to use Tensorboard to visualize graph structure instead of using text file with nodes. You can find more details here.
However the graph itself doesn't have notion of inputs or outputs. You can treat nodes without input connections as good candidates for being input nodes, especially placeholder nodes. Nodes that are connected to loss function are good candidates for being output nodes.
To sum up: In general you need to guess which nodes are the input and which are the output by analyzing network architecture.
As for the repository you referenced, you can read eval.py code and find these lines:
input_x = graph.get_operation_by_name("input_x").outputs[0]
# input_y = graph.get_operation_by_name("input_y").outputs[0]
dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0]

# Tensors we want to evaluate
predictions = graph.get_operation_by_name("output/predictions").outputs[0]

So it is likely that the input node is "input_x" and the output node is "output/predictions".


text:
Q: create pyspark dataframe with json string values and schema I am trying to manually create some dummy pyspark dataframe.
I did the following:
from pyspark.sql.types import StructType,StructField, StringType, IntegerType
data2 = [('{"Time":"2020-08-01T08:14:20.650Z","version":null}')
            ]

schema = StructType([ \
    StructField("raw_json",StringType(),True)
  ])

df = spark.createDataFrame(data=data2,schema=schema)
df.printSchema()
df.show(truncate=False)

but i got the error:
TypeError: StructType can not accept object '[{"Time:"2020-08-01T08:14:20.650Z","version":null}]' in type <class 'str'>

How am i able to put json string into pyspark dataframe as values?
my ideal result is:
+-----------------------------------------------------------------+
|value                                                             |
+-----------------------------------------------------------------------
| {"Time":"2020-08-01T08:14:20.650Z","version":null}|

A: The error is because of your braces. data2 should have list of lists - so replace inner parenthesis with square brackets:
data2 = [['{"applicationTimeStamp":"2020-08-01T08:14:20.650Z","version":null}']]

schema = StructType([StructField("raw_json",StringType(),True)])
df = spark.createDataFrame(data=data2,schema=schema)

df.show(truncate=False)
+------------------------------------------------------------------+
|raw_json                                                          |
+------------------------------------------------------------------+
|{"applicationTimeStamp":"2020-08-01T08:14:20.650Z","version":null}|
+------------------------------------------------------------------+

A: It could also work if you specify data2 as a list of tuples, by adding a trailing comma inside the parentheses to specify that it is a tuple.
from pyspark.sql.types import *

# Note the trailing comma inside the parentheses
data2 = [('{"applicationTimeStamp":"2020-08-01T08:14:20.650Z","version":null}',)]

schema = StructType([
    StructField("raw_json",StringType(),True)
])

df = spark.createDataFrame(data=data2,schema=schema)
df.show(truncate=False)
+------------------------------------------------------------------+
|raw_json                                                          |
+------------------------------------------------------------------+
|{"applicationTimeStamp":"2020-08-01T08:14:20.650Z","version":null}|
+------------------------------------------------------------------+

A: Try this:
import json

rdd = sc.parallelize(data2).map(lambda x: [json.loads(x)]).toDF(schema=['raw_json'])


text:
Q: How to setState() in loop using spread operator I'm trying to set new values for several fields in nested object in state using spread operator in loop, but it works only for last field.
I have an array "formFields" with names of fields which values I want to overwrite. I use map() to compare each element in array with field in state and switch it's value to "true". But it change value only for the last field in array - "comment".
constructor() {
    super();
    this.state = {
        fields: {
            time: false,
            date: false,
            quantity: false,
            comment: false,
        },
    }
}

getFormFields() {
    const formFields = ["time", "quantity", "comment"];
    formFields.map(item => {
        this.setState({
            ...this.state.fields,
            [item]: true
        })
    });
}

What should I do to overwrite values for all the fields I want?

A: Since you are changing state in a loop, and each state you set contains the original item with only changed, the latest change overrides the previous one. Instead, create a new state object with the change, and then setState the object once:
getFormFields() {
  const formFields = ["time", "quantity", "comment"];
  this.setState(formFields.reduce((r, item) => ({
    ...r,
    [item]: true
  }), {}));
}

btw - If the fields you want to set to true are always the same, you can create the object manually, and set it:
getFormFields() {
  this.setState({
      time: true,
      quantity: true,
      comment: true,
  });
}