text:
Q: How to pass values from one class to another class in TestNG framework I am writing automation scripts for travel website.
I have one class in for HomePage. In home page I am storing the value which I've entered in destination field so that I can compare that value on the search result page to ensure search result match with the value I've entered in destination. So I am getting the value from Homepage class and want to use that value in Search result page.
Here is my code below. I am trying to integrate Selenium with TestNG framework. In selenium I've did this using constructor class.
HomePage Class:
 'public class HomePage extends MainSite{

    public static String Rdest ="";

    public HomePage(WebDriver driver) {
        // TODO Auto-generated constructor stub
    }
    @Test
    public void Home() throws InterruptedException
    {
        // Entering values in destination field
             SelectDestination();

                // Clicking calender to 5 months future month
                for (int i = 0; i <= 5; i++) {

driver.findElement(By.xpath("//div[contains(text(),'Select Departure
Date')]/following::a[contains(@class,'ui-datepicker-next ui-corner-all')]
[2]")).click();

                }

                //Calling SelectDate funtion to select date
                SelectDate();

                // clicking Search Flight button
                driver.findElement(By.xpath("//*[@id='btn-search-
flight']")).click();

    }

public   String SelectDestination() throws InterruptedException{

    WebElement dest = driver.findElement(By.id("destination_0"));

        String[] des = { "Zurich", "Lahore", "Geneva", "Sydney", "Moscow",
"Stockholm", "Cali", "Rome" };
        int index = (int) (Math.random() * 8);
         Rdest = des[index];
        dest.sendKeys(des[index]);
        System.out.println(index);
        //Char d =dest.charAt(index);
        System.out.println("Randomly selected destination:"+Rdest);
        Thread.sleep(5000);
        //dest.sendKeys(Keys.ARROW_DOWN);
        dest.sendKeys(Keys.RETURN);
        Thread.sleep(2000);

        System.out.println(Rdest);

        System.out.println("Destination Selected");
        //private static String Destval = Rdest;
        return Rdest;
    }

Am storing the destination value in Rdest Variable
As i dont want to run the entire above function, i store only the Rdest
value in a separate function DestinationVal in Variable in the name of
Destination as below
public String DestinationVal()
{
    String Destination = Rdest;
    System.out.println("Destination function value="+Destination);
    return Destination;
}

Kindly Guide me how i can use this Destination value in Search Result class
    public void SelectDate()
    {
        //Selecting Departure Date
        DateFormat dateFormat = new SimpleDateFormat("dd");
        Date date = new Date();
        String Dd=dateFormat.format(date);
        System.out.println(dateFormat.format(date));
        System.out.println(date);
        driver.findElement(By.xpath("//div[contains(text(),'Select Departure

Date')]/following::a[contains(text(),'"+dateFormat.format(date)+"')]"))
.click();

        //Selecting Return Date
        int Dr= Integer.parseInt(Dd);
        int abc = (int) (Math.random() * 5);
        Dr= Dr+abc;
        System.out.println("Number of days increased:"+Dr);
        String Dr1 = Integer.toString(Dr);
        driver.findElement(By.xpath("//div[contains(text(),'Select Return
Date')]/following::a[contains(text(),'"+Dr1+"')]")).click();

    } '

SearchResult Class:
public class SearchResult extends MainSite {
//@Test (Dataprovider="Destination")
public void Result() throws InterruptedException
{

    // Waiting for the search result to get displayed
            Thread.sleep(10000);
            //Calling Homepage to use destination for comparition
            HomePage hp1 = new HomePage(driver);
            String returnVal = Destination;
            //System.out.println(returnVal);
            //Validating searched source
            String Src =
driver.findElement(By.xpath("//span[contains(text(),'Flexible with
')]/following::div[@class='loc'][1]/span[1]")).getText();
            //System.out.println(Src);
            if(Src.equals("Colombo"))
            { System.out.println("Search result match source location" );}
            else {System.out.println("Source locatoin is not match on second
page");}
            String Dest =
driver.findElement(By.xpath("//span[contains(text(),'Flexible with
')]/following::span[contains(text(),'"+returnVal+"')][1]")).getText();
            //System.out.println(Dest);
            Thread.sleep(1000);
            if (Dest.toLowerCase().contains(returnVal))
{System.out.println("Search Result match Destination location");}
            else {System.out.println("Destination locatoin is not match on
second page");}

            // Clicking on first book now button from the search result
            driver.findElement(By.xpath("//span[contains(text(),'Flexible
with ')]/following::a[@class='btn-book'][1]")).click();
}

A: You can apply this logic:
Class TestA
{
    public void testMethod()
    {
    String testvalue = "XXXXXX";
    }
}

Here testvalue is the variable to which you want to pass,
The destination class, in which you want to use value of Base class:
You can retrieve it by :
TestA OBJ = new TestA();
System.out.println(OBJ.testvalue);

A: Create in Your MainSite which You extend in both classes create getter/setter for destination:
private static String destination;

public String getDestination() {
    return destination;
}

public void setDestination(String destination) {
    this.destination = destination;
}

so You can do following:
HomePage homePage = new HomePage();
homePage.setDestination(homePage.SelectDestination()); //this will return Your random destination and store it in MainSite with get/set

than simply call
SearchResult searchResult = new SearchResult();
searchResult.getDestination();

I hope I got to bottom of a problem. But my suggestion is that You put all of Your pages into PageObject design pattern, check this page https://martinfowler.com/bliki/PageObject.html, and You will have cleaner code and easy to maintain.

A: You need to do the below 3 Steps in Home page Class.

*

*Create one private variable for the destination

*Create one public method to return the Destination variable value

*Update the destination variable value in your test method(after extracting the value)

SearchResult:

*

*Create on Object for the HomePage class as HomePage homepage=new HomePage();

*Access the getDestinationVariable method using the HomePage class Object as
homepage.getDestinationValue();

Code needs to be added in HomePage Class:
//add it as instance variable
private String destinationValue;

public getDestinationValue(){
     return destinationValue;
}

public String SelectDestination() throws InterruptedException{
    -- etc ---
   destinationValue=Rdest;
   return Rdest;
}

SearchResult:
Below code needs to be added in search result class
HomePage homepage=new HomePage();
homepage.getDestinationValue();


text:
Q: Angular 8: How to Show Loader/Spinner only on particular components on different router-outlet based on HTTP Response? How can I Show Loader/Spinner only on particular components on different router-outlet based on HTTP Response,
For Example, I have different modules and i want spinner to show on that router-outlet only when any HTTP Request is done on that module's components only.

A: Use ng-block-ui library which is popular for show loader for specific div, specific router module and easy to customize.
npm install ng-block-ui --save

Include the BlockUIModule in your main app module.
import { BlockUIModule } from 'ng-block-ui';

@NgModule({
  imports: [
    BlockUIModule.forRoot()
  ]
})
export class AppModule { }

Here is the following example for specific showing loading in specific div or container.
@Component({
  selector: 'cmp',
  template: `
    <ng-template #blockTemplate>

    </ng-template>

    <block-ui [template]="blockTemplate">

    </block-ui>
  `
})
export class Cmp {}

Even you should be customize some of loading time delay, loading size as per your router URL or data load events.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Print dependency tree for project I know how to dump dependency tree for package:
swift package show-dependencies

But for project?

A: Not a beautfiful solution and I just finished it (no longer testing) but it works so far for Xcode 14.1:

*

*Create a Scripts/dependenciesTree.sh bash-script under your project root:

if [[ $1 == "" ]]; then
  echo "Missing build dir as 1st parameter"
  exit 1
fi

if [[ $2 == "" ]]; then
  echo "Missing project dir as 2nd parameter"
  exit 1
fi

BUILD_DIR=$1
PROJECT_DIR=$2

echo "Build dependencies tree"
cd "$BUILD_DIR/../../SourcePackages/checkouts"
exportFile="$PROJECT_DIR/dependencies-tree.md"
echo "# Dependencies trees for each Swift-Package" > "$exportFile"
echo "" >> "$exportFile"
echo "Build date: $(date '+%Y-%d-%m %a %H:%M:%S %Z')" >> "$exportFile"
echo "" >> "$exportFile"
for directory in */; do
  echo "Tree for $directory"
  echo "" >> "$exportFile"
  echo "## Tree for $directory" >> "$exportFile"
  pushd $directory
  swift package show-dependencies >> "$exportFile"
  echo "" >> "$exportFile"
  echo "" >> "$exportFile"
  popd
done

*

*Go to your Project configuration, Targets, "Build Phases" and add a "New Run Script Phase". In the script add this lines:

# Script must be run without Xcode environment variables,
# otherwise it may try to build an iOS application targeting macOS based on iOS.
# Which doesn't make any sense and always fails.
env -i "$PROJECT_DIR/Scripts/dependenciesTree.sh" "$BUILD_DIR" "$PROJECT_DIR"

The result is then in the dependencies-tree.md file.
Although, this has one problem: If a package is added from a local directory, not a GIT repository, it won't be listed there. But its transitive dependencies should be listed there, if they reference a GIT repository.


text:
Q: Java Code working in eclipse, not working when packed into jar I have a spring batch processing project, which is running perfect in eclipse.
I generated the executable Jar file and set the referenced jar files in the classpath,
When I run the executable jar file in command line, it throw Exception
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/jdbc/CannotGetJdbcConnectionException
Caused by: java.lang.ClassNotFoundException: org.sprigframework.jdbc.CannotGetJdbcConnectionException

my project needs to get jdbc connection first, and this exception means no connection created.
I packed the referenced jars into the executable jar, so I am sure the jar is there, but java could not load it.
I tried to use remote debug to debug this jar, it fails at the very beginning of load class.
Anyone has idea about this? Thanks.

A: This Error is because

Fatal exception thrown when we can't connect to an RDBMS using JDBC.

The JDBC .jar library you have in your project, but not in the correct directory in your final .jar file.
Or when you're running your jar file in command line, make sure the jdbc .jar file is in your CLASSPATH.


text:
Q: Why am I getting segmentation fault when reversed sorted array is given as input? I am testing it for various distributions and I am getting segmentation fault when reversed (descending) sorted array is given as input. Sometimes it works well even for reversed sorted array and sometimes I am getting segmentation fault error particularly on large reversed sorted array (>100000). Is it because of very deep recursive call if so then what is the limit of recursive call depth, on what factors does it depend and what precautions need to be taken care while writing recursive programs.
int partation(double *a, int lower, int upper) {
    int i = lower, j = upper;
    double t = a[lower], temp;
    while (i <= j) {
        while (i <= upper && a[i] <= t)
            i++;
        while (a[j] > t)
            j--;
        if (i <= j) {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }
    temp = a[lower];
    a[lower] = a[j];
    a[j] = temp;
    return j;
}

void quick_sort(double *a, int lower, int upper) {
    int j;
    if (lower >= upper)
        return;
    else {
        j = partation(a, lower, upper);
        quick_sort(a, lower, j - 1);
        quick_sort(a, j + 1, upper);
    }
}

A: You have a segmentation fault because of a stack overflow.
A reverse sorted array is the worst case for your partition scheme: you recurse n-1 times on an array of n elements.
You can try and improve the partition scheme to avoid this pathological case, but there is a way to avoid deep recursion in the quick_sort function: on recurse on the smaller half and loop on the larger one. The pathological case will just be very slow but no longer crash.
Here is the code:
#include <stdio.h>
#include <time.h>

int partition(double *a, int lower, int upper) {
    /* assuming lower < upper */
    int i = lower, j = upper;
    double t = a[lower], temp;
    while (i <= j) {
        while (i <= upper && a[i] <= t)
            i++;
        while (a[j] > t)
            j--;
        if (i < j) {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }
    temp = a[lower];
    a[lower] = a[j];
    a[j] = temp;
    return j;
}

void quick_sort(double *a, int lower, int upper) {
    while (lower < upper) {
        int j = partition(a, lower, upper);
        if (j - lower < upper - j) {
            if (lower < j - 1) {
                quick_sort(a, lower, j - 1);
            }
            lower = j + 1;
        } else {
            if (j + 1 < upper) {
                quick_sort(a, j + 1, upper);
            }
            upper = j - 1;
        }
    }
}

int main(void) {
    double a[65536];
    for (int n = 2; n <= (int)(sizeof(a) / sizeof(*a)); n += n) {
        for (int i = 0; i < n; i++) {
            a[i] = n - i;
        }
        clock_t t = clock();
        quick_sort(a, 0, n - 1);
        t = clock() - t;
        for (int i = 1; i < n; i++) {
            if (a[i - 1] > a[i]) {
                printf("out of order at %d: %f > %f\n", i - 1, a[i - 1], a[i]);
                return 1;
            }
        }
        printf("a[%d] sorted in %.3f msec\n", n, (double)t * 1000.0 / CLOCKS_PER_SEC);
    }
    return 0;
}

Output:
a[2] sorted in 0.002 msec
a[4] sorted in 0.001 msec
a[8] sorted in 0.001 msec
a[16] sorted in 0.001 msec
a[32] sorted in 0.000 msec
a[64] sorted in 0.002 msec
a[128] sorted in 0.006 msec
a[256] sorted in 0.021 msec
a[512] sorted in 0.074 msec
a[1024] sorted in 0.287 msec
a[2048] sorted in 1.185 msec
a[4096] sorted in 5.104 msec
a[8192] sorted in 19.497 msec
a[16384] sorted in 78.140 msec
a[32768] sorted in 297.297 msec
a[65536] sorted in 1175.032 msec

Regarding your second question, what factors does it depend on and what precautions need to be taken while writing recursive programs? there is no definitive answer:

*

*The limits on stack space (if there is such a concept) are implementation specific, different systems have very different limits: from just a few kilobytes on small embedded systems to several megabytes on large systems.

*Recursing thousands of times is risky, and so is defining large arrays with automatic storage. In the above code, I define an array of 64K doubles, it is not a problem on modern general purpose computers, but could be too much on a small digital sensor. The maximum recursion level with the recurse on smaller half approach is bounded by log(N), which is only 16 for N=65536, should be OK for all systems.

A: Yes, the segmentation it is because too deep recursions.
When you have a reversed array to be quick sorted in your function, the t in the partation function would always be the largest or smallest value in the realm as you always use a[lower] as the value of t. This means that the return value of partation would always be equal to upper or 'lower' when the array is reversed. This leads to a total number of (upper - lower) recursions, and would surely result in an error. To avoid this, use an random value between upper and lower instead of always using a[lower] as the value of t
#include <stdlib.h>
#include <time.h>

int partation(double *a, int lower, int upper)
{
    int i = lower, j = upper;
    double t = a[rand() % (upper - lower) + lower], temp;
    while (i <= j)
    {
        while (i <= upper&&a[i] <= t) i++;
        while (a[j]>t) j--;
        if (i <= j)
        {
            temp = a[i]; a[i] = a[j]; a[j] = temp;
        }
    }
    temp = a[lower];
    a[lower] = a[j];
    a[j] = temp;
    return j;

}

void quick_sort(double *a, int lower, int upper)
{
    int j;
    if (lower >= upper) return;
    else
    {
        j = partation(a, lower, upper);
        quick_sort(a, lower, j - 1);
        quick_sort(a, j + 1, upper);
    }
}

int main()
{
    srand(time(0));
    /*input the value of a here*/
    /*double a[10000];
    for (int i = 10000 - 1, index = 0; --i;++index)
    {
        a[index] = i;
    }*/
    quick_sort(a, 0, 9999);
    return 0;
}


text:
Q: Using DocC for an Objective-C project I am working on an Objective-C library, that is also available via Swift Package Manager, namely Sentry. We want to generate API docs using DocC, but I am running into the problem where when I generate the documentation I get this error:
error: target 'Sentry' is not a Swift source module

Weirdly enough when I build the documentation within Xcode itself (Product -> Build Documentation) it works perfectly well.
This is the command I am using on the command line to try to generate the docs:
swift package \
  generate-documentation \
  --allow-writing-to-directory ./docs \
  --target Sentry \
  --output-path ./docs \
  --transform-for-static-hosting \
  --hosting-base-path Sentry

And our Package.swift can be found here.
So why is it that Xcode can generate the docs perfectly fine, but I can't do it using swift-docc-plugin?


text:
Q: guava cache containsValue public boolean containsValue(@Nullable Object value) {
    if (value == null) {
        return false;
    }
    long now = ticker.read();
    final Segment<K, V>[] segments = this.segments;
    long last = -1L;
    for (int i = 0; i < CONTAINS_VALUE_RETRIES; i++) {
        long sum = 0L;
        for (Segment<K, V> segment : segments) {
            // ensure visibility of most recent completed write
            int unused = segment.count; // read-volatile

            AtomicReferenceArray<ReferenceEntry<K, V>> table = segment.table;
            for (int j = 0; j < table.length(); j++) {
                for (ReferenceEntry<K, V> e = table.get(j); e != null; e = e.getNext()) {
                    V v = segment.getLiveValue(e, now);
                    if (v != null && valueEquivalence.equivalent(value, v)) {
                        return true;
                    }
                }
            }
            sum += segment.modCount;
        }
        if (sum == last) {
            break;
        }
        last = sum;
    }
    return false;
}

there is the containsValue mathed.My question is that why only check modCount when not found the value.if other thread invoke the remove operation before 'return true',this mathed will be wrong.forgive my poor English.

A: Yes, this can race.  So can any operation using the result of containsValue; but if it returns true, then the value was present at some point while the method was being evaluated; that's the best you could possibly do anyway.
As far as modCount goes, that's only being used if the value isn't present because it's used to detect if the map is being concurrently modified and it needs to look again.  But if the value was present at any time during the iteration, then the method should return true, which it does.


text:
Q: How can I sell my biscuits? When I go to the market board there is nowhere to sell country biscuits. When I go to the help page there is no where to get a resolution. They list email help and live chat but there is no time to click on to get to those, and the question and answer forum only have the fact that you sell your biscuits and they don't count towards the quest. Well I would love to not be able to have it count toward my quest I just want to be able to sell them.
How do I sell them?

A: i had this problem but to sell them you have to scroll a little bit left of your farm where the other things are and click on the market stall and sell the biscuits there, it does take a while for someone to buy them, but you wont be able to sell them on the farm board, only the market :) hope this helped.

A: Unfortunately, in this case, it looks like you have to wait until there are biscuits on the board. Sell other things to clear up spaces, and hopefully biscuits will pop up. You can also take things off your board and wait for them to be replaced with new things, which can also help you get a chance to sell your biscuits.

A: If you scroll to the left of your farm & click on the fruit stand you can sell them there.


text:
Q: writing a string into large number of files I have created 10 files using touch command on  linux terminal in a directory having only these created files.
 $ touch a1.c a2.c a3.c a4.c a5.c a6.c a7.c a8.c a9.c a10.c

I want to write a string "stackOverflow"(say) into all these files at a time .
How to do that?Is there any command or some other way ?
Platform -ubuntu 10.04

A: From the command prompt (Bash)
for f in *.c; do echo "stackOverflow" >> $f; done

A: Once your data is in an array it is easy to loop over, see the example.
Just save this in an empty file writeStringToFiles.sh and right click it then under the permissions tab click Allow executing file as a program. You can double click it or run it from the terminal by "cd" to the directory its in then just type "./writeStringToFiles.sh". You can put any commands you want in a bash script like this.
#!/bin/sh
files=(a1.c a2.c a3.c a4.c a5.c a6.c a7.c a8.c a9.c a10.c)
thingToWrite='stackOverflow'

for i in "${files[@]}"
do :
    touch $i
    echo -e $thingToWrite >> $i
done

exit

A: If you files are not empty(at least 1 byte):
$ sed -i '1i\
stackOverflow' a{1..10}.c

will insert stackOverflow at the beginning of every file.


text:
Q: Why two line "Enter their marks" is printed although i only write it to print one line? It prints "Enter the marks" two times when I run it, although it is written to print only one time and then take input. Where do I need to change?
When I took out the above input "Enter the number of student" do-while loop, it works just fine.
#include<stdio.h>
#include <stdlib.h>
#define BOOLEAN int
#define TRUE 1
#define FALSE 0
void main()
{
    int T,N;
    int markIndex,markCtrl,num,markLimit,space,Ntotal = 0,f;
    BOOLEAN markCheck = TRUE;
    char line[300];
    int marks[100];
    char* pointLine;
    do
    {
        printf("Enter the number of students\n");
        scanf("%d",&N);
        Ntotal +=  N;
        if (Ntotal > 5000)
        {
            printf("Sorry you exceeded the Limit\n");
            Ntotal = 0;
        }
    } while(!( N >= 4 && N <= 100 && N%4 == 0 ));

    do
    {
        printf("Enter their marks\n");
        fgets(line,sizeof(line),stdin);
        pointLine = line;

        while( sscanf(pointLine,"%d%n",&num,&space) > 0)
        {
            marks[markIndex++] = num;
            pointLine += space;
        }

        for (markCtrl = 0 ; markCtrl < markIndex; markCtrl++)
        {
            if(marks[markCtrl] < 0 || marks[markCtrl] >100)
            {
                markCheck = FALSE;
                break;
            }
            else
            {
                markCheck = TRUE;
            }
        }
        markLimit = markIndex;
        markIndex = 0;
    } while(!( markCheck == TRUE && markLimit == N));

    for ( f = 0 ; f < markLimit  ; f++)
    {
        printf("%d\n",marks[f]);
    }
}

A: It is because \n is left out in the input stream because of your first scanf.
Clear the stream after first do...while as below.
int c;
while ((c = getchar()) != '\n' && c != EOF) { }


text:
Q: Using the GDAL library, what would lng_var be and how to complete a polygon? Just need some help understanding some code.
What I am trying to do here is create a Shapefile and not sure if I am doing that correctly or not using the library gdal. It should be a shapefile that contains a grid of square polygons. Where each polygon cell is going to be 10 degrees by
10 degrees and the grid should cover the entire world. With the shapefile I am also trying to include a variable that contains a decimal
column called 'LAND' that will be populated with 0.0 for all rows/cells. Not sure I am doing this correctly, I had some filler code and now I am trying to figure out the parts that are needed to make this work. In the end it should look like this (18x36 grid):

form osgeo import gdal
from osgeo import ogr
from osgeo import osr
import os
import random

# Specify that you want to work with a Shapefile
DriverName = "ESRI Shapefile"
# Not sure what this line does
driver = ogr.GetDriverByName(DriverName)

# Name of shapefile to create
FileName = 'gride.shp'

# simple check to see if that file already exists in the system, if so delete it
if os.path.exists(FileName):
  driver.DeleteDataSource(FileName)

# Now create an Empty shapefile Data source
shapeData = driver.CreateDataSource(FileName)

fieldName = 'LAND'

lng_min = -180
lng_max = 180
step = 10

lat_min = -90
lat_max = 90

# lng_var = ??
# lat_var = ??

for lng_var in range(lng_min, lng_max, step):
    ring = org.Geometry(ogr.wkbLinearRing)
    ring.AddPoint(lng_var, lat_var)
    ring.AddPoint(lng_var + step, lat_var)
    ring.AddPoint(lng_var + step, lat_var + step)
    ring.AddPoint()
    ring.AddPoint()
    poly = org.Geometry(ogr.wkbPolygon)
    poly.AddGeometry(ring)

    for lat_var in range(lat_min, lat_max, step):
        ring = org.Geometry(ogr.wkbLinearRing)
        ring.AddPoint(lng_var, lat_var)
        ring.AddPoint(lng_var + step, lat_var)
        ring.AddPoint(lng_var + step, lat_var + step)
        ring.AddPoint()
        ring.AddPoint()
        poly = org.Geometry(ogr.wkbPolygon)
        poly.AddGeometry(ring)

I haven't found a way to integrate my fieldName = 'LAND' yet. Where that should contain the decimal column called 'LAND', populated with 0.0 for all rows/cells.
I want to after this is done be able to open it on QGIS.
Not sure how to complete the polygon that is where there is two AddPoint()'s and also not sure what lng_var will be, or the lat_var when I add the inner loop.


text:
Q: Copy files to different location based on file headers I am trying to achieve the same result, but getting some strange behavior I am unable to solve by myself.
It only filters out the first if, then treats the rest as else. Does not matter how many different if...else I put in there, then it still only filters out the first if, then treats others as else.
I have also tried moving the headers around, so the once normally being treated as else, would be the first if, but is still only runs the first if.
[string] $FileDirectory = "C:\temp\Move by header\input";
[string] $OutputPathHeat = "C:\temp\Move by header\HeatMeter";
[string] $OutputPathWater = "C:\temp\Move by header\WaterMeter";
[string] $OutputPathOther = "C:\temp\Move by header\Other";

foreach ($FilePath in Get-ChildItem $FileDirectory | Select-Object -
ExpandProperty
FullName)
{
    [string] $Header = Get-Content $FilePath -First 1

    if ($Header -match '#serial-number;device-identification;created;value-
                   data-
                   count;act-duration,second(s),inst-value,0,0,0;avg-
                   duration,second(s),inst-value,0,0,0;energy,Wh,inst-
                   value,0,0,0;volume,m3,inst-value,0,0,0.*') {
        Move-Item $FilePath $OutputPathHeat
    } elseif ($Header -match '#serial-number;device-
     identification;created;value-data-
                       count;fabrication-no,,inst-
     value,0,0,0;datetime,,inst-
                       value,0,0,0;volume,m3,inst-value,0,0,0.*') {
        Move-Item $FilePath $OutputPathWater
    } else {
        Move-Item $FilePath $OutputPathOther
    }
}

A: Although you are perhaps not showing us enough of the possible headers, I think you are trying to use -match on just about the whole first line.
Also, in your code, you break up the strings and even the commands quite haphazardly making the code and regexes really unreliable.
It would make more sense to focus only on the differences that distinct one file from the other and match on those.
Have a look at below code:
$RootDirectory   = 'C:\temp\Move by header'
$InputDirectory  = Join-Path -Path $RootDirectory -ChildPath 'input'
$OutputPathHeat  = Join-Path -Path $RootDirectory -ChildPath 'HeatMeter'
$OutputPathWater = Join-Path -Path $RootDirectory -ChildPath 'WaterMeter'
$OutputPathOther = Join-Path -Path $RootDirectory -ChildPath 'Other'

# get an array of Full path and filenames of the files in the input directory.
# because you want files only, add the '-File' switch.
# if you're on PowerShell version below 3.0, use:
# (Get-ChildItem $InputDirectory | Where-Object { !$_.PSIsContainer })
foreach ($FilePath in (Get-ChildItem $InputDirectory -File) | Select-Object -ExpandProperty FullName) {
    $Header = Get-Content $FilePath -First 1

    # test for a string in the header line that distincts it from the other files
    if ($Header -match ';energy,Wh,') {
        # the substring ';energy,Wh,' defines this file as a 'HeatMeter' file
        Move-Item -Path $FilePath -Destination $OutputPathHeat
    }
    elseif ($Header -match ';fabrication-no,,') {
        # the substring ';fabrication-no,,' defines this file as a 'WaterMeter' file
       Move-Item -Path $FilePath -Destination $OutputPathWater
    }
    else {
        # if both key substrings above did not match, move to the 'Other' directory
        Move-Item -Path $FilePath -Destination $OutputPathOther
    }
}

Instead of using the if..elseif..else construction as above, using the switch command can make your code more readable and also it makes it easier for you to add extra tests in between.
Besides that, switch also has a -Regex parameter, so there is no need to write out if ($Header -match ... each time. You can read all about it here: about_Switch
The if..elseif..else block above could then be written as:
# test for a string in the header line that distincts it from the other files
switch -Regex ($Header) {
    # the substring ';energy,Wh,' defines this file as a 'HeatMeter' file
    ';energy,Wh,' { Move-Item -Path $FilePath -Destination $OutputPathHeat; break }

    # the substring ';fabrication-no,,' defines this file as a 'WaterMeter' file
    ';fabrication-no,,' { Move-Item -Path $FilePath -Destination $OutputPathWater; break }

    # if both key substrings above did not match, move to the 'Other' directory
    default { Move-Item -Path $FilePath -Destination $OutputPathOther }
}

Note: if the substrings you want to match against have characters that have special meaning in Regular Expressions, make sure you Escape them using syntax [Regex]::Escape(the string to match against)


text:
Q: Changing base url depending on preprocessor macro value I have a project with a few schemes, one for EA, Staged, and Production.
I want to be able to set my base url based on what build configuration I am running.
#if defined PRODUCTION
#define BASE_URL [NSURL URLWithString:@"https://example.production.com/"]

#elif defined STAGED
#define BASE_URL [NSURL URLWithString:@"http://example.staged.com/"]

#else
#define BASE_URL [NSURL URLWithString:@"https://example.ea.com/"]
#endif

Is there a way to set preprocessor macros in order to define the values of PRODUCTION and STAGED, I'm guessing it's somewhere in the build settings of my target. And would this be the best way to do it?

A: There are a few ways to achieve the functionality, though only one to my knowledge that works with schemes.
The first option, is outside the scope of schemes, and works with the targets preprocessor macros - for development, DEBUG is set to 1, and release, DEBUG is set to 0.  You can add as many macros as you would like - to do so, go to your targets "Build Settings", and search for "Preprocessor Macros" - it's pretty much right there.
To work with schemes, you would need to add an environment variable to your scheme:
Edit Scheme -> Add an environment variable.
To access the environment variable you would need to do:
[[[NSProcessInfo processInfo] environment] objectForKey:@"myKey"]

A: In the "Other C Flags" build setting, put -DPRODUCTION and -DSTAGED, in the different build configurations. (You will need to create those extra build configurations, of course.)

A: I usually store my URLs in a NSObject class (Aptly named URLHub) with class methods like so;
+(NSString *)Login
{
    NSString *url;

    if (developmentMode) {
        url = @"https://dev.mycoolwebservice/api/login";
    } else {
        url = @"https://mycoolwebservice/api/login";
    }

    return url;
}

Then wherever I need to use that url I can grab easily;
#import "URLHub.h"

NSString *url = [URLHub Login];

This approach makes it super simple to update urls throught the entire app since they are all stored in the same place.
In this example to switch over to development urls I just need to flip one BOOL and every url app-wide changes. ;)


text:
Q: Unable to read uninstall keys for x64 registry, vbscript I was trying to read the Uninstall Keys (DisplayName, Display Version, Vendor ..) from both 32 and 64 Bit installation keys. I have below code but it is always giving only 32 bit keys info. As I wrote the below code it is giving the entries from 32  bit twice :(
' Constants (taken from WinReg.h)
'
Const HKEY_CLASSES_ROOT   = &H80000000
Const HKEY_CURRENT_USER   = &H80000001
Const HKEY_LOCAL_MACHINE  = &H80000002
Const HKEY_USERS          = &H80000003

Const REG_SZ        = 1
Const REG_EXPAND_SZ = 2
Const REG_BINARY    = 3
Const REG_DWORD     = 4
Const REG_MULTI_SZ  = 7

' Chose computer name, registry tree and key path
'

Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Add

ObjExcel.Cells (1,1) = "Application Name"
ObjExcel.Cells (1,4) = "Application Vendor"
ObjExcel.Cells (1,2) = "Application Version"
ObjExcel.Cells (1,3) = "DRM Build"

strComputer = InputBox("Enter the Machine name. To run on the current machine, press ENTER", "Machine Name", "")
If strComputer = "" Then
    strComputer = "."
End If

Msgbox "Script is Running and may take couple of minutes to complete. Click on OK to continue",0, "Information"

hDefKey = HKEY_LOCAL_MACHINE

' Connect to registry provider on target machine with current user

Set oReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")

'{impersonationLevel=impersonate}!
' Enum the subkeys of the key path we've chosen

strKeyPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"

row = 2

getRegistryEntries hDefKey, strKeyPath, ObjExcel, oReg, row

strKeyPath = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"

getRegistryEntries hDefKey, strKeyPath, ObjExcel, oReg, row

fileName = Year(now) & month(now) & day(now) & hour(now) & minute(now) & second(now)

ObjExcel.ActiveWorkbook.SaveAs "C:\" & fileName & ".xlsx"
ObjExcel.Quit
Set ObjExcel = Nothing

msgbox "Work Done, file saved in C Drive with the name: " & fileName

Function getRegistryEntries(hDefKey, strKeyPath, byRef objExcel, byRef oReg, byRef row)

    oReg.EnumKey hDefKey, strKeyPath, arrSubKeys

    Set objShell = CreateObject("WScript.Shell")

    For Each strSubkey In arrSubKeys

        ' Show the subkey
        '

        furtherKeys = False
        strDisName = "HKEY_LOCAL_MACHINE\" & strKeyPath & "\" & strSubkey & "\DisplayName"

        On Error Resume Next

        present = False
        disName =  objShell.RegRead(strDisName)
        If disName <> "" Then
            present = True
        End If

        disVersionPresent = false
        disVer = ""
        If present = true Then
            strDisVer = "HKEY_LOCAL_MACHINE\" & strKeyPath & "\" & strSubkey & "\DisplayVersion"
            strDisVendor = "HKEY_LOCAL_MACHINE\" & strKeyPath & "\" & strSubkey & "\Publisher"
            strDRMBuild = "HKEY_LOCAL_MACHINE\" & strKeyPath & "\" & strSubkey & "\DRMBUILD"

            disVer = objShell.RegRead(strDisVer)
            If  err.number = 0 Then
                disVersionPresent = True
            End If
            If disVersionPresent Then
                ObjExcel.Cells (row,1) = disName
                ObjExcel.Cells (row,2) = "'" & disVer
                furtherKeys = True
                disVendor = objShell.RegRead(strDisVendor)
                If  err.number = 0 Then
                    ObjExcel.Cells (row,4) =  disVendor
                End If
                DRMBuild = objShell.RegRead(strDRMBuild)
                If  err.number = 0 Then
                    ObjExcel.Cells (row,3) =  "'" & DRMBuild
                End If
            End If
        End If
        If furtherKeys Then
            row = row + 1
        End If
    Next

End Function


text:
Q: VC++ 'Generating Code', what does it mean? WHen compiling in visual studio the compiler outputs this at what seems to be its own discretion:
1>Generating Code...
what is it doing here exactly?

A: The compiler is given multiple input files at once and it reads (parses) several of those in one go, and only then produces output (object files) for them, before it reads more input files. I suppose this is an optimization, presumably because mixed read/write access to the disk is slower than when it is sorted into (first) read access and (then) write access.

A: It is doing what it says: it is generating the machine code. Many compilers translate C/C++ sources into some intermediate internal representation that is later used as the source to generate the actual machine code. Visual C++ compiler (as many other compilers) does this in batches: first it translates a bunch of source files into that intermediate representation and then converts them all to machine code (and then starts working on the next batch). This is what happens when you see the "Generating code" messages.
I don't know what logic exactly it is using to split the source files into batches. Maybe it works simply by size: once the total size of all intermediate representations generated so far gets to some limit, it switches to "generating code" mode. Maybe there's some other logic at work there as well.
In any case note that the unqualified term "code" in this case does not refer to source code, meaning that it has nothing to do with templates and/or preprocessor or anything like that. Moreover, referring to C sources with unqualified "code" (as opposed to the qualified "source code") is a very niche thing, more at home with marketing department than with actual programmers. At the programmers' level nobody refers to C sources as just "code" :)

A: Visual Studio is invoking the linker LINK.exe it works primarily with object files as input, to produce an executable as output, but also is capable of much other work concerning these and related files. Linker Command-Line Syntax @ MSDN

A: Template instances (and other type of code) might generate code (or not in some conditions).


text:
Q: Let $\lim_{x\to \infty }x^n f(x)=0$ for any $n \in \mathbb{N}$. Then find the asymptote of $g$.
Let $\lim_{x\to \infty }x^n f(x)=0$ for any $n \in \mathbb{N}$. Then find the symptote
  $$g(x)=\dfrac{x^2+f(x)}{x+1+2f(x)}.$$

My try :
$$\lim_{x \to \infty }\dfrac{x^2+f(x)}{x+1+2f(x)}=\lim_{x \to \infty }\dfrac{x^{n+2}+x^nf(x)}{x^{n+1}+2x^nf(x)}=\infty?$$
Please help me.

A: Hint. The asymptote is oblique. Note that
$$\lim_{x\to +\infty }\frac{g(x)}{x}=\lim_{x\to +\infty }\frac{x^2+f(x)}{x^2+x+2xf(x)}=1,$$
because $\lim_{x\to +\infty}f(x)=\lim_{x\to +\infty}xf(x)=0$.
So it remains to find
$$\lim_{x\to +\infty }(g(x)-x))=\lim_{x\to +\infty }\frac{x^2+f(x)-x(x+1+2f(x))}{x+1+2f(x)}\\=\lim_{x\to +\infty }\frac{f(x)-x-2xf(x)}{x+1+2f(x)}=?$$

A: multiply numerator by $x^n$ and denominator by $x^{n+1}$ and pass to limit you get
$$\lim_{x\to \infty}\frac{g(x)}x=1$$
Now
$$g(x)-x=\frac{f(x)-x-2xf(x)}{x+1+2f(x)}$$
so multiplying both numerator and denominator by $x^n$ and passing to limit gives the limit $-1$ so the asymptotic is $y=x-1$.


text:
Q: I have killed all of the Brotherhood of Steel - what now? in FO:NV, i killed all of the Brotherhood of Steel in the Hidden Valley Bunker. I then went to Deathclaw Promontory and picked up the power armour. I try to wear it and it says i have to have Power Armour Training. I've heard that i can only get the training from the Brotherhood, what are my options?
Thanks

A: The other remaining option for you to get the Power Armor Training is to do the For Auld Lang Syne quest given to you by Arcade Gannon. He's one of the possible followers and you can find him in the Old Mormon Fort.

 To trigger the quest, you'll have to gain his trust or progress far enough or you can follow the quest line for the independent Vegas (Yes Man's quests) you can trigger it without gaining his trust.


text:
Q: ngFor trackBy function with custom parameters The trackBy function (e.g. in an ngFor) provides two arguments: index and item (from the collection being iterated over).  Is there a way to pass additional information (as parameters?) to th trackBy function?
My case is that I might be iterating over a variety of types for each instance of my component (which contains the ngFor), with different identifying field names.  Ideally, I'd like to be able to pass a third parameter indicating which field in my item should be read.

A: bind method can help you to do this trick
template.html
<div *ngFor="let item of items; trackBy: trackByFn.bind(this, 'name')">
  {{ item }}
</div>

component.ts
items = [
  {
    id: 1,
    name: 'name1'
  },
  {
    id: 2,
    name: 'name2'
  }
]
trackByFn(customParam, index, item) {
  return item[customParam];
}

A: I know this question is over a year old now, but I'd like to add another option:
You can create an Angular pipe that takes the additional parameter(s) as arguments and returns a TrackByFunction. The use of such pipe would look as follows:
<div *ngFor="let item of items; trackBy: (myParameter | myTrackByFn)">

The code for the pipe looks as follows:
@Pipe({ name: 'myTrackByFn' })
export class MyTrackByFnPipe implements PipeTransform {

  transform<T>(myParameter: any): TrackByFunction<T> {
    return (index: number: item: T) => {
      // ...
    };
  }
}

One of the benefits that comes with this approach is that you can reuse the pipe across components, eliminating the need to reimplement a trackBy function in every component.
You can read more about this approach in Ben Nadel's post.


text:
Q: How to install perf on Ubuntu 18.04? I have tried to install perf using sudo apt-get install linux-tools-$(uname -r) linux-tools-generic
It gives an error saying:
Reading package lists... Done
Building dependency tree
Reading state information...
Done E: Unable to locate package linux-tools-4.18.0-21-generic
E: Couldn't find any package by glob 'linux-tools-4.18.0-21-generic'
E: Couldn't find any package by regex 'linux-tools-4.18.0-21-generic' –

(EDIT)
I did run sudo apt-get update and sudo apt-get upgrade before running the above command, but I still get the same error message as above.
I ran cat /etc/apt/sources.list and got the following message:
deb http://archive.ubuntu.com/ubuntu bionic main universe restricted multiverse

deb-src http://archive.ubuntu.com/ubuntu bionic main universe restricted multiverse #Added by software-properties

uname -a yields: Linux ubuntu 4.18.0-21-generic #22~18.04.1-Ubuntu  SMP Thu May 16 15:07:19 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
output of apt list 'linux-tools-*'
output of apt list --installed 'linux-*'

A: The correct command to install linux-tools for actually used kernel (from official repository) is:
sudo apt install linux-tools-`uname -r`

A: The output of cat /etc/apt/sources.list was quite short, containing only two non-blank lines. It revealed that /etc/apt/sources.list has the bionic repository but is missing the bionic-updates and bionic-security repositories, which are typically present and enabled.
Adding them should fix the problem. The package you're trying to install, linux-tools-4.18.0-21-generic, is provided in bionic-updates.
Since all official updates to stable releases are released through the -security and -updates repositories, you may find a number of updates available for installation. It's a good idea to install those, unless you have a specific and important reason not to do so.
You can enable those repositories with the add-apt-repository command or with either of the methods summarized below. Or you may want to follow one of the procedures given at How do I restore the default repositories?
Graphically
If your system has a graphical desktop installed, you can run the Software & Updates tool and enable them from there. To do that:

*

*Open Software & Updates.

*Click the Updates tab.

*Under "Install updates from:" make sure these boxes are checked:

*

*Important security updates (bionic-security)

*Recommended updates (bionic-updates)

For this purpose, it doesn't matter much whether or not the "Unsupported updates" box is checked. Most users will generally prefer not to enable that repository.
You may need to enter a password to change those settings. That's normal.

*Click Close.

*You will be told, "The information about available software is out-of-date." Click Reload.

*You should now be able to install the linux-tools-4.18.0-21-generic package. Go ahead and attempt to do so.
Manually, by editing /etc/apt/sources.list
If you have no GUI or prefer to manually edit /etc/apt/sources.list, you can do so. Normally I would recommend backing up the file you have, but what you have doesn't contain very much. Still, if you want to you can do so by running sudo cp /etc/apt/sources.list{,.bak}. You can then edit the file. It's owned by root; I suggest editing it with sudoedit. You can run:
sudoedit /etc/apt/sources.list

If you have a specific editor you prefer sudoedit to use, you can specify that. For example, to use nano even if that's not the default, you could run this instead:
VISUAL=nano sudoedit /etc/apt/sources.list

After editing, the contents of your /etc/apt/sources.list file should look like:
deb http://archive.ubuntu.com/ubuntu bionic main universe restricted multiverse
deb-src http://archive.ubuntu.com/ubuntu bionic main universe restricted multiverse
deb http://archive.ubuntu.com/ubuntu bionic-updates main universe restricted multiverse
deb-src http://archive.ubuntu.com/ubuntu bionic-updates main universe restricted multiverse
deb http://security.ubuntu.com/ubuntu/ bionic-security main universe restricted multiverse
deb-src http://security.ubuntu.com/ubuntu/ bionic-security main universe restricted multiverse

The lines that start with deb-src provide source code packages. Including them may make sudo apt update take slightly longer each time it is run, but does not incur any other significant overhead. Still, if you don't want to able to download source code automatically through the package manager, you can comment them out (by placing a # at the beginning of each line you wish to deactivate) or even omit them. You can (re)enable them later.
You may want to use a mirror instead of the master site, to get faster downloads. For example, the main US mirror would be used if you wrote us.archive.ubuntu.com instead of archive.ubuntu.com. Your current deb and deb-src lines don't use one, so I didn't either in what I wrote above. I mainly mention this to point out that if you do decide to use one, you should still keep the URLs in the http://security.ubuntu.com/ubuntu/ lines unchanged.


text:
Q: Reading a file and creating a user in Chef I have a list of IP address along with me. In front of those IP I have a username. What I am trying to do is make Chef read the file having IP and username and once it encounter the IP, it should create a user of that name.
But when I do I get a user but the name of the user comes out to be a number.
Here is my recipe
File.open("/tmp/users.txt", "r") do |file|
    file.readlines.each_with_index do |ip,user|
      if ip = node[:ipaddress]
            user ip[user] do
                action :create
                supports :manage_home => true
                comment 'Test User'
                home '/home/ip[user]'
                shell '/bin/bash'
                password 'password'
            end
      end
   end

my users.txt file
231.27.59.232, test1
272.27.59.15, tes2
985.54.25.22, test3

Now when I run the recipe this is what I get
Recipe: repo_update::users
   * cookbook_file[/tmp/users.txt] action create (up to date)
   * user[1] action create
     - create user 1
   * user[7] action create
     - create user 7
   * user[2] action create
     - create user 2

Please tell me what is wrong here.

A: Lots of problem here... The answer of Tejay is the way to go, I'll just try to explain why your code don't work and how to fix it so it could be of some use later :)
File.open("/tmp/users.txt", "r") do |file|
  file.readlines.each_with_index do |ip,user|
    puts "values are #{ip} and #{user}"
  end
end

Gives:
values are 231.27.59.232, test1
 and 0
values are 272.27.59.15, tes2
 and 1
values are 985.54.25.22, test3
 and 2

each_with_index won't split magically your line into two part, it will just assign the last parameter the actual index in the iteration.
A fixed version of your code would be:
File.open("/tmp/users.txt", "r") do |file|
  file.readlines.each do |line| # just iterate and get line
    ip,myuser=line.gsub("\n",'').split(',') # set ip and myuser variable with values comma separated, using myuser to avoid conflict with the resource name. Using gsub to remove traling carriage return in user name
    if ip == node[:ipaddress] # test equality, a single = will assign ip a value and always be true.
      user myuser do # create the user using the variable, no need to interpolate here
        action :create
        supports :manage_home => true
        comment 'Test User'
        home "/home/#{myuser}" # use interpolation here inside double quotes (won't work in single quotes)
        shell '/bin/bash'
        password 'password'
      end
    end
  end
end

A: The problem is this line:
user ip[user] do

You are calling the [] method on the ip string.  Furthermore, you're going to get a name collision between the resource user and the block variable. Finally, you are giving each user the home of '/home/ip[user]'.  You need to put the string in "'s and wrap the variable in #{ and } Try this:
File.open("/tmp/users.txt", "r") do |file|
  file.readlines.each do |line|
    entries = line.split(',')
    ip = entries[0].strip
    username = entries[1].strip
    if ip = node[:ipaddress]
      user username do
        action :create
        supports :manage_home => true
        comment 'Test User'
        home "/home/#{username}"
        shell '/bin/bash'
        password 'password'
      end
    end
 end

Also, reading this all from a file is a very non cheffy thing to do. Either use a databag or a hash stored in an environment variable, which also saves you from needing to loop at all:
userhash = node['my_users'][node['ipadddress']]
user userhash['username']
  action :create
  supports :manage_home => true
  comment 'test user'
  home userhash['home'] || "/home/#{userhash['username']"
  shell userhash['shell'] || '/bin/bash'
  password userhash['password'] || 'password'
end


text:
Q: Concatenate 2 comma separated values in two columns pandas My dataframe looks like this:
Col1    Col2       Col3     Col4
1,2,3   10,11,12    ABC     A1B1
4       13          DEF     TEST
5,6     14,15       XYZ     C1D1

My output should be like this: (where first comma separated value goes with first comma separated value in another column creating rows and giving the counts as a column)
Col1    Col2    Col3    Col4    Count
1       10      ABC     A1B1    1
2       11      ABC     A1B1    2
3       12      ABC     A1B1    3
4       13      DEF     TEST    1
5       14      XYZ     C1D1    1
6       15      XYZ     C1D1    2

I have tried using the  explode function but it creates the rows of columns making multiple different combinations.
Edited:
The code I've tried:
df.Col1 = df.Col1.str.split(',')
df = df.explode('Col1').reset_index(drop=True)

But it created the multiple combinations of Col1 with the rest of columns.
Looking forward for the assistance.

A: You can try:
#spliting 'Col1' and 'Col2' column values
df['Col1']=df['Col1'].str.split(',')
df['Col2']=df['Col2'].str.split(',')
df=df.agg(pd.Series.explode)
#OR
#df=df.apply(pd.Series.explode)
#Finally create a count column:
df['Count']=df.groupby(['Col3','Col4']).cumcount()+1
#If needed reset the index:
df=df.reset_index(drop=True)

output of df:
    Col1    Col2    Col3    Col4    Count
0   1       10      ABC     A1B1    1
0   2       11      ABC     A1B1    2
0   3       12      ABC     A1B1    3
1   4       13      DEF     TEST    1
2   5       14      XYZ     C1D1    1
2   6       15      XYZ     C1D1    2


text:
Q: Intuition on why $\mathbb{E}[\mathbb{D}^2[X|Y]] \neq \mathbb{D}^2[X]$, compared to $\mathbb{E}[\mathbb{E}[X|Y]] = \mathbb{E}[X]$? Here's what I have intuition-wise so far. When we have two r.vs. $X$ and $Y$ defined on sample space $\Omega$, conditioning on $Y=y$ means that we are 'zooming-in' in the sample space (as in, the set $\{Y=y\} \subseteq \Omega$ is now the sample space we are working with).
The formula $f_{X|Y}(x|y) = \frac{f(x,y)}{f_Y(y)}$ makes complete sense to me, we need to scale the density of $X$ since our sample space become smaller. An analogy is that 2 apples out of 5 fruits should feel lighter than 2 apples out of 3 fruits.
Now, the definition of $\mathbb{E}[X|Y] = \int_{Y=y}x \cdot f_{X|Y}(x|y) dx$ makes sense, we are again finding the weighted average of $X$ restricted (and scaled) to the set $\{Y=y\} \subseteq \Omega$. Similarly, the definition of $\mathbb{D}^2[X|Y] = \mathbb{E}[(X-\mathbb{E}[X|Y])^2]$ makes total sense, we are once again measuring the 'spread' of $X$ (by measuring distance of $X$ from it's expectation), restricted (and scaled) to the set $\{Y=y\} \subseteq \Omega$.
Now, we have the Tower Formula: $\mathbb{E}[\mathbb{E}[X|Y]] = \mathbb{E}[X]$. I do not really have much to say about the tower formula, Right now I'm simply thinking that $\mathbb{E}[X|Y]$ is a function of $Y$, and the weighted average of $\mathbb{E}[X|Y]$ somehow should get back $\mathbb{E}[X]$.
However it is not clear to me why shouldn't $\mathbb{E}[\mathbb{D}^2[X|Y]] = \mathbb{D}^2[X]$ (rather, $\mathbb{E}[\mathbb{D}^2[X|Y]] = \mathbb{D}^2[X] - \mathbb{D}^2[\mathbb{E}[X|Y]]$).

A: Think about the joint distribution of $(X, Y)$ being that you first sample $Y = y$ from the measure $P(Y \in \cdot)$, and then sample $X$ from  the measure $P(X \in \cdot \mid Y = y)$. Then for any nonnegative measurable function $f$,
\begin{align}
E(f(X, Y)) &= \int P(Y \in dy) \int P(X \in dx \mid Y = y) f(x, y) \\
&= \int P(Y \in dy) E(f(X, y) \mid Y = y) \\
&= E(E(f(X, Y) \mid Y)).
\end{align}
So if you can write the joint as above, then the tower property falls out. This amounts to asking whether there is a regular conditional distribution for $X$ given $Y$. This is true if $X, Y$ take values in Polish spaces. To get an even more general tower property, you can use the "modern" definition of conditional expectation described in chapter 4 of https://services.math.duke.edu/~rtd/PTE/pte.html


text:
Q: Login Servlet Requires Two Tries (preface: total java nube)
I have an new web application with an /index.jsp which is going through a Login servlet and then forwarded onto a /WEB-INF/index.jsp if everything checks out during the Login servlet.
Servlet:
import java.io.*;
import com.<co>.<app>.User;
import java.sql.SQLException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletException;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "Login", urlPatterns = { "/Login" })
public class Login extends HttpServlet {

    public Login() { super(); }
    private static String userid = null;
    private static String passwd = null;
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        userid = request.getParameter("userid");
        passwd = request.getParameter("passwd");
        if (passwd.length()==0){ passwd = null; }
        else { passwd.trim(); }

        if (userid != null && passwd != null && passwd.length() != 0)
        {
            System.out.print("Going to see if "+userid+" can authenticate"+"\n");
            int added = 0;
            boolean existinguser = User.ExistingUser(userid);
            boolean authenticated = false;
            try {
                authenticated = User.AuthenticateUser(userid, passwd);
            } catch (NamingException e) {
                response.sendRedirect("/<app>/?error");
            }
            System.out.print("Is "+userid+" an existing user? "+existinguser+"\n");
            System.out.print(userid+" authenticated equals "+authenticated+"\n");
            if (existinguser == true)
            {
                System.out.print("passed the existing IF \n");
                if (authenticated == true)
                {
                    System.out.print("passed the authenticated IF \n");
                    String user = User.GetUserID(userid);
                    String role = User.GetUserRole(userid);
                    Cookie userCookie = new Cookie("user",user);
                    Cookie roleCookie = new Cookie("role", role);
                    userCookie.setMaxAge(30*60);
                    roleCookie.setMaxAge(30*60);
                    response.addCookie(userCookie);
                    response.addCookie(roleCookie);
                    System.out.print("just added the cookies \n");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/index.jsp");
                    System.out.print("setup the forward \n");
                    dispatcher.forward(request, response);
                    System.out.print("WHY THE !@#$ AM I LOGGING THIS??? \n");
                }
                else
                {
                    response.sendRedirect("/<app>/?error");
                }
            }
            else
            {
                try {
                    added = User.AddToApplication(userid);
                } catch (SQLException e) {
                    response.sendRedirect("/<app>/?contactsupport");
                }
                if (added == 1)
                {
                    response.sendRedirect("/<app>/?error");
                }
                else
                {
                    response.sendRedirect("/<app>/?error");
                }
            }
        }
        else
        {
            response.sendRedirect("/<app>/?error");
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Here is the full console log:
Going to see if <user> can authenticate
Is <user> an existing user? true
<user> authenticated equals true
passed the existing IF
passed the authenticated IF
just added the cookies
setup the forward.. goodbye!
WHY THE HELL AM I LOGGING THIS???

For some reason, the first time the user tries to log in it logs all of this information but doesn't end up forwarding to the dashboard home page. The second time the user tries to log in, it again logs all of this to the console output, including the WHY THE HELL AM I LOGGING THIS??? line but does redirect to the dashboard home page.
What gives? Please help? More code can be posted if necessary.
EDIT:

I figured out what is causing it to force me to try twice.. in the header of each dashboard JSP page is the following:
<c:choose>
    <c:when test="${cookie.role.value==null}">
        <c:redirect url="${baseURL}/?what" />
    </c:when>
    <c:otherwise></c:otherwise>
</c:choose>

However, I have moved everything within the dashboard to be pre-processed by a controller which is verifying that the user is still a user and they are still logged in. After setting up the Login servlet to forward to the dashboard's home controller.. Everything worked as planned.


text:
Q: Jquery filtering list I`m having difficult to solve this problem.

list item 1

list item 1

list item 2

list item 2

list item 1

list item 2

What I`m trying to solve is that I have 2 checkbox complete and pending now if I uncheck complete all the list with complete class will hide "BUT" if it has a sublist and that sublist has pending class that parent list will remain visible else it will hide.
I hope somebody can help me. thank you in advance.

A: You can use this jquery code :
$('.complete').each(function() {
    if ($(this).find('.pending').length) {
        $(this).css({display: 'block'})
    } else {
        $(this).css({display: 'none'})
    }
})


text:
Q: Operation not permitted while executing brew install libimobildevice in mac Im trying to install libimobiledevice with brew install libimobiledevice in my mac but I give operation not permitted error and permission denied. Im admin.
cp: utimes: /usr/local/Cellar/openssl@1.1/.: Operation not permitted

A: Did you tried installing it with --HEAD
brew install --HEAD libimobiledevice -g


text:
Q: How to de-select a previous row in a Grid-view? I have gridview with template field of dropdownlist in each row.when i select any value from dropdownlist it will change color of 3rd row below than it.But when i click on another dropdownlist it is changing the color of 3rd row below than it but color of previous row is still stick to it.I want one row colored at a time.How to do it .?
I am doing following.
  protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
    {

            DropDownList ddl = (DropDownList)sender;
            GridViewRow row = (GridViewRow)ddl.NamingContainer;
            int g = row.RowIndex + 3;
            GridView1.Rows[g].BackColor = Color.Yellow;

}

Thanks in advance.

A: Use Code like below...
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
    {
       foreach (GridViewRow gvRow in GridView1.Rows)
        {
            int g1 = gvRow.RowIndex;
            GridView1.Rows[g1].BackColor = Color.White;
        }

        DropDownList ddl = (DropDownList)sender;
        GridViewRow row = (GridViewRow)ddl.NamingContainer;
        int g = row.RowIndex + 3;
        GridView1.Rows[g].BackColor = Color.Yellow;

}

A: You can use ClearSelection() method of DataGridView in order to de-select the rows.


text:
Q: reactjs make content appear next to sidebar When I call my SideBar component in App.js it appears on top of everything with the main page under it and I understand why it does this but I don't know how to get it so that the sidebar appears to the left of the screen with the main app component it right next to it.
Here is my code:
const AppRoute=({component:Component, layout:Layout,...rest}) => {
  <Route {...rest} render = {props=> (
    <Layout>
      <Component {...props}/>
    </Layout>
  )}/>
)

const MainLayout = props =>(

   <SideBar/>
   {props.children}

class App extends Component {

  render() {

    return(
      <BrowswerRouter>

          <Switch>
            <AppRoute path = "/dashboard" layout={MainLayout} component={Dashboard}/>
          </Switch>

      </BrowserRouter>

    )
  }
}

Any help is greatly appreciated!

A: const MainLayout = props =>(

   <SideBar style={{flex: '1 auto'}} />
   {props.children}

try this maybe
you could also apply float: left on both the sidebar, and the main content elements, giving the sidebar a fixed width
or you could try css grid:
const MainLayout = props =>(

   <SideBar />
   {props.children}


text:
Q: Amazon MWS Order Cancel process I am trying to cancel the order on the amazon, initially was having some of the format issues, now all the format issues are removed but feed result is keep showing one or more item is invalid. i am using the correct xml format to cancel the order and also the correct amazon order id and amazon order item id, both id are valid but the result keep showing the invalid item.
Order Acknowledgement Feed Format:
<?xml version="1.0"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
  <Header>
    <DocumentVersion>1.01</DocumentVersion>
    <MerchantIdentifier>M_xxxxx_108291953</MerchantIdentifier>
  </Header>
  <MessageType>OrderAcknowledgement</MessageType>
  <Message>
    <MessageID>1</MessageID>
    <OrderAcknowledgement>
      <AmazonOrderID>111-1111111-7313343</AmazonOrderID>
      <StatusCode>Failure</StatusCode>
      <Item>
        <AmazonOrderItemCode>232327843324</AmazonOrderItemCode>
        <CancelReason>BuyerCanceled</CancelReason>
      </Item>
    </OrderAcknowledgement>
  </Message>
</AmazonEnvelope>

Response On feed submission result: as i try to get the feed result it shows this error 'We are unable to process the XML feed because one or more items are invalid. Please re-submit the feed.', below is the feed submission result.
<?xml version="1.0" encoding="UTF-8"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
    <Header>
        <DocumentVersion>1.02</DocumentVersion>
        <MerchantIdentifier>M_xxxxx_108291953</MerchantIdentifier>
    </Header>
    <MessageType>ProcessingReport</MessageType>
    <Message>
        <MessageID>1</MessageID>
        <ProcessingReport>
            <DocumentTransactionID>7801114004</DocumentTransactionID>
            <StatusCode>Complete</StatusCode>
            <ProcessingSummary>
                <MessagesProcessed>1</MessagesProcessed>
                <MessagesSuccessful>0</MessagesSuccessful>
                <MessagesWithError>1</MessagesWithError>
                <MessagesWithWarning>0</MessagesWithWarning>
            </ProcessingSummary>
            <Result>
                <MessageID>1</MessageID>
                <ResultCode>Error</ResultCode>
                <ResultMessageCode>25</ResultMessageCode>
                <ResultDescription>We are unable to process the XML feed because one or more items are invalid. Please re-submit the feed.</ResultDescription>
            </Result>
        </ProcessingReport>
    </Message>
</AmazonEnvelope>

Can any one one help me on this to make it work.

A: i am able to cancel the entire order in amazon.
xml i am using
<?xml version="1.0"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
    <Header>
            <DocumentVersion>1.01</DocumentVersion>
            <MerchantIdentifier>'.$storeDetails["merchantIdentifier"].'</MerchantIdentifier>
    </Header>
    <MessageType>OrderAcknowledgement</MessageType>
    <Message>
            <MessageID>1</MessageID>
            <OrderAcknowledgement>
                <AmazonOrderID>'.$amazonOrderId.'</AmazonOrderID>
                <StatusCode>Failure</StatusCode>
                <Item>
                                <AmazonOrderItemCode>'.$item['store_product_code'].'</AmazonOrderItemCode>
                                <CancelReason>'.$reason.'</CancelReason>
                            </Item>
            </OrderAcknowledgement>
    </Message>
</AmazonEnvelope

====
Let me know if it helps.


text:
Q: PyQt: keyPressEvent and keyReleaseEvent - holding press without debounce I want implement a QDialog, in which a key is pressed for some time (seconds) and is released afterwards.
I tried doing this with keyPressEvent and keyReleaseEvent functions.
The problem I get is that when a key is pressed the debounce (keyReleaseEvent) occurs very quickly, which is not desired in my case.
Here, is what I do:
def keyPressEvent(self, eventQKeyEvent):
    key = eventQKeyEvent.key()
    if key == 54:
    print('pressed')  # 6

def keyReleaseEvent(self, eventQKeyEvent):
    key = eventQKeyEvent.key()
    if key == 54:
    print('released')  # 6

Output:
'pressed'
'released'
'pressed'
'released'
'pressed'
'released'
...
'pressed'
'released'

I would like to get either:
'pressed'
'released'

or:
'pressed'
'pressed'
'pressed'
...
'pressed'
'pressed'
'released'

A: You need to use isAutoRepeat:
def keyReleaseEvent(self, eventQKeyEvent):
    key = eventQKeyEvent.key()
    if key == 54 and not eventQKeyEvent.isAutoRepeat():
        print('released')


text:
Q: Load from shared memory the one and same 32 bytes (ulong4) by the each warp thread If each warp accesses the shared memory at the same address, how would that load the 32 bytes of data (ulong4)? Will it be 'broadcasted'? Would the access time be the same as if each thread loaded the 2 bytes 'unsigned short int'?
Now, in case I need to load from shared memory 32/64 same bytes in each warp, how could I do this?

A: On devices before compute capability 3.0 shared memory accesses are always 32 bit / 4 bytes wide and will be broadcast if all threads of a warp access the same address. Wider accesses will compile to multiple instructions.
On compute capability 3.0 shared memory accesses can be configured to be either 32 bit wide or 64 bit wide using cudaDeviceSetSharedMemConfig(). The chosen setting will apply to the entire kernel though.

[As I had originally missed the little word "shared" in the question, I gave a completely off-topic answer for global memory instead. Since that one should still be correct, I'll leave it in here:]
It depends:

*

*Compute capability 1.0 and 1.1 don't broadcast and use 64 separate 32 byte memory transactions (two times 16 bytes, extended to the minimum 32 byte transactions size for each thread of the warp)

*Compute capability 1.2 and 1.3 broadcast, so two 32 byte transactions (two times 16 bytes, extended to minimum 32 byte transaction size) suffice for all threads of the warp

*Compute capability 2.0 and higher just read a 128 byte cache line and satisfy all requests from there.

The compute capability 1.x devices will waste 50% of the transferred data, as a single thread can load at most 16 bytes, but the minimum transaction size is or 32 bytes. Additionally, 32 byte transactions are a lot slower that 128 byte transactions.
The time will be the same as if just 8 bytes were read by each thread because of the minimum transaction size, and because data paths are sufficiently wide to transfer either 8 or 16 bytes to each thread per transaction.
Reading 2× or 4× the data will take 2× or 4× as long on compute capability 1.x, but only minimally longer on 2.0 and higher if the data falls into the same cache line so no further memory transactions are necessary.
So on compute capability 2.0 and higher you don't need to worry. On 1.x read the data through the constant cache or a texture if it is constant, or reorder it in shared memory otherwise (assuming your kernel is memory bandwidth bound).


text:
Q: how to center bigger div under smaller div I have a login page that is absolutely centered in the middle of the page both horizontally and vertically.
Inside there are 2 divs, smaller pink one and bigger blue one.
How can I center the bigger one?

.container {
    background: rgba(249, 249, 249, 1);
    bottom: 0;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 1), 0 0px 4px 0 rgba(0, 0, 0, 1);
    height: 342px;
    height: max-content;
    left: 0;
    margin: auto;
    padding: 60px 30px 60px 30px;
    position: absolute;
    right: 0;
    top: 0;
    width: 300px;
    overflow: visible;

}
.smaller {
    background: pink;
}
button {
    background: linear-gradient(rgba(239, 83, 80, 1), rgba(179, 47, 47, 1));
    border: 0;
    color: rgba(255, 255, 255, 1);
    margin: 10px;
    padding: 8px 70px 8px 20px;
    box-sizing: content-box;
    width: 50px;
}
.bigger {
    width: 400px;
    text-align: center;
    background: blue
}

Sign In

    <input>

    <button>Back</button><button>Login</button>

A:

.container {
    background: rgba(249, 249, 249, 1);
    bottom: 0;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 1), 0 0px 4px 0 rgba(0, 0, 0, 1);
    height: 342px;
    height: max-content;
    left: 0;
    margin: auto;
    padding: 60px 30px 60px 30px;
    position: absolute;
    right: 0;
    top: 0;
    width: 300px;
    overflow: visible;

}
.smaller {
    background: pink;
}
button {
    background: linear-gradient(rgba(239, 83, 80, 1), rgba(179, 47, 47, 1));
    border: 0;
    color: rgba(255, 255, 255, 1);
    margin: 10px;
    padding: 8px 70px 8px 20px;
    box-sizing: content-box;
    width: 50px;
}
.bigger {

    width: 400px;
    text-align: center;
    background: blue;
    margin: auto;
    left: 50%;
    transform: translateX(-50%);
    position: absolute;

}

Sign In

    <input>

    <button>Back</button><button>Login</button>

A: Just set width to 100%

.container {
    background: rgba(249, 249, 249, 1);
    bottom: 0;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 1), 0 0px 4px 0 rgba(0, 0, 0, 1);
    height: 342px;
    height: max-content;
    left: 0;
    margin: auto;
    padding: 60px 30px 60px 30px;
    position: absolute;
    right: 0;
    top: 0;
    width: 300px;
    overflow: visible;

}
.smaller {
    background: pink;
}
button {
    background: linear-gradient(rgba(239, 83, 80, 1), rgba(179, 47, 47, 1));
    border: 0;
    color: rgba(255, 255, 255, 1);
    margin: 10px;
    padding: 8px 70px 8px 20px;
    box-sizing: content-box;
    width: 50px;
}
.bigger {
    width: 100%;
    text-align: center;
    background: blue
}

Sign In

    <input>

    <button>Back</button><button>Login</button>

A: I think this will help you

.container {
    background: rgba(249, 249, 249, 1);
    bottom: 0;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 1), 0 0px 4px 0 rgba(0, 0, 0, 1);
    height: 342px;
    height: max-content;
    left: 0;
    margin: auto;
    padding: 60px 30px 60px 30px;
    position: absolute;
    right: 0;
    top: 0;
    width: 450px;
    overflow: visible;

}
.smaller {
    background: pink;
    width: 300px;
    margin:auto;
}
button {
    background: linear-gradient(rgba(239, 83, 80, 1), rgba(179, 47, 47, 1));
    border: 0;
    color: rgba(255, 255, 255, 1);
    margin: 10px;
    padding: 8px 70px 8px 20px;
    box-sizing: content-box;
    width: 50px;
}
.bigger {
    width: 400px;
    text-align: center;
    background: blue;
    margin:auto;
}

Sign In

    <input>

    <button>Back</button><button>Login</button>

A: You may want to consider using flexbox which also is responsive by nature.

.container {
    background: rgba(249, 249, 249, 1);
    bottom: 0;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 1), 0 0px 4px 0 rgba(0, 0, 0, 1);
    height: 342px;
    height: max-content;
    left: 0;
    margin: auto;
    padding: 60px 30px 60px 30px;
    position: absolute;
    right: 0;
    top: 0;
    width: 300px;
    overflow: visible;

}
.smaller {
    background: pink;
}
button {
    background: linear-gradient(rgba(239, 83, 80, 1), rgba(179, 47, 47, 1));
    border: 0;
    color: rgba(255, 255, 255, 1);
    margin: 10px;
    padding: 8px 70px 8px 20px;
    box-sizing: content-box;
    width: 50px;
}
.bigger {
    display: flex;
    background: blue;
    justify-content: space-around;
}

Sign In

    <input>

    <button>Back</button><button>Login</button>


text:
Q: Filter a View that uses a subquery I am trying to create a view VW_Checks. I am using STUFF to merge the records in the columns 'Platforme' and 'Systemname' to avoid a long list of redundant data.
the view:
CREATE VIEW [dbo].[VW_Checks] WITH SCHEMABINDING AS
SELECT  DISTINCT C.CheckID AS CheckID, C.CheckTitle as CheckTitle,
STUFF((SELECT ', ' + PLATFORMNAME
        FROM dbo.CHECK_PLATFORM CPP
        WHERE CPP.CHECKID = C.CHECKID
        for xml path('')),1,1,'') AS Platformname,
STUFF((SELECT ', ' + SYSTEMNAME
        FROM dbo.CHECK_SYSTEM CSS
        WHERE CSS.CHECKID = C.CHECKID
        for xml path('')),1,1,'') AS Systemname
FROM dbo.[CHECK] C INNER JOIN
            dbo.CHECK_CATEGORY CC ON C.CHECKID = CC.CHECKID
            INNER JOIN dbo.CATEGORY CAT ON CC.CATEGORYID = CAT.CATEGORYID
            INNER JOIN dbo.CHECK_SYSTEME CS ON CS.CHECKID = C.CHECKID
            INNER JOIN dbo.CHECK_PLATFORM CP ON CP.CHECKID = C.CHECKID

The view is fine as it is (meaning it shows exactly what I want it to show), but when I try to filter my view, it does not work.
example of my problem:
SELECT *
FROM VW_Checks VW_C
WHERE CONTAINS(VW_P.Platformname,'iOS')

the WHERE clause in the SELECT-statement above does not work at all, as if it's not even there.
Since the VW_P.Platformname is a combined column (using a subquery), I can't create a unique index on my view.
the error message when I try to create a unique index:
    Error: 10127, Severity: 16, Cannot create unique index I_VW_Checks on view VW_Checks because it contains one or more subqueries. Consider changing the view to use only joins instead of subqueries. Alternatively, consider not indexing this view.
How can I alter my view/add indexes to it so I can filter properly, without losing my combined records?

A: CONTAINS() is a statement used with full text indexes.  I suppose you could materialize the view and go through a lot of trouble to create one.  Instead, you could use like:
WHERE ', ' + (VW_P.Platformname + ', ' like '%, ' + 'iOS' + ', %'

I do agree with Gareth that there might be other more efficient ways to do what you want.  However, given this view, LIKE makes more sense than CONTAINS().

A: You can't, but I can't see why you would want to. You are concatenating columns into a single value, then searching this single value for some text. Why not just search the columns before you concatenate them? And add an index to the underlying column if necessary, e.g.
SELECT  c.*
FROM    vw_Checks AS c
WHERE   EXISTS
        (   SELECT  1
            FROM    CHECK_PLATFORM AS cpp
            WHERE   cpp.Platformname LIKE '%iOS%'
            AND     cpp.CheckID = c.CheckID
        );

Or if you have a full text index:
SELECT  c.*
FROM    vw_Checks AS c
WHERE   EXISTS
        (   SELECT  1
            FROM    CHECK_PLATFORM AS cpp
            WHERE   CONTAINS(cpp.Platformname, 'iOS')
            AND     cpp.CheckID = c.CheckID
        );


text:
Q: Rotating a two-dimensional array by 90 degrees in MPI What I need to do is to rotate 2-d array by 90 degrees (3x3 on 3 processors, 4x4 on 4 etc. ) using derived datatypes in MPI. I found that using Alltoall function in C on array:
[ 1][ 2][ 3][ 4]
[ 5][ 6][ 7][ 8]
[ 9][10][11][12]
[13][14][15][16]

I'll get data distributed like this:
1:[ 1][ 5][ 9][13]
2:[ 2][ 6][10][14]
3:[ 3][ 7][11][15]
4:[ 4][ 8][12][16]

What should I do next (what steps should I take) to collect this vectors as an array on one processor (root) in proper order (order that reflects 90 degrees rotation)?
Thanks in advance.

A: So I finally figured out how it should be done by using Alltoallv and Gather functions.
Alltoallv let me to distribute data among processes in reverse order:
0:[ 4][ 8][12][16]
1:[ 3][ 7][11][15]
2:[ 2][ 6][10][14]
3:[ 1][ 5][ 9][13]

then I used Gather to collect the data on rank 0 process into a buffer:
...
//size is a number of processors
MPI_Type_vector(size, 1,1, MPI_INT, &vec );
MPI_Type_commit( &vec );

if(rank==0){
int buffer[size*size];
//recv is a name of an array with data on every processor
MPI_Gather(recv,1,vec, buffer, size, MPI_INT, 0, MPI_COMM_WORLD );
}else{
MPI_Gather(recv,1,vec,NULL,0,MPI_INT,0,MPI_COMM_WORLD);
}
...

as a result I received:
[ 4][ 8][12][16]
[ 3][ 7][11][15]
[ 2][ 6][10][14]
[ 1][ 5][ 9][13]

A: The operation you are looking for is called Transpose
I will give you the pseudo code to transpose a square matrix of length N by N
int matrix[N][N];

for (n=0; n<N-1; ++n)
    for (m=n+1; m<N; ++m)
        swap matrix[n][m] with matrix[m][n]

This is pretty efficient as it does the operation in-place. However as I stated this is for a square matrix. You can probably use this to figure out how to do it for a rectangular matrix.


text:
Q: create new column with incremental values I have below result set which got populated with the following code. I require to add new Column GROUP_ID in this result.
import pandas as pd
import numpy as np

df = pd.read_csv ('dups_check_group_v1.csv',encoding= 'unicode_escape',usecols= ['ID','ENTITY_NAME','ENTITY_VALUE','SECTION_GROUP','DOC_ID'])

mask = df['SECTION_GROUP'].isna()
rest = df[mask]

out = pd.concat([d for _, g in df[~mask].groupby('SECTION_GROUP')
                 for d in [g, rest]])
print(out.sort_values('DOC_ID'))

Result
    ID ENTITY_NAME   ENTITY_VALUE SECTION_GROUP  DOC_ID
0   1     dNumber  U220059090(C)       GROUP 1      40
1   2       tDate       6-Dec-22       GROUP 1      40
4   5    sCompany             bp           NaN      40
2   3     dNumber  U220059090(C)       GROUP 2      40
3   4       tDate       6-Dec-22       GROUP 2      40
4   5    sCompany             bp           NaN      40
5   6     dNumber  U220059090(C)       GROUP 1      42
6   7       tDate       6-Dec-22       GROUP 1      42
9  10    sCompany             bp           NaN      42
7   8     dNumber  U220059090(C)       GROUP 2      42
8   9       tDate       6-Dec-22       GROUP 2      42
9  10    sCompany             bp           NaN      42

what I am looking to achieve with GROUP_ID is as below. any help is really appreciate.

A: Update your existing concat statement to assign group ids dynamically
grps = df[~mask].groupby('SECTION_GROUP')
out = pd.concat([d.assign(GROUP_ID=i) for i, (_, g) in enumerate(grps, 1) for d in [g, rest]])


text:
Q: Models.Student' does not contain a definition for 'Score' I have TWO tables. My primary table is called Student, secondary table is Marks. Dapper is new for me.
This is my code:
s_id is the primary key in the Student table and is foreign key in Marks table (student (parent) – marks(child)).
Controller: join
public ActionResult Index()
{
    string sql ="SELECT TOP 10 * FROM Student AS A INNER JOIN Mark AS B ON A.S_ID = B.S_ID";

    using (SqlConnection connection = new SqlConnection(connectionstring))
    {
        var studentDictionary = new Dictionary<int,Student>();
        var list = connection.Query<Student,Marks,Student>
             (
                 sql,(student, marks) =>
                  {
                      Student Entry;

                      if (!studentDictionary.TryGetValue(student.S_ID,out Entry))
                      {
                          Entry = student;
                          Entry.Marks = new List<Marks>();
                          studentDictionary.Add(Entry.S_ID, Entry);
                      }

                      Entry.Marks.Add(marks);

                      return Entry;
                  },
                splitOn:"S_ID")
               .Distinct()
               .ToList();
                ViewBag.list = list;
    }

    return View();
}

Result.cs
join model
public class Result
{
    public string S_Name { get; set; } //student.cs
    public string S_LName { get; set; } //students.cs
    public int Score { get; set; }       //marks.cs
    public string Status { get; set; }   //marks.cs
}

How to access both student and marks tables columns using result.cs class? It's accessing only student columns why marks table columns not accessing view side?
How can I resolve this issue?
View:
@model IEnumerable<Dapper2Join.Models.Result>
@{
    @foreach (var per in ViewBag.list)
    {

            @per.S_Name
            @per.S_LName
            @per.Score
            @per.Status

    }

A: By default, Dapper mappings work on conventions. You want your Result class as output from query with only selected columns. There are two mistakes you are doing.

*

*You are unnecessarily returning all the columns from both two tables. Instead, you can simply ask for columns you need. Change your SQL query something like below:
string sql ="SELECT TOP 10 Student.S_Name, ... Marks.Score, .... FROM Student INNER JOIN Mark ON Student.S_ID = Mark.S_ID";

Note that I do not know the column names in your table. You may need to use column aliases if those does not match with your property names. Refer the links at the bottom for more information.

*You are mapping Student and Marks classes with result returned by Query. Instead, you can directly map the class you want; i.e. Result. Change your call to Query something like below:
var list = connection.Query<Result>(sql, .....);

Apart from default behavior, Dapper also provides more flexibility and features in mapping. For more details about mapping with Dapper, refer these two answers.


text:
Q: puppetlabs-mysq (v3.0.0): temporary user we have a puppet setup that basically works like this:

*

*Create user "puppetdeploy"

*Grant access to all tables for user "puppetdeploy"

*Runs scripts that creates and updates databases from .sql files, using 'puppetdeploy'

*Revoke all access to user 'puppetdeploy'

.pp file looks something like this:
mysql_user { 'puppetdeploy@localhost':
   ensure => 'present',
   password_hash => '*****',
}->
mysql_grant { 'grant_all_for_puppetdeploy':
   ensure     => 'present',
   options    => ['GRANT'],
   privileges => ['ALL'],
   table      => '*.*',
   user       => 'puppetdeploy@localhost',
}
#... execute scripts to import bunch of .sql files using mysql user 'puppetdeploy'
mysql_grant { 'revoke_all_for_puppetdeploy':
   options    => ['REVOKE'],
   privileges => ['ALL'],
   table      => '*.*',
   user       => 'puppetdeploy@localhost',
}

In later versions of the mysql-module this no longer works, as name for each grant need to be in format '[user]/[table]', and I'm not allowed to have same name for two or more mysql_grants.
Are there any ways to work around this restriction in puppetlabs-mysql 3.0.0, or are there better ways to deal with temporary mysql users?

A: The issue is that such workflows are an ill fit with Puppet's paradigm. A Puppet manifest is not a script. It's a description of state that you want Puppet to enforce. Of course, transitions often require serialized configuration steps to get right, but everything should have one definite state that Puppet has to synchronize to, and it should stay in this state.
All workflows that require one or more resources to take several different states during the same Puppet transactions pose difficulties, and will usually be solved through some kind of hack.
In your specific scenario, it might be best to forgo the mysql_grant type in favor of a script that Puppet deploys and runs, which will do all the steps that are outlined in your manifest excerpt. It's not a very Puppet-y thing to do, but much cleaner, because you don't try and make Puppet juggle the same resource from one state to another.
Better yet, enable Puppet to use the privileges of an actual administrative account.
As a compromise, you could add a custom fact that will allow Puppet to determine that all GRANTs are in order at the start of a followup transaction, and remove the user then.
if $grants_are_deployed {
    mysql_grant { 'revoke_all_for_puppetdeploy': ... }
else {
    mysql_user { 'puppetdeploy@localhost': }
}


text:
Q: Zoom in zoom out div issue This is my DIV
<div class="apple_overlay" id="overlay">

and this is my CSS
div.apple_overlay {
    display: none;
    background: url('img/noisebg.png') #3b3d40 repeat top left;
    width: 702px;
    height: 306px;
    margin-top: 91px;
    direction:rtl;
    padding-left:0px;
    font-size: 11px;
    position: static;
    float:inherit;
    z-index: 9999;
}

When I zoom in the DIV goes to right and when I zoom out the DIV goes left.. Can some one address me how to fix this issue ?
Thanks


text:
Q: Delete all letters except the first letter of each word and keep punctuation I have a text file named "MyTextFile.txt". I want to delete all letters and put in their place dashes  except the first letter of each word, also keep the punctuation.
Suppose the text file "MyTextFile.txt" contains the following strings:
The boy went to the school, then ate his breakfast!
Wow, that's not a nice story!?
The desired result is like this:
T-- b--  w--  t- t-- s----- , t-- a-- h-- b------- !
W-- , t--- ' s n-- a n--- s---- ! ?
Here is my working, which is almost good, but not perfect!
import nltk
file_content = open("MyTextFile.txt", encoding='utf8').read()
tokens = nltk.word_tokenize(file_content)
print(tokens)

first_letter = [i[0] for i in tokens]

new_words = ' '.join(first_letter).strip()
print(new_words)
appendFile = open('results_file.txt', 'w', encoding='utf8')
appendFile.write(new_words)

My output is this:
T b w t t s , t a h b ! W , t ' s n a n s ! ?

A: This kind of manipulation is best done with regex:
import re
txt = "This is a test!"
dashed = re.sub(r"([A-Za-z])([A-Za-z]+)", lambda m: m[1] + "-"*len(m[2]), txt)
print (dashed)

Will output: T--- i- a t---!
And to apply it to files:
with open("input_file.txt", 'r') as i:
    with open("output_file.txt", 'w') as o:
        for txt in i:
            dashed = re.sub(r"([A-Za-z])([A-Za-z]+)", lambda m: m[1] + "-"*len(m[2]), txt)
            o.write(dashed + '\n')

A: Actually, @Uri answer is way better than mine. Here it is anyway :)
import nltk

file_content = "The boy went to the school, then ate his breakfast! Wow, that's not a nice story!?"
tokens = nltk.word_tokenize(file_content)
print(tokens)

new_words = []
for token in tokens:
    token = token.strip()
    if token.isalpha():
        new_word = token[0]
        new_word += "-"*(len(token)-1)
    else:
        new_word = token
    new_words.append(new_word)

new_words = ' '.join(new_words)
print(new_words)
# T-- b-- w--- t- t-- s----- , t--- a-- h-- b-------- ! W-- , t--- ' s n-- a n--- s---- ! ?

A: Note that you need to know previous character in order to do that task - zip will be helpful:
txt = "The boy went to the school, then ate his breakfast! Wow, that's not a nice story!?"
new_txt = txt[0] + ''.join('-' if curr.isalpha() and prev.isalpha() else curr for prev, curr in zip(txt,txt[1:]))
print(new_txt)

Output:
T-- b-- w--- t- t-- s-----, t--- a-- h-- b--------! W--, t---- n-- a n--- s----!?

Explanation: I take txt and txt[1:] that is txt starting at 2nd character then use zip to create single iterable with every element consisting of two characters: prev i.e. previous and curr i.e. current, if both are letters I make - otherwise current character, then I join all characters I made and add first character (txt[0]) at start as it was considered earlier, because it do not have previous.
I think regular expressions are better suited for this task, however giving above sample I want to show that using python language, you can write concise code doing it without regular expressions use.

A: Using simple python logic::
def keepPunc(x):
    temp = x[0]
    for i in range(1,len(x)):
        if x[i].isalpha():
            temp=temp+"-"
        else:
            temp=temp+x[i]
    return temp

def func(a):
    temp = a.split()
    final = [i[0]+"-"*(len(i)-1) if i.isalpha() else keepPunc(i)for i in temp]
    print(a)
    print(' '.join(final))

a = "The boy went to the school, then ate his breakfast! Wow, that's not a nice story!?"
func(a)

output::
The boy went to the school, then ate his breakfast! Wow, that's not a nice story!?
T-- b-- w--- t- t-- s-----, t--- a-- h-- b--------! W--, t---'- n-- a n--- s----!?


text:
Q: shift observation of one group into next group by id in R Suppose I have a dataframe like so:
contracts

        Dates Last.Price Last.Price.1  id        carry
1  1998-11-30      94.50        98.50  QS -0.040609137
2  1998-11-30      31.32        32.13  HO -0.025210084
3  1998-12-31      95.50        98.00  QS -0.025510204
4  1998-12-31      34.00        34.28  HO -0.008168028
5  1999-01-29     100.00       100.50  QS -0.004975124
6  1999-01-29      33.16        33.42  HO -0.007779773
7  1999-02-26     100.25       100.25  QS  0.000000000
8  1999-02-26      32.29        32.37  HO -0.002471424
9  1999-02-26      10.88        11.00  CO -0.010909091
10 1999-03-31     131.50       130.75  QS  0.005736138
11 1999-03-31      44.68        44.00  HO  0.015454545
12 1999-03-31      15.24        15.16  CO  0.005277045

I want to calculate the weights of each id in each month. I have a function that does this. I use dplyr to achieve this:
library(dplyr)
library(lubridate)

contracts <- contracts %>%
  mutate(Dates = ymd(Dates)) %>%
  group_by(Dates) %>%
  mutate(weights = weight(carry))

which gives:
contracts
        Dates Last.Price Last.Price.1  id        carry     weights
1  1998-11-30      94.50        98.50  QS -0.040609137 0.616979910
2  1998-11-30      31.32        32.13  HO -0.025210084 0.383020090
3  1998-12-31      95.50        98.00  QS -0.025510204 0.757468623
4  1998-12-31      34.00        34.28  HO -0.008168028 0.242531377
5  1999-01-29     100.00       100.50  QS -0.004975124 0.390056023
6  1999-01-29      33.16        33.42  HO -0.007779773 0.609943977
7  1999-02-26     100.25       100.25  QS  0.000000000          NA
8  1999-02-26      32.29        32.37  HO -0.002471424 0.184703218
9  1999-02-26      10.88        11.00  CO -0.010909091 0.815296782
10 1999-03-31     131.50       130.75  QS  0.057361377 0.057361377
11 1999-03-31      44.68        44.00  HO  0.015454545 0.015454545
12 1999-03-31      15.24        15.16  CO  0.005277045 0.005277045

Now I want the lag the weights, such that the weights calculated in november are applied in december. So I essentially want to shift the weights column by group, the group being the dates. So the values in November end up being the values in December and so on.
Now I also want the shift to match by id, such that if a new id is included, the group where the id first appears will have an NA in the lagged column.
The desired output is given below:
desired
        Dates Last.Price Last.Price.1  id        carry     weights          w
1  1998-11-30      94.50        98.50  QS -0.040609137 0.616979910         NA
2  1998-11-30      31.32        32.13  HO -0.025210084 0.383020090         NA
3  1998-12-31      95.50        98.00  QS -0.025510204 0.757468623 0.61697991
4  1998-12-31      34.00        34.28  HO -0.008168028 0.242531377 0.38302009
5  1999-01-29     100.00       100.50  QS -0.004975124 0.390056023 0.75746862
6  1999-01-29      33.16        33.42  HO -0.007779773 0.609943977 0.24253138
7  1999-02-26     100.25       100.25  QS  0.000000000          NA 0.39005602
8  1999-02-26      32.29        32.37  HO -0.002471424 0.184703218 0.60994398
9  1999-02-26      10.88        11.00  CO -0.010909091 0.815296782         NA
10 1999-03-31     131.50       130.75  QS  0.057361377 0.057361377         NA
11 1999-03-31      44.68        44.00  HO  0.015454545 0.015454545 0.18470322
12 1999-03-31      15.24        15.16  CO  0.005277045 0.005277045 0.81529678

Take note of February 1999. CO has an NA because it first appears in February.
Now look at March 1999, CO has the value from Februray, QS has an NA only because the February value was NA (due to division by 0).
Can this be done?
Data:

contracts  <- read.table(text = "Dates, Last.Price, Last.Price.1, id,carry
1998-11-30, 94.500, 98.500, QS, -0.0406091371
1998-11-30, 31.320, 32.130, HO, -0.0252100840
1998-12-31, 95.500, 98.000, QS, -0.0255102041
1998-12-31, 34.000, 34.280, HO, -0.0081680280
1999-01-29, 100.000, 100.500, QS, -0.0049751244
1999-01-29, 33.160, 33.420, HO, -0.0077797726
1999-02-26, 100.250, 100.250, QS,  0.0000000000
1999-02-26, 32.290, 32.370, HO, -0.0024714242
1999-02-26, 10.880, 11.000, CO, -0.0109090909
1999-03-31, 131.500, 130.750, QS,  0.0057361377
1999-03-31, 44.680, 44.000, HO,  0.0154545455
1999-03-31, 15.240, 15.160, CO,  0.0052770449", sep = ",", header = T)

desired <- read.table(text = "Dates,Last.Price,Last.Price.1,id,carry,weights,w
1998-11-30,94.5,98.5, QS,-0.0406091371,0.616979909839741,NA
1998-11-30,31.32,32.13, HO,-0.025210084,0.383020090160259,NA
1998-12-31,95.5,98, QS,-0.0255102041,0.757468623182272,0.616979909839741
1998-12-31,34,34.28, HO,-0.008168028,0.242531376817728,0.383020090160259
1999-01-29,100,100.5, QS,-0.0049751244,0.390056023188584,0.757468623182272
1999-01-29,33.16,33.42, HO,-0.0077797726,0.609943976811416,0.242531376817728
1999-02-26,100.25,100.25, QS,0,NA,0.390056023188584
1999-02-26,32.29,32.37, HO,-0.0024714242,0.184703218189261,0.609943976811416
1999-02-26,10.88,11, CO,-0.0109090909,0.815296781810739,NA
1999-03-31,131.5,130.75, QS,0.057361377,0.057361377,NA
1999-03-31,44.68,44, HO,0.0154545455,0.0154545455,0.184703218189261
1999-03-31,15.24,15.16, CO,0.0052770449,0.0052770449,0.815296782", sep = ",", header = TRUE)

weights function:
weight <- function(vec) {
  neg <- which(vec<0)
  w <- vec
  w[neg] <- vec[vec<0] / sum(vec[vec<0])
  w[-neg] <- vec[vec>=0] / sum(vec[vec>=0])
  w
}

A: contracts %>%
  group_by(Dates) %>%
  mutate(weights = weight(carry)) %>%
  arrange(Dates) %>%
  group_by(id) %>%
  mutate(w = dplyr::lag(weights)) %>%
  ungroup()
# # A tibble: 12 x 7
#    Dates      Last.Price Last.Price.1 id       carry   weights       w
#    <chr>           <dbl>        <dbl> <chr>    <dbl>     <dbl>   <dbl>
#  1 1998-11-30       94.5         98.5 " QS" -0.0406    0.617    NA
#  2 1998-11-30       31.3         32.1 " HO" -0.0252    0.383    NA
#  3 1998-12-31       95.5         98   " QS" -0.0255    0.757     0.617
#  4 1998-12-31       34           34.3 " HO" -0.00817   0.243     0.383
#  5 1999-01-29      100          100.  " QS" -0.00498   0.390     0.757
#  6 1999-01-29       33.2         33.4 " HO" -0.00778   0.610     0.243
#  7 1999-02-26      100.         100.  " QS"  0       NaN         0.390
#  8 1999-02-26       32.3         32.4 " HO" -0.00247   0.185     0.610
#  9 1999-02-26       10.9         11   " CO" -0.0109    0.815    NA
# 10 1999-03-31      132.         131.  " QS"  0.00574   0.00574 NaN
# 11 1999-03-31       44.7         44   " HO"  0.0155    0.0155    0.185
# 12 1999-03-31       15.2         15.2 " CO"  0.00528   0.00528   0.815

Notes:

*

*I used dplyr::lag instead of just lag because of the possibility of confusion with stats::lag, which behaves significantly differently than dplyr::lag. While most of the time it'll work just fine, it works until it doesn't ... and it doesn't usually warn you :-)

*This is lagging by Dates regardless of month. I'll assume that you are certain that Dates are always perfectly frequent. If you think there's the possibility in a gap (where lagging by-row is not correct), then you'll need to break out the year/month into a new field and join on itself instead of doing a lag.