问:
Mongodb. Get docs whose array field contains only words from query
Is it possible in mongodb to find documents in which all the words in the field are contained in the query and not vice versa?

pseudo query:

```<code>{title:
    {$in: ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]}
}
</code>```

docs:

```<code>{'title': ["brown", "fox"}    #true
{'title': ["lazy", "dog"]}    #true
{'title': ["lazy", "dog", "sleep"]}    #false 'sleep' not in query
{'title': ["brown", "dog"]}    #true
{'title': ["jumps", "quick"]}    #true
{'title': ["smile", "fox"]}    #false 'smile' not in query
</code>```

答:
MongoDB aggregation offers more operations than standard .find method.

Takes two or more arrays and returns an array that contains the elements that appear in every input array.
  https://docs.mongodb.com/manual/reference/operator/aggregation/setIntersection/#exp._S_setIntersection

Once we get intersection, we compare array size (I assume your arrays cannot have duplicate values)

```<code>db.collection.aggregate([
  {
    $match: {
      $expr: {
        $eq: [
          {
            $size: "$title"
          },
          {
            $size: {
              $setIntersection: [
                "$title",
                [
                  "the",
                  "quick",
                  "brown",
                  "fox",
                  "jumps",
                  "over",
                  "the",
                  "lazy",
                  "dog"
                ]
              ]
            }
          }
        ]
      }
    }
  }
])
</code>```

MongoPlayground

Body:
Is it possible in mongodb to find documents in which all the words in the field are contained in the query and not vice versa?

pseudo query:

{title:
    {$in: ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]}
}

docs:

{'title': ["brown", "fox"}    #true
{'title': ["lazy", "dog"]}    #true
{'title': ["lazy", "dog", "sleep"]}    #false 'sleep' not in query
{'title': ["brown", "dog"]}    #true
{'title': ["jumps", "quick"]}    #true
{'title': ["smile", "fox"]}    #false 'smile' not in query

Body:
MongoDB aggregation offers more operations than standard .find method.

Takes two or more arrays and returns an array that contains the elements that appear in every input array.
  https://docs.mongodb.com/manual/reference/operator/aggregation/setIntersection/#exp._S_setIntersection

Once we get intersection, we compare array size (I assume your arrays cannot have duplicate values)

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $eq: [
          {
            $size: "$title"
          },
          {
            $size: {
              $setIntersection: [
                "$title",
                [
                  "the",
                  "quick",
                  "brown",
                  "fox",
                  "jumps",
                  "over",
                  "the",
                  "lazy",
                  "dog"
                ]
              ]
            }
          }
        ]
      }
    }
  }
])

MongoPlayground


来源: stackexchange

问:
While doing binary to hex conversions in java, my answers always have a null in front of them
So my code works and outputs the correct answer however it gives me a null in the answer.

```<code>private void toHex() {
    char hexNum[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    String binary = num;

    if(binary.length() % 4 != 4) {
        while(binary.length() % 4 != 0) {
            binary = "0" + binary;
        }
    }
    for(int i = 0; i < binary.length(); i+=4) {
        String temp2 = binary.substring(i, i+4);
        int sum = 0;
        sum += Integer.parseInt(temp2.charAt(0) + "")*8;
        sum += Integer.parseInt(temp2.charAt(1) + "")*4;
        sum += Integer.parseInt(temp2.charAt(2) + "")*2;
        sum += Integer.parseInt(temp2.charAt(3) + "")*1;
        hex = hex + hexNum[sum];
        sum = 0;
        temp2 = "";
    }
}
private void outHex() {
    System.out.print("Your number from binary to hexadecimal is: 0x" + hex);
    pw.print("Your number from binary to hexadecimal is: 0x" + hex);
}
</code>```

Btw I declare num as a string outside the method and it is user inputted data. The hex is declared as a string outside the methods as well.

答:
I would bet you declared hex as.

```<code>String hex;
</code>```

Which defaults to null.

Try the following:

```<code>String hex = "";
</code>```

Which is an empty string.

ContentLicense: CC BY-SA 4.0

Body:
So my code works and outputs the correct answer however it gives me a null in the answer.

private void toHex() {
    char hexNum[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    String binary = num;

    if(binary.length() % 4 != 4) {
        while(binary.length() % 4 != 0) {
            binary = "0" + binary;
        }
    }
    for(int i = 0; i < binary.length(); i+=4) {
        String temp2 = binary.substring(i, i+4);
        int sum = 0;
        sum += Integer.parseInt(temp2.charAt(0) + "")*8;
        sum += Integer.parseInt(temp2.charAt(1) + "")*4;
        sum += Integer.parseInt(temp2.charAt(2) + "")*2;
        sum += Integer.parseInt(temp2.charAt(3) + "")*1;
        hex = hex + hexNum[sum];
        sum = 0;
        temp2 = "";
    }
}
private void outHex() {
    System.out.print("Your number from binary to hexadecimal is: 0x" + hex);
    pw.print("Your number from binary to hexadecimal is: 0x" + hex);
}

Btw I declare num as a string outside the method and it is user inputted data. The hex is declared as a string outside the methods as well.

Body:
I would bet you declared hex as.

String hex;

Which defaults to null.

Try the following:

String hex = "";

Which is an empty string.


问:
It seems schema.org/Review is not recognized by Google Search anymore or I made a mistake
I have received a message a couple of days ago that Google Search Engine has a problem identifying my ObjectType 'ItemReviewed'.

I am a collaborator on a moviesite and implement schema.org to my reviews.

```<code>    <div itemprop="review" itemscope itemtype="http://schema.org/Review">
    <span itemprop="reviewBody">

    <span itemprop="itemreviewed">Title of the movie</span>

    <IMG>itemprop="image"</IMG>

    <img border="0" src="https://example.com/wp-content/img/30star.png" alt="rating" />
    <div itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating"><meta itemprop="worstRating" content = "0"/>Rating: <span itemprop="ratingValue">3</span> / <span itemprop="bestRating">5</span></div>
    Review by <span itemprop="author">Selina</span> op <meta itemprop="datePublished" content="2020-02-13">13 februari 2020<p></div>

</code>```

Can anybody help me. It worked fine for years up until a few days ago.

NOTE: I know google has recently changed the markup for businesses so the rating is not something self-serving, but this a movieblog and the ratings are rating the movie not the website. Should I use another markup?

We are talking about genuine, independent, and unpaid editorial reviews

答:
Google recently started to report on reviews.

In your case you have marked up itemprop="review" outside the scope of an item. Which is invalid unless you did not share all the code?

You've also marked up itemreviewed. It should be itemReviewed with capital R. You should not place the review in another item and use itemReviewed at the same time. They are different ways to do the same thing.

Your itemReviewed is just some text. This is interpreted as it being a 'Thing'. Google only supports reviewing a very restricted list of types, where a basic Thing is not included:

https://developers.google.com/search/docs/data-types/review-snippet

Movie is on the list, which I suspect is what you are reviewing. So you need to mark up your Movie and either place the review inside that with the property review, or place the Movie inside your review with the property itemReveiwed.

Body:
I have received a message a couple of days ago that Google Search Engine has a problem identifying my ObjectType 'ItemReviewed'.

I am a collaborator on a moviesite and implement schema.org to my reviews.

    Title of the movie

    itemprop="image"

<meta itemprop="worstRating" content = "0"/>Rating: 3 / 5

    Review by Selina op <meta itemprop="datePublished" content="2020-02-13">13 februari 2020

Can anybody help me. It worked fine for years up until a few days ago.

NOTE: I know google has recently changed the markup for businesses so the rating is not something self-serving, but this a movieblog and the ratings are rating the movie not the website. Should I use another markup?

We are talking about genuine, independent, and unpaid editorial reviews


问:
How did scipy ver 0.18 scipy.interpolate.UnivariateSpline deal with values not strictly increasing?
I have a program written in python 2.7.5 scipy 0.18.1 that is able to run scipy.interpolate.UnivariateSpline with arrays that are non-sequential. When I try to run the same program in python 2.7.14 / scipy 1.0.0 I get the following error:

File "/usr/local/lib/python2.7/site-packages/scipy/interpolate/fitpack2.py", line 176, in init
    raise ValueError('x must be strictly increasing')

Usually I would just fix the arrays to remove the non-sequential values. But in this case I need to reproduce the exact same solution produced by the earlier version of python/scipy. Can anyone tell me how the earlier code dealt with the situation where the values were not sequential?

答: IIRC this was whatever the FITPACK (the fortran library the univariatespline class wraps) was doing. So the first stop would be to remove the check from your local scipy install and see if this does the trick</p>


问:
Watson is already running. Second session cannot be started
I have installed IBM watson studio but when i attempt to open it, I am getting an error stating " Watson is already running. Second session cannot be started"</p>

答:
This problem is a result of Watson Studio being logged on two devices at the same time.

Please take the following steps:
You will need to log out from one device to use on another.
You can perform this on myibm.ibm.com

Login in to https://myibm.ibm.com/dashboard/
Click 'Manage' on IBM Watson Studio Desktop
Click on head next to 'Manage devices'

Manage Devices is a way to help the you remotely log out of one device in order to log in from another (and has the same effect as Sign out and Exit from within the SPSS Client). You simply click here 'Deactivate' and you should be able to use software on another computer.

Please let me know about further issues.


问:
Formatting multiple arguments passed to a function in Java
Often the number of arguments passed to a function can be large. Consider the following case:

```<code>calculate(dataManager.getLastUpdate().getNumberOfChildren(),
          dataManager.getLastUpdate().getNumberOfParents(),
          dataManager.getLastUpdate().getNumberOfGrandChildren(),
          long milliseconds,
          int somethingelse)
</code>```

Is there a guideline in Java that offers a way to align the arguments? Fitting all arguments in a line would not look pretty.

答: Referring to your example, Eclipse and other IDEs format it the way you have above (1 argument per line, all left aligned) and usually that looks pretty good.</p>

ContentLicense: CC BY-SA 3.0

Body:
Often the number of arguments passed to a function can be large. Consider the following case:

calculate(dataManager.getLastUpdate().getNumberOfChildren(),
          dataManager.getLastUpdate().getNumberOfParents(),
          dataManager.getLastUpdate().getNumberOfGrandChildren(),
          long milliseconds,
          int somethingelse)

Is there a guideline in Java that offers a way to align the arguments? Fitting all arguments in a line would not look pretty.


问:
Text data in RowHeader
How to display any text data (names, cities etc) in row header? By default, it showing and fits only 1-3 number chars, but when you try to change numbers to words, row header don,t changing its size and shows only part of that words

P.s We talking about android library TableView by evrencoskun

答:
As you can see, In the Sample app, Row Header has a content wıdth value;

```<code><RelativeLayout android:id="@+id/root"
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:background="@color/cell_background_color"
            android:layout_width="@dimen/row_header_width"
            android:layout_height="@dimen/cell_height">
</code>```

So, to achieve what you want, you need to either change the constant row_header_width value or you can set the Row Header width size using the below code;

```<code>tableView.setRowHeaderWidth(int rowHeaderWidth)
</code>```

Title: Text data in RowHeader

Body:
As you can see, In the Sample app, Row Header has a content wıdth value;

<RelativeLayout android:id="@+id/root"
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:background="@color/cell_background_color"
            android:layout_width="@dimen/row_header_width"
            android:layout_height="@dimen/cell_height">

So, to achieve what you want, you need to either change the constant row_header_width value or you can set the Row Header width size using the below code;

tableView.setRowHeaderWidth(int rowHeaderWidth)


问:
How do I write to a conditional output
In my code I have defined a conditional output:

```<code>class EccGenerate[D <: Data](data: D, doubleBit : Boolean = true) extends Module {
  val eccBits = calcCodeBits(data.getWidth)

  val io = IO(new Bundle {
    val in = Input(data.cloneType)
    val out = Output(UInt(eccBits.W))
    val par = if (doubleBit) Some(Output(Bool())) else None
  })
</code>```

Trying to use the := operator on the par output fails, because it is not always an output.  When using conditional inputs, I would use io.par.get() to retrieve the current value of the input, is there a corresponding primitive, operator or function call I can use to set the value of a conditional output?

答:
You basically need to check if io.par is Some or None, there are several ways to do this:

Imperatively

if (io.par.isDefined) {
  io.par.get := ...
}
```

<ol start="2">
<li>Pattern Matching</li>
</ol>

<pre class="lang-scala prettyprint-override"><code>io.par match {
  case Some(port) => port := ...
  case None => // Do nothing
}
</code>```

Functional Programming (ish)

io.par.foreach(_ := ...)
```

I tend to prefer #2 or #3 depending on what I'm doing, but #1 may be more clear to people less familiar with Scala and Functional Programming.

For more information, check out the API Docs for Option: https://www.scala-lang.org/api/2.12.10/scala/Option.html

Title: How do I write to a conditional output

Body:
In my code I have defined a conditional output:

class EccGenerate[D <: Data](data: D, doubleBit : Boolean = true) extends Module {
  val eccBits = calcCodeBits(data.getWidth)

  val io = IO(new Bundle {
    val in = Input(data.cloneType)
    val out = Output(UInt(eccBits.W))
    val par = if (doubleBit) Some(Output(Bool())) else None
  })

Trying to use the := operator on the par output fails, because it is not always an output.  When using conditional inputs, I would use io.par.get() to retrieve the current value of the input, is there a corresponding primitive, operator or function call I can use to set the value of a conditional output?

Body:
You basically need to check if io.par is Some or None, there are several ways to do this:

Imperatively

if (io.par.isDefined) {
  io.par.get := ...
}

Pattern Matching

io.par match {
  case Some(port) => port := ...
  case None => // Do nothing
}

Functional Programming (ish)

io.par.foreach(_ := ...)

I tend to prefer #2 or #3 depending on what I'm doing, but #1 may be more clear to people less familiar with Scala and Functional Programming.

For more information, check out the API Docs for Option: https://www.scala-lang.org/api/2.12.10/scala/Option.html


问:
Why has this file I/O operation in Java caused NullPointerException
I was writing code for a small tool that removes a user-given string from a file whose name is fed to the program from the command line. But when run, it throws a NullPointerException. I can't figure out why. Please help me solve this mystery. Thank you very much. This code is as follows.</p>

```<code>/**
 * Remove certain lines from a text file.
 */

import java.util.*;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class LineCutter {
    public static void main(String[] args) {

        if (args.length < 1) {
            System.out.println("Usage: java LineCutter filename");
            System.exit(1);
        }
        System.out.println("Enter the line to be removed:");
        Scanner lineToRemove = new Scanner(System.in);
        lineToRemove.nextLine();
        FileReader fr = null;
        FileWriter fw = null;
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            fr = new FileReader(args[1]);
            br = new BufferedReader(fr);
            fw = new FileWriter(new File("output.txt"));
            bw = new BufferedWriter(fw);

            String line = br.readLine();
            while(line != null) {
                if (!line.equals(lineToRemove))
                    bw.write(line);
                line = br.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                br.close(); // NullPointerException
                fw.close();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Operations finished.");
    }
}
</code>```

答:
Probably because fr = new FileReader(args[1]); is throwing an exception (probably because it can't find the file specified in args[1]), and so br continue to be null, and so you are invoking .close() in a null object.

I would also point out that here:

```<code>if (!line.equals(lineToRemove))
                bw.write(line);
</code>```

you are invoking equals between a String and a Scanner

Body:
I was writing code for a small tool that removes a user-given string from a file whose name is fed to the program from the command line. But when run, it throws a NullPointerException. I can't figure out why. Please help me solve this mystery. Thank you very much. This code is as follows.

/**
 * Remove certain lines from a text file.
 */

import java.util.*;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class LineCutter {
    public static void main(String[] args) {

        if (args.length < 1) {
            System.out.println("Usage: java LineCutter filename");
            System.exit(1);
        }
        System.out.println("Enter the line to be removed:");
        Scanner lineToRemove = new Scanner(System.in);
        lineToRemove.nextLine();
        FileReader fr = null;
        FileWriter fw = null;
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            fr = new FileReader(args[1]);
            br = new BufferedReader(fr);
            fw = new FileWriter(new File("output.txt"));
            bw = new BufferedWriter(fw);

            String line = br.readLine();
            while(line != null) {
                if (!line.equals(lineToRemove))
                    bw.write(line);
                line = br.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                br.close(); // NullPointerException
                fw.close();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Operations finished.");
    }
}

Body:
Probably because fr = new FileReader(args[1]); is throwing an exception (probably because it can't find the file specified in args[1]), and so br continue to be null, and so you are invoking .close() in a null object.

I would also point out that here:

if (!line.equals(lineToRemove))
                bw.write(line);

you are invoking equals between a String and a Scanner


问:
Asterisk configure error due to missing uuid development package
I am installing asterisk 13.

OS: Linux 3.10.0-229.el7.x86_64

Asterisk version :  asterisk-certified-13.21

While running configure command I am having following error:

```<code>...
checking for LIBEDIT... no
checking for history_init in -ledit... no
checking for tgetent in -ltermcap... yes
checking for uuid_generate_random in -luuid... no
checking for uuid_generate_random in -le2fs-uuid... no
checking for uuid_generate_random... no
configure: error: *** uuid support not found (this typically means the uuid development package is missing)
...
</code>```

Error indicates that uuid development package is missing
but i have installed uuid.devel package
Kindly find the out put of the command as follows

```<code>command :rpm -qa | grep uuid
output:
uuid-1.6.2-26.el7.x86_64
uuid-devel-1.6.2-26.el7.i686
libuuid-2.23.2-21.el7.x86_64
uuid-1.6.2-26.el7.i686
</code>```

Hence i believe i have the required package but still i am having this error any ideas for the same.

答:
The question is already answered, but if you came here and you are trying to install Asterisk on Ubuntu, try:

```<code>sudo apt install uuid-dev
</code>```

Body:
I am installing asterisk 13.

OS: Linux 3.10.0-229.el7.x86_64

Asterisk version :  asterisk-certified-13.21

While running configure command I am having following error:

...
checking for LIBEDIT... no
checking for history_init in -ledit... no
checking for tgetent in -ltermcap... yes
checking for uuid_generate_random in -luuid... no
checking for uuid_generate_random in -le2fs-uuid... no
checking for uuid_generate_random... no
configure: error: *** uuid support not found (this typically means the uuid development package is missing)
...

Error indicates that uuid development package is missing
but i have installed uuid.devel package
Kindly find the out put of the command as follows

command :rpm -qa | grep uuid
output:
uuid-1.6.2-26.el7.x86_64
uuid-devel-1.6.2-26.el7.i686
libuuid-2.23.2-21.el7.x86_64
uuid-1.6.2-26.el7.i686

Hence i believe i have the required package but still i am having this error any ideas for the same.

Body:
The question is already answered, but if you came here and you are trying to install Asterisk on Ubuntu, try:

sudo apt install uuid-dev


问:
Unable to see DBMS_OUTPUT in Oracle SQL Developer
I am using Oracle Sql Developer (Version 18.4.0.376).
In Sql editor all DBMS_OUTPUT.PUT_LINE are not disabled automatically.

Please refer the below screen shots

Can any one suggest me, How to get ride this issue.

答:
Install the latest database like 18 or 19c

Establish the oracle connection with user credentials

Open the sql editor and execute the sample pl/sql procedure

Choose the dbms output window from views menu and set the buffer size as you required.


问:
Calculate all possible sum combinations in a given array of space delimited numbers using BASH
Is there a way to calculate all possible sum combinations in a given array of space delimited 'n' numbers using pure BASH?

example: 2 3 4....n

Output: 5 7 6 9 and so on

答:
Use an indicator to tell what elements to sum. You can implement it as an array of ones and zeros, where 1 means include in the sum. To walk around all the combinations, just start with an array of ones of the same length as the array of the numbers, implementing binary decrement is easy. Skip the computation if the indicator has only one 1, as you don't want the numbers alone included. To report each sum just once, use an associative array to hold the sums.

```<code>#!/bin/bash
sum () {
    sum=0
    for n in "$@" ; do
        ((sum += n ))
    done
    printf %d "$sum"
}

numbers=(2 3 4)
indicator=()
for _i in "${numbers[@]}" ; do
    indicator+=(1)
done

declare -A sums

while si=$(sum "${indicator[@]}") ; (( si > 0 )) ; do
    if (( si != 1 )) ; then
        sum=0
        for ((i=0; i<${#numbers[@]}; ++i)) ; do
            (( indicator[i] && (sum+=numbers[i]) ))
        done
        sums[$sum]=1
    fi

    # Binary decrement.
    i=0
    until (( indicator[i] || i > ${#indicator[@]} )) ; do
        indicator[i++]=1
    done
    indicator[i]=0
done
echo "${!sums[@]}"
</code>```

Body:
Use an indicator to tell what elements to sum. You can implement it as an array of ones and zeros, where 1 means include in the sum. To walk around all the combinations, just start with an array of ones of the same length as the array of the numbers, implementing binary decrement is easy. Skip the computation if the indicator has only one 1, as you don't want the numbers alone included. To report each sum just once, use an associative array to hold the sums.

#!/bin/bash
sum () {
    sum=0
    for n in "$@" ; do
        ((sum += n ))
    done
    printf %d "$sum"
}

numbers=(2 3 4)
indicator=()
for _i in "${numbers[@]}" ; do
    indicator+=(1)
done

declare -A sums

while si=$(sum "${indicator[@]}") ; (( si > 0 )) ; do
    if (( si != 1 )) ; then
        sum=0
        for ((i=0; i<${#numbers[@]}; ++i)) ; do
            (( indicator[i] && (sum+=numbers[i]) ))
        done
        sums[$sum]=1
    fi

    # Binary decrement.
    i=0
    until (( indicator[i] || i > ${#indicator[@]} )) ; do
        indicator[i++]=1
    done
    indicator[i]=0
done
echo "${!sums[@]}"


问:
Render 3D scene on locked system
I have written a Direct3D 9 based rendering engine in c# using SlimDX. In a new project I now need to distribute pictures of a loaded 3d scene using a webservice. The problem is that in order to render anything at all I need a Direct3d device. Is there any way to create a direct3d device without a user being logged in to the system and the desktop not being locked?

If that is not possible, does anyone know of a workaround? In the end I need either an executable which can be run from the task planner using some local user account or a service, which periodically renders pictures of the scene from certain viewpoints.

The engine is split into two parts: the engine itself and the renderer. So if there's no other way then I could also implement a new renderer using opengl or any other technology which allows for rendering without having a visible form.

Edit:

What I have so far is this:

```<code>protected override void OnContinue() {
        base.OnContinue();

        NativeFunctions.SafeWindowStationHandle hwinsta = NativeFunctions.WindowStation.OpenWindowStation(
            "WinSta0",
            true,
            NativeFunctions.AccessMask.WINSTA_ALL_ACCESS);

        if(hwinsta == null || hwinsta.IsClosed || hwinsta.IsInvalid)
            Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());

        if(NativeFunctions.WindowStation.SetProcessWindowStation(hwinsta.DangerousGetHandle())) {
            NativeFunctions.SafeDesktopHandle ptrDesktop = NativeFunctions.WindowStation.OpenInputDesktop(
                0,
                true,
                NativeFunctions.AccessMask.DESKTOP_CREATEWINDOW);

            if(ptrDesktop.IsClosed || ptrDesktop.IsInvalid)
                return;

            if(!NativeFunctions.WindowStation.SetThreadDesktop(ptrDesktop.DangerousGetHandle()))
                return;

            Log log = Logger.Instance.CreateLog("DXService", true, true, false);

            log.LogMessage("Desktop set, creating D3D-Object.", LOGMESSAGELEVEL.CRITICAL, true);

            Direct3D direct3D = new Direct3D();
            log.LogMessage("Direct3D object created,  creating device.", LOGMESSAGELEVEL.CRITICAL, true);

            if(direct3D.AdapterCount == 0) {
                log.LogMessage("FATAL: direct3D.AdapterCount == 0");
            }
        }
    }
</code>```

This is part of a minimal WindowsService. I put the important code into the OnContinue function because it's easier to debug than the startup code. I gave this services the right to interact with the active desktop. when I run the service as a local systemaccount getting the desktop and windowstation works but the number of GraphicsAdapters still is 0, when I run the service using a dedicated user account then I can't even open the WindowStation. Is there anything else I can try or which I'm doing wrong? I am testing this on a Windows 7 machine, while I am logged in since debugging becomes very difficult otherwise. Might this be a problem?

Thanks

答:
Back in the days of XP I worked on a project which successfully invoked Direct3D hardware rendering from a service on a machine with no-one logged into the console.  I completely forget the (ingenious) details, but it required some use of the "Window Station and Desktop Functions" API to somehow get hold of a usable HWND.  Newer/server OS are likely completely different anyway with all the new security stuff though.

I'd be surprised if OpenGL worked any better than Direct3D in this area, although it might be worth a try.  Other things you might consider:

NVidia seem to be very much developing their GPGPU/CUDA stuff with headless servers in mind.  It just works.  It does mean completely reimplementing your stuff on a non-graphics API though.

Microsoft's RemoteFX (Server2008R2 and Win7) seems to making it easier for VMs to gain access to server GPUs.  (Perversely, your easiest option might just be to run your renderer in a VM.)

Title: Render 3D scene on locked system

Body:
I have written a Direct3D 9 based rendering engine in c# using SlimDX. In a new project I now need to distribute pictures of a loaded 3d scene using a webservice. The problem is that in order to render anything at all I need a Direct3d device. Is there any way to create a direct3d device without a user being logged in to the system and the desktop not being locked?

If that is not possible, does anyone know of a workaround? In the end I need either an executable which can be run from the task planner using some local user account or a service, which periodically renders pictures of the scene from certain viewpoints.

The engine is split into two parts: the engine itself and the renderer. So if there's no other way then I could also implement a new renderer using opengl or any other technology which allows for rendering without having a visible form.

Edit:

What I have so far is this:

protected override void OnContinue() {
        base.OnContinue();

        NativeFunctions.SafeWindowStationHandle hwinsta = NativeFunctions.WindowStation.OpenWindowStation(
            "WinSta0",
            true,
            NativeFunctions.AccessMask.WINSTA_ALL_ACCESS);

        if(hwinsta == null || hwinsta.IsClosed || hwinsta.IsInvalid)
            Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());

        if(NativeFunctions.WindowStation.SetProcessWindowStation(hwinsta.DangerousGetHandle())) {
            NativeFunctions.SafeDesktopHandle ptrDesktop = NativeFunctions.WindowStation.OpenInputDesktop(
                0,
                true,
                NativeFunctions.AccessMask.DESKTOP_CREATEWINDOW);

            if(ptrDesktop.IsClosed || ptrDesktop.IsInvalid)
                return;

            if(!NativeFunctions.WindowStation.SetThreadDesktop(ptrDesktop.DangerousGetHandle()))
                return;

            Log log = Logger.Instance.CreateLog("DXService", true, true, false);

            log.LogMessage("Desktop set, creating D3D-Object.", LOGMESSAGELEVEL.CRITICAL, true);

            Direct3D direct3D = new Direct3D();
            log.LogMessage("Direct3D object created,  creating device.", LOGMESSAGELEVEL.CRITICAL, true);

            if(direct3D.AdapterCount == 0) {
                log.LogMessage("FATAL: direct3D.AdapterCount == 0");
            }
        }
    }

This is part of a minimal WindowsService. I put the important code into the OnContinue function because it's easier to debug than the startup code. I gave this services the right to interact with the active desktop. when I run the service as a local systemaccount getting the desktop and windowstation works but the number of GraphicsAdapters still is 0, when I run the service using a dedicated user account then I can't even open the WindowStation. Is there anything else I can try or which I'm doing wrong? I am testing this on a Windows 7 machine, while I am logged in since debugging becomes very difficult otherwise. Might this be a problem?

Thanks


问:
Ceaser Cipher Using OOP Logic
Below is my code for a class based Ceaser's cipher, this is for MIT 6.001 Ps4b.py

Question:

In the test cases at the end of the code file (test case#02), the expected output is (24, 'hello').

While the actual output of the program is (2, 'hello')

And this makes sense because lines 330-332 :

```<code>plaintext = PlaintextMessage('hello', 2)
print('Expected Output: jgnnq')
print('Actual Output:', plaintext.get_message_text_encrypted())
</code>```

creates an instance of PlaintextMessage with the shift value set to 2.
where 'jgnnq' is the encryption of 'hello'.

And lines 335-337:

```<code>ciphertext = CiphertextMessage('jgnnq')
print('Expected Output:', (24, 'hello'))
print('Actual Output:', ciphertext.decrypt_message())

</code>```

here:
string = 'jgnnq'
decrypted string = 'hello'
best factor actual is 2, but expected is 24
should print a tuple containing the factor used to (de)crypt the string  and the decrypted string (which is 'hello').

So my question is why is the expected 'best factor' for test case#02 is 24 while the factor used to (de)crypt the string is 2.

The test cases are provided by MIT OCW and were not modified on my part.

Code:

```<code>def load_words(file_name):
    '''
    file_name (string): the name of the file containing
    the list of words to load

    Returns: a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    '''
    # print("Loading word list from file...")
    # inFile: file
    inFile = open(file_name, 'r')
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.extend([word.lower() for word in line.split(' ')])
    # print("  ", len(wordlist), "words loaded.")
    return wordlist

def is_word(word_list, word):
    '''
    Determines if word is a valid word, ignoring
    capitalization and punctuation

    word_list (list): list of words in the dictionary.
    word (string): a possible word.

    Returns: True if word is in word_list, False otherwise

    Example:
    >>> is_word(word_list, 'bat') returns
    True
    >>> is_word(word_list, 'asdf') returns
    False
    '''
    word = word.lower()

    word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
    return word in word_list

def get_story_string():
    """
    Returns: a story in encrypted text.
    """
    f = open("story.txt", "r")
    story = str(f.read())
    f.close()
    return story

WORDLIST_FILENAME = 'words.txt'
words = load_words(WORDLIST_FILENAME)

class Message(object):
    def __init__(self, text):
        '''
        Initializes a Message object

        text (string): the message's text

        a Message object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''

        self.message_text = text
        self.valid_words = load_words(WORDLIST_FILENAME)
        #self.valid_words = [word for word in text.split() if is_word(words, word)]

    def get_message_text(self):
        '''
        Used to safely access self.message_text outside of the class

        Returns: self.message_text
        '''
        return self.message_text

    def get_valid_words(self):
        '''
        Used to safely access a copy of self.valid_words outside of the class.
        This helps you avoid accidentally mutating class attributes.

        Returns: a COPY of self.valid_words
        '''
        return self.valid_words.copy()

    def build_shift_dict(self, shift):
        '''
        Creates a dictionary that can be used to apply a cipher to a letter.
        The dictionary maps every uppercase and lowercase letter to a
        character shifted down the alphabet by the input shift. The dictionary
        should have 52 keys of all the uppercase letters and all the lowercase
        letters only.

        shift (integer): the amount by which to shift every letter of the
        alphabet. 0 <= shift < 26

        Returns: a dictionary mapping a letter (string) to
                 another letter (string).
        '''

        lowercase_letters = ascii_lowercase
        uppercase_letters = ascii_uppercase

        # alphabet = lowercase_letters + uppercase_letters

        # alphabet_shifted = alphabet[-shift:] + alphabet[:-shift]

        lowercase_shifted = lowercase_letters[shift:] + lowercase_letters[:shift]

        uppercase_shifted = uppercase_letters[-shift:] + uppercase_letters[:-shift]

        # shift_dict = {letter: shift for letter, shift in zip(alphabet, alphabet_shifted)}

        shift_dict_lowercase = {letter: shift for letter, shift in zip(lowercase_letters, lowercase_shifted)}

        shift_dict_uppercase = {letter: shift for letter, shift in zip(uppercase_letters, uppercase_shifted)}

        return [shift_dict_lowercase, shift_dict_uppercase]

    def apply_shift(self, shift):
        '''
        Applies the Caesar Cipher to self.message_text with the input shift.
        Creates a new string that is self.message_text shifted down the
        alphabet by some number of characters determined by the input shift

        shift (integer): the shift with which to encrypt the message.
        0 <= shift < 26

        Returns: the message text (string) in which every character is shifted
             down the alphabet by the input shift
        '''
        shift_dict_lowercase, shift_dict_uppercase = self.build_shift_dict(shift)

        plain_msg = self.message_text

        encrypted_msg = []

        for char in plain_msg:
            if char in ascii_lowercase:
                encrypted_msg.append(shift_dict_lowercase[char])
            elif char in ascii_uppercase:
                encrypted_msg.append(shift_dict_uppercase[char])
            else:
                encrypted_msg.append(char)

        # encrypted_msg = [shift_dict_lowercase.get(char, char) for char in plain_msg]

        return ''.join(encrypted_msg)

class PlaintextMessage(Message):
    def __init__(self, text, shift):
        '''
        Initializes a PlaintextMessage object

        text (string): the message's text
        shift (integer): the shift associated with this message

        A PlaintextMessage object inherits from Message and has five attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
            self.shift (integer, determined by input shift)
            self.encryption_dict (dictionary, built using shift)
            self.message_text_encrypted (string, created using shift)

        '''
        Message.__init__(self, text)
        self.shift = shift
        self.encryption_dict = self.build_shift_dict(shift)
        self.message_text_encrypted = self.apply_shift(shift)

    def get_shift(self):
        '''
        Used to safely access self.shift outside of the class

        Returns: self.shift
        '''
        return self.shift

    def get_encryption_dict(self):
        '''
        Used to safely access a copy self.encryption_dict outside of the class

        Returns: a COPY of self.encryption_dict
        '''
        return self.encryption_dict.copy()

    def get_message_text_encrypted(self):
        '''
        Used to safely access self.message_text_encrypted outside of the class

        Returns: self.message_text_encrypted
        '''
        return self.message_text_encrypted

    def change_shift(self, shift):
        '''
        Changes self.shift of the PlaintextMessage and updates other
        attributes determined by shift.

        shift (integer): the new shift that should be associated with this message.
        0 <= shift < 26

        Returns: nothing
        '''
        self.__init__(self.message_text, shift)

class CiphertextMessage(Message):
    def __init__(self, text):
        '''
        Initializes a CiphertextMessage object

        text (string): the message's text

        a CiphertextMessage object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''
        Message.__init__(self, text)

        # need to optimize this:

    def decrypt_message(self):
        '''
        Decrypt self.message_text by trying every possible shift value
        and find the "best" one. We will define "best" as the shift that
        creates the maximum number of real words when we use apply_shift(shift)
        on the message text. If s is the original shift value used to encrypt
        the message, then we would expect 26 - s to be the best shift value
        for decrypting it.

        Note: if multiple shifts are equally good such that they all create
        the maximum number of valid words, you may choose any of those shifts
        (and their corresponding decrypted messages) to return

        Returns: a tuple of the best shift value used to decrypt the message
        and the decrypted message text using that shift value
        '''
        # using a dictonary to get the max number of valid words in a string
        # have to figure out how to see if a word is valid after applying the
        # shift to it.
        results = {}
        words_found = {n: [] for n in range(26)}
        for n in range(26):
            for word in self.message_text.split():
                m = Message(word)
                word = m.apply_shift(-n)
                # print(word)
                if is_word(words, word):
                    results[n] = results.get(n, 0) + 1
                    words_found[n].append(word)
        # print(results)
        # print(words_found)
        # print(max(results))

        best_factor = max(results)

        return best_factor, PlaintextMessage(self.message_text, -best_factor).get_message_text_encrypted()

        # num_words_per_factor = {n:len(words_found[n]) for n in range(26)}
        # best_factor =
        # print(best_factor)

# plain_text_msg = PlaintextMessage('Hello, Cat, Dog, Kate', 0)

# print(plain_text_msg.get_message_text())

# encrypted_msg = plain_text_msg.apply_shift(3)

# print(encrypted_msg)

# cipher_msg = CiphertextMessage(encrypted_msg)

# decrypted_msg = cipher_msg.decrypt_message()

# print(decrypted_msg)

if __name__ == '__main__':

#    #Example test case (PlaintextMessage)
#    plaintext = PlaintextMessage('hello', 2)
#    print('Expected Output: jgnnq')
#    print('Actual Output:', plaintext.get_message_text_encrypted())
#
#    #Example test case (CiphertextMessage)
#    ciphertext = CiphertextMessage('jgnnq')
#    print('Expected Output:', (24, 'hello'))
#    print('Actual Output:', ciphertext.decrypt_message())

    #TODO: WRITE YOUR TEST CASES HERE

    #TODO: best shift value and unencrypted story

    #Example test case (PlaintextMessage)
    plaintext = PlaintextMessage('hello', 2)
    print('Expected Output: jgnnq')
    print('Actual Output:', plaintext.get_message_text_encrypted())

    #Example test case (CiphertextMessage)
    ciphertext = CiphertextMessage('jgnnq')
    print('Expected Output:', (24, 'hello'))
    print('Actual Output:', ciphertext.decrypt_message())

</code>```

答:
Thanks.
Was able to adjust the line :

```<code>lowercase_shifted = lowercase_letters[shift:] + lowercase_letters[:shift]
</code>```

to

```<code>lowercase_shifted = lowercase_letters[-shift:] + lowercase_letters[:-shift]

</code>```

And changed decrypt_message function to be:

```<code>def decrypt_message(self):
        '''
        Decrypt self.message_text by trying every possible shift value
        and find the "best" one. We will define "best" as the shift that
        creates the maximum number of real words when we use apply_shift(shift)
        on the message text. If s is the original shift value used to encrypt
        the message, then we would expect 26 - s to be the best shift value
        for decrypting it.

        Note: if multiple shifts are equally good such that they all create
        the maximum number of valid words, you may choose any of those shifts
        (and their corresponding decrypted messages) to return

        Returns: a tuple of the best shift value used to decrypt the message
        and the decrypted message text using that shift value
        '''
        # using a dictonary to get the max number of valid words in a string
        # have to figure out how to see if a word is valid after applying the
        # shift to it.

        def get_key(val, my_dict):
            for key, value in my_dict.items():
                if val == value:
                    return key

            return "key doesn't exist"

        results = {}
        # shift can range from 0 to 26
        words_found = {n: [] for n in range(27)}
        for n in range(26):
            for word in self.message_text.split():
                m = Message(word)
                word = m.apply_shift(-n)
                # print(word)
                if is_word(words, word):
                    results[n] = results.get(n, 0) + 1
                    words_found[n].append(word)

        best_factor = get_key(max(results.values()), results)

        # print(best_factor)

        return 26-best_factor, PlaintextMessage(self.message_text, -best_factor).get_message_text_encrypted()
</code>```

and now the actual output matches the expected.

Title: Ceaser Cipher Using OOP Logic

Body:
Below is my code for a class based Ceaser's cipher, this is for MIT 6.001 Ps4b.py

Question:

In the test cases at the end of the code file (test case#02), the expected output is (24, 'hello').

While the actual output of the program is (2, 'hello')

And this makes sense because lines 330-332 :

plaintext = PlaintextMessage('hello', 2)
print('Expected Output: jgnnq')
print('Actual Output:', plaintext.get_message_text_encrypted())

creates an instance of PlaintextMessage with the shift value set to 2.
where 'jgnnq' is the encryption of 'hello'.

And lines 335-337:

ciphertext = CiphertextMessage('jgnnq')
print('Expected Output:', (24, 'hello'))
print('Actual Output:', ciphertext.decrypt_message())

here:
string = 'jgnnq'
decrypted string = 'hello'
best factor actual is 2, but expected is 24
should print a tuple containing the factor used to (de)crypt the string  and the decrypted string (which is 'hello').

So my question is why is the expected 'best factor' for test case#02 is 24 while the factor used to (de)crypt the string is 2.

The test cases are provided by MIT OCW and were not modified on my part.

Code:

def load_words(file_name):
    '''
    file_name (string): the name of the file containing
    the list of words to load

    Returns: a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    '''
    # print("Loading word list from file...")
    # inFile: file
    inFile = open(file_name, 'r')
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.extend([word.lower() for word in line.split(' ')])
    # print("  ", len(wordlist), "words loaded.")
    return wordlist

def is_word(word_list, word):
    '''
    Determines if word is a valid word, ignoring
    capitalization and punctuation

    word_list (list): list of words in the dictionary.
    word (string): a possible word.

    Returns: True if word is in word_list, False otherwise

    Example:
    >>> is_word(word_list, 'bat') returns
    True
    >>> is_word(word_list, 'asdf') returns
    False
    '''
    word = word.lower()

    word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
    return word in word_list

def get_story_string():
    """
    Returns: a story in encrypted text.
    """
    f = open("story.txt", "r")
    story = str(f.read())
    f.close()
    return story

WORDLIST_FILENAME = 'words.txt'
words = load_words(WORDLIST_FILENAME)

class Message(object):
    def __init__(self, text):
        '''
        Initializes a Message object

        text (string): the message's text

        a Message object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''

        self.message_text = text
        self.valid_words = load_words(WORDLIST_FILENAME)
        #self.valid_words = [word for word in text.split() if is_word(words, word)]

    def get_message_text(self):
        '''
        Used to safely access self.message_text outside of the class

        Returns: self.message_text
        '''
        return self.message_text

    def get_valid_words(self):
        '''
        Used to safely access a copy of self.valid_words outside of the class.
        This helps you avoid accidentally mutating class attributes.

        Returns: a COPY of self.valid_words
        '''
        return self.valid_words.copy()

    def build_shift_dict(self, shift):
        '''
        Creates a dictionary that can be used to apply a cipher to a letter.
        The dictionary maps every uppercase and lowercase letter to a
        character shifted down the alphabet by the input shift. The dictionary
        should have 52 keys of all the uppercase letters and all the lowercase
        letters only.

        shift (integer): the amount by which to shift every letter of the
        alphabet. 0 <= shift < 26

        Returns: a dictionary mapping a letter (string) to
                 another letter (string).
        '''

        lowercase_letters = ascii_lowercase
        uppercase_letters = ascii_uppercase

        # alphabet = lowercase_letters + uppercase_letters

        # alphabet_shifted = alphabet[-shift:] + alphabet[:-shift]

        lowercase_shifted = lowercase_letters[shift:] + lowercase_letters[:shift]

        uppercase_shifted = uppercase_letters[-shift:] + uppercase_letters[:-shift]

        # shift_dict = {letter: shift for letter, shift in zip(alphabet, alphabet_shifted)}

        shift_dict_lowercase = {letter: shift for letter, shift in zip(lowercase_letters, lowercase_shifted)}

        shift_dict_uppercase = {letter: shift for letter, shift in zip(uppercase_letters, uppercase_shifted)}

        return [shift_dict_lowercase, shift_dict_uppercase]

    def apply_shift(self, shift):
        '''
        Applies the Caesar Cipher to self.message_text with the input shift.
        Creates a new string that is self.message_text shifted down the
        alphabet by some number of characters determined by the input shift

        shift (integer): the shift with which to encrypt the message.
        0 <= shift < 26

        Returns: the message text (string) in which every character is shifted
             down the alphabet by the input shift
        '''
        shift_dict_lowercase, shift_dict_uppercase = self.build_shift_dict(shift)

        plain_msg = self.message_text

        encrypted_msg = []

        for char in plain_msg:
            if char in ascii_lowercase:
                encrypted_msg.append(shift_dict_lowercase[char])
            elif char in ascii_uppercase:
                encrypted_msg.append(shift_dict_uppercase[char])
            else:
                encrypted_msg.append(char)

        # encrypted_msg = [shift_dict_lowercase.get(char, char) for char in plain_msg]

        return ''.join(encrypted_msg)

class PlaintextMessage(Message):
    def __init__(self, text, shift):
        '''
        Initializes a PlaintextMessage object

        text (string): the message's text
        shift (integer): the shift associated with this message

        A PlaintextMessage object inherits from Message and has five attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
            self.shift (integer, determined by input shift)
            self.encryption_dict (dictionary, built using shift)
            self.message_text_encrypted (string, created using shift)

        '''
        Message.__init__(self, text)
        self.shift = shift
        self.encryption_dict = self.build_shift_dict(shift)
        self.message_text_encrypted = self.apply_shift(shift)

    def get_shift(self):
        '''
        Used to safely access self.shift outside of the class

        Returns: self.shift
        '''
        return self.shift

    def get_encryption_dict(self):
        '''
        Used to safely access a copy self.encryption_dict outside of the class

        Returns: a COPY of self.encryption_dict
        '''
        return self.encryption_dict.copy()

    def get_message_text_encrypted(self):
        '''
        Used to safely access self.message_text_encrypted outside of the class

        Returns: self.message_text_encrypted
        '''
        return self.message_text_encrypted

    def change_shift(self, shift):
        '''
        Changes self.shift of the PlaintextMessage and updates other
        attributes determined by shift.

        shift (integer): the new shift that should be associated with this message.
        0 <= shift < 26

        Returns: nothing
        '''
        self.__init__(self.message_text, shift)

class CiphertextMessage(Message):
    def __init__(self, text):
        '''
        Initializes a CiphertextMessage object

        text (string): the message's text

        a CiphertextMessage object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''
        Message.__init__(self, text)

        # need to optimize this:

    def decrypt_message(self):
        '''
        Decrypt self.message_text by trying every possible shift value
        and find the "best" one. We will define "best" as the shift that
        creates the maximum number of real words when we use apply_shift(shift)
        on the message text. If s is the original shift value used to encrypt
        the message, then we would expect 26 - s to be the best shift value
        for decrypting it.

        Note: if multiple shifts are equally good such that they all create
        the maximum number of valid words, you may choose any of those shifts
        (and their corresponding decrypted messages) to return

        Returns: a tuple of the best shift value used to decrypt the message
        and the decrypted message text using that shift value
        '''
        # using a dictonary to get the max number of valid words in a string
        # have to figure out how to see if a word is valid after applying the
        # shift to it.
        results = {}
        words_found = {n: [] for n in range(26)}
        for n in range(26):
            for word in self.message_text.split():
                m = Message(word)
                word = m.apply_shift(-n)
                # print(word)
                if is_word(words, word):
                    results[n] = results.get(n, 0) + 1
                    words_found[n].append(word)
        # print(results)
        # print(words_found)
        # print(max(results))

        best_factor = max(results)

        return best_factor, PlaintextMessage(self.message_text, -best_factor).get_message_text_encrypted()

        # num_words_per_factor = {n:len(words_found[n]) for n in range(26)}
        # best_factor =
        # print(best_factor)

# plain_text_msg = PlaintextMessage('Hello, Cat, Dog, Kate', 0)

# print(plain_text_msg.get_message_text())

# encrypted_msg = plain_text_msg.apply_shift(3)

# print(encrypted_msg)

# cipher_msg = CiphertextMessage(encrypted_msg)

# decrypted_msg = cipher_msg.decrypt_message()

# print(decrypted_msg)

if __name__ == '__main__':

#    #Example test case (PlaintextMessage)
#    plaintext = PlaintextMessage('hello', 2)
#    print('Expected Output: jgnnq')
#    print('Actual Output:', plaintext.get_message_text_encrypted())
#
#    #Example test case (CiphertextMessage)
#    ciphertext = CiphertextMessage('jgnnq')
#    print('Expected Output:', (24, 'hello'))
#    print('Actual Output:', ciphertext.decrypt_message())

    #TODO: WRITE YOUR TEST CASES HERE

    #TODO: best shift value and unencrypted story

    #Example test case (PlaintextMessage)
    plaintext = PlaintextMessage('hello', 2)
    print('Expected Output: jgnnq')
    print('Actual Output:', plaintext.get_message_text_encrypted())

    #Example test case (CiphertextMessage)
    ciphertext = CiphertextMessage('jgnnq')
    print('Expected Output:', (24, 'hello'))
    print('Actual Output:', ciphertext.decrypt_message())

Body:
Thanks.
Was able to adjust the line :

lowercase_shifted = lowercase_letters[shift:] + lowercase_letters[:shift]

to

lowercase_shifted = lowercase_letters[-shift:] + lowercase_letters[:-shift]

And changed decrypt_message function to be:

def decrypt_message(self):
        '''
        Decrypt self.message_text by trying every possible shift value
        and find the "best" one. We will define "best" as the shift that
        creates the maximum number of real words when we use apply_shift(shift)
        on the message text. If s is the original shift value used to encrypt
        the message, then we would expect 26 - s to be the best shift value
        for decrypting it.

        Note: if multiple shifts are equally good such that they all create
        the maximum number of valid words, you may choose any of those shifts
        (and their corresponding decrypted messages) to return

        Returns: a tuple of the best shift value used to decrypt the message
        and the decrypted message text using that shift value
        '''
        # using a dictonary to get the max number of valid words in a string
        # have to figure out how to see if a word is valid after applying the
        # shift to it.

        def get_key(val, my_dict):
            for key, value in my_dict.items():
                if val == value:
                    return key

            return "key doesn't exist"

        results = {}
        # shift can range from 0 to 26
        words_found = {n: [] for n in range(27)}
        for n in range(26):
            for word in self.message_text.split():
                m = Message(word)
                word = m.apply_shift(-n)
                # print(word)
                if is_word(words, word):
                    results[n] = results.get(n, 0) + 1
                    words_found[n].append(word)

        best_factor = get_key(max(results.values()), results)

        # print(best_factor)

        return 26-best_factor, PlaintextMessage(self.message_text, -best_factor).get_message_text_encrypted()

and now the actual output matches the expected.


问:
Drools fireAllRules with multiple facts in session, how to know which fact failed
I am inserting multiple facts to the drools session and calling the fireAllRules on the session. If any one facts fails an exception is thrown and the rule is not executed for the remaining facts.

My question is:

Is there a way to continue executing remaining facts even if one fact failed?

Is there a way to know the facts which failed among the multiple facts inserted to the session?

//My scala code snippet:

```<code>val ruleSession:KieSession = kBase.newKieSession();

ruleSession.insert(fact1);
ruleSession.insert(fact2);
ruleSession.insert(fact3);

ruleSession.fireAllRules()
ruleSession.dispose()
</code>```

Let me know any helpful thoughts. Thanks

答:
As the above link in the comment(by Prog_G) says I implemented the ConsequenceExceptionHandler and handled the exception gracefully in the handleException method, I logged the failed fact and removed it from executing the further rules, sample code is given below. Hope this help someone having similar use cases.

//Drools Session creation

```<code>KieBaseConfiguration kconfig = new RuleBaseConfiguration();
kconfig.setProperty(ConsequenceExceptionHandlerOption.PROPERTY_NAME, "com.xxx.RuleExceptionHandler"); // set my exception handler name to RuleBaseConfiguration
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieBase kieBase = kContainer.newKieBase("ims-hw-rules",kconfig); // create KieBase passing the config
KieSession kSession = kieBase.newKieSession();
</code>```

//ConsequenceExceptionHandler Implementation.

```<code>public class RuleExceptionHandler implements ConsequenceExceptionHandler{
    @Override
    public void handleException(Match match, RuleRuntime workingMemory, Exception exception) {

        //if(exception instanceof MyException) {
            if(match.getObjects().size() >0) {
                for (Object object : match.getObjects()) {
                    JSONData fact = (JSONData) object;
                    //logFailedFact(fact);
                }
            }

            if(match.getFactHandles()!= null) {
                for (FactHandle factHandle : match.getFactHandles()) {
                    workingMemory.delete(factHandle); // delete the failed fact from executing remaining rules.
                }
            }
        //}
    }
}
</code>```

Body:
I am inserting multiple facts to the drools session and calling the fireAllRules on the session. If any one facts fails an exception is thrown and the rule is not executed for the remaining facts.

My question is:

Is there a way to continue executing remaining facts even if one fact failed?

Is there a way to know the facts which failed among the multiple facts inserted to the session?

//My scala code snippet:

val ruleSession:KieSession = kBase.newKieSession();

ruleSession.insert(fact1);
ruleSession.insert(fact2);
ruleSession.insert(fact3);

ruleSession.fireAllRules()
ruleSession.dispose()

Let me know any helpful thoughts. Thanks

Body:
As the above link in the comment(by Prog_G) says I implemented the ConsequenceExceptionHandler and handled the exception gracefully in the handleException method, I logged the failed fact and removed it from executing the further rules, sample code is given below. Hope this help someone having similar use cases.

//Drools Session creation

KieBaseConfiguration kconfig = new RuleBaseConfiguration();
kconfig.setProperty(ConsequenceExceptionHandlerOption.PROPERTY_NAME, "com.xxx.RuleExceptionHandler"); // set my exception handler name to RuleBaseConfiguration
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieBase kieBase = kContainer.newKieBase("ims-hw-rules",kconfig); // create KieBase passing the config
KieSession kSession = kieBase.newKieSession();

//ConsequenceExceptionHandler Implementation.

public class RuleExceptionHandler implements ConsequenceExceptionHandler{
    @Override
    public void handleException(Match match, RuleRuntime workingMemory, Exception exception) {

        //if(exception instanceof MyException) {
            if(match.getObjects().size() >0) {
                for (Object object : match.getObjects()) {
                    JSONData fact = (JSONData) object;
                    //logFailedFact(fact);
                }
            }

            if(match.getFactHandles()!= null) {
                for (FactHandle factHandle : match.getFactHandles()) {
                    workingMemory.delete(factHandle); // delete the failed fact from executing remaining rules.
                }
            }
        //}
    }
}


问:
Zoom/scale at mouse position
I am struggling to figure out and determine how to zoom on my mouse position based on this example. (https://stackblitz.com/edit/js-fxnmkm?file=index.js)

```<code>let node,
    scale = 1,
    posX = 0,
    posY = 0,
    node = document.querySelector('.frame');

const render = () => {
  window.requestAnimationFrame(() => {
    let val = `translate3D(${posX}px, ${posY}px, 0px) scale(${scale})`
    node.style.transform = val
  })
}

window.addEventListener('wheel', (e) => {
  e.preventDefault();

  // Zooming happens here
  if (e.ctrlKey) {
    scale -= e.deltaY * 0.01;
  } else {
    posX -= e.deltaX * 2;
    posY -= e.deltaY * 2;
  }

  render();
});
</code>```

My desired effect is based on this example (https://codepen.io/techslides/pen/zowLd?editors=0010) when zooming in. Currently my example above only scales to the center of the "viewport" but I want it to be where my cursor currently is.

I have searched high and low for a solution that is not implemented via canvas. Any help would be appreciated!

Caveat The reason why I am using the wheel event is to mimic the interaction of Figma (the design tool) panning and zooming.

答:
Here's my version, support pan and zoom (hold CTRL key).

let editor = document.getElementById("editor");
let editorCanvas = editor.querySelector(".canvas");
let scale = 1.0;

const minScale = 0.1;
const maxScale = 8;
const scaleStep = 0.003;

let ctrlDown = false;
let dragging = false;
let dragStartX = 0;
let dragStartY = 0;
let previousScrollLeft = 0;
let previousScrollTop = 0;

window.addEventListener("keydown", (e) => {
    if (e.ctrlKey) {
        ctrlDown = true;
        editorCanvas.style.cursor = "move";
    }
});

window.addEventListener("keyup", (e) => {
    ctrlDown = false;
    editorCanvas.style.cursor = "default";
});

editor.addEventListener("mousedown", (e) => {
    dragging = true;
    dragStartX = e.x - editor.offsetLeft;
    dragStartY = e.y - editor.offsetTop;
    previousScrollLeft = editor.scrollLeft;
    previousScrollTop = editor.scrollTop;
});

editor.addEventListener("mouseup", (e) => {
    dragging = false;
});

editor.addEventListener("mousemove", (e) => {
    if (ctrlDown && dragging) {

        requestAnimationFrame(() => {
            let currentX = e.x - editor.offsetLeft;
            let currentY = e.y - editor.offsetTop;

            let scrollX = previousScrollLeft + (dragStartX - currentX)
            let scrollY = previousScrollTop + (dragStartY - currentY);

            editor.scroll(scrollX, scrollY);
        });
    }
});

editor.addEventListener("wheel", (e) => {
    e.preventDefault();

    requestAnimationFrame(() => {
        if (e.ctrlKey) {
            scale -= e.deltaY * scaleStep;

            if (scale < minScale) {
                scale = minScale;
            }

            if (scale > maxScale) {
                scale = maxScale;
            }

            if (scale < 1) {
                editorCanvas.style.transformOrigin = "50% 50% 0";
            } else {
                editorCanvas.style.transformOrigin = "0 0 0";
            }

            editorCanvas.style.transform = `matrix(${scale}, 0, 0, ${scale}, 0, 0)`;

            let rect = editorCanvas.getBoundingClientRect();

            let ew = rect.width;
            let eh = rect.height;

            let mx = e.x - editor.offsetLeft;
            let my = e.y - editor.offsetTop;

            editor.scroll((ew - editor.offsetWidth) * (mx / editor.clientWidth), (eh - editor.offsetHeight) * (my / editor.clientHeight));
        } else {
            editor.scrollTop += e.deltaY;
            editor.scrollLeft += e.deltaX;
        }
    });
}, { passive: false });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background-color: lightgray;
}

#editor {
    position: relative;
    width: 1024px;
    height: 768px;
    box-sizing: border-box;
    border: 1px solid darkgray;
    background-color: gray;
    overflow: auto;
}

.canvas {
    position: relative;
    width: 100%;
    height: 100%;
    background-color: white;
}

.frame {
    position: absolute;
    box-sizing: border-box;
    border: 1px solid darkslategrey;
    transition: all 0.25s;
}

.frame.one {
    top: 80px;
    left: 400px;
    width: 300px;
    height: 250px;
    background-color: pink;
}

.frame.two {
    top: 350px;
    left: 150px;
    width: 200px;
    height: 150px;
    background-color: gold;
}

.frame.three {
    top: 130px;
    left: 70px;
    width: 100px;
    height: 150px;
    background-color: cyan;
}

.frame.four {
    top: 368px;
    left: 496px;
    width: 32px;
    height: 32px;
    background-color: lime;
}

.frame:hover {
    cursor: pointer;
    border: 3px solid darkslategrey;
}

.frame:active {
    filter: invert();
}</code>```

<!DOCTYPE html>

      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Zoom Editor</title>

```

Title: Zoom/scale at mouse position

Body:
I am struggling to figure out and determine how to zoom on my mouse position based on this example. (https://stackblitz.com/edit/js-fxnmkm?file=index.js)

let node,
    scale = 1,
    posX = 0,
    posY = 0,
    node = document.querySelector('.frame');

const render = () => {
  window.requestAnimationFrame(() => {
    let val = `translate3D(${posX}px, ${posY}px, 0px) scale(${scale})`
    node.style.transform = val
  })
}

window.addEventListener('wheel', (e) => {
  e.preventDefault();

  // Zooming happens here
  if (e.ctrlKey) {
    scale -= e.deltaY * 0.01;
  } else {
    posX -= e.deltaX * 2;
    posY -= e.deltaY * 2;
  }

  render();
});

My desired effect is based on this example (https://codepen.io/techslides/pen/zowLd?editors=0010) when zooming in. Currently my example above only scales to the center of the "viewport" but I want it to be where my cursor currently is.

I have searched high and low for a solution that is not implemented via canvas. Any help would be appreciated!

Caveat The reason why I am using the wheel event is to mimic the interaction of Figma (the design tool) panning and zooming.

Body:
Here's my version, support pan and zoom (hold CTRL key).

let editor = document.getElementById("editor");
let editorCanvas = editor.querySelector(".canvas");
let scale = 1.0;

const minScale = 0.1;
const maxScale = 8;
const scaleStep = 0.003;

let ctrlDown = false;
let dragging = false;
let dragStartX = 0;
let dragStartY = 0;
let previousScrollLeft = 0;
let previousScrollTop = 0;

window.addEventListener("keydown", (e) => {
    if (e.ctrlKey) {
        ctrlDown = true;
        editorCanvas.style.cursor = "move";
    }
});

window.addEventListener("keyup", (e) => {
    ctrlDown = false;
    editorCanvas.style.cursor = "default";
});

editor.addEventListener("mousedown", (e) => {
    dragging = true;
    dragStartX = e.x - editor.offsetLeft;
    dragStartY = e.y - editor.offsetTop;
    previousScrollLeft = editor.scrollLeft;
    previousScrollTop = editor.scrollTop;
});

editor.addEventListener("mouseup", (e) => {
    dragging = false;
});

editor.addEventListener("mousemove", (e) => {
    if (ctrlDown && dragging) {

        requestAnimationFrame(() => {
            let currentX = e.x - editor.offsetLeft;
            let currentY = e.y - editor.offsetTop;

            let scrollX = previousScrollLeft + (dragStartX - currentX)
            let scrollY = previousScrollTop + (dragStartY - currentY);

            editor.scroll(scrollX, scrollY);
        });
    }
});

editor.addEventListener("wheel", (e) => {
    e.preventDefault();

    requestAnimationFrame(() => {
        if (e.ctrlKey) {
            scale -= e.deltaY * scaleStep;

            if (scale < minScale) {
                scale = minScale;
            }

            if (scale > maxScale) {
                scale = maxScale;
            }

            if (scale < 1) {
                editorCanvas.style.transformOrigin = "50% 50% 0";
            } else {
                editorCanvas.style.transformOrigin = "0 0 0";
            }

            editorCanvas.style.transform = `matrix(${scale}, 0, 0, ${scale}, 0, 0)`;

            let rect = editorCanvas.getBoundingClientRect();

            let ew = rect.width;
            let eh = rect.height;

            let mx = e.x - editor.offsetLeft;
            let my = e.y - editor.offsetTop;

            editor.scroll((ew - editor.offsetWidth) * (mx / editor.clientWidth), (eh - editor.offsetHeight) * (my / editor.clientHeight));
        } else {
            editor.scrollTop += e.deltaY;
            editor.scrollLeft += e.deltaX;
        }
    });
}, { passive: false });

body {
    background-color: lightgray;
}

#editor {
    position: relative;
    width: 1024px;
    height: 768px;
    box-sizing: border-box;
    border: 1px solid darkgray;
    background-color: gray;
    overflow: auto;
}

.canvas {
    position: relative;
    width: 100%;
    height: 100%;
    background-color: white;
}

.frame {
    position: absolute;
    box-sizing: border-box;
    border: 1px solid darkslategrey;
    transition: all 0.25s;
}

.frame.one {
    top: 80px;
    left: 400px;
    width: 300px;
    height: 250px;
    background-color: pink;
}

.frame.two {
    top: 350px;
    left: 150px;
    width: 200px;
    height: 150px;
    background-color: gold;
}

.frame.three {
    top: 130px;
    left: 70px;
    width: 100px;
    height: 150px;
    background-color: cyan;
}

.frame.four {
    top: 368px;
    left: 496px;
    width: 32px;
    height: 32px;
    background-color: lime;
}

.frame:hover {
    cursor: pointer;
    border: 3px solid darkslategrey;
}

.frame:active {
    filter: invert();
}

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Zoom Editor</title>
  </head>
  <body>
      <div id="editor">
          <div class="canvas">
              <div class="frame one"></div>
              <div class="frame two"></div>
              <div class="frame three"></div>
              <div class="frame four"></div>
          </div>
      </div>
  </body>
</html>


问:
How do I group a set of entities (people) into 10 equal portions but based on their usage for EX using Oracle's Toad 11g (SQL)
Hi I have a list of 2+ mil people and their usage put in order from largest to smallest.

I tried ranking using row_number () over (partition by user column order by usage desc) as rnk

but that didnt work ..the results were crazy.

Simply put, I just want 10 equal groups of 10 with the first group consisting of the highest usage in the order of which i had first listed them.

HELP!

答:
You can use ntile():

```<code>select t.*, ntile(10) over (order by usage desc) as usage_decile
from t;
</code>```

The only caveat:  This will divide the data into exactly 10 equal sized groups.  If usage values have duplicates, then users with the same usage will be in different deciles.

If you don't want that behavior, use a more manual calculation:

```<code>select t.*,
       ceil(rank() over (order by usage desc) * 10 /
            count(*) over ()
           ) as usage_decile
from t;
</code>```

Body:
You can use ntile():

select t.*, ntile(10) over (order by usage desc) as usage_decile
from t;

The only caveat:  This will divide the data into exactly 10 equal sized groups.  If usage values have duplicates, then users with the same usage will be in different deciles.

If you don't want that behavior, use a more manual calculation:

select t.*,
       ceil(rank() over (order by usage desc) * 10 /
            count(*) over ()
           ) as usage_decile
from t;


问:
Function for adjusted Rsquare on test data?
w.r.t  R/Rstudio  I know there is RMSE and R2 function which i can leverage to calculate RMSE and Rsquare on test data.  Is there a similar function for adjusted R square on test data?</p>

答:
Assuming that you are referring to the adjusted R squared from a linear model it can be extracted from the output of summary.lm.  Using the built in BOD data.frame for purposes of example:

```<code>s <- summary(lm(demand ~ Time, BOD))
s$adj.r.squared
## [1] 0.5561503
</code>```

Try str(s) to see the various items you can get from summary.lm in much the same manner.

Body:
Assuming that you are referring to the adjusted R squared from a linear model it can be extracted from the output of summary.lm.  Using the built in BOD data.frame for purposes of example:

s <- summary(lm(demand ~ Time, BOD))
s$adj.r.squared
## [1] 0.5561503

Try str(s) to see the various items you can get from summary.lm in much the same manner.


问:
How can I find the count of semicolon separated values?
I have a list of all email ids which I have copied from the 'To' field, from an email I received in MS Outlook. These values (email ids) are separated by a semicolon. I have copied this big list of email ids into Excel. Now I want to find the number of email ids in this list; basically by counting the number of semi colons.

One way I can do this is by writing C code. i.e. store the big list as string buffer, and keep comparing the chars to ";" in a while(char == ';') loop.
But I want to do it quickly.

Is there any quick way to find that out using either:

1.) Regular expression (I use powergrep for processing the regexps)

2.) In excel itself (any excel macro/plugin for that?)

3.) DOS script method

4.) Any other quick way of getting it done?

答: If counting the number of semicolons is good enough for you, you can do it in Perl using this solution: Perl FAQ 4.24: How can I count the number of occurrences of a substring within a string</p>

OwnerDisplayName: goldenmean

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

OwnerDisplayName: Igor Oks


问:
USB Mass Storrage on File Level
The Challenge: I have an Linux hand-held device, which records data and stores it to the disc. It should exchange these data with a Windows application via USB. When this data is accessible by the user - e.g. via USB-mass-storage - it has to be encrypted. It should work out-of-the-box, with a variety of OS, also for citrix terminal sessions, etc.

The Plan: I create a file-system in user-space with FUSE, and offer it to windows via mass-storage. Whenever Windows accesses one file, I get a callback and encrypt the data on the fly. Further more, we can have some dynamic content - e.g. when some password is written into a file, more content is shown.

The Problem: When using the mass-storage gadget (e.g. g_file_storage) it only accepts files or block-devices - but no file-systems (directories). Why?

[...] it provides a simple interface to read and write sectors of data—much like the low-level interface used to access any hard drive [...]. Operating systems may treat the USB drive like a hard drive, and can format it with any file system they like. (from wikipedia)

So there is no chance to have a dynamic file-system via mass-storage... and this seems to be the reason, why my android mobile phone un-mounts all data on the phone, when I connect it to the PC.

Options:

Create a 'block-device in userspace' - similar to FUSE (need a reverse-FAT-driver, when I want to offer files dynamically)

Implement my own nbd-server to create a block-device (need a reverse-FAT-driver as well?)

I save encrypted files to a partition, and pass this partition to the mass-storage gadget (Problem would be the performance and the lack of dynamic interaction)

Do not offer a mass-storrage device and watch out for other ideas (eth over USB)

At the moment, only the last option seems to be realistic - or do you have another tip for me?

I would be grateful!

Charly

答: Looking at the options, I'd consider using the ethernet-gadget, and doing IP autoconfiguration in the device, then running Samba to export the filesystem to the Windows host. This would give you the level of control you need.</p>

Title: USB Mass Storrage on File Level


问:
Numpy Indexing problem..... Advance indexing what is X[0] doing here?
```<code>import numpy as np

X = np.array([[0, 1, 0, 1], [1, 0, 1, 1], [0, 0, 0, 1], [1, 0, 1, 0]])

y = np.array([0, 1, 0, 1])

counts = {}

print(X[y == 0])

# prints = [[0 1 0 1]
# [0 0 0 1]]
</code>```

I want to know why X[y==0] printing two data point. Shouldn't it print only [0 1 0 1] ?

because X[0]?

答:
y == 0 gives an array with same dimensions as y, with elements True where the corresponding element in y is 0, and False otherwise.

Here, y has 0 elements at indices 0 and 2. So, X[y == 0] gives you an array containing X[0] and X[2].

Body:
import numpy as np

X = np.array([[0, 1, 0, 1], [1, 0, 1, 1], [0, 0, 0, 1], [1, 0, 1, 0]])

y = np.array([0, 1, 0, 1])

counts = {}

print(X[y == 0])

# prints = [[0 1 0 1]
# [0 0 0 1]]

I want to know why X[y==0] printing two data point. Shouldn't it print only [0 1 0 1] ?

because X[0]?


问:
Best way to edit Arrays in Vue. v-model issue
Im pretty new to Vue and have been trying edit an array of strings using the v-model property. I've created a small jsfiddle and am having issue editing the array. An error pops up saying I should be using an object when using v-model but when I hit the delete button it seems so know its been edited. also adding a new input field will reset the previous ones.

what is the best way to about this editing an array and keeping it in the same format

答:
You can do it, but Vue is warning you that you shouldn't because doing so could create unwanted side effects. Less obvious in a simple case like this one.

The warning's suggestion is that you should make each array element an object and reference that object's property instead.  That way you maintain the array's integrity.

```<code>value_options: [
  { key: 1, value: 'testing bro' },
  { key: 1, value: 'yea testing' }
];
</code>```

Then reference the property instead of the array element itself.

```<code> <div v-for="(option, index) in field_data.value_options">
      <input v-model="option.value">
</code>```

Body:
You can do it, but Vue is warning you that you shouldn't because doing so could create unwanted side effects. Less obvious in a simple case like this one.

The warning's suggestion is that you should make each array element an object and reference that object's property instead.  That way you maintain the array's integrity.

value_options: [
  { key: 1, value: 'testing bro' },
  { key: 1, value: 'yea testing' }
];

Then reference the property instead of the array element itself.

 <div v-for="(option, index) in field_data.value_options">
      <input v-model="option.value">


问:
How to append to a data frame from multiple loops
I have a code, which takes in files from csv and takes a price difference, but to make it simplar I made a reproducible example as seen below. I want to append each result to the end of a specific column name. For example the first loop will go through size 1 and minute 1 so it should append to column names 1;1, for file2, file 3, file4. So the output should be :

```<code>1;1  1;2   1;3   2;1  2;2  2;3
0    0     0       same below as for 1
0    0     0
2    2     2
2    2     2
4    4     4
4    4     4
5    5     5
0    0     0
0    0     0
0    0     0
2    2     2
2    2     2
4    4     4
4    4     4
6    6     6
6    6     6
0    0     0
0    0     0
0    0     0
2    2     2
2    2     2
4    4     4
4    4     4
6    6     6
7    7     7
</code>```

I am using a loop to set prefixed data frame columns, because in my original code the number of minutes, sizes, and files is inputted by the user.

```<code>import numpy as np
import pandas as pd
file =[1,2,3,4,5,6,6,2]
file2=[1,2,3,4,5,6,7,8]
file3=[1,2,3,4,5,6,7,9]
file4=[1,2,1,2,1,2,1,2]
size=[1,2]
minutes=[1,2,3]
list1=[file,file2,file3]
data=pd.DataFrame(file)
data2=pd.DataFrame(file2)
data3=pd.DataFrame(file3)
list1=(data,data2,data3)
datas=pd.DataFrame(file4)
col_names = [str(sizer)+';'+str(number) for sizer in size for number in minutes]
datanew=pd.DataFrame(columns=col_names)

for sizes in size:
    for minute in minutes:
        for files in list1:
            pricediff=files-data
             datanew[str(sizes)+';'+str(minute)]=datanew[str(sizes)+';'+str(minute)].append(pricediff,ignore_index=True)
print(datanew)
</code>```

Edit: When trying this line: datanew=datanew.append({str(sizes)+';'+str(minute): df['pricediff']},ignore_index=True) It appends the data but the result isn't "clean"

The result from my original data, gives me this:

```<code>    111;5.0,1111;5.0
"0                                          4.5
1                                          0.5
2                                            8
3                                            8
4                                            8
                        ...
704                                        3.5
705                                        0.5
706                                       11.5
707                                        0.5
708                                        9.0
Name: pricediff, Length: 709, dtype: object",
"price    0.0
0        0.0
Name: pricediff, dtype: float64",
"0      6.5
1      6.5
2      3.5
3     13.0
Name: pricediff, Length: 4, dtype: float64",
</code>```

答:
What you are looking for is:

datanew=datanew.append({str(sizes)+';'+str(minute): pricediff}, ignore_index=True)
```
<p>This happens because you cannot change length of a single column of a dataframe without modifying length of the whole data frame.</p>
<p>Now consider the below as an example:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd

df=pd.DataFrame({"a": list("xyzpqr"), "b": [1,3,5,4,2,7], "c": list("pqrtuv")})

print(df)

#this will fail:
#df["c"]=df["c"].append("abc", ignore_index=True)
#print(df)

#what you can do instead:
df=df.append({"c": "abc"}, ignore_index=True)

print(df)

#you can even create new column that way:
df=df.append({"x": "abc"}, ignore_index=True)
</code>```

Edit

In order to append pd.Series do literally the same:

abc=pd.Series([-1,-2,-3], name="c")
df=df.append({"c": abc}, ignore_index=True)

print(df)

abc=pd.Series([-1,-2,-3], name="x")
df=df.append({"x": abc}, ignore_index=True)
```

Body:
I have a code, which takes in files from csv and takes a price difference, but to make it simplar I made a reproducible example as seen below. I want to append each result to the end of a specific column name. For example the first loop will go through size 1 and minute 1 so it should append to column names 1;1, for file2, file 3, file4. So the output should be :

1;1  1;2   1;3   2;1  2;2  2;3
0    0     0       same below as for 1
0    0     0
2    2     2
2    2     2
4    4     4
4    4     4
5    5     5
0    0     0
0    0     0
0    0     0
2    2     2
2    2     2
4    4     4
4    4     4
6    6     6
6    6     6
0    0     0
0    0     0
0    0     0
2    2     2
2    2     2
4    4     4
4    4     4
6    6     6
7    7     7

I am using a loop to set prefixed data frame columns, because in my original code the number of minutes, sizes, and files is inputted by the user.

import numpy as np
import pandas as pd
file =[1,2,3,4,5,6,6,2]
file2=[1,2,3,4,5,6,7,8]
file3=[1,2,3,4,5,6,7,9]
file4=[1,2,1,2,1,2,1,2]
size=[1,2]
minutes=[1,2,3]
list1=[file,file2,file3]
data=pd.DataFrame(file)
data2=pd.DataFrame(file2)
data3=pd.DataFrame(file3)
list1=(data,data2,data3)
datas=pd.DataFrame(file4)
col_names = [str(sizer)+';'+str(number) for sizer in size for number in minutes]
datanew=pd.DataFrame(columns=col_names)

for sizes in size:
    for minute in minutes:
        for files in list1:
            pricediff=files-data
             datanew[str(sizes)+';'+str(minute)]=datanew[str(sizes)+';'+str(minute)].append(pricediff,ignore_index=True)
print(datanew)

Edit: When trying this line: datanew=datanew.append({str(sizes)+';'+str(minute): df['pricediff']},ignore_index=True) It appends the data but the result isn't "clean"

The result from my original data, gives me this:

    111;5.0,1111;5.0
"0                                          4.5
1                                          0.5
2                                            8
3                                            8
4                                            8
                        ...
704                                        3.5
705                                        0.5
706                                       11.5
707                                        0.5
708                                        9.0
Name: pricediff, Length: 709, dtype: object",
"price    0.0
0        0.0
Name: pricediff, dtype: float64",
"0      6.5
1      6.5
2      3.5
3     13.0
Name: pricediff, Length: 4, dtype: float64",

Body:
What you are looking for is:

datanew=datanew.append({str(sizes)+';'+str(minute): pricediff}, ignore_index=True)

This happens because you cannot change length of a single column of a dataframe without modifying length of the whole data frame.

Now consider the below as an example:

import pandas as pd

df=pd.DataFrame({"a": list("xyzpqr"), "b": [1,3,5,4,2,7], "c": list("pqrtuv")})

print(df)

#this will fail:
#df["c"]=df["c"].append("abc", ignore_index=True)
#print(df)

#what you can do instead:
df=df.append({"c": "abc"}, ignore_index=True)

print(df)

#you can even create new column that way:
df=df.append({"x": "abc"}, ignore_index=True)

Edit

In order to append pd.Series do literally the same:

abc=pd.Series([-1,-2,-3], name="c")
df=df.append({"c": abc}, ignore_index=True)

print(df)

abc=pd.Series([-1,-2,-3], name="x")
df=df.append({"x": abc}, ignore_index=True)


问:
Generation of numpy arrays for permutations with constraints
To make a long story short, I'm trying to generate all the possible permutations of a set of numpy arrays. I have three numbers [j,k,m] and I would like to specify a maximum value for each one [J,K,M]. How would I then get all the combinations of arrays under these values? How could I force the k values to always be even as well? For instance:

So with the max values set to [1,2,2], the permutations would be: [0,0,0], [0,0,1], [0,0,2], [0,2,0], [0,2,1], [0,2,2], [1,0,0], [1,0,1] ...

I realise I don't have any example to code to show but I'm afraid I have literally no idea where to start with this.

From other answers it seems like sympy would be of some use?

答:
I found answer that might be interested for you here and generalised it. So you can construct list of possible values for each item like so:

```<code>X = [[0, 1], [0, 1, 2], [0, 1, 2]]
</code>```

And then use:

```<code>np.array(np.meshgrid(*X)).T.reshape(-1, len(X))
</code>```

Output contains 18 items that you wanted. Actually, if you have only maximum values [J, K, L], you can construct X using X = [range(J+1), range(K+1), range(L+1)]

Body:
I found answer that might be interested for you here and generalised it. So you can construct list of possible values for each item like so:

X = [[0, 1], [0, 1, 2], [0, 1, 2]]

And then use:

np.array(np.meshgrid(*X)).T.reshape(-1, len(X))

Output contains 18 items that you wanted. Actually, if you have only maximum values [J, K, L], you can construct X using X = [range(J+1), range(K+1), range(L+1)]


问:
Finding element in Selenium + Python with repeating classes
I'm using Selenium + Python to scrape match results on a Battlefy page for later manipulation and entering into a database. I'm trying to scrape the names of the teams and the results using Selenium because the dynamically loading JS requires me to use a headless browser. However, I'm trying to get the text of each college using the class name, but using Selenium's find_elements_by_class_name method doesn't seem to be working.

Web page: https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1

Current code:

```<code>>>> chrome_path = r"C:\Users\...\chromedriver.exe"
>>> driver = webdriver.Chrome(chrome_path)
>>> driver.get("https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1")
>>> team = driver.find_elements_by_class_name("team-name overflow-ellipsis float-right")
>>> for item in teams:
    print(item.text)
</code>```

Which does not print anything and returns an empty array. I must be doing something incorrectly. How can I scrape each team name's text when it's covered by a class name?

答:
To scrape the names of the teams using Selenium  and Python you have to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>driver.get("https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1")
print([my_elem.text for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".team-name.overflow-ellipsis.float-right")))])
</code>```

Using XPATH:

```<code>driver.get("https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1")
print([my_elem.text for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='team-name overflow-ellipsis float-right']")))])
</code>```

Console Output:

```<code>['Cougars', 'University of Illinois at Urbana-Champaign', 'Maryville Esports', 'Michigan State University', 'Purdue University', 'Illinois Wesleyan Titans', 'UMN Varsity Gold', 'UC LoL A Team', 'Arbor Esports', 'CWRU 300 Spartans', 'Bethany Esports', 'BGC at OSU', 'University of Wisconsin', 'CGC UIC', 'Indiana University - Purdue University Indianapolis - High Tempo Gaming', 'Missouri State University', 'KSU Wildcats', 'University of Manitoba Bisons', 'Nebraska', 'S&T eSports', 'Illinois State University - Redbird Esports', 'WUSTL Bears', 'University of Iowa A Team', 'TSUES', 'Division 2+', 'Grizzlies', 'Principia College esports', 'Northwestern Varsity', 'Wright State University - Raiders', 'Milwaukee School of Engineering - Raiders', 'UPIKE Esports', 'UMDads', 'Jayhawk Esports', 'NKU Esports', 'Warriors', 'Spartans', 'ND Lol', 'SDSU Team Alpha', 'Rose-Hulman', 'SIUe eSports', 'UND', 'MTU GOLD', 'Polar Bears', 'Purdue Fort Wayne Esports', 'CSU LOL', 'Aquinas Esports', 'Shawnee State Bears', 'Lewis Flyers', 'NDSU League of Legends Club', 'South Dakota Mines - Hardrockers', 'GVSU Laker Legends', 'G&E Club @ Iowa State University', 'MVC Vikings', 'Match from North (Dukes)']
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
I'm using Selenium + Python to scrape match results on a Battlefy page for later manipulation and entering into a database. I'm trying to scrape the names of the teams and the results using Selenium because the dynamically loading JS requires me to use a headless browser. However, I'm trying to get the text of each college using the class name, but using Selenium's find_elements_by_class_name method doesn't seem to be working.

Web page: https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1

Current code:

>>> chrome_path = r"C:\Users\...\chromedriver.exe"
>>> driver = webdriver.Chrome(chrome_path)
>>> driver.get("https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1")
>>> team = driver.find_elements_by_class_name("team-name overflow-ellipsis float-right")
>>> for item in teams:
    print(item.text)

Which does not print anything and returns an empty array. I must be doing something incorrectly. How can I scrape each team name's text when it's covered by a class name?

Body:
To scrape the names of the teams using Selenium  and Python you have to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

driver.get("https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1")
print([my_elem.text for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".team-name.overflow-ellipsis.float-right")))])

Using XPATH:

driver.get("https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1")
print([my_elem.text for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='team-name overflow-ellipsis float-right']")))])

Console Output:

['Cougars', 'University of Illinois at Urbana-Champaign', 'Maryville Esports', 'Michigan State University', 'Purdue University', 'Illinois Wesleyan Titans', 'UMN Varsity Gold', 'UC LoL A Team', 'Arbor Esports', 'CWRU 300 Spartans', 'Bethany Esports', 'BGC at OSU', 'University of Wisconsin', 'CGC UIC', 'Indiana University - Purdue University Indianapolis - High Tempo Gaming', 'Missouri State University', 'KSU Wildcats', 'University of Manitoba Bisons', 'Nebraska', 'S&T eSports', 'Illinois State University - Redbird Esports', 'WUSTL Bears', 'University of Iowa A Team', 'TSUES', 'Division 2+', 'Grizzlies', 'Principia College esports', 'Northwestern Varsity', 'Wright State University - Raiders', 'Milwaukee School of Engineering - Raiders', 'UPIKE Esports', 'UMDads', 'Jayhawk Esports', 'NKU Esports', 'Warriors', 'Spartans', 'ND Lol', 'SDSU Team Alpha', 'Rose-Hulman', 'SIUe eSports', 'UND', 'MTU GOLD', 'Polar Bears', 'Purdue Fort Wayne Esports', 'CSU LOL', 'Aquinas Esports', 'Shawnee State Bears', 'Lewis Flyers', 'NDSU League of Legends Club', 'South Dakota Mines - Hardrockers', 'GVSU Laker Legends', 'G&E Club @ Iowa State University', 'MVC Vikings', 'Match from North (Dukes)']

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC