text:
Q: Unable to connect Spring cloud config server to local Repository windows I am new to spring cloud my objective was to connect local git repo (windows machine --> created at folder Z:/Spring_boot_cloud_microservices_udemy/Projects/local-git-repo/) to spring cloud server.But when i enter its corresponding url (http://localhost:8888/limit-services/default) I am getting default whitelabel error page of eclipse,Can anyone kindly let me identify my mistake .
Following are the projects created :
where limit-service is one of the micro service

Following are its corresponding code:
1] application.properties (limit-service  -- >   Micro service)
spring.application.name=limit-services
server.port=8081
# custom limits to access for config properties
limit-service.minlimit=121
# custom limits to access for config properties
limit-service.maxlimit=1

2] application.properties (spring-cloud-config-server)
spring.application.name=spring-cloud-config-server
server.port=8888
spring.cloud.config.server.git.uri=file://Z:/Spring_boot_cloud_microservices_udemy/Projects/local-git-repo/

3] Spring boot Main class (spring-cloud-server):
@EnableConfigServername
@SpringBootApplication
public class SpringConfigCloudServerApplication {
public static void main(String[] args) {
        System.setProperty("spring.devtools.restart.enabled", "false");
        SpringApplication.run(SpringConfigCloudServerApplication.class, args);
    }

}

4] Local git repo linked to Spring-cloud-server:

5] logs captured on hitting following url is: http://localhost:8888/limit-services/default
2020-05-15 07:22:03.943  INFO 30412 --- [           main] c.s.s.SpringConfigCloudServerApplication : Started SpringConfigCloudServerApplication in 13.168 seconds (JVM running for 14.341)
2020-05-15 07:22:11.689  INFO 30412 --- [nio-8888-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-05-15 07:22:11.690  INFO 30412 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-05-15 07:22:11.700  INFO 30412 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 10 ms
2020-05-15 07:22:11.953  INFO 30412 --- [nio-8888-exec-1] .c.s.e.MultipleJGitEnvironmentRepository : Cannot pull from remote null, the working tree is not clean.

A: After refering following link: https://github.com/in28minutes/in28minutes-initiatives/tree/master/The-in28Minutes-TroubleshootingGuide-And-FAQ#debugging-problems-with-spring-cloud-config-server   i was able to identify my mistake, the mistake was i did not commit application.properties file to my local repo hence i was getting following log info message : Cannot pull from remote null, the working tree is not clean. after commiting file i was able to get desired result.


text:
Q: Approximating area of $log(a)$ of $y=1/x$ from $1$ to $a$ by $n$ rectangles of equal width The problem asks to show that the corresponding approximation to area under $y=1/x$ from $b$ to $ab$ by $n$ rectangles has exactly the same area. I'm not sure where to start. Then Deduce by the method of exhaustion, that the areas under $y = 1/x$ from $1$ to a and from b to ab are equal. And finally deduce the definition of $log$, that $log (ab) = log (a) + log (b)$.
Any help would be appreciated, thanks

A: First I suggest you make a graph to visualize the approximation.
You could try to write the first approximation (with $x$ from $1$ to $a$).
You have $n$ rectangles, all of them having width equal to $\frac{a-1}{n}$.And the $k$-th rectangle has height $\frac{1}{1+k\frac{a-1}{n}}$.
So the first approximation is
$$S_1 = \sum_{k=1}^n\frac{a-1}{n}\times\frac{1}{1+k\frac{a-1}{n}}=\sum_{k=1}^n\frac{a-1}{n+k(a-1)}$$
The second approximation has $n$ rectangles of width $\frac{ba-b}{n}=\frac{b(a-1)}{n}$ and height $\frac{1}{b+k\frac{b(a-1)}{n}}$.
Thus,
$$S_2=\sum_{k=1}^n \frac{b(a-1)}{n}\times\frac{1}{b+k\frac{b(a-1)}{n}}$$
The $b$'s simplify and we see that $S_1=S_2$.
Remark: this goes with the fact that $\log(ab) - \log(b)=\log(a)+\log(b)-\log(b) = \log(a) = \log(a)-\log(1)$.

A: Part 1
We show that corresponding rectangles have equal areas.
Figure 1 demonstrates how to construct the product $ab$ via straightedge and compass. It is important to note that the lines $CB$ and $AD$ are parallel. (You could choose the line through $O$ perpendicular to $OA$, and then visualise the rectangular approximations concurrently on the full graph of $y=1/x$).

$\tag{Fig. 1}$
Next, consider any partition $P_1=(x_0,...,x_n)$ of the interval $[1,a]$, where $1=x_0\lt x_1\lt ... \lt x_n=a$. From Figure 1 we can construct the partition $P_2=(y_0,...,y_n)$ of $[b,ab]$ by the same parallel projection as was used to construct the line segment $OD$. Figure 2 demonstrates the case $n=4$ .

$\tag{Fig. 2}$
The value of this construction is that we can plainly see, via similar triangles, a simple relation between corresponding points of $P_1$ and $P_2$:   $$\tag{1}\frac{x_i}{y_i}=\frac{1}{b}.$$
Hence, as areas of rectangles $A\left(\square_{a_i}\right)$ and $A\left(\square_{b_i}\right)$ are simply the widths $\Delta x=x_i -x_{i-1}$, $\Delta y=y_i -y_{i-1}$ multiplied by the heights $f(x_{i-1})=\frac{1}{x_{i-1}}$ and $f(y_{i-1})=\frac{1}{y_{i-1}}$, we get
$$\tag{2} A\left(\square_{a_i}\right)=\frac{x_i-x_{i-1}}{x_{i-1}} =\frac{\frac{y_i}{b}-\frac{y_{i-1}}{b}}{\frac{y_{i-1}}{b}}=\frac{y_i-y_{i-1}}{y_{i-1}}=A\left(\square_{b_i}\right).$$
Part 2
In modern parlance The Method of Exhaustion was essentially the demonstration that you could approximate a given figure by shapes with known areas arbitrarily closely. In order to show that the two areas are indeed equal, we take a single rectangle in the partition $P_1$ as in Figure 3.

$\tag{Fig. 3}$
Next, we consider what happens to the shaded area $A\left(\color{grey}{\blacksquare}\right)$ after we subdivide the interval $\Delta x$ in two:

$\tag{Fig. 4}$
It is easy to show what this picture  suggests, which is that the sum of the shaded areas in Figure 4 is exactly $$\tag{3}\frac{1}{2}A\left(\color{grey}{\blacksquare}\right).$$ In general, after $n$ such subdivisions the sum of the $2n$ shaded regions is $$\tag{4}\frac{1}{2n}A\left(\color{grey}{\blacksquare}\right)$$
and since we know $\frac{1}{n} \rightarrow 0 $ as $n \rightarrow \infty$ (obviously the Greeks would not have considered a limit like this) the differences between the rectangles inscribed under and circumscribed over the graph of $y$ can be made arbitrarily small. Since the graph of $y=1/x$ is contained in the shaded regions an equivalent statement is that the areas of the rectangles get arbitrarily close to the area under $y$ as $n$ increases.  By Part 1 we can conclude $\log{a}$ is equal to the area $\square$ under the graph of $y$ between $b$ and $ab$.
Part 3
By definition $\square$ is equal to the difference between $\log{ab}$ and $\log{b}$. Hence we can conclude  $$\tag{4} \log{a}= \log{ab} - \log{b}\implies \log{a} + \log{b}= \log{ab}.$$ (Alternatively, you could note that the same equality holds between $\log{b}$ and the area under the graph between $a$ and $ab$. You can then visualise the sum on the graph by marking off $a$, $b$, and $ab$ and considering the overlaps of shaded regions).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert int bytestream to a float bytestream I have a 32-bit integer. The bit stream is actually a bit stream for a 32-bit float (IEEE 754). I tried converting it with:
unpack('f', $input);

This generates a float, but it seems it is not the right number
For example, if I pass in 1, I should be coming out with 1.4012984e-45, according to the IEEE754 converter,
but I am coming with 2.5638762224389E-9
Thanks a lot for any help/advice.

A: You're confusing things:
<?php
$s = "\x01\x00\x00\x00";
$t = "0001"; //same as "\x30\x30\x30\x31"
var_dump(unpack('f', $s));
var_dump(unpack('f', $t));

gives

array(1) {
  [1]=>
  float(1.4012984643248E-45)
}
array(1) {
  [1]=>
  float(2.5638762224389E-9)
}

According to the manual, these results are not guaranteed (the "f" modifier in unpack will depend on the endianness of the system). But one thing is a byte stream which has actually those values and other thing is to have a byte stream which happens to translate to "0001" when the ASCII charset is considered.


text:
Q: How can I block a Bot with .htaccess Im having problems with bot* and *bot.  I have limited knowledge of .htaccess but have been blocking bots with .htaccess rules below.
My question is in 2 parts:

*

*Is my approach correct and if not how do I improve it, and

*what is the correct syntaxt to block *bot and bot*
Many thanks in advance
#Enable RewriteEngine
RewriteEngine On

# Stop the Nasties!!
RewriteBase /

RewriteCond %{HTTP_USER_AGENT} ^autoemailspider [OR]
RewriteCond %{HTTP_USER_AGENT}  baiduspider [NC,OR]
RewriteCond %{HTTP_USER_AGENT}  baidu [NC,OR]
RewriteCond %{HTTP_USER_AGENT}  Baiduspider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Baiduspider* [OR]

RewriteRule ^.* - [F,L]

A: RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [OR]
RewriteCond %{HTTP_USER_AGENT} ^Bot\ mailto:craftbot@yahoo.com [OR]
RewriteCond %{HTTP_USER_AGENT} ^Download\ Demon [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus
RewriteRule ^.* - [F,L]

Yes, it is right way...
And, if you want to block any IP, then as an example:
Order Deny,Allow
Deny from 127.0.0.1

A: You can combine all those conditions into one as:
RewriteCond %{HTTP_USER_AGENT} (autoemailspider|baidu) [NC]
RewriteRule ^ - [F]

NC is for ignore case.


text:
Q: How to avoid using global functions in NodeJS? I have a global function in my main JS file and i need to call it several times from a module. I heard it is bad because it can create a function name collision between a local (from module) and a global function name (from main js). The global function can be called 100 times from the require module. Is there an alternative way to achieve the following without using global functions?
main.js with global function
const myMod = require('./module.js");
global.myGlobalFunction = function(param){
console.log("do something with",param);
}

module.js with the calls of the global function:
module.exports = function(){
myGlobalFunction("class");
myGlobalFunction("this");
myGlobalFunction("bubu");
// other jobs to do
}

A: The neater way to do it is to use modules like this:
module.js
class myGlobalUtil {
  myGlobalFunction(param){
    console.log("do something with",param)
  }
  get GetFromParam(myParam){
    return this.myGlobalFunction(myParam);
  }
}
module.exports = myGlobalUtil;


text:
Q: How do you change the mouse over highlighting? In GWT, I am using CellTable.
When you mouse over the CellTable it highlights each row.
How do change the behavior of the highlighting from the mouse over? Specifically:

*

*change the color of highlighting

*disable/enable

*make it highlight only the specific grid item at your cursor (instead of the entire row)
( The current hack I have is to create a bunch of 1 column wide CellTables and add them to a VerticalPanel layout... creating the illusion that there is one CellTable and it highlights each grid according to your cursor. Is this bad? Why? performance? )

A: I'll just add for number 2) on your list, you can simply do
cellList.setSkipRowHoverStyleUpdate(true)

That completely disables highlighting. There are also two more setSkip-functions on CellList related to hovering.

A: You will notice the CellTable uses a ResourceBundle, which means all the css styles get obfuscated ... this makes it more difficult to override styles.
The CellTable constructor will actually allow you to override the default ResourceBundle. So first, you need to create your own resource bundle like this:
public interface CellTableResources extends Resources {

        public CellTableResources INSTANCE =
                GWT.create(CellTableResources.class);

        /**
         * The styles used in this widget.
         */
        @Source("CellTable.css")
        CellTable.Style cellTableStyle();
}

Then you need to create your own CSS file. I recommend copying the CellTable style directly into your project and use that as a starting point. You can find it here:
http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/src/com/google/gwt/user/cellview/client/CellTable.css
Make sure the style is injected first, and then you just feed it into the CellTable's constructor like this:
   CellTableResources.INSTANCE.cellTableStyle().ensureInjected();
   myCellTable = new CellTable<T>(Integer.MAX_VALUE,CellTableResources.INSTANCE);

Specifically, you'll want to tweak these styles:

*

*cellTableKeyboardSelectedRow

*cellTableKeyboardSelectedRowCell

*cellTableSelectedRow

*cellTableSelectedRowCell

*cellTableKeyboardSelectedCell

It is important to note that the cell table differentiates between the 'selected row' and the 'keyboard selected row'. The selected row is the actual row selected (ie via SelectionModel). The keyboard selected row refers to what is highlighted when the user is pressing the up / down key, but does not mean the row is actually selected (if that makes sense).

A: *

*CellTable can be styled via CSS: How do I style a gwt 2.1 CellTables headers?

*To disable highlighting just set the hover CSS property to nothing.

*Possibly - try tweaking the .cellTableSelectedRow and .cellTableSelectedRowCell.
Here is the original CellTable.css: http://www.google.com/codesearch/p?hl=en#A1edwVHBClQ/user/src/com/google/gwt/user/cellview/client/CellTable.css&q=cellTableLastColumn&d=8


text:
Q: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'esnext' /* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

I am not able to find what is the error:
Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'esnext'

A: It is telling you that the value for  "module": "es2020" is invalid and that it needs to be one of the values it mentions. Since your target is set to es2015, perhaps setting "module": "es2015" would fix your issue


text:
Q: c++ error c2373 redefinition different type modifiers When I run my program, I get this error.

c++ error c2373 'readBalance' redefinition different type modifiers

I want to read what is in the file then write.
// ReadAndWrite.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

double readBalance;
double balance;

int main ()
{
    double readBalance();
    double balance = 0;
    ifstream readfile;
    readfile.open("renatofile.txt");
    char output [100];

    if (readfile.is_open())
    {
         while(!readfile.eof())
         {
             readfile>>output;
         }
    }
    readfile.close();
    balance=atof(output);
    return balance;
}

Can it be because I'm returning balance?

A: I'm guessing what you wanted to do was to define readBalance as a function and then call it from main, something like this:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cstdlib>       // you need this for atof

using namespace std;

double readBalance();    // this is a function prototype
double balance;          // this is a global variable - you don't need this at all

int main ()
{
    cout << readBalance() << endl;    // this will print the balance
    return 0;
}

double readBalance()
{
    double balance = 0;               // this local variable hides the global...
    ifstream readfile;
    readfile.open("renatofile.txt");
    char output [100];

    if (readfile.is_open()) {
        while(!readfile.eof()) {
            readfile>>output;
        }
    }
    readfile.close();
    balance=atof(output);
    return balance;
}

Note that you've declared balance both globally and locally and that's probably not what you want.
Btw, you're also missing the include needed for the atof function (cstdlib).

A: It is because of
    double readBalance();

I don't know why you put that there.

A: Function declarations placed in local scope still declare names with external linkage, not local names. This means that your local double readBalance(); declaration declares readBalance as name of a global function. At the same time, a few lines above you declared readBalance as a global variable.
Since both entities are global (i.e. have external linkage), they conflict with each other. This conflict is what triggers the error message.
You might note that balanceis also "redeclared" in local scope. With balance the conflict does not occur, since in local scope balance is declared as a variable. Variable declarations placed in local scope produce local names with no linkage. Thus, local variable balance is completely independent from the global variable balance declared above. This is perfectly legal.
So, the question is why are you attempting to declare readBalance as a variable and as a function at the same time? And what is readBalance supposed to be (since you never use it in your code)?


text:
Q: Unexpected token ILLEGAL with gzip compression I am having a problem with gzip compression on my site.  I've combined several javascript files to one files and they work ok without compression. Afterwards I've compressed them (gzip) and tried to run the site again, but get the following error:

Uncaught SyntaxError: Unexpected token ILLEGAL

I've compressed the file using several methods, one using gzip software and I also tried other gzip online compression tools like this one.
I can't understand why I get this error why it doesn't work, because the non-compressed version does work. I ran the site on Chrome, latest version.
It also tells me that the error is in line 1

all_js.js.gz:1

Of course the compressed code has many lines, not just one.
I've read a few answers, but nothing regarding gzip compression.
I get this error when working with Visual Studio (ASP.NET) on local machine.
I tried serving the file from S3 with 'application/x-gzip' headers, but it still didn't work. I want to serve my files via CDN after compressing, so I don't search for server compression solutions.

A: You cannot compress a javascript file with gzip or any other zip routine and load it into your webpage.
You can do one of two things:

*

*Use a javascript code compression tool like the YUI compressor.

*Configure your webserver to compress the files (please read the documentation of your webserver, it should not be very difficult)


text:
Q: Найти и выделить слово в  Я хочу написать функцию выделения определённого слова в textarea, но не знаю как можно найти координаты этого слова, подскажите пожалуйста выход из ситуации?

<script type="text/javascript">
function findSelectTxt(text) {
    var input = document.getElementById ("myText");
    // Координаты начала и конца выделения 'text'
    input.selectionStart = 6;
    input.selectionEnd = 15;
    input.focus ();
}
</script>
<textarea id="myText">здесь некоторый текст</textarea>
<button onclick="findSelectTxt('некоторый')">Найти и выделить</button>

A: с помощью indexOf находим индекс начала строки, а индекс конца искомой строки получаем так: длина искомой строки (кол-во символов) + позиция первого символа искомой строки

function findSelectTxt(text) {
    var input = document.getElementById ("myText");
    // Координаты начала и конца выделения 'text'
    input.selectionStart = input.value.indexOf(text);
    input.selectionEnd = input.value.indexOf(text) + text.length;
    input.focus ();
}
<textarea id="myText">здесь некоторый текст</textarea>
<button onclick="findSelectTxt('здесь')">Найти и выделить здесь</button>
<button onclick="findSelectTxt('некоторый')">Найти и выделить некоторый</button>


text:
Q: Run curl from .sh script with defined Content-Type When I'm trying to run test.sh script I've always receive error from curl:
curl: (6) Couldn't resolve host 'application'

test.sh:
#!/bin/sh
CT="Content-Type:\ application/json"

TEST="curl http://127.0.0.1 -H $CT"
echo $TEST

RESPONSE=`$TEST`
echo $RESPONSE

But if I just run following command from console everything fine:
curl http://127.0.0.1 -H Content-Type:\ application/json

Could you please let me know what is wrong in script, as I understand something is wrong with 'space' escape, but have no idea how to fix it.
Also I've tried following combination, but result the same:
CT="Content-Type: application/json"
TEST="curl http://127.0.0.1 -H \"$CT\""

UPD:
bash / dash is only available on server. (/bin/sh --> bash)
GNU bash, version 4.2.10(1)-release (x86_64-pc-linux-gnu)

A: Run the following: (delete the space after Content-Type)
#!/bin/bash
CT="Content-Type:application/json"

TEST="curl http://127.0.0.1 -H $CT"
echo $TEST

RESPONSE=`$TEST`
echo $RESPONSE

A: You can try with: bash -c your_bash_file.sh It worked for me with the same problem


text:
Q: How to get live scsi traces from Vscsistats? Here are things I already know, using vscsistat -t option I can get command traces for "VM/.vmdk" on ESxi.
Steps to get scsi traces are:

*

*Start capturing traces, On Successful starting will generated log_channel (id)
vscsiStats -s -t -w worldgroupid -i handleid

*Dump traces to file in binary format
logchannelloger channelname filename

*Get human readable fromat from trace file.
vscsistats -e filename

With this steps, each time I fire command vscsistats -e filename to get scsitrace in human readable format from tracefile, It returns trace data from beginning  to till time command is fired.
If I fire command after 10 minutes then again it return traces from begining to time of firing command.
So question is there any way to dump traces as they come to binary file directly to stdout like tail -f or blktrace -o - |blkparse -i - like on linux?

A: It is not designed like that:
  VscsiStats -- This tool controls vscsi data collection for virtual machine disk
                disk I/O workload characterization. Users can start and stop online data
                data collection for particular VMs as well as print out online histogram data.
                Command traces can also be collected and printed.

  The following histogram related options are available:
     -h, --help will print the usage
     -l, --list will list the available virtual machines and their virtual disks
     -r, --reset will reset the stats
     -s, --start will start vscsiStats collection; exclusive of -x
     -x, --stop will stop vscsiStats collection; exclusive of -s
     -w <worldgroup id>, --worldgroupid specifies a worldID to use for this operation
     -i <handle id>, --handleid specifies a vscsi handleID to use for this operation
           requires the -w option
     -p <histoType>, --printhistos will print out the current histograms for the specified
            histogram type. May be used in conjunction with -w and -i.
            histoType must be one and only one of:
                 all, ioLength, seekDistance, outstandingIOs, latency, interarrival
     -c, --csv will use comma as delimiter in conjunction with -p

  The following command trace related options are available:
     -t, --tracecmds will start scsi cmd traces; in conjunction with -s
         Note:- the -t option consumes significant system resources so
                enabling it indefinitely is not advisable
              - try to limit the #virtual disk for which cmd tracing is enabled at any
                given time by using --worldgroupid and/or --handleid options.
              - trace contains NO customer sensitive data
                - only information recorded is:
                  - serialnumber, IO block size, number of scatter-gather elements
                  - command type, block number, timestamp
                - Therefore, actual data/payload of commands is not stored
              - If successfully started, log channel id(s) will be printed out.
                To store the command trace in a file for later processing, invoke:
                $ logchannellogger <log_channel_id> <binary_trace_file>
     -e <trace file name>, --traceprettyprint reads in a vscsi cmd trace from the given
        filename and sends a CSV formatted output to stdout; exclusive of all other options

  vscsiStats Usage:
         vscsiStats [options]

What you can do is launching watch -n 1 cat <file> to refresh the content of your file in another shell.
If you don't want to start manually your commands, you can batch them and add them to cron.
By the way be carefull some file in esxi are reset each reboot.
Here the way to add a script to cron without being reset each startup:

*

*edit file /etc/rc.local.d/local.sh
  #add to crontab a task
  echo "01 00 1,15 * * root /vmfs/volumes/datastore1/script/yourscript.sh" >> /var/spool/cron/crontabs/root
  #stop crontab process
  kill $(cat /var/run/crond.pid)
  #start crontab process
  crond

do not forget to set your script as executable
chmod +x /vmfs/volumes/datastore1/script/yourscript.sh


text:
Q: Перенос данных между таблицами и их сохранение Работаю с фреймворком YII2 совсем недавно и по этому много чего еще не знаю и не понимаю. В БД есть 3 таблицы)
Таблица хранящая название тем S_QUIZ_TOPIC с полями:
integer $ID_REC
string $NAME_TOPIC
integer $RANDOM
integer $MAX_TIME
string $DT_UP
integer $STATUS

Таблица хранящая вопросы S_QUIZ_QUESTION с полями:
integer $ID_REC
string $NAME_QUEST
string $TEXT_QUEST
string $MSG_QUEST
integer $RANDOM
string $DT_UP
integer $STATUS

И связывающая эти 2 таблицы S_QUIZ_TQ:
integer $ID_REC
integer $ID_TOPIC
integer $ID_QUESTION
string $DT_UP
integer $STATUS

Задача следующая:
Нужно реализовать 2 таблицы, в одной должен выводится список всех вопросов (Поле $NAME_QUEST), которые есть в таблице S_QUIZ_QUESTION, во второй должен выводиться список вопросов, которые входят в эту тему. Реализовать перенос данных между этими таблицами и сохранение их в бд в связывающую таблицу.
Сделал 2 таблицы в которых отображаются следующие данные:
1) В левой таблице выводится список всех вопросов из таблицы S_QUIZ_QUESTION.
2) В правой таблице выводится список вопросов, которые входят в данную тему.
Вывел данные в таблицу следующим образом:

         Вопросы входящие в эту тему

         Вопросы входящие в экзамен

               <?php Pjax::begin(); ?>

Вопросы не входящие в эту тему

                  <input id="search-avaliable">

                  <?= Html::activeDropDownList($model, 'ID_REC', $LeftItems, ['multiple' => true, 'size' => 20, 'style' => 'width: 100%']) ?>
               <?php Pjax::end(); ?>

            >>

            <<

            <?php Pjax::begin(); ?>

Вопросы входящие в эту тему

               <input id="search-assigned">

               <?= Html::activeDropDownList($model, 'ID_REC', $RightItems, ['multiple' => true, 'size' => 20, 'style' => 'width: 100%']) ?>
            <?php Pjax::end(); ?>

Теперь возник вопрос, как мне реализовать перенос данных между этими таблицами? Я могу выбрать любую тему щелчком мыши в левой таблице. Но что мне теперь следует сделать, что бы при нажатии на соответствующие клавиши выбранный вопрос переносился из левой таблицы в правую и сохранялся в бд и наоборот?
Код контроллера:
public function actionView($id)
{
    $model = $this->findModel($id);
    $searchModel = new SQuizQuestionSearch();
    $dataProviderLeft = $searchModel->search(Yii::$app->request->queryParams);
    $dataProviderRight = new ActiveDataProvider([
        'query' => $model->getQuestions(),
    ]);

    $LeftItems = ArrayHelper::map($dataProviderLeft->getModels(),'ID_REC','NAME_QUEST');
    $RightItems = ArrayHelper::map($dataProviderRight->getModels(), 'ID_REC', 'NAME_QUEST');

    return $this->render('view', [

        'model' => $model,
        'searchModel' => $searchModel,

        'dataProviderLeft' => $dataProviderLeft,
        'LeftItems' => $LeftItems,

        'dataProviderRight' => $dataProviderRight,
        'RightItems' => $RightItems,
    ]);
}

Код модели S_QUIZ_TOPIC:
public function getSQUIZTQs()
{
    return $this->hasMany(SQUIZTQ::className(), ['ID_TOPIC' => 'ID_REC']);
}

public function getQuestions()
{
    return $this->hasMany(SQuizQuestion::className(), ['ID_REC' => 'ID_QUESTION'])->via('sQUIZTQs');
}

Код модели S_QUIZ_QUESTION:
public function getSQUIZTQs()
{
    return $this->hasMany(SQUIZTQ::className(), ['ID_QUESTION' => 'ID_REC']);
}

public function getTopic()
{
    return $this->hasMany(SQuizTopic::className(), ['ID_REC' => 'ID_TOPIC'])->via('sQUIZTQs');
}

Код модели S_QUIZ_TQ:
public function getIDQUESTION()
{
    return $this->hasOne(SQuizQuestion::className(), ['ID_REC' => 'ID_QUESTION']);
}

public function getIDTOPIC()
{
    return $this->hasOne(SQuizTopic::className(), ['ID_REC' => 'ID_TOPIC']);
}

Фото как это выглядит:

A: Вот переделаный view, в котором реализовано перемещение данных между этими таблицами:

      <?php Pjax::begin(); ?>

Вопросы не входящие в эту тему

         <input id="search-avaliable">

         <?= Html::activeListBox($model, 'ID_REC', $LeftItems, ['multiple' => true, 'size' => 20, 'style' => 'width: 100%', 'id' => 'first']) ?>
      <?php Pjax::end(); ?>

      >>

      <<

      <?php Pjax::begin(); ?>

Вопросы входящие в эту тему

         <input id="search-assigned">

         <?= Html::activeListBox($model, 'ID_REC', $RightItems, ['multiple' => true, 'size' => 20, 'style' => 'width: 100%', 'id' => 'second']) ?>
      <?php Pjax::end(); ?>


text:
Q: Windows service starts winforms application I have this problem, I wrote a WinForms application, I have use it for a while with no problems. Next I just wrote a windows service to start/stop automatically my winforms app. But now the window is not shown, and in the task manager it's running. Besides, for testing my service, first it was a console app, so Console.WriteLine() was useful to display data, status, variables, etc, once it became a service, no console anymore. So, it's anything I'm missing?
Well, what I need is the service starting/stoping the winform application. It's a monitoring like. So, if the winform app is not running, creates a process, and starts it. But if is midnight, then the app should not be running, then the service finds the process and closes it. I don't want to turn the winform app into a service, or the service into a winform app.
I first thought just to put a shortcut to my winforms app in the "startup" folder to start it, but I need to close it, and/or restart it. So that's why I wrote the service.
Thanks!

A: As of Windows Vista, a service can't interact directly with the desktop, meaning that it can't produce a visible form.
Even if you set it to try to do so, the best you will get is a UAC-style prompt indicating to the user than your program would like to be displayed. This was the result when we tried to follow this: How can a Windows service execute a GUI application?
We have one Windows app that absolutely needs to interact with the desktop  it was originally written as a Windows Service.  In order to get around the restrictions, we were forced to write it as a WinForms app with the Visible property of the main form set to "false".  When we need to show it, we set it to "true".  It's a hack and we know it, but we never could find a better solution.
This post does provide alternatives.  They didn't work for us, but perhaps your situation is different.  http://msdn.microsoft.com/en-us/library/windows/desktop/ms683502(v=vs.85).aspx


text:
Q: Am I allowed to declare a lifecycle interceptor on an interceptor? I have my business bean defined thus:
@Local
@Interceptors(BusinessInterceptor.class})
public class MyBean implements SomeBean { ... }

And then I want my BusinessInterceptor to be configured with Spring's SpringBeanAutowiringInterceptor:
@Interceptors(SpringBeanAutowiringInterceptor.class)
public class BusinessInterceptor {
    @Autowired
    private SomeSpringBean someSpringBean;
}

Is this allowed/legal? I'm getting errors (NPEs, mostly) suggesting that the fields in BusinessInterceptor have not been initialized properly.

A: I doubt this can work. If I understand well your scenario, you have basically two DI containers, one is Spring and the other the app. server itself. Each one manages different elements. The BusinessInterceptor is created by the app. server which is unaware of Spring -- the @Autowired bean is then not set.
( Note that Spring and EJB3 have become quite similar now. You can have the same functionalities as EJB with Spring. Spring has indeed declarative transactions, dependency injection and AOP facilities similar to EJB3 interceptors (these are the main managed features). On the other hand, EJB3 is now so lightweight that there isn't really a compelling reason to use Spring with with EJB3. See Future of enterprise Java: full stack Spring or full stack Java EE. But this does not answer the question, and is just a little digression of mine :)


text:
Q: Shrink into one page with ClosedXML I create an Excel sheet with ClosedXML, everything looks good now but sometimes the content goes overflow a little bit. To ensure that won't happen, I want to shrink the content into one page no matter what.
So question is: How do I shrink everything into one page with ClosedXML.

A: worksheet.PageSetup.FitToPages(1, 1);


text:
Q: AJAX.BeginForm PostURL being corrupted I'm experiencing a strange problem while trying to use the Ajax.BeginForm method of ASP.NET MVC3.   The form renders properly on the page with the correct action attribute.  However, when the form is submitted, the "OnFailure" event is returning a "Not Found" 404 error.
If I watch the request with fiddler, I see that the post URL is "/[Object NodeList]" which is obviously invalid.
My Razor code is as follows:
@using (Ajax.BeginForm("Save", "Items", new AjaxOptions { UpdateTargetId = "itemContainer", InsertionMode = InsertionMode.Replace, OnFailure = "onFailure"}))
{
    <div style="position:absolute; bottom:20px; left:200px;">
        <button type="submit" id="Save" name="action" value="Save">Save</button>
        <button type="submit" id="Cancel" name="action" value="Cancel">Cancel</button>
    </div>
}

A: The problem was using "action" for the name attribute on the submit buttons.  As soon as I changed the name attribute to a different value, everything started working perfectly.
I'm guessing that there is a jQuery selector in the unobtrusive ajax library that got confused.

A: Do you have unobtrusive JavaScript on or off in your web.config?  Im first guessing here the ms Ajax library is acting goofy so enable unobtrusive so we get jquery support.
What is your form action set to? Post your form HTML element if you can .


text:
Q: How to Best Manage High PostgreSQL CPU Use? I am trying to fix a high PostgreSQL CPU use problem.  We are using PostgreSQL 8.0.9 and when our JEE web application (in JBoss) is used in certain load increase conditions, top shows a slow increase in processes for PostgreSQL.  When the problem occurs, there are approximately 12-15 PostgreSQL processes all showing SELECT on the far right of the process information and approximately 6-7% CPU usage each and then the app slows down a lot.
JBoss version: JBoss (MX MicroKernel) 4.0.3
Operating system: CentOS Linux 5.5
Kernel and CPU: Linux 2.6.18-194.26.1.el5 on x86_64
Processor information: 2 x Intel(R) Xeon(R) CPU E5420 @ 2.50GHz, 8 cores
Currently, our thought is to throw more hardware at it.  If we do this, would the best option be something like Option A below or Option B?
Option A: 4 x AMD Opteron™ 6100 Series Processors each with 12 Cores
Option B: 4 x Intel® Xeon® 7500 series Processors each with 8 Cores
Is it correct to assume that CentOS Linux 5.5 with PostgreSQL 8.0.9 will scale proportionately with the addition of this many processors and cores (Ex. 4 processors each with 12 cores)?  Is there something else I should consider in terms of throwing more hardware at it?

A: The question is impossible to answer, we have no idea what is going on. You're talking about 12-15 connections, that's next to nothing. But, when executing very complex queries, or using a bad database schema, lack of indexes, etc. cpu usage can go up any time.
Version 8.0.9 is serious problem, 8.0 is EOL as of october 2010 and the lastest fix is version 8.0.26 (4 years of bugfixes after 8.0.9). You should at least update to this version, to fix many bugs in 8.0.
Start logging the queries, use EXPLAIN to see the queryplan, take a look at VACUUM and you might need a REINDEX as well. Your hardware looks fine for now, you first have to find the source of the problems.
Consider to hire a PostgreSQL dba for a couple of days.

A: If you're showing high CPU usage, it could be due to slow queries. I would suggest enabling the slow query logging features in postmaster.conf and checking for queries that take longer than they should.
There's also the possibility that you are I/O bound, as slow disks can easily cause queries to start backing up. I would suggest installing htop and checking what percentage of your CPU wait time is attributed to iowait.
Aside from that, I would highly encourage upgrading to the latest version. There have been some massive performance improvements since 8.0, and the current stable version (9.0.x at the time of writing) offers more information when EXPLAIN VERBOSE ANALYZEing queries.
Generally speaking (and all other conditions being equal), PostgreSQL scales really well as you add cores (each additional core adds approximately a 96% gain in performance (out of a theoretical 100% performance gain possible per additional core)).
My initial gut feeling however is that your disks can not keep up.

A: I think you'll benefit from the book PostgreSQL 9.0 High Performance.  It's available in PDF (instant download) as well as in dead tree format.
We've just rebuilt our database using the advice in this book.  Our new database box blows the old one away, and we didn't have to spend a ton of money doing it.  There are chapters that specifically address each of your questions.  There are answers, but better yet, there are also methods (how do you measure your hardware to know how fast it is?)
I'm no Postgresql expert, but I'll tell you what I've learned about hardware and Postgresql.  Your mileage may vary.
In general, for the databases I've had experience with, what matters more than number and speed of CPUs is:

*

*Adequate RAM.  Databases drink memory like a wino drinks rotgut.

*I/O bandwidth.  Databases love I/O.

You get I/O bandwidth with RAID.  RAID10 does well for the bulk of Postgresql data.  The more drives, the better for performance.  Put xlog on a separate device, if you can.  That one can be RAID1.  The use of a hardware RAID card with battery-backed cache will give you the best performance.

A:
When the problem occurs, there are
approximately 12-15 PostgreSQL
processes all showing SELECT on the
far right of the process information
and approximately 6-7% CPU usage each
and then the app slows down a lot.

12x6=72%, so even at the lowest point, the CPUs are rather busy.  Throw in everything else, and it's pretty clear why you're running flat-out.  (This is assuming you're looking at the CPUs as an aggregate; when you look at process time in top, are you pressing the 1 key to see all the individual CPU time, or just looking at the number it presents, which is all the CPUs combined?)

Currently, our thought is to throw
more hardware at it. If we do this,
would the best option be something
like Option A below or Option B?
Option A: 4 x AMD Opteron™ 6100 Series
Processors each with 12 Cores
Option B: 4 x Intel® Xeon® 7500 series
Processors each with 8 Cores

More cores.  PostgreSQL will use a process-per-core model, so the more the better.  I would look at maybe 2x AMD CPU at 12 each for 24 cores total, and then purchase the remaining 2 CPUs over time, allowing you to budget them in.

Is it correct to assume that CentOS Linux 5.5 with PostgreSQL 8.0.9 will scale proportionately with the addition of this many processors and cores (Ex. 4 processors each with 12 cores)?

Yes.  I may be mistaken but I believe that older kernel compiles used a fixed number in a C header file to determine the max number of CPUs to look for, which usually had an upper bound of 32 at compile time.  If you had a "big" machine you would just bump the number to something higher and recompile.  Not entirely sure but I think they removed that constant in the 2.6 series so you should be fine.

Is there something else I should consider in terms of throwing more hardware at it?

You may wish to look at tuning the software a bit more before throwing hardware at it (or tune it and still get the new hardware).
If it is a SELECT statement, any chance you can log it and then use EXPLAIN to find out where it is spending its time?  Use PgAdmin to run and tune the query by hand until you can get the execution time down a bit.  If the SELECT statement is programmatic, you could still look at the impact of using a new index.
How much memory have you allocated to PostgreSQL?  How much on a per-process basis?  How much shared memory is allocated?  All of these can have an adverse impact on how the database runs.
Are there any other processes or services that could be disabled (to free up memory) or re-niced (to reduce CPU consumption)?

A: I've been recently experiencing similar issues on a small database (7 tables, 30 MB) with queries having lots of joins. The machine is a VM with 2GB RAM and always seem to use less than 160MB of it.
It worked out very fast until we added about 1M of new data. Then the server (8.4.5) started to hit 100% CPU for anywhere between 5 seconds to 30 minutes with the same queries that were sub-second.
We managed to fix the problem by server upgrade. Tests with 8.4.9 and 8.4.12 did not show the bad behaviour (but 8.4.8 did).


text:
Q: Automatically offset parasite axes in matplotlib I am creating plots with up to 5 parasite y-axes using Matplotlib 3.1 and parasite_axes and I would like to automatically spaces the yaxes instead of specifying an offset in the code. Currently I have to plot the figure to see if the axis overlap then manually adjust the width of the figure to make the correct amount of space for the parasite axes and then manually add an offset to each axis so they don't overlap. If anything changes in the figure, such as DPI or the number of digits in the label, then I have to go through all of this again.
I have tried to get the bbox of just the yaxis but I seem to be unable to get anything except for the bbox of the entire plot. Without knowing the width of the axis there doesn't seem to be any way to calculate the correct spacing for these.
#Example from the matplotlib website:
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
                                axes=par2,
                                offset=(offset, 0))

par1.axis["right"].toggle(all=True)
par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right"].label.set_color(p3.get_color())

plt.show()


text:
Q: How to solve Microsoft SQL Server. Error 233. Provider: SSL Provider After the global RansomeWare attack, we updated our Windows Server 2012 R2 only to find out that our SQL Server Management Studio (SSMS) stopped working. Whenever we try to connect to SSMS locally or remotely it provides us the following Error:

A connection was successfully established with the server, but then
  an error occured during the login process. (Provider: SSL  Provider,
  error: 0 - No process is on the other end of the pipe.) (Microsoft SQL
  Server, Error: 233)

I tried logging in with "Windows Authentication" and the error was same. I also tried solutions for similar SQL Error 233 issues but with no result. All the SQL Error 233 issues I came across on Stack Overflow are related to Shared Memory provider but not SSL Provider.
Finally I came across this post: https://www.sqlservercentral.com/Forums/Topic1810025-3411-1.aspx and tried the following solutions:

*

*Enabled Ciphers RC4 128/128, RC4 50/128, RC4 56/128

*Enabled TLS 1.0    Server Protocol

*Disabled SSL 2.0 (Registry does not have SSL 3.0) [also tried
enabling SSL 2.0 but didn't work as well]

*Enabled TLS 1.0,1.1,1.2 Protocols althogether as well.

But none of them worked and we still couldn't log in to SQL Server Management Studio.
Any help or suggestion is highly appreciated. Thank you in advance.

A: After much tinkering I found out that the Windows update have modified the TLS and SSL settings wrong. I had to specifically make changes to the Cipher Suits and Protocols in the registry in order to make it work and now we can log in to SSMS successfully (both locally and remote log in). So the specific changes I have made to registry is as follows:

Changes in Schannel:: (Inlcuding Client Side Protocols)
Protocols Enabled: Multi-Protocol Unified Hello, PCT 1.0, TLS 1.0
Protocols Disabled: SSL 2.0, SSL 3.0, TLS 1.1, TLS 1.2
Ciphers Enabled: NULL, DES 56/56, RC2 40/128, RC2 56/128, RC2 128/128,
  RC4 40/128, RC4 56/128, RC4 64/128, RC4 128/128, Triple DES 168, AES
  128/128, AES 256/256
Hashes Enabled: MD5, SHA, SHA 256, SHA 384, SHA 512
Key Exchanges Enabled: Diffie-Hellman, PKCS, ECDH
Cipher Suite Changes::
Disabled: SSL_CK_RC4_128_WITH_MD5,
  SSL_CK_DES_192_EDE3_CBC_WITH_MD5
Enabled: Everything else realted to TLS

To achieve this easily (changes to security and modification of registry) I also used this tool (IISCrypto): https://www.nartac.com/Products/IISCrypto
Do make sure that each cipher or protocols mentioned here are specifically enabled or disabled, or else the issue won't be resolved.
Hope this helps!


text:
Q: qt progress bar is not working properly I have one problem..
I am making post request to php script. And I am getting back result as an xml. How can I make my qprogressbar working.
I have tried this:
v
oid MainWindow::init()
{
    url = "http://127.0.0.1:8888/direkt_php_qt.php";
    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(updateDataTransferProgress(qint64,qint64)));
    connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
}

void MainWindow::updateDataTransferProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    ui->progressBar->setMaximum(bytesTotal + (bytesTotal * 0.25));
    ui->progressBar->setValue(bytesReceived);
    ui->progressBar->show();
}

But it's not working. I am getting error:
Object::connect: No such signal QNetworkAccessManager::downloadProgress(qint64,qint64)
How can I make this work with manager variable or something like that.
EDIT 2:
This is for example function that is calling init()
void MainWindow::Citanje_korisnika()
{
    init();

    QUrl params;
        params.addQueryItem("action","Citanje_korisnika");

        QByteArray data;
        data.append(params.toString());
        data.remove(0,1);

        QNetworkRequest request;
        request.setUrl(url);
        request.setHeader(QNetworkRequest::ContentTypeHeader,
        QVariant("application/x-www-form-urlencoded"));

        reply = manager->post(request, data);

}

I tried your code but I always get unexpectedly out from program. Can you change me my function from which I am calling post method so it can work with init()

A: donwloadProgress is a signal of QNetworkReply.
Try something like this:
url = "http://127.0.0.1:8888/direkt_php_qt.php";
manager = new QNetworkAccessManager(this);

QNetworkReply* reply = manager->get(QNetworkRequest(url));
connect(reply, SIGNAL(downloadProgress(qint64, qint64)),this, SLOT(updateDataTransferProgress(qint64,qint64)));


text:
Q: When radio button selection changes do not cause refresh? When the selection of the radio buttons change I would like to show/hide the panel in the next table cell.  I have it hiding and showing fine but each time it causes the page to refresh to the top.  Is their a way to stop that refresh?  I would like to hide and show the panel dynamically.

                <asp:RadioButtonList runat="server" ID="rblPlayerStatus" AutoPostBack="true" >
                    <asp:ListItem>Free Agent</asp:ListItem>
                    <asp:ListItem>I have teammate</asp:ListItem>
                </asp:RadioButtonList>

                <asp:Panel runat="server" ID="pnlTeamMate">
                    <asp:Label runat="server" ID="lblTeamMate" Text="Choose Teammate" />
                </asp:Panel>

A: Use the AJAX.ASP.Net library - then you add a ScriptManager item, and an UpdatePanel.  Anything within the UpdatePanel will update through AJAX, not a full page refresh.

A: Do you have any server side logic based on which show and hide the panel. If yes then you could use update panel control. If it is just client side logic such as
If Free Agent is select show FreeAgent Panel else Team Panel
use javascript or rather jquery to achieve the same.

A: From your code, I can't see where you hide and show the panel. You could use an updatepanel, but that is best used when you need to retrieve more information from the server.
If you simply want to show and hide the panel, you can do it better with Javascript, by adding some code to the OnClick event to set the panel's visibility css attribute. There are a few tutorials on google about how to do this. Something like this should be sufficient to get you started.

A: Solution would be either using AJAX (UpdatePanel and ScriptManager) or removing
AutoPostback = true and using JavaScript to display/hide the panel


text:
Q: How analize preview rectangle camerax android? I am a beginner developer. I'm sorry for my english.
I am trying to make a barcode reader application. I use MLKit and CameraX.
I want to analyze only the part of the preview that is in the rectangle. Now the preview is being analyzed in full. I only want to analize what is in the rectangle. I tried to use the ViewPort, but it seems I didn't quite understand what it was for, because it could not solve the problem. I looked for solutions on the Internet, but my problem remained relevant. I think that before analysis it is necessary to crop the image and only then analyze it, but is this true?
My layout:
    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="false"
        tools:background="@android:color/white"
        tools:context=".ui.BarcodeScanningFragment">

        <androidx.camera.view.PreviewView
            android:id="@+id/viewFinder"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <com.t_ovchinnikova.android.scandroid_2.ui.ViewFinderOverlay
            android:id="@+id/overlay"
            android:layerType="software"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </FrameLayout>

Camera class:
    class CameraSource (private val overlay: ViewFinderOverlay) {

    private lateinit var cameraExecutor: ExecutorService

    val preview : Preview = Preview.Builder()
        .build()

    fun startCamera() {

        val cameraProviderFuture = ProcessCameraProvider.getInstance(overlay.context)

        cameraProviderFuture.addListener(Runnable {
            //Используется для привязки жизненного цикла камер к владельцу жизненного цикла
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            bindCameraUseCases(cameraProvider)
        }, ContextCompat.getMainExecutor(overlay.context))
    }

    @SuppressLint("UnsafeOptInUsageError")
    private fun bindCameraUseCases(cameraProvider: ProcessCameraProvider) {

        val imageAnalysis = ImageAnalysis.Builder()
            .setTargetResolution(Size(overlay.width, overlay.height))
            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
            .build()

        val orientationEventListener = object : OrientationEventListener(overlay.context) {
            override fun onOrientationChanged(orientation : Int) {
                // Monitors orientation values to determine the target rotation value
                val rotation : Int = when (orientation) {
                    in 45..134 -> Surface.ROTATION_270
                    in 135..224 -> Surface.ROTATION_180
                    in 225..314 -> Surface.ROTATION_90
                    else -> Surface.ROTATION_0
                }

                imageAnalysis.targetRotation = rotation
            }
        }
        orientationEventListener.enable()

        cameraExecutor = Executors.newSingleThreadExecutor()

        val analyzer = BarcodeAnalyzer()

        imageAnalysis.setAnalyzer(cameraExecutor, analyzer)

        var cameraSelector : CameraSelector = CameraSelector.Builder()
            .requireLensFacing(CameraSelector.LENS_FACING_BACK)
            .build()

        val useCaseGroup = UseCaseGroup.Builder()
            .addUseCase(preview)
            .addUseCase(imageAnalysis)
            .build()

        cameraProvider.bindToLifecycle(overlay.context as LifecycleOwner, cameraSelector, useCaseGroup)
    }
}

class ViewFinderOverlay:
    class ViewFinderOverlay(context: Context, attrs: AttributeSet) : View(context, attrs) {

    private val boxPaint: Paint = Paint().apply {
        color = ContextCompat.getColor(context, R.color.barcode_reticle_stroke)
        style = Paint.Style.STROKE
        strokeWidth = context.resources.getDimensionPixelOffset(R.dimen.barcode_stroke_width).toFloat()
    }

    private val scrimPaint: Paint = Paint().apply {
        color = ContextCompat.getColor(context, R.color.barcode_reticle_background)
    }

    private val eraserPaint: Paint = Paint().apply {
        strokeWidth = boxPaint.strokeWidth
        xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
    }

    private val boxCornerRadius: Float =
        context.resources.getDimensionPixelOffset(R.dimen.barcode_reticle_corner_radius).toFloat()

    var boxRect: RectF? = null

    fun setViewFinder() {

        val overlayWidth =  width.toFloat()
        val overlayHeight = height.toFloat()

        val boxWidth = overlayWidth * 80 /100
        val boxHeight = overlayHeight * 36 / 100

        val cx = overlayWidth / 2
        val cy = overlayHeight / 2

        boxRect = RectF(cx - boxWidth / 2, cy - boxHeight / 2, cx + boxWidth / 2, cy + boxHeight / 2)

        invalidate()
    }

    override fun draw(canvas: Canvas) {
        super.draw(canvas)
        boxRect?.let {

            canvas.drawRect(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat(), scrimPaint)

            eraserPaint.style = Paint.Style.FILL
            canvas.drawRoundRect(it, boxCornerRadius, boxCornerRadius, eraserPaint)
            eraserPaint.style = Paint.Style.STROKE
            canvas.drawRoundRect(it, boxCornerRadius, boxCornerRadius, eraserPaint)
            // Draws the box.
            canvas.drawRoundRect(it, boxCornerRadius, boxCornerRadius, boxPaint)
        }
    }
}

ViewFinderOverlay - a view that is superimposed on the camera preview.
Screen:
[1]: https://i.stack.imgur.com/cYvFP.jpg
Image analyzer:
        @SuppressLint("UnsafeOptInUsageError")
    override fun analyze(imageProxy: ImageProxy) {

        val mediaImage = imageProxy.image
        if (mediaImage != null) {
            val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)

            val scanner = BarcodeScanning.getClient()

            scanner.process(image)
                .addOnSuccessListener { barcodes ->
                    barcodes?.firstOrNull().let { barcode ->
                        val rawValue = barcode?.rawValue
                        rawValue?.let {
                        }
                    }
                }
            imageProxy.close()
        }
    }

Help me please. I would be glad to any advice.

A: You can take a look at LifecycleCameraController. It takes care of creating use cases as well as configuring ViewPort.
However AFAIK, MLKit doesn't respect the crop rect. What you can do is checking the MLKit result, and discard any barcode whose coordinates are outside of the crop rect.


text:
Q: mySqlTrigger altering the same table it exist I have a simple table
CREATE  TABLE `accounting`.`Foo` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `This` VARCHAR(45) NULL ,
  `That` VARCHAR(45) NULL ,
  `The_Other` VARCHAR(45) NULL ,
  `Times_altered` INT NULL ,
  PRIMARY KEY (`ID`) );

I wish to have a trigger simply count the under of times that this record is altered.  My 'DBA' is telling me that I cannot alter the table I am in in Mysql with a trigger as it will cause a 'loop'.
I am not a SQL guy:  but something tells me I need a new DBA.
Is this in fact true?
Cant I simply increment the   Times_altered INT NULL ?

A: Something like this:
CREATE  TABLE `accounting`.`Foo` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `This` VARCHAR(45) NULL ,
  `That` VARCHAR(45) NULL ,
  `The_Other` VARCHAR(45) NULL ,
  `Times_altered` INT NULL ,
  PRIMARY KEY (`ID`) );

CREATE  TABLE `accounting`.`logs` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `table` VARCHAR(45) NULL ,
  `update_count` int NULL ,
  PRIMARY KEY (`ID`) );

CREATE TRIGGER `update_counter` UPDATE ON `Foo`
FOR EACH ROW BEGIN
   INSERT INTO logs SET update_count = update_count + 1 WHERE table = 'Foo';
END;

Note: code above isn't tested.
http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html

A: A trigger is indeed not the right choice. A trigger in MySQL gets activated for each row affected by your update statement, which means if you update 10 rows, the Times_altered column in your design gets updated 10 times. And should the same value in Times_altered be in all rows of the table or just in one? Either way not the best design in my opinion.
Now you could have a second table like in cetver's answer. Again updating is not an option, cause it would produce wrong results. That's why he's inserting. Then you'd have for each table multiple rows and you'd have to query the maximum value...But note, it may still be the wrong result, depending on if you want to count if the table's rows were altered one time with one statement, or how much rows were affected.
I would suggest, either you do it like this:
CREATE  TABLE `accounting`.`Foo` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `This` VARCHAR(45) NULL ,
  `That` VARCHAR(45) NULL ,
  `The_Other` VARCHAR(45) NULL ,
  PRIMARY KEY (`ID`) );

CREATE  TABLE `accounting`.`logs` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `table` VARCHAR(45) NULL ,
  `update_count` int NULL ,
  PRIMARY KEY (`ID`) );

SET TRANSACTION ISOLATION LEVEL READ-COMMITED;
START TRANSACTION;
UPDATE Foo SET whatever = whatever;
UPDATE logs SET update_count = update_count + 1 WHERE table = 'Foo';
COMMIT;

Why the transaction? It's to make the process concurrency safe.
Or you use a stored procedure (something like this):
DELIMITER $$
CREATE PROCEDURE my_update (IN stmt varchar(1000), IN tablename varchar(100))
BEGIN
SET @sql = stmt;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE stmt;
SET @sql = CONCAT('UPDATE logs SET update_count = update_count + 1 WHERE table = ', tablename, ';');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE stmt;
END $$
DELIMITER ;

Then you'd use the procedure like this:
SET TRANSACTION ISOLATION LEVEL READ-COMMITED;
START TRANSACTION;
CALL my_update('UPDATE Foo SET whatever = whatever', 'Foo');
COMMIT;

Or you put the start transaction into the procedure.


text:
Q: Splitting matplotlib bar graph into 3 Plotting the severity of accident by the month which it occurred. My data has 3 values for severity (0,1,2) all which are under one graph. I want to create three separate graphs for each severity value.
month = df.groupby(['Month','Severity']).size().unstack()
print(month)
month.plot(kind='bar')
plt.legend(title = 'Severity')
plt.show()

A: Here's my solution using Matplotlib:
# Import packages
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Create random data - Just convert your data to a Pandas dataframe
months = np.array(['January', 'February', 'March', 'April', 'May', 'June', 'July',
                      'August', 'September', 'October', 'November', 'December'])
numMonths = months.shape[0]

sev0 = np.random.randint(13000, 15500, (numMonths,))
sev1 = np.random.randint(250, 350, (numMonths,))
sev2 = np.random.randint(20, 35, (numMonths,))

d = {'Month': months, 'Sev_0': sev0, 'Sev_1': sev1, 'Sev_2': sev2}
df = pd.DataFrame(data=d)

# Create plots
for i in range(3):
    yData = "Sev_" + str(i)
    plt.figure(figsize=(12,10))

    plt.title(yData)
    plt.bar(df.Month, df[yData].to_numpy())
    plt.xlabel('Month')
    plt.ylabel('Number of Accidents')

where df is your data (replace my random data generation with your actual data).
Here is a sample output:

If you want to get fancy, you can use Plotly, which has hover and zoom features
Also, you can control which severity value is being plotted when all in one interactive graph.
import plotly
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, plot, iplot, download_plotlyjs
init_notebook_mode(connected=True)
plotly.offline.init_notebook_mode(connected=True)

dataAllSev = []
for i in range(3):
    yData = "Sev_" + str(i)

    dataAllSev.append(go.Bar(x=df.Month, y=df[yData].to_numpy(), name=yData))

fig = go.Figure(data=dataAllSev)
fig.update_layout(title="Number of Accidents by Severity Level", xaxis_title='Month', yaxis_title='Number of Accidents')
fig.show()

Here is the combined graph in Plotly:


text:
Q: Python PIL Choose Fonts According to Language I'm using Pillow to add texts to different images. Most of the time Roboto.ttf fonts are well enough. But sometimes there're unicode chars such as Japanese Kanji and Korean characters that Roboto cannot display.
For aesthetic reasons I want to keep using Roboto if possible. But if there's a unicode type object such as "都道312号線", I'd like to apply another font like unicode.ttf. Right now I'm getting weird symbols using Roboto, resulting in "??312??".
I'm using ImageDraw.Draw(img).text(position, inputtext, font=font), where inputtext is of unicode type. Thanks a lot.


text:
Q: Share gallery photo to ionic android app I am trying to send  an image from the image gallery to my ionic application, using the 'share' feature.
I have also added the following in my AndroidManifest.xml
<intent-filter>
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="image/*" />
</intent-filter>

i am using below code to get shared image
$ionicPlatform.ready(function() {
       window.plugins.webintent.getExtra(webintent.EXTRA_STREAM,
    function (url)
    {  console.log(url);

    }, function()
    {
        console.log('failed');
    });
  });

I was getting url value null.
What i went wrong?
Any help on this problem would be greatly appreciated!
FYI i am using this plugin:
https://github.com/Initsogar/cordova-webintent


text:
Q: Bootstrap Tabbed Nav/Split Dropdown Button Issue I tried adding a tabbed nav to a page, like this:

Home

Menu 1

Menu 2

HOME

Some content.

Menu 1

Some content in menu 1.

Menu 2

Some content in menu 2.

But it was being displayed incorrectly:

So I switch from Bootstrap 4.0.0 to 3.3.7, and it appears properly, but my split dropdown menu button breaks.

        <button type="button" class="btn btn-primary">{{ session.username }}</button>
        <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Toggle Dropdown
        </button>

          Messages
          Friend Requests

          Log Out

How can I have both components display correctly?  Switching between 4.0.0 and 3.3.7 breaks one or the other.

A: Nav-tabs work differently in bootstrap version 4, you need:

      Home

      Menu 1

      Menu 2

Note sure about this, but bootstrap 4 documentation uses show class for the active tab-content (you may need to replace in with show):

See here: W3Schools Bootstrap 4 nav-tabs
See here: Bootstrap 4 documentation


text:
Q: Compiling a autoit script via cmd/batch not working with #include I have this script I made with some help from MC ND and it works but if I have #include <Constants.au3> in the autoit file it will throw a error. It works if the #include isn't there. If I compile it using the autoit its self then it compile ok. This is my code:
@echo off
    setlocal enableextensions disabledelayedexpansion
    for %%a in ("%cd%\*.au3") do (
        Aut2exe.exe /in "%%~fa" /out "%%~dpna.exe" /icon "%%~dpa\icon.ico" /x86 /comp 4
    )
    endlocal
xcopy *.exe Compile\*.exe
del /f *.exe
xcopy /D /I /V /Y Compile\Aut2exe.exe
del /f Compile\Aut2exe.exe

Thanks if any one can help.

A: From the AutoIt Documentation

The search order used by AutoIt depends on which form of #include you
  use. The tables below show the order directories are searched using
  both forms.
Using #include <>
Standard library
The path of the currently running interpreter with "\Include" appended is
searched.

User-defined libraries
The registry value mentioned above is read and each directory is searched
in the order they appear in.

Script directory
The directory of the currently executing script.

Aut2Exe uses the same algorithm as AutoIt3.exe with the only difference being
  it looks for the Include sub-directory as being in a sibling directory to
  itself (..\Include)

From your posted code, it "seems" you have copied the aut2exe to the scripts folders, but the file you are referencing is in the standard libraries folder and, according to documentation, it will not be found.
You can

*

*Copy the constants.au3 to the same folder that holds the scripts

*Configure the registry entry to point to the folder holding the include file

*Call the aut2exe file from its folder in standard distribution of autoit so it can find the include folder

*Change the #include directive to #include "path\filename" to directly point to the include file


text:
Q: Why does my deposit feature only let me deposit 10,000 or less? I created a bank app, and when I try to deposit money that is over 10,000, my error message that I set up displays, but any number under works.. I assume this has something to do with value types. I used int, however I tried double but can't figure that out too.
/* FUNCTION DEFINITION */
void DepositMoney(int initialbalance, int deposit);

// Main Program
int main()
{
int initialbalance=10000;
int deposit;

cout << " \t ***** What you want to Do ??? Choose the Action character *****" << endl << endl;

            cout <<" \t   W : Money Withdraw" << endl
            <<"\t   D : Deposit" << endl //I CHOSE THIS ONE
            <<"\t   B : Balance" << endl
            <<"\t   T : Transfer" << endl
            <<"\t   C : Change Details" << endl
            <<"\t   Q : Quit or Exit" << endl << endl ;

            string input;
            cin >> input;
            bool t=true;
                if (input=="W" || input=="w"){

                    cout<<"\n\t Your balance is: " << initialbalance<<endl;
                    cout<<"\n\t How much would you like to withdraw: ";
                    cin>> withdraw;

                   withdrawMoney(initialbalance, withdraw);
                   initialbalance -= withdraw;
                    t=false;

                }
                else if (input=="D" || input=="d"){
                    cout<<"\n\t Your balance is: " << initialbalance<<endl;
                    cout<<"\n\t How much would you like to deposit: ";
                    cin>>deposit;

                    DepositMoney(initialbalance, deposit);
                    initialbalance += deposit;
                    t=false;

// Function for Deposit
    void DepositMoney(int initialbalance, int deposit)
    {
    // Get how much user want to deposit and display balance after adding
                if(initialbalance < deposit)
                        cout <<"\n\t The amount you entered is not not valid."<<endl; //THIS MSG DISPLAYS
                    else
                        initialbalance += deposit;
                    cout<<"\n\t Your new balance is: " << initialbalance <<endl<<endl<<endl;
    }

I tried changing every data type that said int to double, but that didn't even run the code.

A: When you call DepositMoney(), you have this check: if (initialbalance < deposit). At this point, initialbalance is 10000, so if the amount is greater, then you cannot deposit it. Based on the logic, you likely wanted a check like that in withdrawMoney(), not in DepositMoney().


text:
Q: `openssl digest | head -c 10` gives strange results I'm using salted hashes of some memorable words as login/pass for anonymous accounts and just now I've noticed that sometimes I get no result for my method and then I've discovered that it was not working properly from the start. What I do is:
pc ~ % echo "A simple string." | openssl sha512 | head -c 10
(stdin)= f%

Surprisingly for me this only gives one character instead of 10 on Linux and Mac in bash and zsh. All head -c-ed hashes are of random length, but head -n 1 prints the whole string correctly:
pc ~ % echo "A simple string." | openssl sha512 | head -n 10
(stdin)= f261768808d0b30162a8e412b3195ad1aa0fa21dfcf67968dd9f5050e919eee6bbbc2ce8845d80cb4930b478407e28e7d9f0d5750cbe069f17de5eff52060e54

Perhaps it uses threads, there is an encoding problem or I just don't understand stdio piping, but how do I fix the bug? It should just print an arbitrary hashed string trimmed to a fixed length. I'm also just curious about the reason of such behaviour.

A: Okay I'm just really dumb. The prefix (stdin)=  is also a part of the piped string. If anyone needs to get rid of it, see https://unix.stackexchange.com/questions/42797/openssl-dgst-sha1-producing-an-extraneous-stdin-prefix-and-trailing-new.


text:
Q: How can I find out whether the Field List is currently visible in a DevExpress PivotGrid control I am wanting to use a toggle button to show or hide the Field List in a pivotgrid, but to do this (and show appropriate tooltips) I need to know whether the field list is currently visible or not. Is there an easy way to do this? It feels like it should be straightforward, but I cannot find any property that indicates the current visibility.

A: The answer is to use the Pivot.IsFieldListVisible property, which I couldn't see on looking. In case anyone else is a blind as me.


text:
Q: Add pointer to the bottom of a div as a continuation of its background image I'm looking for a way to stack divs, with a pointer leading into the next div that is a continuation of the previous div's background image.
I've looked around and I've seen some options, but in all of them the bottom div has to be a solid color.
For example: http://jsfiddle.net/nhqKb/

#container{
    height: 300px;
    background: url('http://farm8.staticflickr.com/7358/9532233404_58763bd668_b.jpg') no-repeat;
    position: relative;
}

#one {
    position: absolute;
    width: 100px;
    left: 0;
    bottom: 0;
    border-bottom: 20px solid green;
    border-right: 20px solid transparent;
}

#two {
    position: absolute;
    left: 120px;
    bottom: 0;
    right: 0;
    border-bottom: 20px solid green;
    border-left: 20px solid transparent;
}

Is there any way to implement this using divs with background images instead of solid colors?

A: You can use skewX and pseudo elements to make this.
#container {
    background: url('https://images.unsplash.com/photo-1440635592348-167b1b30296f?ixlib=rb-0.3.5&q=80&fm=jpg&w=1080&fit=max&s=a029f986631f264fdbc8c0272cab9c40') no-repeat;
    height: 300px;
    position: relative;
    overflow: hidden;
}

#one {
    background-color: rgba(0, 0, 0, 0.3);
    bottom: 0;
    left: 0;
    padding-bottom: 15px;
    position: absolute;
    width: 100%;
}
#one:before,
#one:after {
  background-color: inherit;
  bottom: 100%;
  content: '';
  padding-bottom: inherit;
  position: absolute;
  width: 50%;
}
#one:before {
  right: 50%;
  -ms-transform-origin: 100% 100%;
  -webkit-transform-origin: 100% 100%;
  transform-origin: 100% 100%;
  -ms-transform: skewX(45deg);
  -webkit-transform: skewX(45deg);
  transform: skewX(45deg);
}
#one:after {
  left: 50%;
  -ms-transform-origin: 0 100%;
  -webkit-transform-origin: 0 100%;
  transform-origin: 0 100%;
  -ms-transform: skewX(-45deg);
  -webkit-transform: skewX(-45deg);
  transform: skewX(-45deg);
}

HTML code:


text:
Q: How to fix dependencies for upgrading Docker engine? I am creating a docker-compose for a express.js application that uses redis and mysql. I am doing this on a distro of Linux Mint.
When I run
docker-compose up

I get
ERROR: client and server don't have same version (client : 1.22, server: 1.18)

So the first thing I did was try downgrading my version of compose but I cant do that because it doesn't support my compose file. So the next thing I tried is changing the API version.
export COMPOSE_API_VERSION=auto

Then after running docker-compose up I got this error.
Traceback (most recent call last):
  File "bin/docker-compose", line 6, in <module>
  File "compose/cli/main.py", line 71, in main
  File "compose/cli/main.py", line 124, in perform_command
  File "compose/cli/command.py", line 41, in project_from_options
  File "compose/cli/command.py", line 121, in get_project
  File "compose/cli/command.py", line 92, in get_client
  File "compose/cli/docker_client.py", line 120, in docker_client
  File "site-packages/docker/api/client.py", line 166, in __init__
docker.errors.InvalidVersion: API versions below 1.21 are no longer supported by this library.
[25236] Failed to execute script docker-compose

So at this point I changed the API version to something that it would support so I ran.
export COMPOSE_API_VERSION=1.22

and then I wanted to upgrade the docker engine so I ran this command.
sudo apt-get upgrade docker-engine

and I got this error
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 docker-engine : Depends: init-system-helpers (>= 1.18~) but 1.14ubuntu1 is to be installed
                 Depends: lsb-base (>= 4.1+Debian11ubuntu7) but 4.1+Debian11ubuntu6mint1 is to be installed
                 Depends: libdevmapper1.02.1 (>= 2:1.02.97) but 2:1.02.77-6ubuntu2 is to be installed
                 Depends: libltdl7 (>= 2.4.6) but 2.4.2-1.7ubuntu1 is to be installed
                 Depends: libsystemd0 but it is not installable
E: Unable to correct problems, you have held broken packages.

So far I cant find anything on how to fix these dependencies so I am wondering what I am doing wrong here and how do I get this application up and running with Docker?
I will include my docker-compose.yml and Dockerfile below.
docker-compose.yml:
version: '2'
volumes:
services:
 web:
    build: .
    command: "PORT=3002 node bin/www"
    volumes:
      - .:/usr/app/
      - /usr/app/node_modules
    ports:
      - "3002:3002"
    depends_on:
      - redis
      - mysql
 redis:
    image: 'bitnami/redis:latest'
    environment:
        - ALLOW_EMPTY_PASSWORD=yes
    ports:
        - '6379:6379'
    volumes:
        - /path/to/redis-persistence:/bitnami
 mysql:
     image: mysql:5.7
     container_name: mysql
     restart: always
     environment:
         - MYSQL_ROOT_PASSWORD=goon
         - MYSQL_DATABASE=TERRA_TEST
         - MYSQL_DATABASE=TERRA_DEV
     ports:
         - "33061:3306"
volumes:
    appconf:

Dockerfile:
FROM ubuntu

Run apt-get update

Run apt-get install curl -y

Run curl -sL https://deb.nodesource.com/setup_10.x

Run apt-get install -y nodejs

Run apt-get install -y git

run apt-get install npm -y

Run git clone https://github.com/sdrafahl/TerraServer.git

ADD configKeys.json TerraServer/

WORKDIR /TerraServer

run npm install

EXPOSE 3002

CMD PORT=3002 node bin/www

Docker Info:
Containers: 3
 Running: 1
 Paused: 0
 Stopped: 2
Images: 15
Server Version: 18.03.1-ce
Storage Driver: aufs
 Root Dir: /var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 39
 Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 773c489c9c1b21a6d78b5c538cd395416ec50f88
runc version: 4fc53a81fb7c994640722ac585fa9ca548971871
init version: 949e6fa
Security Options:
 apparmor
 seccomp
  Profile: default
Kernel Version: 4.4.0-53-generic
Operating System: Linux Mint 18.1
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 7.756GiB
Name: shane-OptiPlex-980
ID: NAAR:UM5J:CQRX:QTJM:NFU4:IQWP:64XZ:SB4X:UEMR:X7S2:MEQ7:PG34
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false

A: The docker-engine package is old, possibly from your distribution vendor rather than docker. I'd recommend following the steps to install docker-ce directly from docker.
https://docs.docker.com/install/linux/docker-ce/ubuntu/


text:
Q: How to stop service using AlarmManager I have an alarm manager that runs a service repeatedly every minute. I want to stop the alarm manager using a button.
The alarm manager stops when I am inside the app but when it comes out of the app and I want to stop the clock again, it will not stop as there is no pending intent in memory. Using a new pending intent, the previous pending intent will not stop, even though I am using the same id.
btnStart.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {

    Intent intent = new Intent(G.context, MyService.class);
    intent.setAction("1020");
     pendingIntent = PendingIntent.getService(G.context, 1020, intent, 0);
    G.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 2000, pendingIntent);

  }
});//for start button  alarm manager

btnStop.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    Intent intent = new Intent(G.context, MyService.class);
    intent.setAction("1020");
    PendingIntent alarmIntent = PendingIntent.getBroadcast(G.context,  1020, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmIntent.cancel();
    G.alarmManager.cancel(alarmIntent);

  }
});//for stop button alarm manager

A: You can make pendingIntent global and use the same to set/stop as in
Intent intent = new Intent(G.context, MyService.class);
intent.setAction("1020");
pendingIntent = PendingIntent.getService(G.context, 1020, intent, 0);

btnStart.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    G.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 2000, pendingIntent);

  }
});

btnStop.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    pendingIntent.cancel();
    G.alarmManager.cancel(pendingIntent);

  }
});


text:
Q: Android - Tabs with zone in common first, sorry for my english.
I need to do a actionbar with tabs, and one zone in common.
Like a bottonbar.
That is a picture to example.
http://es.tinypic.com/view.php?pic=nmf85c&s=8#.U5PHD65fJhE
When I move the tabs, the green area does not move
My code is:
package com.deimon.wine;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.deimon.wine.TabMomento;/*the code to create the tab, like PlaceholderFragment*/
import com.deimon.wine.TabComida;
import com.deimon.wine.TabPrecio;
import com.deimon.wine.Configuracion;

public class AplicacionActivity extends ActionBarActivity implements
        ActionBar.TabListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
     * derivative, which will keep every loaded fragment in memory. If this
     * becomes too memory intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aplicacion);

        // Set up the action bar.
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        actionBar.setSelectedNavigationItem(position);
                    }
                });
        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        }
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            switch (position) {
            case 0:
                fragment = new TabMomento();/*charge the first tab*/
                break;
            case 1:
                fragment = new TabComida();/*charge the second tab*/
                break;
            case 2:
                fragment = new TabPrecio();/*charge the thirst tab*/
                break;
            default:
                break;
            }
            return fragment;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
            case 0:
                return getString(R.string.tab1);
            case 1:
                return getString(R.string.tab2);
            case 2:
                return getString(R.string.tab3);
            }
            return null;
        }
    }
}

Regards

A: For your question and the requirement, the only thing I did was:
1) Set the height of the View Pager
2) Add other views below the View Pager and set the height and width as wrap_content and match_parent for width.
Here's the layout for it:

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:paddingTop="10dp"/>

    <View
        android:id="@+id/mylistview"
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:background="#fff" >
    </View>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text = "fIXED cONTENT"
        android:textSize = "30sp"
        android:textColor = "#fff">
    </TextView>

</LinearLayout>

This is how the view looks like now:
Image http://imageshack.com/a/img834/9374/w36p.png
Image http://imageshack.com/a/img843/9553/5n8y.png
Let me know if you need the implementation of it.
Good Luck..:)


text:
Q: Getting Cannot find 'linkBuilder' in scope Error when trying to shorten a url in Swift iOS I am using firebase dynamic urls to shorten my url. I read the whole documentation and i dont understand why the code is not working.
here is my code:
let link = "https://mywebsite.com/share/?shop="+concatenate(getKey!,"&title="+shopName.text!.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!,"&desc="+summary.text!.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!,"&img="+profileImgURL)

linkBuilder.shorten() { link, warnings, error in // i get an error here sayiny "cannot find linkBuilder in scope"
          guard let link = link, error != nil else { return }
          print("The short URL is: \(link)")
        }

what am i missing or doing wrong?

A: You forgot to define what linkBuilder is. Put this after let link =:
let dynamicLinksDomainURIPrefix = "https://example.com/link"
let linkBuilder = DynamicLinkComponents(link: link, domainURIPrefix: dynamicLinksDomainURIPRefix)

Documentation


text:
Q: perf tuning for ESX vmfs3 on RAID looking for recommendations on ESX4 OS - VMFS version3:
RAID-5 : matching the stripe size with VMFS block size? (64K, 128K etc)
RAID controller options: "adaptive read ahead, write-back" on PERC 6i
i have read that smaller stipes are good for writes and larger for reads. Since this is virtual env, not sure whats good.
what impact if any has aligning VMFS & data disks in Virtual machines? Appreciate your comments.

A: I think that it's more important to know what the vm's will be doing.  Are they heavy IO, especially writes?
ESX can be very heavy on disk IO, in fact it's usually the biggest bottleneck.  You end up doing a lot of big file copies (creating new guests, cloning and vmotion) and you are combining the disk IO of several servers onto a envirmonment usually reserved for a single server.
SQL Server is particularly write heavy, so on that alone I'd try to use RAID 10.

A: If you're using 2003 server, make sure your NTFS partitions are aligned with the underlying storage. Look at http://www.nptech.com/blog/2009/03/04/how-to-align-virtual-machine-os-and-data-partitions-in-esx-server/ for one method. I tend to be lazy and partition 2003 server disks with a Vista, 7 or 2008 server install DVD ISO, and then populate the resulting partitions having booted from the 2003 install media.
If you're going to be running write heavy workloads, I'd benchmark RAID 5 against RAID 10 before you enter production. RAID 5 with multiple concurrent writes can be a performance challenge.


text:
Q: olympic mathematics For each integer $a_0 > 1$, define the sequence $a_0, a_1, a_2,
\ldots$ by:
$$a_{n+1} = \begin{cases} \sqrt{a_n}, & \mbox{if } \sqrt{a_n}\mbox{ is an integer,} \\a_n+3, &\mbox{otherwise,}\end{cases}$$
Determine all values of $a_0$ for which there is a number $A$ such that $a_n = A$ for infinitely many values
of $n$.
I have figured that if there exists an $i$ such that $a_i
\ \mathrm{mod}\, 3 = 2$, the elements after $a_i$ are all different.
I think there are many ways to solve this question so i would appreciate any answers.
i think the answer is $a_0\ \mathrm{mod}\, 3 = 0$
  but i can't prove it
examples: 7,10,13,16,4,2 doesn't work
3,6,9,3 works
please tell me if i can improve my question.

A: That only says you have a term $a_0$ in this sequence that generates a cycle.
$a^2=a+3$ means that $a=3k$ or $a=3k+1$

*

*For the case: $a_0=3k$
Try with $a_0=6$, $a_1=a+3=9$, $a_2=3$, $a_3=6$. for infinite values of $k$, $a_k$ is cyclic.
All terms of this sort would map to this small circle, because the distance of leapback is incomparably large in relation of the incremental value which is $3$, let's denote $3k$ is the starting edge $a_0$, at some extent $a_n$ would be written as $3(3x^2)$ by incrementing repeatedly its following terms, the draw back of this sequence is evaluated to $3x(3x-1)$ for larger values of $x$ this is estimated to be very big comparingly to the incremental constant and should override the edge $3k$ where it finally leads straight to the limited 3 steps cycle.
This python code shows my conjecture:
for i in range(1000000):
    s=3*i
    while(s!=0 and s!=3 and s!=6 and s!=9):
          if (sqrt(s)==int(sqrt(s))):
               s=sqrt(s)
          else:
               s=s+3
    print i

The loop will never halt for all $3k$ terms tested up to 3 millions.

*

*For the case $3k+1$ it's trickier to prove since there is a small exception when $\sqrt{a}$ is a square itself where the oddity occurs.

A: There is no integer $a$ so that $a^2 \equiv 2 \mod 3$ (as $0^2 \equiv 0 \mod 3$, $1^2 \equiv 1 \mod 3$ and $2^2 \equiv 1 \mod 3$ so if $a_0\equiv 2 \mod 3$ then by induction $a_{i+1} = a_i + 3 \equiv a_0 \equiv 2 \mod 3$ and the sequence never repeats.
There are infinitely many squares that are multiples of $3$.  The square roots of these are multiples of $3$.  So $a_0 = 3k$ will eventually lead to a $a_n = (3m)^k$ so $a_{n+1} = 3m < a_n$ so $a_n$ will repeat infinitely.  So any multiple of $3$ will be such a starting point.
(Obviously if a sequence repeats once it will, by induction, repeat infinitely many times.
This just means we must consider $a_0 \equiv 1 \mod 3$.
If $a_0 = 1$ then $a_1 = \sqrt 1 = 1$  so $a_0$ is such a starting point.
But $a_0 = 4 \implies a_1 = 2$ so $4$ is not a valid starting point.
If $a_0 = 7; a_1 = 10;a_2 = 13; a_3 = 16; a_4 = 4$ so $7$ iss not a valid starting point.  Is any $1 + 3k$ other than $1$?
Well, it can't be less than $25$ as that will lead to $25$ which leads us to $5\equiv 2 \mod 3$.  We need to be lead to a $(3k + 1)^2 $ that leads to $3k + 1$ that does not lead to and $3k + 1 < (3m + 2)^2 < (3k+1)^2$.
Not sure any such number exists.  $49$ for example is such that $7 < 16 < 49$ is a failure.
But if $(3k+1)^2> 49$  then $k > 2$ and  $(3k-2)^2 = 9k^2 - 12k + 4 \ge 18k-12k +4 = 6k+ 4 > 3k + 1$ so $3k + 1 < (3k-2)^2 < (3k+1)^2$.
So there is no such $1 + 3k$ (other than $1$ that will work).
So $a_0 = 1$ and $a_0 = 3k$ are all such starting points.


text:
Q: How to add an html entity with Reflex.Dom? As it should be text "© is rendered escaped. How then should I render the © html entity unescaped with Reflex.Dom?

A: Yes, just use text "copyright ©". No need to use HTML codes :)


text:
Q: consecutive days problem I have a problem with my conseutive days counter. I visited the site every day in the last two months. Yesterday the counter showed 62 consecutive days. Today I see 2 consecutive days on my profile page. How can be this possible?

A: Are you sure there was no more than 24 hours gap between your logins/visits?
Consecutive days are calculated on the basic of GMT days, so if you don't measure time in GMT, it's safe to assume that day is each subsequent 24 hours period.
On the margin, it would be more fair, it the algorithm would measure the time gap between logins/visits.


text:
Q: Please help me to understand jQuery's new .on method I used to use .live but I am now trying to replace those with the better .on but I don't seem to understand the API instructions because the code below does nothing and I should be getting an alert. Can anyone see where I am messing this up?
<!DOCTYPE html>

        <title>Online Media Player</title>
        <link rel="stylesheet" href="/assets/css/music-player.css" type="text/css" media="screen" charset="utf-8">

Please select your choice of music

            Rock
            Hip Hop
            Country
            Featured Artist

A: You should call on on the container of the elements and pass it the selector of the elements you want to attach to. Your existing code is calling on not on the container but on the links themselves. Try:
$('.main-center').on('click', '.openplayer', function(e) {
    var genre = $(this).data('genre');
    e.preventDefault();
    alert(genre);
});


text:
Q: Continuity of hypergeometric function $_{1}F_1(a;2;k\pi i)$ in the argument $a$ For $0\leq a \leq 2$, are the hypergeometric functions $_{1}F_1(a;2;k\pi i)$, $_{1}F_1(a;2;-k\pi i)$ continuous in the argument $a$? where $k\in \{1,2,3 \}$. How to prove it?
Are the following equations  valid?
$$\lim_{a\to 2} {}_{1}F_1(a;2;\pm k\pi i)={}_{1}F_1(2;2;\pm k\pi i)$$
$$\lim_{a\to 0^+} {}_{1}F_1(a;2;\pm k\pi i)={}_{1}F_1(0;2;\pm k\pi i)$$
$$\lim_{a\to c} {}_{1}F_1(a;2;\pm k\pi i)={}_{1}F_1(c;2;\pm k\pi i)$$
where $0<c<1$.

A: Note that ${}_1 F_1(a;2;z)$ is an entire function of both $a$ and $z$. In general, ${}_1 F_1(a;b;z)$ is entire in $a$ and $z$, and is meromorphic in $b$. ${}_1 F_1(a;b;z)/\Gamma(b)$ is entire in all three variables.


text:
Q: why are widgets placed on the TabItem invisible when using ScrolledComposite SWT? Here is my code which actually does all the GUI work for Domain(right side contained in the picture attached).In this function What i am doing is I am creating a composite "test" on the "newTabFolder".Then i am creating ScrolledComposite "sc" on it and then Creating a composite "compositeInTab" on it and after placing all the widgets on "compositeInTab" I am creating a TabItem for placing the composite "test" on it.
public DomainUI(Composite composite, TabFolder newTabFolder, boolean comingFromSelf)
{
    Composite test = new Composite(newTabFolder,SWT.NONE);
    test.setLayout(new FillLayout());
    ScrolledComposite sc = new ScrolledComposite(test, SWT.V_SCROLL|SWT.H_SCROLL);
    final Composite compositeInTab = new Composite(sc, SWT.NONE);
    sc.setExpandHorizontal(true);
    sc.setExpandVertical(true);
    sc.setMinHeight(compositeInTab.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
    sc.setMinWidth(compositeInTab.computeSize(SWT.DEFAULT, SWT.DEFAULT).x);
    sc.setContent(compositeInTab);
    compositeInTab.setLayout(null);
    sc.setAlwaysShowScrollBars(true);

    /*HERE I AM CREATING LABELS AND TEXT FIELDS AND SETTING THEIR BOUNDS*/
    systemCodeLabel = new Label(compositeInTab, 0);
    systemCodeText = new Text(compositeInTab, SWT.BORDER);
    systemCodeLabel.setText("System Code");
    systemCodeLabel.setBounds(350, 60, 100, 15);
    systemCodeText.setBounds(480, 60, 150, 17);
    // CREATION OF LABELS AND TEXTFIELDS ENDED

    // CREATION OF TABLE STARTS
    myTable = new CreateTable(compositeInTab, 1);
    myTable.setBounds(50, 230, 0, 0);
    myTable.table.setSize(myTable.table.computeSize(570, 250));

    //here i filled data in table

    for(int i=0; i<myTable.table.getColumnCount(); i++)
    {
        myTable.table.getColumn(i).pack();
     myTable.table.getColumn(i).setWidth(myTable.table.getColumn(i).getWidth()+10);
    }

    TabItem tabItem1 = new TabItem(newTabFolder, SWT.NONE);
    tabItem1.setText("Domain");
    tabItem1.setControl(test);
    newTabFolder.setBounds(0, 0, 480, 300);
}

A: It seems to be a matter of layouts. I fiddled around a little bit and managed to get this working:
public static void main(String[] args)
{
    Display display = Display.getDefault();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    ScrolledComposite scrollComp = new ScrolledComposite(shell, SWT.V_SCROLL | SWT.H_SCROLL);
    Composite innerComp = new Composite(scrollComp, SWT.NONE);
    innerComp.setLayout(new GridLayout(4, true));

    for(int i = 0; i < 32; i++)
        new Button(innerComp, SWT.PUSH).setText("Button");

    scrollComp.setMinHeight(innerComp.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
    scrollComp.setMinWidth(innerComp.computeSize(SWT.DEFAULT, SWT.DEFAULT).x);
    scrollComp.setContent(innerComp);
    scrollComp.setExpandHorizontal(true);
    scrollComp.setExpandVertical(true);
    scrollComp.setAlwaysShowScrollBars(true);

    shell.pack();
    shell.open();

    shell.setSize(200, 200);

    while(!shell.isDisposed())
    {
        if(!display.readAndDispatch())
            display.sleep();
    }
}

It will show the scrollbars. However, if I change the layout of the shell to a GridLayout, it will not work. Maybe your "combination" of layouts seems to be the problem...