text:
Q: right doctype for RDFa breadcrumbs navigation and validator I need to make my mind clear about HTML doctypes. in this page: http://kovo.intl.uk.to I add breadcrumbs navigation using RDFa. but then page was no more valid. I googled and I found out to change doctype to:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
Now the page is 100% valid, but what means XHTML and such LOW number? At my webpages I am using HTML 4.01 strict due I write pages mostly in Slovak for Slovak people and what I see on some computers and how they are used is "stone age" (Windows XP + ie8 in better case :D).
Is this correct solution and what affects have doctypes to users or search engines ?

A: RDFa 1.0 can be used in XHTML 1.0 (using the DOCTYPE included in your question).
RDFa 1.1 can be used in probably any (X)HTML version (all interpreted through the HTML5 parsing rules), i.e.: HTML5, XHTML5, HTML 4.01, XHTML 1.0, XHTML 1.1, …:

*

*HTML+RDFa 1.1 (W3C Recommendation 22 August 2013)

Support for RDFa in HTML4 and HTML5

*XHTML+RDFa 1.1 - Second Edition (W3C Recommendation 22 August 2013)

Support for RDFa via XHTML Modularization

A: From Wikipedia:

XHTML 1.0 is "a reformulation of the three HTML 4 document types as
  applications of XML 1.0"

So you are fine, it's still an equivalent of HTML 4:
 There are three formal DTDs for XHTML 1.0, corresponding to the three different versions of HTML 4.01:

- XHTML 1.0 Strict is the XML equivalent to strict HTML 4.01, and includes elements and attributes that have not been marked deprecated in the HTML 4.01 specification. As of May 25, 2011, XHTML 1.0 Strict is the document type used for the homepage of the website of the World Wide Web Consortium.
- XHTML 1.0 Transitional is the XML equivalent of HTML 4.01 Transitional, and includes the presentational elements (such as center, font and strike) excluded from the strict version.
- XHTML 1.0 Frameset is the XML equivalent of HTML 4.01 Frameset, and allows for the definition of frameset documents—a common Web feature in the late 1990s.

XHTML+RDFa from Wikipedia:

XHTML+RDFa is one of the techniques used to develop Semantic Web
  content by embedding rich semantic markup. Version 1.1 of the language
  is a superset of XHTML 1.1

A: Try to use this
<!DOCTYPE html>

              <title>Kovove webstránky</title>

                <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
                <link rel="stylesheet" href="../css/main.css" />

                            Domov

                            Tvorba

                            Blog

                            Daco iné

                                        kovo.intl.uk.to >

                        Domovská stránka

Nadpis 1

                        blablablabla
                        blablabl
                        blablablabla
                        blablablabla
                        blablablabla
                        blablablablablablablablablablablablablablablablablablablablablablablablablablab
                        lablablablablablablablablsdasdasdasdasdasdasdsdfsdgdfgdfgdfgdfgdfgdfgdfgdfgdfgdfgdfgfdg
                        ablablablablablablablablablablablablablablablablablablablablablablablablablabl
                        ablablablablablablablablablablablablablablablablablablabla

                    © 2014 Matej Kovác
                    (X)HTML valid

On the other hand you should read more about the semantic web.
This validates ok!


text:
Q: How can I test my Bash script on older versions of Bash? I'm working on a Bash library and want to ensure I'm supporting as many environments as possible - including old installations of Bash. My development environment is Bash 4.3, but some of my users may well be running much older versions and presently I have no way to confirm or deny that my library will work for them. In particular I'd like to be compatible with OSX (which still ships with Bash 3.2, AFAIK).
I know Bash can run in POSIX-compliant mode; is there a similar setting to disable modern functionality? Or a way to run Bash in some sort of compatibility mode? I'm looking for any technique short of actually finding and booting up old operating systems and testing my library there.
Update
For example, I've avoided using associative arrays since they were introduced in Bash 4, but it's hard to be sure without testing that I'm not accidentally using some other Bash 4+ feature.

A: Although it's nice to know that it's possible to compile arbitrary versions of bash locally (as discussed in my other answer), these days there's a much simpler option - the official Docker bash images.
To test a script against multiple bash versions is often as simple as:
for v in 3 4 5; do # or whatever versions you're interested in
  docker run -v "$PWD:/mnt" "bash:$v" \
    bash /mnt/your_script.sh
done

A: Have a look at shenv: https://github.com/shenv/shenv. Just like rbenv, pyenv, goenv and others, but for shells, it lets you install different versions of Bash among others (zsh, fish, yash, etc.).
(Disclaimer: I'm the one who forked pyenv into shenv!)

A: Finally coming back to this question, it's pretty easy to just compile (without installing) the bash version(s) you're interested in. Here's how I'm testing Bash 3.2.57:
$ mkdir ~/bash
$ cd ~/bash
$ wget http://ftp.gnu.org/gnu/bash/bash-3.2.57.tar.gz
$ tar xvzf bash-3.2.57.tar.gz
$ cd bash-3.2.57
$ ./configure
$ make
# if `make` fails due to yacc, run `sudo apt-get install byacc`
# No need to run `make install`
$ ./bash -version
GNU bash, version 3.2.57(1)-release (armv7l-unknown-linux-gnu)
Copyright (C) 2007 Free Software Foundation, Inc.

Now you have a bash 3.2.57 binary you can run, without actually "installing" it or modifying your normal environment.
To run a shell script against this version:
$ ./bash your_script.sh

To enter a clean interactive prompt:
$ env -i PATH="$PWD:$PATH" ./bash --noprofile --norc
bash-3.2$ bash -version
GNU bash, version 3.2.57(1)-release (armv7l-unknown-linux-gnu)
Copyright (C) 2007 Free Software Foundation, Inc.
bash-3.2$

Using env -i rather than just calling ./bash directly leaves you with a mostly-empty environment (run env from inside the shell to see what's still set). Updating the PATH allows calls to bash (e.g. bash -version) to invoke the local bash shell, not the system-wide installation (but note this pulls in your whole PATH). Adding --noprofile --norc avoids loading your .bashrc and associated scripts.
If you don't want to pick up any PATH modifications, just execute export PATH="$PWD:$PATH" once inside the subshell instead of as part of the env command.

I have a Docker image (repo) using these installation steps, if that's helpful for folks to reference. I wouldn't necessarily suggest using this image directly, but you're welcome to copy from the Dockerfile/install script. MIT licensed.

A: You can use Bash own facilities to emulate older version of Bash. Look up "compat" options on shopt.
Mind you, while it does change behavior as described under each compatNN entry in the man page, it does not remove features that are otherwise present on the current version. For example, this doesn't cause any errors:
shopt -s compat31
shopt -s globstar

Even though globstar was only introduced on Bash 4.0.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Query, SQL, Ruby on Rails I am working a project and encountered a problem regarding writing the best query for the problem.
I will start presenting the problem and the solution I found.
We have the following ERD structure:

A Player has many Scores, and a Score has many Handicap Results.
We have a many to many relationship between Handicap and League.
In my app at some point I run a calculation formula that takes all players from a Customer or League and for each score of the player we create a handicap result corresponding to he Handicaps that the Club / League has.
HandicapResults: value, score_id, handicap_id
Handicaps: game_type(string), league_ids (association between the handicap and leagues)
Score: league_id, player_id, game_type(string), play_at (date), round_id (integer)
On the customers#show action I want to display for all handicaps and players the result.
The result is the LAST SCORE PLAYED SORTED BY ROUND_ID DESC AND PLAY_AT DESC. From this score we the the handicap_result corresponding to customer handicaps.
The solution I found for one player would be:

The only problem is that this will do 1 select for all players displayed in the view. I would want to write a select that would return the values for a collection of players (player_ids).
At the moment the sql returns the handicap_result corresponding to the last score played (sorted_by round_id desc and play_at desc) where score.league_id included in handicap.league_ids and score.game_type = handicap.game_type.
I would want to created a method that can have as parameters player_ids, handicaps, ... all informations required for the query.
That returns the following:
Ex:
player_ids: [1, 2, 3]
handicaps: [handicap_1, handicap_2]
# and return something like:
{
   #player_id 1: { handicap_1.id: value, handicap_2.id: value }
   .........
   #player_id 5: { handicap_1.id: value, handicap_2.id: value }
}

# the value is the handicap_result where handicap_result.handicap_id == handicap_1.id / handicap_2.id and for the corresponding score

Hopefully I described the problem correctly and people can understand me. I really wish that someone can help me into writing the query that runes 1 time and returns the values for a given collection of players.
Thank you and have a nice day!


text:
Q: Mongo db decimal to string is not working as expected I am using MongoDB to do some calculations as per below.
Creating one collection called "Numbers"
Insert a big number let's say 2^64 ( we can store this big as MongoDB support decimal128 as default data type)
// inserting
db.numbers.insertOne({newBig: 1298074200000000000000000000000000})
// converting
db.numbers.aggregate({$addFields:{test: {$toString: "$newBig"}}})

Now when I am converting the above number to a string, it's not giving expected results.
// getting following output
[{
    _id: ObjectId("61c2c1557d78b0f039bcee5a"),
    newBig: 1.2980742e+33,
    test: '1.29807e+33'
}]

As pointers, M I missing something here?
Please acknowledge, thanks :)


text:
Q: A/D conversion loop infinitly I'm quit new one PIC microcontroller, and i'm stuck with a new problem.
I was using the A/D converter of my PIC18F46j50 to catch 4 push buttons on 1 PIN (RB2), and it worked well. But since I soldered a 32.768kHz oscillator for Timer1, it doesn't work anymore.
unsigned int HAL_SWITCH_GetValADC(void){
    ADCON0bits.VCFG0 = 0;
    ADCON0bits.VCFG1 = 0;
    ADCON0bits.CHS = 0b1000;
    ADCON1bits.ADFM = 1;        // A/D Result format select bit : right justified
    ADCON1bits.ADCAL = 0;       // A/D Calibration bit
    ADCON1bits.ACQT = 0b111;    // A/D Acquisition Time 12 Tad = 12us
    ADCON1bits.ADCS = 0b001;    //Tad = 1us (Fosc/8)
    ADCON0bits.ADON = 0b01;     // A/D enable

    PIR1bits.ADIF = 0; //make sure A/D Int not set
    ADCON0bits.GO=1; //and begin A/D conv.
    while(!PIR1bits.ADIF);
    NOP();
    return (((unsigned int) ADRESH << 8) | ADRESL);
}

Using breakpoint I determined that the problem come from the while loop, when i debug step by step, it works fine, but the programm never stops if the breakpoint is on NOP();
got error like "No source code lines were found at current PC" + few adress, mostly those of the interupt instructions... I don't know if their is a link.
Also someone told me to change the clock used by the A/D convertor... How can I manage to do so ?
Ask for more code if it can help.

A: One way I know of acknowledging whether the conversion is complete is reading the GO/DONE bit of ADCON0. The bit goes low once the conversion is complete. So you can use
ADCON0bits.GO=1;
while(ADCON0bits.GO);

If you still want to go with ADIF, you should make sure you have enabled the ADC interrupt. Also check whether the oscillator pins have some voltage on them or whether it is soldered well. The voltage should be around 2.3V to 3V, not exactly but a stable value when measured with DC voltmeter.
Good Luck.

A: ADCON1bits.ACQT = 0b111 <- that's not 12 Tad, but 20 Tad (according to datasheet), which translates roughly to 20us. Try using 0b101, for the value you are trying to achieve. Try setting bit 6 of ADCON1 register (ADCAL, responsible for automatic calibration) to 1 and running your code again.
You have also put semicolon after the while loop, which does not seem like a good idea at the moment.
Weren't you going for something more like:
while(!PIR1bits.ADIF)
{
    NOP();
}
    return (((unsigned int) ADRESH << 8) | ADRESL);
EDIT:
What is nop function exactly? Is it literal use of nop assembly instruction or is it a delay function? Other thing, you should probably put whole A/D routine with saving the result to into a loop, since it's 10-bit A/D converter. PIC18F46J50 datasheet suggests something like this(page 400):
#include "p18cxxx.h"
#define COUNT 500 //@ 8MHz = 125uS.
#define DELAY for(i=0;i<COUNT;i++)
#define RCAL .027 //R value is 4200000 (4.2M)//scaled so that result is in//1/100th of uA
#define ADSCALE 1023 //for unsigned conversion 10 sig bits
#define ADREF 3.3 //Vdd connected to A/D Vr+
int main(void)
{
 int i;
 int j = 0; //index for loop
 unsigned int Vread = 0;
 double VTot = 0;
 float Vavg=0, Vcal=0, CTMUISrc = 0; //float values stored for calcs
//assume CTMU and A/D have been setup correctly
//see Example 25-1 for CTMU & A/D setup
setup();
CTMUCONHbits.CTMUEN = 1; //Enable the CTMU
CTMUCONLbits.EDG1STAT = 0; // Set Edge status bits to zero
CTMUCONLbits.EDG2STAT = 0;
 for(j=0;j<10;j++)
 {
 CTMUCONHbits.IDISSEN = 1; //drain charge on the circuit
 DELAY; //wait 125us
 CTMUCONHbits.IDISSEN = 0; //end drain of circuit

 CTMUCONLbits.EDG1STAT = 1; //Begin charging the circuit
 //using CTMU current source
 DELAY; //wait for 125us
 CTMUCONLbits.EDG1STAT = 0; //Stop charging circuit

 PIR1bits.ADIF = 0; //make sure A/D Int not set
 ADCON0bits.GO=1; //and begin A/D conv.
 while(!PIR1bits.ADIF); //Wait for A/D convert complete

 Vread = ADRES; //Get the value from the A/D
 PIR1bits.ADIF = 0; //Clear A/D Interrupt Flag
 VTot += Vread; //Add the reading to the total
 }

 Vavg = (float)(VTot/10.000); //Average of 10 readings
 Vcal = (float)(Vavg/ADSCALE*ADREF);
 CTMUISrc = Vcal/RCAL; //CTMUISrc is in 1/100ths of uA
}


text:
Q: Creating multiple subviews inside view controller I have a view controller named ViewController.

*

*ViewController displays a UIView that has a button on it, which allows me to advance to a second view controller - SecondViewController.

*SecondViewController also has a button on it, which allows me to advance to a third view controller.

However, I am having trouble displaying ThirdViewController.  When I tap the button in  SecondViewController it throws an error:

Warning: Attempt to present ... on ... whose view is not in the window hierarchy!

I have been to a bunch of other sites and posts that address this issue, but cannot seem to find a working solution.  I have implemented quite a few solutions, but none seem to work.
Here is my code:
- (void)secondaryView:(UIView *)secondaryView
{
    UIView *theView = secondaryView;

    UIViewController *viewController = [[UIViewController alloc] init];
    viewController.view.frame = [UIScreen mainScreen].bounds;

    [viewController.view addSubview:theView];
    viewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:viewController animated:YES completion:nil];
}

secondaryView is a UIView that I am constructing elsewhere in the application.  I add it to the viewController then present the viewController.
Is there any way to dynamically create UIViewControllers, add a UIView to each one, and add them to the window hierarchy?

A: If you can use navigation in your ViewControllers, you can try the below code
In the place where you call the firstViewController,
   -(void)callFirst
    {
    FirstViewController *first = [FirstViewController alloc] init];
    UINavigationController *navigationController = [UINavigationController alloc] initWithRootViewController:first];
    navigationController.modalPresentaionStyle = UIModalPresenationFormSheet;
    [self presentModalViewController:navigationController animated:YES];
}

And in the FirstViewController button action ,you can write
-(void)callSec
{
SecondViewController *sec = [SecondViewController alloc] init];
[self.NavigationController pushViewController:sec animated:YES];
}

And in SecondViewController you can do the same
  -(void)callThird
    {
        ThirdViewController *third = [ThirdViewController alloc] init];
        [self.NavigationController pushViewController:third animated:YES];

    }

Try this...And in these ViewControllers you can do whatever coding you want to meet the requirement like
-(void)viewDidLoad
{
UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(20,20,400,400)];
newView.backGroundColor = [UIColor redColor];
[self.view addSubView:newView];
}


text:
Q: Vuetify Flex Layout - is not filling the height I have tried loads of different options with the following code, however, I can't get this to fill the remaining height. (The second layout should fill the remaining height) what am I doing wrong here?
<template>

    <v-container fluid fill-height>
      <v-layout row wrap>
        <v-flex
          v-for="(offer, index) in offers"
          :key="index"
          xs2
          class="pa-1"
        >
          <SiteButton
            :site-name="offer.siteName"
          />
        </v-flex>
      </v-layout>
      <v-layout column fill-height>
        <v-flex grow>
          <v-card>

              test

          </v-card>
        </v-flex>
      </v-layout>
    </v-container>

</template>

EDIT:
So here is my new code:
<template>
  <v-layout column wrap>
    <v-flex>
      <v-layout row wrap class="red">
        <v-flex
          v-for="(offer, index) in offers"
          :key="index"
          class="pa-1"
          xs2
        >
          <SiteButton
            :site-name="offer.siteName"
          />
        </v-flex>
      </v-layout>
    </v-flex>
    <v-flex grow align-content-start>
      <v-card height="100%">

          test

      </v-card>
    </v-flex>
  </v-layout>
</template>

This creates the following:

I would like the card with "test" to start straight after the links at the top, and then fill the rest of the height.
Thank you in advanced for your help!
Regards,
Josh

A: Try using column fill-height on the right side, and then grow on the v-flex...
<v-container fluid fill-height>
    <v-layout row wrap>
        <v-flex v-for="(offer, index) in offers" :key="index" xs2 class="pa-1">
            <v-btn>{{ offer.siteName }}</v-btn>
        </v-flex>
    </v-layout>
    <v-layout column fill-height>
        <v-flex grow>
            <v-card class="fill-height">

 test

            </v-card>
        </v-flex>
    </v-layout>
</v-container>

https://codeply.com/p/bwE5ifP4Pe

A: You don't need as much markup in your scenario and can cut this down to just a few lines.
I just filled in some numbers instead of your custom component in the v-for.
This will stretch the lower card to the maximum amount right after your for loop. The v-row and v-col is the way to go now in 2.0 (https://vuetifyjs.com/en/components/grids/).

  <v-row class="blue">
    <v-col cols="2" v-for="i in 15" :key="i" class="pa-1">
      <v-btn>{{ i }}</v-btn>
    </v-col>
  </v-row>

Down

Codesandbox example


text:
Q: Importing json; Typescript error: Module has no exported member I'm trying to import a .json file into my Angular8 project, but for some reason I keep getting the 'Module has no exported member' error.
I tried to simplify the code, but no result this is what I have.
First I added this in the compilerOptions object (tsconfig.json)
"resolveJsonModule": true,
"esModuleInterop": true,
// assests/example.json
{
  "name": "Spaghetti",
  "desc": "Vegetarische spaghetti bolgnese",
  "rating": 3.7
}

// recipe component
import { example } from '../../../assets/example.json';

  constructor() {
    console.log(example.name);
  }

I keep getting this error:
Module '"@angular/recipe-app/src/assets/example"' has no exported member 'example'.ts(2305)
What am I doing wrong?

A: You have to use the import without the brackets around the example. You can use one of the following examples:
import example from "../../../assets/example.json";

OR
import * as example from "../../../assets/example.json";

A: You should have something like this
import * as something from '../../../assets/example.json';

and then you can refer something in your .ts file


text:
Q: viewing small pictures as the big picture? I don't really know what the problem is here.
I am trying to view the small pics as big pics when I click on them. I have succeeded, however, an error message is appearing in the inspector-window that says: "Cannot set property 'onclick' of undefined"
here is the code to make the small images big.
var Bigimg = document.getElementById("BigImg");
var smallimg = document.getElementsByClassName("small-img"); // this is an array

smallimg[0].onclick=function() {
    Bigimg.src = smallimg[0].src;
}

smallimg[1].onclick=function() {
    Bigimg.src = smallimg[1].src;
}

smallimg[2].onclick=function() {
    Bigimg.src = smallimg[2].src;
}

smallimg[3].onclick=function() {
    Bigimg.src = smallimg[3].src;
}

again it's working as it should, however, I am trying to move on to the next step where I am trying to get my shop-cart to function, but I am trying to test my code with the help of Console.log(the button I am pressing) and it's not working.


text:
Q: SQL Server Compare two tables I have two tables, each has 1 column:
If all of Table B's rows are contained within Table A, such as
TABLE A ('A')
       ,('B')
       ,('C')
       ,('D')

TABLE B ('B')
       ,('C')

Then, let the variable @In = 1
Otherwise, if Table B contains rows that are not in A, Let @In = 0
How can I do this?

A: Try this:
IF EXISTS (SELECT * FROM B
           EXCEPT
           SELECT * FROM A)
    SET @In = 0
ELSE
    SET @In = 1

See here for documentation on EXCEPT and INTERSECT: https://msdn.microsoft.com/en-GB/library/ms188055.aspx
Assuming you are using SQL Server 2005+ of course!
EDIT: Fixed my reverse logic on the assignment of 0/1 (whoops!).
See SQL Fiddle here for a working example: http://sqlfiddle.com/#!3/b9769/4
EDIT 2: Swapped tables A and B in EXISTS clause after clarification.

A: How about this:
select case when count(*) > 0 then 0 else 1
from a full outer join b on a.a = b.b
where a.a = null or b.b= null

A: This is based on Neil's suggestion (It works):
create table A (col varchar(10))
create table B (col varchar(10))
declare @InT Int, @InB Int, @In Int

INSERT INTO A VALUES
    ('A')
   ,('B')
   ,('C')
   ,('D')

INSERT INTO B VALUES
    ('B')
   ,('C')
   ,('Z')

select @InT =  count(*) from A join B on A.col = B.col
select @InB =  count(*) from B

IF (@InT = @InB)
  SET @In = 1
Else
  SET @In = 0

print '@In = ' + CAST(@In As VARCHAR(10))
print '@InT = ' + CAST(@InT As VARCHAR(10))
print '@InB = ' + CAST(@InB As VARCHAR(10))

DROP TABLE A
DROP TABLE B

A: This is based on Beercohol's query. (I still get the same @In if I uncomment the table B's Z.
create table A (col varchar(10))
create table B (col varchar(10))
DECLARE @In INT

INSERT INTO A VALUES
    ('A')
   ,('B')
   ,('C')
   ,('D')

INSERT INTO B VALUES
    ('B')
   ,('C')
 --  ,('Z')

IF EXISTS (SELECT * FROM A
       EXCEPT
       SELECT * FROM B)
   SET @In = 0
ELSE
   SET @In = 1

PRINT @In
DROP TABLE A
DROP TABLE B


text:
Q: How can I prove the experiment data follows heavy-tail distribution? I have several test results of server response delay. According to our theory analysis, the delay distribution should have heavy-tail behavior. But how could I prove that the test result does follow heavy-tail distribution?

A: I think the most straightforward way is to make a best fit of half normal distribution to and look how well it describe the tail.
In Python you can make this with the help of scipy.stats.halfnorm.fit() or use a longtail module that is dedicated for plotting and analysing heavy tails (https://github.com/Mottl/longtail):
import numpy as np
import longtail

# generate random values from heavy tailed distribution (let's take Laplace)
X = np.random.laplace(size=10000)
X = X[X>0]  # take only right half of the distribution

# get best fit of half normal distribution to our data:
params = longtail.fit_distributions(X, distributions=['halfnorm'])

# visualize X and best fit:
longtail.plot(X, params=params)

Since points at the tail are above the half normal approximation, the given distribution can be considered as having heavier tail than half normal:

A: I am not an expert, but I think that estimating the kurtosis of your delay distribution would be a good start.
If you know the theoretical delay distribution, you can also do a goodness of fit test.


text:
Q: Order of accuracy of Runge-Kutta method The following Runge-Kutta method is given by the Butcher tableau:
$$ \begin{array}{c|ccccc}
\tau_1 =0 & a_{11}=0 & a_{12} = 0\\
\tau_2 =1 & a_{21} = \frac{1}{2} & a_{22} = \frac{1}{2}\\
\hline
& b_1 = \frac{1}{2} & b_2 = \frac{1}{2} & \
\end{array} $$
and I want to show that its order of accuracy is $2$.
I have tried the following:
$$t^{n,1}=t^n \\ t^{n,2}=t^n+ \frac{h}{2} \\ \zeta^{n,1}=y(t^n) \\ \zeta^{n,2}=y(t^n)+ \frac{h}{2} f(t^n, y(t^n))$$
$$\delta^n=y(t^n+h f \left( t^n+ \frac{h}{2}, y(t^n)+ \frac{h}{2} f(t^n, y(t^n))\right))-y(t^n+h) \\ = -\frac{h}{2} f(t^n,y(t^n))+ \frac{h}{2} f(t^{n+1}, \zeta^{n,2})- \frac{h^2}{2} f_t(t^n,y(t^n))-\frac{h^2}{2} f_y(t^n, y(t^n)) f(t^n,y(t^n))+O(h^3)$$
$$f(t^{n+1}, \zeta^{n,2})=f \left( t^n+h, y(t^n)+ \frac{h}{2} (f(t^n,y(t^n))+f(t^{n+1}, \zeta^{n,2})) \right)=f(t^n,y(t^n))+hf_t(t^n,y(t^n))+ \frac{h}{2} (f(t^n,y(t^n))+ f(t^{n+1}, \zeta^{n,2})) f_y(t^n, y(t^n))+O(h^2)$$
So we have:
$\delta^n=\frac{h^2}{4} f(t^{n+1}, \zeta^{n,2}) f_y(t^n,y(t^n))- \frac{h^2}{4} f_y(t^n,y(t^n)) f(t^n, y(t^n))+O(h^3)$
Is it right so far or have I done something wrong?
If it is right  then it should hold $f(t^{n+1}, \zeta^{n,2}) f_y(t^n,y(t^n))= f_y(t^n,y(t^n)) f(t^n, y(t^n))$ so that we get $\delta^n=O(h^3)$. But does this hold? If so, how could we show this?

A: This is the trapezoidal method, one scheme among the Lobatto family.
The scheme could be written as follows
\begin{align*}
k_1&=f(t_{n-1},y_{n-1})\\
k_2&=f(t_n,y_{n-1}+\frac{h}{2}k_{1}+\frac{h}{2}k_{2})\\
y_{n}&=y_{n-1}+\frac{h}{2}k_{1}+\frac{h}{2}k_{2}
\end{align*}
Now to show order of consistency, we insert our exact solution in the numerical scheme, as shown below.
\begin{align*}
\tilde{k_1}&=f(t_{n-1},y(t_{n-1}))\\
\tilde{k_2}&=f(t_n,y(t_{n-1})+\frac{h}{2}\tilde{k_{1}}+\frac{h}{2}\tilde{k_{2}})\\
\end{align*}
Note $\tilde{k_1}$ and $\tilde{k_2}$ have the exact solution $y(t_{n-1})$ as
argument. Now we do Taylor expansion around $(t_{n-1},y(t_{n-1})).$ Note
that $\tilde{k_1}=f$. Expanding $\tilde{k_2}$ we obtain
$$
\tilde{k_2}=f+hf_t+f_y\frac{h}{2}\left(\tilde{k_1}+\tilde{k_2}\right)+O(h^2)
$$
From this we can see that $\tilde{k_2}=f+O(h)$. Hence we can rewrite the above expression as
$$
\tilde{k_2}=f+hf_t+hff_y
$$
Plug this into $y(t_n)$ to obtain
$$
y(t_n)=y(t_{n-1})+\frac{h^2}{2}f_t+hf+\frac{h^2}{2}ff_y+O(h^3)
$$
This exactly matches the expansion of $f(t,y)$ upto the second order. Hence
the method is consistent of order $2$.


text:
Q: how to use a value from sql result as table name for its sub query? In my application I want use dynamic table name.
In my application I have two queries.
1) SELECT `table_name` FROM `data_tables` WHERE `table_id`="1"

From this query I get a table name and I am saving it in a variable; for e.g: $tab
I have another query:
2) SELECT * FROM `'.$tab.'`;

I want to know is there anyway to club these queries? Is it a good practice?
My application is currently working fine, but I would like some insight.

A: DECLARE @Name varchar(max)
SELECT @Name =`table_name` FROM `data_tables` WHERE `table_id`="1"
SELECT * FROM `@Name`


text:
Q: C#: How to read information in File summary tab?
Possible Duplicate:
Read/Write 'Extended' file properties (C#)

Does anyone know how to read information in a file's summary tab using C#?
Summary tab: Right click on file, then "Summary"
Thanks


text:
Q: can we Mock an Object conditionally in Java? I'm using Mockito and I'm in a weird situation where I've to authenticate a client and then make an actual API call using the same code:
//@Mock //I want to mock this only for authentication
CloseableHttpClient httpClient;

 //when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(someResponse);

response = httpClient.execute(httpUriRequest);

Now I want to use the actual httpClient object for Authentication and Mocked httpClient object for the actual API call. How can I achieve this requirement?

A: Thank you, everyone, for your response.
I solved the problem with Mockito.spy().
Dropping my solution if anyone finds it helpful in the future.
    @Test
    public void myTest(){

    //This object will be a normal instance
    CloseableHttpClient httpClient;

    //Authentication: /oauth/token
    //response is real because httpClient is an actual instance.
    response = httpClient.execute(httpUriRequest);

    CloseableHttpClient spyHttpClient = Mockito.spy(httpClient);
    doReturn(mockedCloseableHttpResponse).when(spyHttpClient).execute(any(HttpUriRequest.class));

    //Actual API call: /v1/users
    //response is mockedCloseableHttpResponse because httpClient is a spy instance.
    response = httpClient.execute(httpUriRequest);

    //Assertion code here

    }

Here is more details about mockito-spy: Mockito – Using Spies


text:
Q: Why is it so easy to decompile .NET IL code? Why is it so easy to decompile .NET IL-code into source code, compared to decompiling native x86 binaries? (Reflector produces quite good source code most of the time, while decompiling the output of a C++ compiler is almost impossible.)
Is it because IL contains a lot of meta data? Or is it because IL is a higher abstraction than x86 instructions? I did some research and found the following two usefull articles, but neither of them answers my question.

*

*MSIL Decompiler Theory

*C Decompiler - Quick primer

A: There are a number of things that make reverse engineering il fairly easy.

*

*Type information. This is massive. In x86 assembler, you have to infer the types of variables based on how they are used.

*structure. Information on the structure of the application is more available in il disassemblies. This, combined with type information, gives you an amazing amount of data. You're working at a pretty high level at this point (relative to x86 assembler). In native assembler, you have to infer the structure layouts (and even the fact that they are structures) based on how the data is used. Not impossible, but much more time consuming.

*names. Knowing the names of things can be useful.
These things, combined, means you have quite a lot of data about the executable. Il is basically working at a level much closer to the source than a compiler of native code would be. The higher level the bytecode works at, the easier reverse engineering is, generally speaking.

A: C# and IL nearly map one-to-one.  (This is less so with some newer C# 3.0 features.)  The closeness of the mapping (and the lack of an optimizer in the C# compiler) makes things so 'reversible'.

A: Extending Brian's correct answer
If you think all IL is easily decompilable, I suggest writing a non-trivial F# program and attempting to decompile that code.  F# does a lot of code transformations and hence has a very poor mapping from the actual emitted IL and the original code base.  IMHO, it is significantly more difficult to look at decompiled F# code and get back the original program than it is for C# or VB.Net.

A: I think you've got the most important bits already.

*

*As you say, there's more metadata available. I don't know the details of what is emitted by a C or C++ compiler, but I suspect far more names and similar information are included in IL. Just look at what the decompiler knows about what's in a particular stack frame, for example - as far as the x86 is concerned, you only know how the stack is used ; in IL you know what the contents of the stack represent (or at least, the type - not the semantic meaning!)

*Again, as you've already mentioned, IL is a higher level abstraction than x86. x86 has no idea what a method or function call is, or an event, or a property etc. IL has all that information still within it.

*Typically C and C++ compilers optimise much more heavily than (say) the C# compiler. This is because the C# compiler assumes that most of the optimisation can still be performed later - by the JIT. In some ways it makes sense for the C# compiler not to try to do much optimisation, as there are various bits of information which are available to the JIT but not the C# compiler. Optimised code is harder to decompile, because it's further away from being a natural representation of the original source code.

*IL was designed to be JIT-compiled; x86 was designed to be executed natively (admittedly via micro-code). The information the JIT compiler needs is similar to that that a decompiler would want, so a decompiler has an easier time with IL. In some ways this is really just a restatement of the second point.


text:
Q: How to select selected value multivalue in recyclerview i want to get selected ids in activity which is selected in recyclerview adapter
holder.images.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (holder.checked.getVisibility() == View.VISIBLE) {

                holder.checked.setVisibility(View.GONE);

            } else if (holder.checked.getVisibility() == View.GONE) {

                holder.checked.setVisibility(View.VISIBLE);

            }
        }
    });

A: Use list to handle your selected items or positions
declare list for store selected items
private List<Integer> selectedPositions=new ArrayList();

update code in onBindViewHolder like below
holder.checked.setVisibility(selectedPositions.contains(position)?View.VISIBLE:View.GONE);
holder.images.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (selectedPositions.contains(position)) {
                    holder.checked.setVisibility(View.GONE);
                      selectedPositions.removeAt(selectedPositions.indexOf(position));
                    } else  {
                    holder.checked.setVisibility(View.VISIBLE);
                    selectedPositions.add(position);

            }
        }
    });

A: Here that solution i created arrylist and put data size
public static ArrayList<Integer> dataSize=new ArrayList<>();

and pass to adapter
  holder.checked.setVisibility(idpositions.get(position)==0?View.GONE:View.VISIBLE);

    holder.images.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (dataSize.size()>0) {

                if (holder.checked.getVisibility() == View.VISIBLE) {

                    holder.checked.setVisibility(View.GONE);

                    dataSize.set(position,0);

                } else if (holder.checked.getVisibility() == View.GONE) {

                    dataSize.add(position,data.getId());

                    holder.checked.setVisibility(View.VISIBLE);

                }

            }
        }
    });

and on button click simply get that arraylist and  get your selected value
  if(dataSize.size()>0){

        for (int i = 0; i < dataSize.size(); i++) {

            if (dataSize.get(i)==0){
                continue;
            }else {
                ids= ids+String.valueOf(dataSize.get(i))+",";
            }

        }

        Toast.makeText(this, ids, Toast.LENGTH_SHORT).show();

    }

A: Now, you need to declare a list to hold those selected ids
private List<DATA_TYPE> selectedIds = new ArrayList();

What you can do is declare one isSelected boolean in your model. In onBindViewHolder method, set visibility as
if (YOUR_POJO.isSelected()) {
   holder.checked.setVisibility(View.VISIBLE);
} else {
   holder.checked.setVisibility(View.GONE);
}

When you click on image check if it was already selected based on that you can add/remove its id
holder.images.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(YOUR_POJO.isSelected()){
             YOUR_POJO.setSelected(false);
             if (selectedIds.contains(YOUR_POJO.getId()){
                selectedIds.remove(YOUR_POJO.getId());
             }
        } else {
             YOUR_POJO.setSelected(true);
             selectedIds.add(YOUR_POJO.getId());
        }
        notifyItemChanged(holder.getAdapterPosition(), YOUR_POJO);
    }
});

Hope this helps.

A: Create an interface class like this;
public interface ItemSelectedListener{
    void onItemSelected(int selectedposition);
}

In your adapter initialize your interface;
    private List<ItemSelectedListener> mItemSelectedSubscribers = new ArrayList<ItemSelectedListener>();

Add this method in your adapter ;
public void subscribeItemSelection(ItemSelectedListenerlistener) {
        mItemSelectedSubscribers .add(listener);
    }

Set this loop in your click events;
for (ItemSelectedListener listener : mMediaSelectedSubscribers) {
    listener.onItemSelected(position);
                }

In your activity, implement your interface and you will set a implemented methods. this methods look like this;
int selectedPosition;
    @Override
        public void onMediaSelected(int position) {
            selectedPosition = position;
        }

When you do this you can use your selected position where you want in your activity
Hope this help!


text:
Q: Power saving with Optimus Some context before I ask this question:
I thought I understood how Optimus works, until I encountered this https://bugs.launchpad.net/ubuntu/+source/nvidia-prime/+bug/1765363 issue, with the prime tool on Ubuntu. Note that my question is not specific to Ubuntu.
I was under the impression that on an Optimus laptop, if the proprietary drivers are present, then the system will try to use the dGPU with the proprietary drivers. This will only result in a usable system though, if the display manager scripts described here ( https://wiki.archlinux.org/index.php/NVIDIA_Optimus#Display_Managers ) are in place for your chosen display manager.
I was also under the impression that if the proprietary drivers are not present, then the system will try to use Intel + Nouveau, and power saving is implemented into Nouveau, so in this case, the Nvidia card will be powered off, unless you use DRI_PRIME=1 to run some command.
If the proprietary drivers are not present, or they are blacklisted, and on top of that, nouveau is also blacklisted, then I assumed previously that the Nvidia GPU will not even power on at all.
On distros, in which there was no downstream implementation of any prime functionality (say, Arch Linux), what I did was that I had a script, which

*

*when passed the "on" flag to, it copied the DM scripts to the proper location, and unblacklisted Nvidia;

*when passed the "off" flag to, it deleted the DM scripts and blacklisted Nvidia.
I thought this script was working properly, but I never ran any serious tests on battery usage, cause I very rarely ran my laptop off battery, I just wanted to have power saving options in case I needed it.
In light of the first link (to launchpad) in this post, I feel my understanding is shaken. So I have a couple of questions.
Questions:

*

*If I understand correctly, the current (18.04) implementation of PRIME in Ubuntu only doesn't work if one uses a newer Nvidia GPU, in which Nouveau's power saving doesn't work (for example, in my Geforce GTX 950m, it should work), right?

*If both the proprietary drivers and Nouveau are blacklisted, then does the dGPU still power on during boot?

*If so, assuming a generic system (as in, with no in-built Optimus manager, for example Arch Linux), what needs to be done to have a reliable Optimus setup which actually saves me power in Intel mode? Is having bbswitch installed, and using it to turn off the GPU when Intel mode is active is the only way?


text:
Q: $http.delete throwing error in angularJS I am making an api call to a Delete method like this -
$http.delete('http://localhost:45467/api/v1/proddetails/' + prodId, null )
    .success(function (data, status, headers, config) {
        if(data.status == "200")
        {
            console.log('data deleted');
        }
        deferred.resolve(data);
    })
    .error(function (data, status, headers, config) {
        console.log("some error occurred");
        deferred.reject(data);
    });

The delete endpoint looks like this -
[HttpDelete]
public HttpResponseMessage Delete(int productId)

When I run this and look into the Chrome console, I am presented with this error -
OPTIONS http://localhost:45467/api/v1/proddetails/34
(index):1 XMLHttpRequest cannot load
http://localhost:45467/api/v1/proddetails/34. No 'Access-Control-Allow-
Origin' header is present on the requested resource. Origin
'http://localhost:5100' is therefore not allowed access. The response had
HTTP status code 405.

Can't seem to figure out what's wrong here. The other Get and Post requests are working fine. How to fix this?
Note1: I have CORS already enabled -
[EnableCors(origins: "*", headers: "*", methods: "*")]

Note2: I am making use of interceptors to add an auth token to each request. I am not sure if that is causing any issue.
Note3: This is how I define route in asp.net webapiconfig file -
config.Routes.MapHttpRoute(
            name: "ProdApi",
            routeTemplate: "api/v1/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Thanks in advance.

A: I finally figured out what the problem was. Actually this post was helpful -
PUT and Delete not working with ASP.NET WebAPI and Database on Windows Azure
I just needed to replace productId param to id - which is present in  webapiconfig config. I am not sure why this works. Ideally I should be able to put any name for a parameter and not bound by what I put in route. Hope someone can explain this.

A: You're doing an HTTP request to a different domain than your page is on. The browser is blocking it for security reasons.
No 'Access-Control-Allow-Origin' header is present on the requested resource.

This question explains how to make DELETE http requests work with asp.net-web-api.

A: Change $http.delete() to $http.del()


text:
Q: Extracting data from ArcGIS REST endpoint I am trying to export the data in GeoJSON or JSON format from this REST service.  I keep getting an  error from the request.
http://maps3.arcgisonline.com/ArcGIS/rest/services/A-16/FEMA_100-Year_Flood_Zones_in_the_USA/MapServer/1
I need the geometry and attributes returned.
I am using this page to try and query for all of the data.
http://maps3.arcgisonline.com/ArcGIS/rest/services/A-16/FEMA_100-Year_Flood_Zones_in_the_USA/MapServer/1/query
I choose the format as JSON and in the Return Fields (Comma Separated): I enter "*"
What else do I need to enter into the QUERY to return this layer?

I entered objectid is not null into the where clause and it returned the cryptic Esri rings format
http://maps3.arcgisonline.com/ArcGIS/rest/services/A-16/FEMA_100-Year_Flood_Zones_in_the_USA/MapServer/1/query?text=&geometry=&geometryType=esriGeometryPoint&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&objectIds=&where=objectid+is+not+null&time=&returnIdsOnly=false&returnGeometry=true&maxAllowableOffset=&outSR=&outFields=%22*%22&f=pjson

A: You need to make a request to the ?query endpoint of the layer, and supply a where clause. Specify &f=json to receive the response in JSON.
Note that ArcGIS Server by default only returns the first 1000 records, so you may need to batch your requests using OBJECTID ranges as the where clause until you've retrieved all records, using this syntax:
http://maps3.arcgisonline.com/ArcGIS/rest/services/A-16/FEMA_100-Year_Flood_Zones_in_the_USA/MapServer/1/query?&where=objectid%3E=1000+and+objectid%3C1999&f=json
That is, use where objectid < 999 in the first request, then where objectid >= 1000 and objectid < 1999, etc, until there are no more responses.
See Converting ArcGIS Server JSON to GeoJSON to convert this JSON response to GeoJSON

A: You can see 'maxRecordCount' in rest service.
Then you make a request with 'returnIdsOnly' with your filter where/spatial.
On this request there is no limit to the number of object IDs returned in the ID array response so you have full list of oids and then you make n-request (chunk) -> ceil((len(oids) / maxRecordCount )) with group of oids using in request query only 'objectIds'
You can see it in my toolbox for arcgis pro where I use this logic Download service


text:
Q: Microsoft Word BI Publisher: how to hide table header row at first occurrence Currently I am working on Oracle report using BI publisher desktop extension for MS Word.
In RTF layout I have a requirement to build receipts table and dynamically loop through receipts XML data. In oversimplified way it looks like that:
`<G_RECEIPTS>
<RECEIPT_DATE>2022-05-12</RECEIPT_DATE><RECEIPT_AMOUNT>10</RECEIPT_AMOUNT>
</G_RECEIPTS>
<G_RECEIPTS>
<RECEIPT_DATE>2022-05-26</RECEIPT_DATE><RECEIPT_AMOUNT>5</RECEIPT_AMOUNT>
</G_RECEIPTS>
<G_RECEIPTS>
<RECEIPT_DATE>2022-05-11</RECEIPT_DATE><RECEIPT_AMOUNT>5</RECEIPT_AMOUNT>
</G_RECEIPTS>`

And preview output looks ok

But according to the requirements, table header row (item, quantity and so on) should not be visible on first appearance, only after page break. Based on this example: header row must be hidden after "Content" word, but visible on page 2
Originally I tried to capture "current page" system variable, but according to the official oracle forums, it is technically not possible.

A: You can use xdoxslt:set_variable, and if:xdoxslt:get_variable. Set it to 0 before the table, for the header row, repeat on all pages, use an if condition checking if variable is >0 for the whole row. Then set the variable to 1 each data row. I have not tested it, but that's where I'd start.
Some example syntax:
<?xdoxslt:set_variable($_XDOCTX, 'variable name', value)?>

<?xdoxslt:get_variable($_XDOCTX, 'variable name')?>

<?xdoxslt:set_variable($_XDOCTX, 'x', xdoxslt:get_variable($_XDOCTX, 'variable name' + 1)?>

Agreed with the other commenters, this is a strange requirement. I'd push back and ask for rationalization why the requirement exists.


text:
Q: SDE Topology dirty areas don't go away Just looking for an explanation on SDE Topology dirty areas that don't go away.   My workflow involves editing a version of SDE data, then once finished I use the Validate Topology in Current Extent tool.  There is now a white box around my extent which looks good.
Next when I save, reconcile and post the dirty area boxes all return.
Is the picture below the way my data should look, or am I missing some steps?
Thanks,
Frank

The topo rules look something like this.

A: In many situations, a dirty area in you parent version will be present in your child version after you reconcile.  Additionally, in some situations reconciling can generate new dirty areas that aren't present in either version.
ArcGIS help:
http://resources.arcgis.com/en/help/main/10.1/index.html#/Dirty_areas_in_versioned_feature_classes/00620000000q000000/
I don't really have a good solution for you.  Every time I have had to deal with versioned topology I've tried to make sure that both the versions are free of dirty areas before I rec/post.  I still sometimes end up with dirty areas though.


text:
Q: C# - WCF - Serializing external classes I was receiving a "cannot serialize type..." error while attempting to serialize a BindingList. My initial thought was that the collection was the problem. I bypassed the collection and attempted to return a single instance of the class...same error. The classes are contained in a seperate project (but in the same solution); my next move was to copy and paste the class from the external project into the WCF project. With no other changes, the object now serializes.
Is this a namespace or persmissions issue? I can't rearchitect the solution at this point. What would prevent the class from seralizing in another project with the same code?  Thanks in advance.

A: Often when we get this error there is a sub class that does not have the Serializable or DataContract / DataMember attribute.
What is the class that you are using as T? Is that class marked as serializable?
Edit
For the error in the comment see "An attempt was made to load a program with an incorrect format" even when the platforms are the same

A: The fix for this was to simply recreate the WCF solution and add the class library projects to it. I have no idea what the problem was. Maybe bad meta information or something.


text:
Q: Set Button in PluginDocumentSettingPanel Content (Wordpress Gutenberg) I'm trying to create a new panel in the edit-post sidebar (Wordpress Gutenberg), I already managed to set the panel with the title and the text in the content part but I need to add a button there and no I find a way to do it.
var registerPlugin = wp.plugins.registerPlugin;
var PluginDocumentSettingPanel = wp.editPost.PluginDocumentSettingPanel;
// var btn = wp.element.createElement( 'button' );
var el = wp.element.createElement;
var __ = wp.i18n.__;

/* I tried to do it with a function, but it didn't work

function setButton() {
    btn.innerHTML = 'Submit';
    btn.type = 'submit';
    btn.name = 'formBtn';
    btn.onclick = function () {
        alert( 'Button is clicked');
    };
}
********************************************************/

function MyDocumentSettingPlugin() {
    return el(
        PluginDocumentSettingPanel,
        {
            name: 'my-document-setting-plugin',
            title: 'My Panel',
            icon: 'dashicon-name',
        },
        __( 'My Document Setting Panel Content', 'text-domain' ),
        // setButton(),        <---------- I need to add a button here
    );
}

registerPlugin( 'my-document-setting-plugin', {
    render: MyDocumentSettingPlugin,
} );

Please help :/

A: I finally solved it like this:
var registerPlugin = wp.plugins.registerPlugin;
var PluginDocumentSettingPanel = wp.editPost.PluginDocumentSettingPanel;
var Button = wp.components.Button;
var el = wp.element.createElement;
var __ = wp.i18n.__;

function onButtonClick() {
    alert( 'Button is clicked' );
}

function MyDocumentSettingPlugin() {
    return el(

        PluginDocumentSettingPanel,
        {
            name: 'my-document-setting-plugin',
            title: 'My Panel',
            icon: 'dashicon-name',
        },
        __( 'My Document Setting Panel Content', 'text-domain' ),

        el(
            Button,
            {
                className: 'myclass',
                isDefault: true,
                onClick: onButtonClick,
            },
            __( 'Button Text', 'text-domain' ),
        ),

    );
}

registerPlugin( 'my-document-setting-plugin', {
    render: MyDocumentSettingPlugin,
} );


text:
Q: Cypress - use of regular expression in 'contains' function returning no match Cypress is supposed to allow regular expressions in its 'contains' function, but it is finding no match, whereas there are a lot of elements containing the search text. I have to put in the full name to allow it to find it - but I want to get all the elements with names starting with 'Tier2_Forest' not just one.
For instance, this works:
cy.get('#database-col')
  .find('div.el-row div.card header.card-header p.card-header-title')
  .contains('Tier2_Forest : Tier2_Forest_ManEvents')
  .as('dbCard');

But this doesn't:
cy.get('#database-col')
  .find('div.el-row div.card header.card-header p.card-header-title')
  .contains('Tier2_Forest')
  .as('dbCard');

Have also unsuccessfully tried it in the format recommended by Cypress for regex - i.e. line starts with that phrase:
contains(/^Tier2_Forest/)
For some reason when I use contains('.db') it returns a list of elements containing '.db' at the end of their names - but I don't want those...
Snippet of the generated DOM:

[]

A: I would say you are on the right track, but .contains(/^Tier2_Forest/) fails because the text is not at the beginning of the string, there is white space preceding it.
Just try .contains(/Tier2_Forest/)
or more precisely .contains(/\s*Tier2_Forest/)
where \s* matches any whitespace character (equal to [\r\n\t\f\v ])
Check it out in https://regex101.com

A: I had the same problem and I solved it like this:
It takes into account spaces and line breaks if there are any.
.contains(/^\s*\n?Tier2_Forest/) // check begins, with nothing before
.contains(/^\s*\n?Tier2_Forest : Forest Database\s*\n?$/) //exact same sentence, check nothing before, check nothing after


text:
Q: Ranking elements in TreeSet I know a java treeset can't have identical elements and so I have to somehow differentiate an element from another even if they have the same "value". I want to be able to rank the elements and I'm noticing an interesting behavior.
TreeSet<Integer> set = new TreeSet<Integer>(new Comparator<Integer>()
        {
            public int compare(Integer arg0, Integer arg1)
            {
                if(arg0 > arg1)
                    return -1;
                return 1;
            }
        });

        set.add(40);
            set.add(20);
        set.add(30);
            set.add(20);

        for(Integer i:set)
        {
            System.out.println("Rank: "+(set.headSet(i,false).size()+1)+" Number: "+i);
        }

And this is the output:
Rank: 1 Number: 40
Rank: 3 Number: 30
Rank: 5 Number: 20
Rank: 5 Number: 20

This is what headset is supposed to do:
Returns a view of the portion of this set whose elements are less than (or equal to, if inclusive is true) toElement. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports.

I'm sorting in descending order so I think it should do the opposite.  The first element has nothing greater than it, so it returns 0, and then I add 1 to get its rank.  The second element has one thing larger than it, so I think it should return 1, adding 1 makes 2.  That's kind of weird.  I think I'm making a simple mistake.  I also need to figure out how to deal with the two 20's.  I want their rank to both be 3 but the treeset thinks they're different numbers.  I suppose I could use TreeMultiSet or some other third party library.

A: The two 20 are an issue because your implementation of compare violate the contract:

The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y.

if x=20 and y=20, this is not true in your implemenation: 1 == -(1)
You can fix this issue by returning 0, if arg0.equals(arg1).
Note: You need to use "equals" instead of "==" for objects of class Integer.

A:
I suppose I could use TreeMultiSet or some other third party library.

Since you're violating one of the basic characteristics of a set, I'd say you shouldn't use a Set or TreeSet, at least directly.   Options:

*

*use a List (and keep it sorted with Collections.sort() and Collections.binarySearch())

*use an IdentityHashMap and just use the value as the key mapped to itself

*use a TreeMap and map the value to # of occurences (extract to a list and sort as needed)

*use a 3rd party library (Bag or MultiSet)

*implement your own bag/multiset

Since I don't know more about the programming context, its hard to suggest a specific solution, but hopefully this brings up some other ideas to consider.


text:
Q: MongoDB query results aggregation I need to aggregate results of multiple searches together.
Currently, we do multiple lookups. For example, first - find user, then using retrieved userid find work order, then for each product ID in the order, lookup full product information.
Can this be aggregated into a single query, somehow?

A: Depends allot on how you handle your schema, so my answer could vary depending on what your specific needs are. however I did post a way on a work around to a similar situation (in a example of 3 schemas) you can find it here.
also it depends on if you have object id references or not, if its all stored directly then it could be a single aggregation query.


text:
Q: Complex/Nested XML Reading in C# I have been trying to read this XML file however it is complex/nested a good amount compared to the examples I have seen online. I have tried using LINQ and XMLReader with no luck.
LINQ will read each OrderScreen; however, when it comes to the Cell of each OrderScreen it loads all possible Cells into each OrderScreen even if the Cell does not belong to that OrderScreen. I understand why it does it, but I am fairly new to LINQ and most of the examples I see are not this complex and do not really cover this.
XMLReader works pretty well but it does not continue reading the next Cell after it completed the reading of one OrderScreen, it just reads the first Cell of the next OrderScreen then assumes it is at the end of the document. I did not include that code because all the searches I have seen people using LINQ over XMLReader.
XML is below first, most recent LINQ code after that
Any help is greatly appreciated!
<Screens>
  <DeleteScreens></DeleteScreens>
  <NewScreens>
    <OrderScreen>
      <ScreenNumber></ScreenNumber>
      <Title></Title>
      <NumberOfColumns></NumberOfColumns>
      <OptionScreen></OptionScreen>
      <ShowQuantityButtons></ShowQuantityButtons>
      <PrepSequenceScreen></PrepSequenceScreen>
      <Cell>
        <CellNumber></CellNumber>
        <CellName></CellName>
        <InventoryNumber></InventoryNumber>
        ...more Cell elements..
        <OptionGroup>
          <Type></Type>
          <ScreenNumber></ScreenNumber>
          <Cells></Cells>
        </OptionGroup>
        ...more OptionGroups...
      </Cell>
      ...more Cells...
    </OrderScreen>
    ...more OrderScreens...
  </NewScreens>
  <UpdateMenus>
     <Menu>
      <MenuNumber></MenuNumber>
      <MenuTitle></MenuTitle>
      ...more Menu elements...
    </Menu>
    ...more Menus...
  </UpdateMenus>
<Screens>

XDocument xdoc;
xdoc = XDocument.Load(@"C:\Users\Kwagstaff\Desktop\PMM_3.0\PMM_3.0\XML\Screens.xml");
var ORDERSCREENS = from a in xdoc.Descendants("OrderScreen")
 select new
 {
  ScreenNumber = a.Element("ScreenNumber").Value,
  Title = a.Element("Title").Value,
  NumberOfColumns = a.Element("NumberOfColumns").Value,
  OptionScreen = a.Element("OptionScreen").Value,
  ShowQuantityButtons = a.Element("ShowQuantityButtons").Value,
  PrepSequenceScreen = a.Element("PrepSequenceScreen").Value,
  Cell = from b in xdoc.Descendants("Cell")
  select new
  {
   CellNumber = b.Element("CellNumber"),
  }
};

A: In my opinion, the proper way to do that is with entities and decorators, you will need to do some research but as example
for something like
<MyComplexXML>
....
   <xalAddress>...</xalAddress>
   <multiPoint>
     <MultiPoint>...</MultiPoint>
   </multiPoint>
...
</MyComplexXML>

First, you create your classes like this
using System.Xml.Serialization;

namespace MyComplexXML_Model
{
    /// <summary>
    /// Address field for MyComplexXML
    /// </summary>
    public class Address
    {
        /// <summary>
        /// XalAddress
        /// </summary>
        [XmlElement("xalAddress")]
        public XalAddress XalAddress;
        [XmlElement("multiPoint")]
        public MultiPointAddress MultiPointAddress;
    }
}

and

using System.Xml.Serialization;

namespace MyComplexXML_Model
{

    public class MultiPointAddress
    {
        [XmlElement("MultiPoint", Namespace = "http://www.sample.net/sample")]
        public MultiPoint Multipoint;
    }
}

and when your complete hierarchies are in place you can call your root element like this
  var ns = new XmlSerializerNamespaces();
    ns.Add("sample", "http://www.sample.net/sample");
    ...

    var ms = new MemoryStream();
    var sw = new StreamWriter(ms);

    //Deserialize from  file
    var sr = new StreamReader(@"myfile.xml");
    var city = (MyComplexXML)new XmlSerializer(typeof(MyComplexXML)).Deserialize(sr);

Hope this point you in the right direction.


text:
Q: Failure to attach an existing EBS volume to a spot instance I have been using AWS spot instances with persistance storage; something along these lines. I have been this successfuly for months with different instance types, and extended my volume several times as i got more data (128gb > 256gb > 512gb).
In my last experiment, I extended my ebs volume to 1TB, ran some batch process on a m4.16xlarge machine, and after one day, the second status check failed (instance reachability check); unfortunetly i don't have the system log for that moment now.
I thought it's a generic failure, and launched a new c4.8xlarge spot instance with the same ebs volume; no errors, ssh successful, data there.
Now i'm trying to create a new m4.16xlarge with the same ebs, but it fails; full server log here. I'm not able to mount the volume with this or any other instance type now.
Do you have ideas what might have wrong and how i can remedy this?

A: The filesystem on your EBS volume is corrupted. Don't ask me how it became that way.
In the log, you'll see the following:
[   14.022730] EXT4-fs (xvdf1): ext4_check_descriptors: Checksum for group 0 failed (8312!=23362)
[   14.029039] EXT4-fs (xvdf1): group descriptors corrupted!
mount: mount /dev/xvdf1 on /permaroot failed: Structure needs cleaning

You'll need to fix your filesystem before trying to mount it again.
After some Googling, I found this, which you can try. But note that I do not warrant it's validity.
http://www.webdesignblog.asia/operating-systems/linux-os/ext4-fs-group-descriptors-corrupted-cannot-mount-disk-using-ubuntu/#sthash.XYgsfq3E.fTLnfoTc.dpbs


text:
Q: callback функция с циклом for внутри Есть следующий код, функция для перебора массива и функция для работы с элементом массива -handler4. Которая должна взять строку из массива и сделать из неё новую abc->cba; 123->321
 При использовании цикла for в функции handler4 происходит бесконечная итерация, почему так? Если использовать  for(i=0;i<strings.length;i++) то нет бесконечного цикла, но выводится только первый элемент массива. Почему так?

let textArray = ["abc", 123];
function processArray(array, callback) {
  let value = "New value: ";
  for (i = 0; i < array.length; i++)
    //console.log(i)
    value += callback(array[i]);
  return value;
}
 function handler4(element) {
  let backwards = "";
  let strings = element.toString();
  for (i = strings.length - 1; i >= 0; i--) backwards += strings[i];
  console.log(element);
  return backwards + ", ";
}

    alert(processArray(textArray,handler4))

A: У Вас i - одна и та же глобальная переменная. Ее надо объявлять как локальную в каждой функции:
for (var i = 0; i < array.length; i++)

...

for (var i = strings.length - 1; i >= 0; i--) backwards += strings[i];

let textArray = ["abc", 123];

function processArray(array, callback) {
  let value = "New value: ";
  for (var i = 0; i < array.length; i++)
    //console.log(i)
    value += callback(array[i]);
  return value;
}

function handler4(element) {
  let backwards = "";
  let strings = element.toString();
  for (var i = strings.length - 1; i >= 0; i--) backwards += strings[i];
  console.log(element);
  return backwards + ", ";
}

console.log(processArray(textArray, handler4))


text:
Q: How to delete multiple rows from a datagridview by selecting the checkboxes in C#? I have datagridview and header checkbox to check all the check boxes in the rows in the checkbox column (index of the column for all the check boxes 0).
I have following code in the deleted button event:
for (int i = 0; i < datagridview.Rows.Count; i++) {
            if (Convert.ToBoolean(datagridview.Rows[i].Cells[0].Value) == true) {
                datagridview.Rows.RemoveAt(i);
            }
        }

The datagridview.rows.count keeps decreasing as the row deleted but I in the loop keeps increasing. Thus, instead of deleting all the checked rows, it deletes some of them only. It does not delete the one with rows index 0, 1, 2 and so on with the new data in the datagridview as I increase in the code.

A: The problem is that by keep increasing the index on deletion, you skip the next item in the list:
0: [X] Item 0
1: [X] Item 1
2: [X] Item 2

on iteration 0 ... we delete Item 0 on index 0 OK

0: [X] Item 1
1: [X] Item 2

on iteration 1 ... we delete Item 2 on index 1 BUT we skipped Item 1 which is now on index 0

Therefore, you should iterate the list in the reverse order, that way when you remove an item, the next previous item's index is still the same:
for (int i = datagridview.Rows.Count; i >= 0 ; i--)
{
    // ....
}

A: I solved the issue after getting hints from Charles as below. Thank you!
 for (int i = 0; i < dgvBaleDisposition.Rows.Count; i++)
            {
                if (Convert.ToBoolean(dgvBaleDisposition.Rows[i]
                                      .Cells[0].Value) == true)
                {
                    dgvBaleDisposition.Rows.RemoveAt(i);
                }

                i = i - 1;
                j = j + 1;

                if (j == countRows)
                {
                    break;
                }
            }


text:
Q: Why is this code being executed when the user have not selected anything? I am trying to execute the code under the spinnerOnItemSelected listener from my adapter , when the  user selects a number from the spinner, but the code is being ran as soon as the fragment is launched which is not what I want. I would like for it to run only when the user selects an item from the spinner.
public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") final int position) {
    holder.produceName.setText(cartArrayList.get(position).getProductName());
    holder.producePrice.setText("$" + cartArrayList.get(position).getItemPrice());
    holder.numberOfItemsTv.setText("Quantiy: " + cartArrayList.get(position).getQuantity());
    getCurrentUserUid();

    // and store name of courses
    String[]  quantity = { "1", "2",
            "3", "4",
            "5", "6" };

    ArrayAdapter ad
            = new ArrayAdapter(
            ct,
            android.R.layout.simple_spinner_item,
            quantity);

    // set simple layout resource file
    // for each item of spinner
    ad.setDropDownViewResource(
            android.R.layout
                    .simple_spinner_dropdown_item);

    // Set the ArrayAdapter (ad) data on the
    // Spinner which binds data to spinner
    holder.spinner.setAdapter(ad);

    holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Log.i("tapped","tapped");

            String selectedItemFromSpinner =  adapterView.getItemAtPosition(i).toString();

            Log.i("selectedItemFromSpinner",selectedItemFromSpinner);

            FirebaseDatabase.getInstance().getReference("Cart").child(loggedInUserId).child(cartArrayList.get(position).getTimestamp()).child("quantity").setValue(selectedItemFromSpinner).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful()){
                        holder.middleQUanityTv.setText( selectedItemFromSpinner + "");
                        holder.numberOfItemsTv.setText("Quantity: " + selectedItemFromSpinner + "");

                    }
                }
            });

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

    //Log.i("IMAGES", productArrayList.get(position).getProductImage());
    Glide.with(ct)
            .load(cartArrayList.get(position).getProductImage())
            .centerCrop()
            .into(holder.productImage);

}


text:
Q: Sum of filesize of a list of files I have a text-file that contains a list of filenames (one filename per line).
Now I would like to calculate the size of all these files. I think I will have to do a ls -la on every line of the file and then accumulate the filesize.
I think that awk will be part of the solution, but thats just guess.

A: I would use the -s file test and perl:

-s  File has nonzero size (returns size in bytes).

Something like this:
#!/usr/bin/env perl;
use strict;
use warnings;

my $sum = 0;
while ( my $filename = <> ) {
    chomp ( $filename );
    $sum += -s $filename;
}

print "Sum is $sum bytes\n";

(reads filenames either from STDIN or from a file specified on command line, e.g. myscript.pl file_list.txt)
You could "one liner" this:
perl -nle '$sum += -s $_; END { print $sum }'

(and either pipe in a 'file name list' or specify a file argument after it as before)

A: With GNU stat:
stat -c %s -- $(<list) | paste -d+ -s - | bc

*

*stat displays information about the file

*

*-c specifies the format, %s gives the filesize in bytes

*paste -d+ -s concats the output together line by line with a + as delimiter

*bc piped to bc, it will be calculated together.

Add a -L option to stat, if for symlinks, you'd rather count the size of the file that the symlink eventually resolves to.
That assumes a shell like ksh, bash or zsh with the $(<file) operator to invoke split+glob on the content of a file.
Here list is expected to be a space, tab or newline (assuming the default value of $IFS) delimited list of file patterns (as in *.txt /bin/*). For a list of file paths, one per line, you'd need to disable globbing and limit $IFS to newline only, or with GNU xargs:
xargs -rd '\n' -a list stat -c %s -- | paste -sd+ - | bc

A: You need just last line of du -c output
du -ch $(<list) | tail -1

A: Another alternative, using ordinary shell commands. Even handles the filename-with-spaces case. Assumes that list of file names is in a file named fnames.
tr '\n' '\0' < fnames | xargs -0 cat | wc -c

wc is oddly useful in counting situations. Keep it in mind.

A: I also came up with a solution:
cat files.txt | while read f; do ls -la $f; done | awk '{s+=$5;} END {print s;}'

A: For filenames with space in my list, I used this (inspired by @Costas's answer):
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
du -ch $(<list) |tail -1
IFS=$SAVEIFS


text:
Q: Component Getting Rendered Infinite times in Nextjs I am trying to render the TEXT CLOUD in my Nextjs app, but it is getting rendered infinite time.I am using Next JS. Please help
Here is the code and screenshots:
import dynamic from "next/dynamic";
import { useRef} from "react";

const container = '.tagcloud';
const texts = [
    '3D', 'TagCloud', 'JavaScript',
    'CSS3', 'Animation', 'Interactive',
    'Mouse', 'Rolling', 'Sphere',
    '6KB', 'v2.x',
];
 const tag = {
    radius: 100,
    maxSpeed: 'normal',
    initSpeed: 'fast',
    direction: 135,
    keep: true
}
const Text_cloud=dynamic(
  () => {
      const refTag=useRef();
      return {TagCloud(container,texts,tag)};
    },
    { ssr: false }
  );

export default Text_cloud;

I am exporting this Component and using it in another page skills:
import React, { useState,useRef } from "react";
import Web from "../Component/web";
import Programming from "../Component/programming";
import Editing from "../Component/Editing";
import styles from "../styles/skill.module.css"
import Btn from "../Component/btn";
import Text_cloud from "../Component/text_cloud";

function Skill() {

    const [skill, setskill] = useState("Web")
    return (<>

                 setskill("Web")} className={styles.skilla}><Btn name="Web Dev" />
                 setskill("Programming")} className={styles.skilla}><Btn name="Programming" />
                 setskill("Editing")} className={styles.skilla}><Btn name="Editing" />

                    <Text_cloud />

        {skill === "Web" && <Web />}
        {skill === "Programming" && <Programming />}
        {skill === "Editing" && <Editing />}
    </>)
}

export default Skill;

After running the server I get this output and error:
It get render two times
And the error it shows is:
Here is the error Screenshot
Please help me out here


text:
Q: Add label or modifying widget on django-filter form I'm looking for a way of specifying what the select fields in the filter form are for, this is how it looks like right now:

And is hard to understand what the select inputs are for, the ideal would be to change the default option ("Unkown" and "--------") but it should be custom for each one. Already tried that but couldn't find a way to do it, it is possible?
If someone knows a way of doing this it would be great.
Adding a label should be the easier way, but don't know how to do it.
filters.py
class PatientFilter(django_filters.FilterSet):
    class Meta:
        model = Patient
        fields = {
            'dni': ['exact'],
            'first_name': ['icontains'],
            'last_name': ['icontains'],
            'risk': ['exact'],
            'status': ['exact'],
            'ubication': ['exact'],
            'supervisor': ['exact'],
        }

HTML
    {% if filter %}
        <form action="" method="get" class="form form-inline">
            {% bootstrap_form filter.form layout='inline' field_class="mr-3 mt-3" %}

            {% bootstrap_button 'Filter' button_class="btn-secondary" %}
            Clear

        </form>
    {% endif %}

The select inputs are foreign keys, here is its definition in models.py
status = models.CharField(max_length=15, choices=STATUS_CHOICES)
ubication = models.ForeignKey(Ubication, on_delete=models.CASCADE)
supervisor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)

I'm using tables2 with django-filters.

A: you can do this by adding empty_label to your ModelChoiceFilters.
class PatientFilter(django_filters.FilterSet):

    ubication = django_filters.ModelChoiceFilter(
        queryset=Ubication.object.all(),
        empty_label="Placeholder",
    )

    class Meta:
        model = Patient
        fields = {
            'dni': ['exact'],
            'first_name': ['icontains'],
            'last_name': ['icontains'],
            'risk': ['exact'],
            'status': ['exact'],
            'ubication': ['exact'],
            'supervisor': ['exact'],
        }

Edit:
For adding placeholder to CharFields you can try this:
from django.forms.widgets import TextInput

class FooFilter(filters.FilterSet):
     bar = filters.CharFilter(..., widget=TextInput(attrs={'placeholder': 'baz'}))


text:
Q: speed string search in PHP I have a 1.2GB file that contains a one line string.
What I need is to search the entire file to find the position of an another string (currently I have a list of strings to search).
The way what I'm doing it now is opening the big file and move a pointer throught 4Kb blocks, then moving the pointer X positions back in the file and get 4Kb more.
My problem is that a bigger string to search, a bigger time he take to got it.
Can you give me some ideas to optimize the script to get better search times?
this is my implementation:
function busca($inici){
        $limit = 4096;

        $big_one    = fopen('big_one.txt','r');
        $options    = fopen('options.txt','r');

        while(!feof($options)){
            $search = trim(fgets($options));
            $retro  = strlen($search);//maybe setting this position absolute? (like 12 or 15)

            $punter = 0;
            while(!feof($big_one)){
                $ara = fgets($big_one,$limit);

                $pos = strpos($ara,$search);
                $ok_pos = $pos + $punter;

                if($pos !== false){
                    echo "$pos - $punter - $search : $ok_pos <br>";
                    break;
                }

                $punter += $limit - $retro;
                fseek($big_one,$punter);
            }
            fseek($big_one,0);
        }
    }

Thanks in advance!

A: Why don't use exec + grep -b?
exec('grep "new" ext-all-debug.js -b', $result);
// here we have looked for "new" substring entries in the extjs debug src file
var_dump($result);

sample result:
array(1142) {
    [0]=>  string(97) "3398: * insert new elements. Revisiting the example above, we could utilize templating this time:"
    [1]=>  string(54) "3910:var tpl = new Ext.DomHelper.createTemplate(html);"
    ...
}

Each item consists of string offset in bytes from the start of file and the line itself, separated with colon.
So after this you have to look inside the particular line and append the position to the line offset. I.e.:
[0]=>  string(97) "3398: * insert new elements. Revisiting the example above, we could utilize templating this time:"

this means that "new" occurrence found at 3408th byte (3398 is the line position and 10 is the position of "new" inside this line)

A: $big_one    = fopen('big_one.txt','r');
$options    = fopen('options.txt','r');

while(!feof($options))
{
  $option = trim(fgets($options));
  $position = substr($big_one,$option);

  if($position)
    return $position; //exit loop
}

the size of the file is quite large though.  you might want to consider storing the data in a database instead.  or if you absolutely can't, then use the grep solution posted here.


text:
Q: Image parsing in python (connected components analysis) I have an image of mathematical formula and I need to parse symbols of it, but also save where they were (center of each symbol). For example image like this needs to be transformed into 15 different images 75x75, 1 per each symbol.
What I have tried is:

*

*Transform to gray and then binary: pixels close to white(> 250) becomes 255 and other become 0

*Use BNF to find all components and then transform them into images (with rescaling and everything else)

But I am sure it is not the best way to do it, maybe there is standard approach for this problem exist?
Here is my code:

class Parser:

    def init(self, targetSizes=(75, 75), binaryThreshold=cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU,
                 scaleFully=False, scaleFullyRate=0.9, whiteThreshold=249, blackThreshold=0,
                 rescalingInterpolation=cv2.INTER_AREA, pixelsInImageThreshold=20,
                 rescaleOriginalImage=True, rescaleToAtLeast=200, rescaleToAtMaximum=1000):
        self.targetWidth = targetSizes[0]
        self.targetHeight = targetSizes[1]

        self.binaryThreshold = binaryThreshold

        self.scaleFully = scaleFully
        self.scaleFullyRate = scaleFullyRate

        self.whiteThreshold = whiteThreshold
        self.blackThreshold = blackThreshold

        self.rescalingInterpolation = rescalingInterpolation
        self.pixelsInIMageThreshold = pixelsInImageThreshold

        self.rescaleOriginalImage = rescaleOriginalImage
        self.rescaleOriginalMin = rescaleToAtLeast
        self.rescaleOriginalMax = rescaleToAtMaximum

        self.parseMode = 1

    def _imageToBinary(self, image, zeroValueTrash=0, oneValueTrash=253):
        grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        ret, binary = cv2.threshold(grayImage, self.blackThreshold, self.whiteThreshold, self.binaryThreshold)
        # cv2.imwrite("Test.png", binary)
        return binary

    def _BNF(self, binaryImage):

        Q = MyQueue()
        whitePixels = []
        gg = 0
        for i in range(len(binaryImage)):
            for j in range(len(binaryImage[i])):
                if binaryImage[i][j] > self.whiteThreshold-1:
                    Q.put((i, j))
                    binaryImage[i][j] = 0
                    obj = []
                    gg += 1
                    while not Q.empty():
                        i, j = Q.pop()

                        obj.append((i, j))

                        if i + 1 < len(binaryImage) and binaryImage[i + 1][j] != 0:
                            Q.put((i + 1, j))
                            binaryImage[i + 1][j] = 0

                        if j - 1 > 0 and binaryImage[i][j - 1] != 0:
                            Q.put((i, j - 1))
                            binaryImage[i][j - 1] = 0

                        if i - 1 > 0 and binaryImage[i - 1][j] != 0:
                            Q.put((i - 1, j))
                            binaryImage[i - 1][j] = 0

                        if j + 1 < len(binaryImage[i]) and binaryImage[i][j + 1] != 0:
                            Q.put((i, j + 1))
                            binaryImage[i][j + 1] = 0

                        if self.parseMode == 1:
                            if i + 1 < len(binaryImage) and j+1 < len(binaryImage[i+1]) and binaryImage[i + 1][j+1] != 0:
                                Q.put((i + 1, j+1))
                                binaryImage[i + 1][j+1] = 0
                            if i + 1 < len(binaryImage) and j - 1 > 0 and binaryImage[i + 1][j-1] != 0:
                                Q.put((i + 1, j-1))
                                binaryImage[i + 1][j-1] = 0
                            if i - 1 > 0 and j - 1 > 0 and binaryImage[i - 1][j - 1] != 0:
                                Q.put((i - 1, j - 1))
                                binaryImage[i - 1][j - 1] = 0
                            if i - 1 > 0 and j + 1 < len(binaryImage[i-1]) and binaryImage[i - 1][j + 1] != 0:
                                Q.put((i - 1, j + 1))
                                binaryImage[i - 1][j + 1] = 0

                    cv2.imwrite("tmp/{}.png".format(gg), binaryImage)
                    whitePixels.append(obj)
        return whitePixels

    def parseImage(self, image_path: str) -> list:

        image = cv2.imread(image_path)
        if self.rescaleOriginalImage:
            image = self.scaleOriginal(image)

        binary = self._imageToBinary(image)

        whitePixels = self._BNF(binary)

        return whitePixels

    def isScaleable(self, imageShape):
        return True

    def scaleOriginal(self, image: np.ndarray):
        # To be created
        return image

@staticmethod
    def _getImageAndCenterFromDotes(Dotes, originalImage=None):
        i_mx, j_mx = -1, -1
        i_mn, j_mn = 100500, 100500  # just big numbers

        # finding upper right and lower left corner of image
        for el in Dotes:
            i, j = el

            if i_mx < i:
                i_mx = i
            if j_mx < j:
                j_mx = j
            if j_mn > j:
                j_mn = j
            if i_mn > i:
                i_mn = i

        # updating image center
        imageCenter = Point((i_mx + i_mn) // 2, (j_mx + j_mn) // 2)

        # finding out size of image
        width, height = i_mx - i_mn + 1, j_mx - j_mn + 1
        image = np.zeros((width, height)) if originalImage is None else np.zeros((width, height, 3))

        # recreating image from dotes
        if originalImage is not None:
            for el in Dotes:
                i, j = el
                image[i - i_mn][j - j_mn] = originalImage[i][j]
        else:
            for el in Dotes:
                i, j = el
                image[i - i_mn][j - j_mn] = 255

        return image, imageCenter

    def scaleParsedImage(self, image: np.ndarray):
        """
        :param image: np.ndarray
        :return: scaledImage np.ndarray
        """
        width, height = image.shape if len(image.shape) == 2 else image.shape[0], image.shape[1]

        newWidth = self.targetWidth if width > self.targetHeight else width
        newHeight = self.targetHeight if height > self.targetHeight else height
        if self.scaleFully and newHeight < self.targetHeight * self.scaleFullyRate and newWidth * self.scaleFullyRate:
            scaleRate = min((self.targetWidth * self.scaleFullyRate / newWidth), (
                    self.targetHeight * self.scaleFullyRate / newHeight))

            newWidth = math.ceil(newWidth * scaleRate)
            newHeight = math.ceil(newHeight * scaleRate)

        scaled = cv2.resize(image, (newHeight, newWidth), interpolation=self.rescalingInterpolation)

        # pasting our scaled image in the middle
        x_add, y_add = (self.targetWidth - newWidth) // 2, (self.targetHeight - newHeight) // 2
        resized = np.zeros((self.targetWidth, self.targetHeight)) if len(image.shape) == 2 else np.zeros((self.targetWidth, self.targetHeight, 3))
        for x in range(newWidth):
            for y in range(newHeight):
                resized[x + x_add][y + y_add] = scaled[x][y]

        return resized

    def parseAndConvert(self, image_name: str) -> list:
        imagesInDotes = self.parseImage(image_name)
        original = 255 - cv2.imread(image_name)

        images = []

        for dotes in imagesInDotes:
            image = self._getImageAndCenterFromDotes(dotes, original)
            images.append([self.scaleParsedImage(image[0]), image[1]])
        rawImages = []
        for image, center in images:
            rawImages.append(RawImage(image, center))

        return rawImages

A: Have a look at the (imho not all too intuitively named) function cv.findContours():
https://docs.opencv.org/3.4/d4/d73/tutorial_py_contours_begin.html
It should do most things that you are doing by hand right now out of the box, which is extracting and measuring binary objects.
If you encouter problems where a single symbol is made up of several objects (like i, % or "), look into the morphological operations to merge them into a single one: erode(), dilate(), or open and close via morphologyEx() (Tutorial here: https://docs.opencv.org/4.x/d9/d61/tutorial_py_morphological_ops.html).


text:
Q: How does conservation of angular momentum not violate the time invariance of Newtonian mechanics? Richard Feynman states:

This follows from the fact that if we substitute −t for t in the original differential equation, nothing is changed, since only second derivatives with respect to t appear. This means that if we have a certain motion, then the exact opposite motion is also possible. In the complete confusion which comes if we wait long enough, it finds itself going one way sometimes, and it finds itself going the other way sometimes. There is nothing more beautiful about one of the motions than about the other. So it is impossible to design a machine which, in the long run, is more likely to be going one way than the other, if the machine is sufficiently complicated.
One might think up an example for which this is obviously untrue. If we take a wheel, for instance, and spin it in empty space, it will go the same way forever. So there are some conditions, like the conservation of angular momentum, which violate the above argument. This just requires that the argument be made with a little more care. Perhaps the walls take up the angular momentum, or something like that, so that we have no special conservation laws. Then, if the system is complicated enough, the argument is true. It is based on the fact that the laws of mechanics are reversible.

*

*Richard Feynman 46-3 paragraphs 2 & 3 (https://www.feynmanlectures.caltech.edu/I_46.html).

I am not convinced that, if angular momentum is conserved, that a wheel will eventually (on an enormous enough time span) reverse itself in the absence of other forces or temperature gradients.
If a wheel is spinning alone in empty space, it must conserve its angular momentum such that it can never reverse. Doesn't this violate Feynman's argument? I do not understand his refutation, how can we avoid having "special conservation laws?"

A: Feynman isn't saying that a wheel spinning in empty space will eventually reverse itself. As he says, that is an example for which the earlier claim is "obviously untrue," essentially because it is too simple a system.
His argument is that if we add complexity - perhaps we have $10^{23}$ wheels which may exchange angular momentum with each other or with the environment (e.g. the walls, some background radiation field, external particles) - then the fact that the total angular momentum in the universe is conserved is not sufficient to constrain the dynamics of the individual wheels in any meaningful way. When we restrict our focus only to the wheels and not to the surrounding environment with which they may exchange angular momentum, angular momentum is no longer a conserved quantity.


text:
Q: MIME subject decoding, when RFC are not respected Subject mime field is in ASCII. Every character excluded by the ASCII table has to be Q/encoded or base64/encoded. Content-Type field in the header has also nothing to do with the way subject is encoded. Am I correct?
However (and unfortunately) some clients (read Microsoft Outlook 6 for example) insert a string encoded in whatever (BIG5 for example) in the header, without specifying with q/base64 encoding that the string is in BIG5. How can i handle these wrongly-encoded emails? Is there a standard way, to parse these?
My goal is to have the biggest compatibility possible, even by using 3rd part paid programs; how can i do that? (sorry for my buggy english)

A: Subject header encoding has nothing to do with Content-Type header. There is no "perfect" way to handle Subject. I've implemented this just by a hack that tries to see if all characters of text fit in big5, if not then try next encoding in order.
Big5, utf-8, latin-1, q/base64 and finally ascii


text:
Q: Exception in Hibernate 'Cannot Release Connection'? I have used Spring DATA JPA in my application, which is wrapper over hibernate.
While interaction with database at one point I am getting expection
Caused by: org.hibernate.exception.GenericJDBCException: Cannot release connection
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
    at org.hibernate.jdbc.ConnectionManager.closeConnection(ConnectionManager.java:478)
    at org.hibernate.jdbc.ConnectionManager.aggressiveRelease(ConnectionManager.java:429)
    at org.hibernate.jdbc.ConnectionManager.afterStatement(ConnectionManager.java:304)
    at org.hibernate.jdbc.AbstractBatcher.closePreparedStatement(AbstractBatcher.java:572)
    at org.hibernate.jdbc.AbstractBatcher.closeStatement(AbstractBatcher.java:291)
    at org.hibernate.jdbc.AbstractBatcher.closeQueryStatement(AbstractBatcher.java:307)
    at org.hibernate.jdbc.AbstractBatcher.closeQueryStatement(AbstractBatcher.java:234)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:1967)
    at org.hibernate.loader.Loader.doQuery(Loader.java:802)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
    at org.hibernate.loader.Loader.doList(Loader.java:2533)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
    at org.hibernate.loader.Loader.list(Loader.java:2271)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:452)
    at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363)
    at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1268)
    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:246)

connection handling in hibernate is the internal handling we don't explicitly release or close the connection.
I can't understand how to resolve this issue..

A: Finally I got the solution. I solved this problem by setting some additional configuration for by database.
Here is the detailed link: http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html
In nutshell ("testOnBorrow", "testOnReturn", "testWhileIdle") these are the parameters I played with to remove above exception.
Above exception show at some point of time our database connection object get invalidated somehow. But these setting helps us to keep check on our database connection.
Cheers :)


text:
Q: How can I press individual option in actionsheet in React Native? I am still new to React Native. I have an actionsheet with two options and a cancel option. I am having trouble understanding how to make each option do something different when pressed.
My code:
import React, { useRef } from "react"
import ActionSheet from 'react-native-actionsheet'
import { View, Text, Pressable } from "react-native";
import Icon from 'react-native-vector-icons/FontAwesome';

const ActionSheet = () => {

  let actionSheet = useRef();
  let optionArray = ['Orange', 'Cherry', 'Cancel'];

  const showActionSheet = () => {
    actionSheet.current.show();
  }

  return (
    <View
      <Pressable onPress={showActionSheet}>
        <View>
          <Text>Choose Fruit</Text>
          <Icon name="angle-right" size={15}/>
        </View>
      </Pressable>
      <ActionSheet
        ref={actionSheet}
        options={optionArray}
        cancelButtonIndex={2}
        onPress={{????}}
      />
    </View>
  );
};

What I'd like to do is navigate to a different screen when an option is pressed
Would appreciate any help. Thank you in advance!

A: The onPress function provides an index argument. Thus consider the following code snippet.
const onActionSelect = (index) => {

    if (index === 1) {
      // first action pressed
    } else if (index === 2) {
      // second action pressed
    }
    // and so on
}

<ActionSheet
        ref={actionSheet}
        options={optionArray}
        cancelButtonIndex={2}
        onPress={onActionSelect}
/>


text:
Q: Serre spectral sequence degeneration in homology vs cohomology Let $\pi\colon E \rightarrow B$ be a fiber bundle with fiber $F$.  I am not assuming that $B$ is simply-connected.  We then have Serre spectral sequences in both rational homology and rational cohomology:
$$E^2_{pq} \cong H_p(B;H_q(F;\mathbb{Q})) \Longrightarrow H_{p+q}(E;\mathbb{Q})$$
$$E_2^{pq} \cong H^p(B;H^q(F;\mathbb{Q})) \Longrightarrow H^{p+q}(E;\mathbb{Q})$$
Since $B$ is not simply connected, the coefficient systems have to be regarded as local (twisted) coefficient systems on $B$.  Assume that I know that one of these spectral sequences degenerates at the second page.  Does it follow that the other one does as well?

A: The answer is yes, and this follows from the comments, but it's worth spelling out the (non-obvious) details.
By Will Sawin's comment, the claim will follow if we can show that
$$
\dim_\mathbb{Q} H^p(B;H^q(F;\mathbb{Q})) = \dim_\mathbb{Q} H_p(B;H_q(F;\mathbb{Q}))
$$
for all $p,q\ge0$. The Universal Coefficient Theorem does not hold with twisted coefficients. However, note that the vector spaces on the right are by definition the homology groups of the chain complex
$$
C_*(\widetilde{B})\otimes_\pi H_q(F;\mathbb{Q}),
$$
with differential induced by that of the chain complex $C_*(\widetilde{B})$ of the universal cover. Here $\pi=\pi_1(B)$ and we are taking tensor product of $\mathbb{Z}\pi$-modules.
Following archipelago's comment, let's see what happens if we dualize this chain complex by taking Hom into the rationals. By the tensor-hom adjunction there are natural isomorphisms
$$
{\rm Hom}_\mathbb{Z}\big(C_*(\widetilde{B})\otimes_\pi H_q(F;\mathbb{Q}),\mathbb{Q}\big)\cong {\rm Hom}_\pi\big(C_*(\widetilde{B}),{\rm Hom}_\mathbb{Z}(H_q(F;\mathbb{Q}),\mathbb{Q})\big) \cong {\rm Hom}_\pi\big(C_*(\widetilde{B}), H^q(F;\mathbb{Q})\big),$$
and so we get precisely the cochain complex whose cohomology gives the vector spaces on the left. Since everything in sight is a rational vector space, the usual algebraic Universal Coefficient Theorem implies the claim.


text:
Q: Scale TCP Socket based architecture in .NET Scenario : n number of vehicles create tcp socket connections with the tcp server. Server then dumps incoming messages to a DB. Admins can send commands to the vehicles through the sockets as well so sockets have to be persistent.
Problem : Currently, there is only single tcp server and DB sever.
Question : How to make this architecture scalable in .NET. We want to have more tcp servers and DBs. Whats the best method/technology stack.
Thanks

A: I believe what you are looking for is a messaging infrastructure, there are several well established libraries/products in this section( e.g. RabbitMQ, ZeroMQ, ...)
almost all of them supports patterns for distributing message across several producers/consumers, which makes writing scalable applications easier,
ZeroMQ is something in the middle and the usage is very similar to sockets.
Aside from library selection I suggest you to have a look at ZMQ Guide, it describes patterns and best practices for writing an scalable application.


text:
Q: Mongoose set text index for a field I have schema like this :
var mySchema = new Schema({
          title:  String,
          body: String,
          path: String
        });

I want add text index to title field.
I used this code :
mySchema.index({title: 'text'});

But it's not working , i be appreciated if tell me where i am  wrong.


text:
Q: How to retain NaN values using pandas factorize()? I have a Pandas data frame with several columns, with some columns comprising categorical entries. I convert (or, encode) these entries to numerical values using factorize() as follows:
for column in df.select_dtypes(['category']):
     df[column] = df[column].factorize(na_sentinel=None)[0]

The columns have several NaN entries, so I let na_sentinel=None to retain the NaN entries.  However, the NaN values are not retained (they get converted to numerical entries), which is not what I desire. My Pandas version is 1.3.5.  Is there something I am missing?

A: Factorize converts NaN values by default to -1. The NaN values are retained in this way since the NaN values can be identified by the -1. You would probably want to keep the default which is:
na_sentinel =-1

see
https://pandas.pydata.org/docs/reference/api/pandas.factorize.html


text:
Q: Mapbox map not filling ion-content fullscreen I'm trying to make my header transparent with
<ion-header no-border>
  <ion-toolbar >
    <ion-buttons slot="start">
      <ion-menu-button color="primary"></ion-menu-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>
<ion-content fullscreen>

</ion-content>

and in .scss
ion-content{
  --ion-background-color: transparent;
}

ion-toolbar {
  --background: transparent;
  --color: white;
}

#map {
  height: 100%;
  width: 100%;
}

but still the div with id="map" doesn't get fullscreen and I always get this no matter what

How do I solve the problem?

A: html.file
<ion-header>
  <ion-toolbar color="transparent">
    <ion-buttons slot="start">
      <ion-menu-button color="light"></ion-menu-button>
    </ion-buttons>
    <ion-title color="light" text-center>Sign In</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content fullscreen>
</ion-content>

css.file
ion-content{
   padding: 0px;
}