问:
Why does the 'git diff' command in PowerShell/Windows Terminal spoil the output to a file and does not spoil the output to the console?
I work in an operating system "Windows 10" (version 22H2). I use the program "Git for Windows" (version 2.35.1). I am running the program "Git" from the shell "PowerShell" version 7.3.0 in the terminal emulator "Windows Terminal" version 1.16.

In the project I'm working on, text files are stored in UTF-8 encoding without BOM.

The system locale I have configured as ru-Ru, so the OEM encoding is used "CP866" in console:

```<code>PS C:\Users\Илья\source\repos\test> (Get-WinSystemLocale).Name
ru-RU
PS C:\Users\Илья\source\repos\test> [System.Console]::OutputEncoding.CodePage
866
PS C:\Users\Илья\source\repos\test> [System.Console]::InputEncoding.CodePage
866
</code>```

The "PowerShell" preference variable $OutputEncoding is configured in UTF-8:

```<code>PS C:\Users\Илья\source\repos\test> $OutputEncoding.CodePage
65001
</code>```

Case 1. Output of the result of the 'git diff' command to a file (patch):

```<code>PS C:\Users\Илья\source\repos\test> git diff > my.patch
</code>```

As a result, the following happens to the text (this is a patch fragment, not the whole patch):

```<code>D0 A8 D0 B0 D0 BB D0 B0 D0 BD D0 B4 D1 8B        (in the project file, UTF-8 no BOM)
Ш     а     л     а     н     д     ы
 |
 | interpretation in "CP866"
 |
D0 A8 D0 B0 D0 BB D0 B0 D0 BD D0 B4 D1 8B
╨  и  ╨  ░  ╨  ╗  ╨  ░  ╨  ╜  ╨  ┤  ╤  Л
 |
 | converting to "UTF-8"
 |
╨        и     ╨        ░        ╨        ╗
E2 95 A8 D0 B8 E2 95 A8 E2 96 91 E2 95 A8 E2 95  (in the 'my.patch' file, UTF-8 no BOM)
   ╨        ░        ╨        ╜        ╨
97 E2 95 A8 E2 96 91 E2 95 A8 E2 95 9C E2 95 A8
┤        ╤        Л
E2 94 A4 E2 95 A4 D0 9B
</code>```

In the 'my.patch' file, mojibake is obtained. In addition, it increases in size by 2-3 times due to the above converting.

Case 2. Output of the result of the 'git diff' command to the console window:

```<code>PS C:\Users\Илья\source\repos\test> git diff
</code>```

The result displayed in the console window turns out to be readable, not corrupted.

I know that for readable output to a file in case 1, you can configure the encoding as follows (this is not my question):

```<code>PS C:\Users\Илья\source\repos\test> [System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8
</code>```

I also know that redirecting > to a file in 'PowerShell' is the same as passing data through the pipeline to the Out-File cmdlet. It doesn't need to be explained.

My question. Why does the 'git diff' command in PowerShell/Windows Terminal spoil the output to a file (case 1) and does not spoil the output to the console (case 2)?

I have read the Windows Console documentation, especially the section about architecture, which tells about the communication "Client - Device - Server - Terminal". I also read a series of 5 posts in on the site 'Microsoft Developer Blogs', especially the post about ConPTY. But I couldn't figure it out completely myself.

In answer, I would like to get something like a scheme of how the programs work in case 1 and in case 2. For example, something like this:

```<code>Case 1. Git -> System.Console -> PowerShell -> 'my.patch' file
Case 2. Git -> PowerShell -> Windows Terminal
</code>```

Why the encoding settings from the 'System.Console' class are used in the case 1, but not in the case 2? What program does the class 'System.Console' represent (Windows Terminal, conhost.exe, ConPTY or ConPTY built in conhost.exe)? Understanding how all these programs work is important to me, as I can use this understanding to write programs in C++ and PowerShell.

Body:
I work in an operating system "Windows 10" (version 22H2). I use the program "Git for Windows" (version 2.35.1). I am running the program "Git" from the shell "PowerShell" version 7.3.0 in the terminal emulator "Windows Terminal" version 1.16.

In the project I'm working on, text files are stored in UTF-8 encoding without BOM.

The system locale I have configured as ru-Ru, so the OEM encoding is used "CP866" in console:

PS C:\Users\Илья\source\repos\test> (Get-WinSystemLocale).Name
ru-RU
PS C:\Users\Илья\source\repos\test> [System.Console]::OutputEncoding.CodePage
866
PS C:\Users\Илья\source\repos\test> [System.Console]::InputEncoding.CodePage
866

The "PowerShell" preference variable $OutputEncoding is configured in UTF-8:

PS C:\Users\Илья\source\repos\test> $OutputEncoding.CodePage
65001

Case 1. Output of the result of the 'git diff' command to a file (patch):

PS C:\Users\Илья\source\repos\test> git diff > my.patch

As a result, the following happens to the text (this is a patch fragment, not the whole patch):

D0 A8 D0 B0 D0 BB D0 B0 D0 BD D0 B4 D1 8B        (in the project file, UTF-8 no BOM)
Ш     а     л     а     н     д     ы
 |
 | interpretation in "CP866"
 |
D0 A8 D0 B0 D0 BB D0 B0 D0 BD D0 B4 D1 8B
╨  и  ╨  ░  ╨  ╗  ╨  ░  ╨  ╜  ╨  ┤  ╤  Л
 |
 | converting to "UTF-8"
 |
╨        и     ╨        ░        ╨        ╗
E2 95 A8 D0 B8 E2 95 A8 E2 96 91 E2 95 A8 E2 95  (in the 'my.patch' file, UTF-8 no BOM)
   ╨        ░        ╨        ╜        ╨
97 E2 95 A8 E2 96 91 E2 95 A8 E2 95 9C E2 95 A8
┤        ╤        Л
E2 94 A4 E2 95 A4 D0 9B

In the 'my.patch' file, mojibake is obtained. In addition, it increases in size by 2-3 times due to the above converting.

Case 2. Output of the result of the 'git diff' command to the console window:

PS C:\Users\Илья\source\repos\test> git diff

The result displayed in the console window turns out to be readable, not corrupted.

I know that for readable output to a file in case 1, you can configure the encoding as follows (this is not my question):

PS C:\Users\Илья\source\repos\test> [System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8

I also know that redirecting > to a file in 'PowerShell' is the same as passing data through the pipeline to the Out-File cmdlet. It doesn't need to be explained.

My question. Why does the 'git diff' command in PowerShell/Windows Terminal spoil the output to a file (case 1) and does not spoil the output to the console (case 2)?

I have read the Windows Console documentation, especially the section about architecture, which tells about the communication "Client - Device - Server - Terminal". I also read a series of 5 posts in on the site 'Microsoft Developer Blogs', especially the post about ConPTY. But I couldn't figure it out completely myself.

In answer, I would like to get something like a scheme of how the programs work in case 1 and in case 2. For example, something like this:

Case 1. Git -> System.Console -> PowerShell -> 'my.patch' file
Case 2. Git -> PowerShell -> Windows Terminal

Why the encoding settings from the 'System.Console' class are used in the case 1, but not in the case 2? What program does the class 'System.Console' represent (Windows Terminal, conhost.exe, ConPTY or ConPTY built in conhost.exe)? Understanding how all these programs work is important to me, as I can use this understanding to write programs in C++ and PowerShell.


来源: stackexchange

问:
I don't understand this regexp match
My input string is "ssn".

My regexp is /^(s)(s)?((n)(n)?)?$/

Executing:

```<code>var regexp = /^(s)(s)?((n)(n)?)?$/;
var match = regexp.exec("ssn");
console.log(match);
</code>```

Yields:

```<code>[
    "ssn",
    "s",
    "s",
    "n",
    "n",
    null
]
</code>```

Why is the "n" in "ssn" matched 2 times ?

The desired output is:

```<code>[
    "ssn",
    "s",
    "s",
    "n",
    null,
    null
]
</code>```

ContentLicense: CC BY-SA 4.0

Title: I don't understand this regexp match

Body:
My input string is "ssn".

My regexp is /^(s)(s)?((n)(n)?)?$/

Executing:

var regexp = /^(s)(s)?((n)(n)?)?$/;
var match = regexp.exec("ssn");
console.log(match);

Yields:

[
    "ssn",
    "s",
    "s",
    "n",
    "n",
    null
]

Why is the "n" in "ssn" matched 2 times ?

The desired output is:

[
    "ssn",
    "s",
    "s",
    "n",
    null,
    null
]


问:
How to hide an element when scrolled underneath another without using background
I'm trying to do something similar to position: sticky but without the top element actually obscuring the element that has scrolled underneath. This is because I need the top element to be able to have a transparent background.

Here I've tried to use clip-path to hide the part of the element that would have been obscured but when testing this in Stackblitz the effect is not consistent, eg if you scroll quickly.

Is there an established way of doing this?

let cells = d3.selectAll('.cell');
let header = d3.select('.header');

d3.select('.frame').on('scroll.vertical', function () {

  const scrollTop = this.scrollTop;
  const headerBottom = header.node().getBoundingClientRect().bottom;

  // hold the header element in place
  header.style('transform', `translate(0px, ${scrollTop}px)`);

  cells.style('clip-path', function () {
    // clip the difference between the cell's position
    // and the header element's bottom
    const y = this.getBoundingClientRect().y;
    const clip = Math.max(0, headerBottom - y);
    return `inset(${clip}px 0px 0px 0px)`;
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#app {
  display: grid;
  grid-template-columns: 50px;
  grid-template-rows: repeat(4, 50px);
}

.header {
  border: 1px dotted blue;
  z-index: 1;
  /* background: white; */
}

.frame {
  width: 100px;
  height: 100px;
  overflow: auto;
}</code>```

Header

Cell 1

Cell 2

Cell 3

Cell 4

```

Body:
I'm trying to do something similar to position: sticky but without the top element actually obscuring the element that has scrolled underneath. This is because I need the top element to be able to have a transparent background.

Here I've tried to use clip-path to hide the part of the element that would have been obscured but when testing this in Stackblitz the effect is not consistent, eg if you scroll quickly.

Is there an established way of doing this?

let cells = d3.selectAll('.cell');
let header = d3.select('.header');

d3.select('.frame').on('scroll.vertical', function () {

  const scrollTop = this.scrollTop;
  const headerBottom = header.node().getBoundingClientRect().bottom;

  // hold the header element in place
  header.style('transform', `translate(0px, ${scrollTop}px)`);

  cells.style('clip-path', function () {
    // clip the difference between the cell's position
    // and the header element's bottom
    const y = this.getBoundingClientRect().y;
    const clip = Math.max(0, headerBottom - y);
    return `inset(${clip}px 0px 0px 0px)`;
  });
});

#app {
  display: grid;
  grid-template-columns: 50px;
  grid-template-rows: repeat(4, 50px);
}

.header {
  border: 1px dotted blue;
  z-index: 1;
  /* background: white; */
}

.frame {
  width: 100px;
  height: 100px;
  overflow: auto;
}

Header

Cell 1

Cell 2

Cell 3

Cell 4


问:
Liking a post with firebase
I want to like a post with firebase and swift. The Firebase doc says how I can do it.
But instead of posting  let uid = Auth.auth().currentUser?.uid for the uid I want to post a string like below. But it shows me an error.

It says: initializer for conditional binding must have optional type not 'string'
Why can I not use a string for uid and how to fix that?

```<code>        let ref = Database.database().reference().child("user").child(userID)

        ref.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
          if var post = currentData.value as? [String: AnyObject],
             let uid = ViewController.placeidUebertragen {

            var likes: [String: Bool]
            likes = post["followedPoi"] as? [String: Bool] ?? [:]
            var likeCount = post["followedPoiCounter"] as? Int ?? 0
            if let _ = likes[uid] {
              // Unstar the post and remove self from stars
              likeCount -= 1
              likes.removeValue(forKey: uid)
            } else {
              // Star the post and add self to stars
              likeCount += 1
              likes[uid] = true
            }
            post["followedPoiCounter"] = likeCount as AnyObject?
            post["followedPoi"] = likes as AnyObject?

            // Set value and report transaction success
            currentData.value = post
            return TransactionResult.success(withValue: currentData)
          }
          return TransactionResult.success(withValue: currentData)
        }) { error, committed, snapshot in
          if let error = error {
            print(error.localizedDescription)
          }

        }
</code>```

Title: Liking a post with firebase

Body:
I want to like a post with firebase and swift. The Firebase doc says how I can do it.
But instead of posting  let uid = Auth.auth().currentUser?.uid for the uid I want to post a string like below. But it shows me an error.

It says: initializer for conditional binding must have optional type not 'string'
Why can I not use a string for uid and how to fix that?

        let ref = Database.database().reference().child("user").child(userID)

        ref.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
          if var post = currentData.value as? [String: AnyObject],
             let uid = ViewController.placeidUebertragen {

            var likes: [String: Bool]
            likes = post["followedPoi"] as? [String: Bool] ?? [:]
            var likeCount = post["followedPoiCounter"] as? Int ?? 0
            if let _ = likes[uid] {
              // Unstar the post and remove self from stars
              likeCount -= 1
              likes.removeValue(forKey: uid)
            } else {
              // Star the post and add self to stars
              likeCount += 1
              likes[uid] = true
            }
            post["followedPoiCounter"] = likeCount as AnyObject?
            post["followedPoi"] = likes as AnyObject?

            // Set value and report transaction success
            currentData.value = post
            return TransactionResult.success(withValue: currentData)
          }
          return TransactionResult.success(withValue: currentData)
        }) { error, committed, snapshot in
          if let error = error {
            print(error.localizedDescription)
          }

        }


问:
How can I make a minimum moves algorithm more efficient?
There are 6 different tile colors that are arranged on a 2D rectangular grid. What is the minimum number of adjacent swaps (horizontal and vertical, not diagonal) that will result in no same colored tiles being adjacent? The program must support grid sizes up to 15 x 15 and must return "no solution" if none exists

My solution appears to work, but for no more than 16 - 20 tiles in the file. Otherwise it runs out of memory and/or takes too long.

My program looks for every tile that has another same colored one adjacent to it, and attempts to swap in all four directions (up, down, left, right). Those newly swapped grids are sent to a queue, which the program iterates through (as per the breadth-first-search method) and then applies the four way swap to each. The number of moves simultaneously are being tracked in another array. ArrayLists representing the grid are one dimensional and use integer values rather than Strings (to conserve memory) and the program uses math to determine adjacencies. It also tracks any before seen grids to terminate some unnecessary processing. This program does not account for a possibility of no solution occurring.

Below is the four way swap method (repeatedly called with iteration):

```<code>public static boolean minSwaps(ArrayList<Integer> tiles, int moves) {
    boolean solved = true;
    for (int i = 0; i < tiles.size(); i++) {
      if (hasAdjacent(tiles, i)) {
        solved = false;
        try {
          ArrayList<Integer> tilesNew = (ArrayList<Integer>)tiles.clone();
          Collections.swap(tilesNew, i, i - length);
          queue.add(tilesNew);
          Main.moves.add(moves + 1);
        }
        catch(Exception e) {}
        try {
          ArrayList<Integer> tilesNew = (ArrayList<Integer>)tiles.clone();
          Collections.swap(tilesNew, i, i + length);
          queue.add(tilesNew);
          Main.moves.add(moves + 1);
        }
        catch(Exception e) {}
        try {
          if (i + 1 % length != 0) {
            ArrayList<Integer> tilesNew = (ArrayList<Integer>)tiles.clone();
            Collections.swap(tilesNew, i, i + 1);
            queue.add(tilesNew);
            Main.moves.add(moves + 1);
          }
        }
        catch(Exception e) {}
        try {
          if (i % length != 0) {
            ArrayList<Integer> tilesNew = (ArrayList<Integer>)tiles.clone();
            Collections.swap(tilesNew, i, i - 1);
            queue.add(tilesNew);
            Main.moves.add(moves + 1);
          }
        }
        catch(Exception e) {}
      }
    }
    return solved;
  }
</code>```

Additionally, here is a link to the program in its entirety with the file (replit.com)
https://replit.com/join/quivtthrqo-roya3

Body:
There are 6 different tile colors that are arranged on a 2D rectangular grid. What is the minimum number of adjacent swaps (horizontal and vertical, not diagonal) that will result in no same colored tiles being adjacent? The program must support grid sizes up to 15 x 15 and must return "no solution" if none exists

My solution appears to work, but for no more than 16 - 20 tiles in the file. Otherwise it runs out of memory and/or takes too long.

My program looks for every tile that has another same colored one adjacent to it, and attempts to swap in all four directions (up, down, left, right). Those newly swapped grids are sent to a queue, which the program iterates through (as per the breadth-first-search method) and then applies the four way swap to each. The number of moves simultaneously are being tracked in another array. ArrayLists representing the grid are one dimensional and use integer values rather than Strings (to conserve memory) and the program uses math to determine adjacencies. It also tracks any before seen grids to terminate some unnecessary processing. This program does not account for a possibility of no solution occurring.

Below is the four way swap method (repeatedly called with iteration):

public static boolean minSwaps(ArrayList<Integer> tiles, int moves) {
    boolean solved = true;
    for (int i = 0; i < tiles.size(); i++) {
      if (hasAdjacent(tiles, i)) {
        solved = false;
        try {
          ArrayList<Integer> tilesNew = (ArrayList<Integer>)tiles.clone();
          Collections.swap(tilesNew, i, i - length);
          queue.add(tilesNew);
          Main.moves.add(moves + 1);
        }
        catch(Exception e) {}
        try {
          ArrayList<Integer> tilesNew = (ArrayList<Integer>)tiles.clone();
          Collections.swap(tilesNew, i, i + length);
          queue.add(tilesNew);
          Main.moves.add(moves + 1);
        }
        catch(Exception e) {}
        try {
          if (i + 1 % length != 0) {
            ArrayList<Integer> tilesNew = (ArrayList<Integer>)tiles.clone();
            Collections.swap(tilesNew, i, i + 1);
            queue.add(tilesNew);
            Main.moves.add(moves + 1);
          }
        }
        catch(Exception e) {}
        try {
          if (i % length != 0) {
            ArrayList<Integer> tilesNew = (ArrayList<Integer>)tiles.clone();
            Collections.swap(tilesNew, i, i - 1);
            queue.add(tilesNew);
            Main.moves.add(moves + 1);
          }
        }
        catch(Exception e) {}
      }
    }
    return solved;
  }

Additionally, here is a link to the program in its entirety with the file (replit.com)
https://replit.com/join/quivtthrqo-roya3


问:
Can we distinguish one trackpad scroll in windows from other?
I am trying to distinguish one trackpad scroll user action (which translates into multiple mouse wheel events on windows) from the next user action? Is there a way to achieve it like in case of MacOS? I tried the value of lparam and wparams in mousewheel callback, one of these is of course zdelta the other remains same even if there is a significant time difference between two user scrolls(possibly os is distinguishing events)

Highly appreciate the answers.


问:
React Root Container template for a Dashboard app
I am very new in React and trying to build a dashboard app.
I am using react material for the design.

How can I define a full width responsive root container as a placeholder for all the other components.

Like we define full width container Bootstrap as the placeholder or the parent element for everything, how can I get one for react when using material.

I tried using dashboard templates which has some complicated layout definition


问:
SvelteKit: CORS error only on full page load
I have a SvelteKit +page.svelte route with a corresponding +page.ts endpoint that fetches data from a Django server running on a different subdomain.

In Django the CORS headers are correctly specified. When I navigate from another route to my fetching route, I get all the data and everything just works fine but once I trigger a full page reload on my fetching route, I receive a:

CORS error: No 'Access-Control-Allow-Origin' header is present on the requested resource

+page.svelte

```<code><script lang="ts">

    /** @type {import('./$types').PageData} */
    export let data : Object;
</script>
<main>
    {JSON.stringify(data.books)}
</main>
</code>```

+page.ts

```<code>import { error } from '@sveltejs/kit';

/** @type {import('./$types').PageLoad} */
export async function load({ fetch }) {
    const response = await fetch("https://api.my-domain.com/api/books/", {
        method: "GET",
        accept: "application/json"
    });

    if (response.ok) {
        const books = await response.json();

        return {
            books
        };
    }

    throw error(500, {
        message: "Service unavailable right now. Please try again later!"
    })
}
</code>```

Can someone please explain to me why there is a CORS error when triggering a full page reload but not when triggering a simple navigate from another origin route?

Body:
I have a SvelteKit +page.svelte route with a corresponding +page.ts endpoint that fetches data from a Django server running on a different subdomain.

In Django the CORS headers are correctly specified. When I navigate from another route to my fetching route, I get all the data and everything just works fine but once I trigger a full page reload on my fetching route, I receive a:

CORS error: No 'Access-Control-Allow-Origin' header is present on the requested resource

+page.svelte

    {JSON.stringify(data.books)}

+page.ts

import { error } from '@sveltejs/kit';

/** @type {import('./$types').PageLoad} */
export async function load({ fetch }) {
    const response = await fetch("https://api.my-domain.com/api/books/", {
        method: "GET",
        accept: "application/json"
    });

    if (response.ok) {
        const books = await response.json();

        return {
            books
        };
    }

    throw error(500, {
        message: "Service unavailable right now. Please try again later!"
    })
}

Can someone please explain to me why there is a CORS error when triggering a full page reload but not when triggering a simple navigate from another origin route?


问:
Wordpress Ninja Forms preventing form submission
We have Ninja Forms setup on a Wordpress site. Occasionally, when a user fills out the fields to submit the form, they are presented with the error "Please correct errors before submitting this form". All fields are filled out, with valid values. This happens in testing, and prevents the form from being submitted. Even if the fields are cleared and the values are reentered. I have Googled this issue extensively, and cannot find any references to what might be causing the issue. Any help or insight that anyone can provide would be extremely helpful.

We have tried reentering the field values, which has not worked. The form will still not submit. Refreshing the page and filling out the form again fixes the issue, and the form will successfully submit.


问:
How can I add a new parent/mixin to a class in a Scala 3 compiler plugin?
I have this phase:

class ExpPhase extends PluginPhase {
  import tpd._

  val phaseName = "expPhase"

  override val runsAfter = Set("typer")

  override def transformTypeDef(tree: TypeDef)(implicit ctx: Context): Tree =
    if tree.isClassDef && !tree.rhs.symbol.isStatic then  // only look at classes & traits, not objects
      val c2 = QuotesCache.init(ctx.fresh)
      implicit val quotes = scala.quoted.runtime.impl.QuotesImpl()(using c2)
      import quotes.reflect.*

      // Add new parent, SJ_Serialize, so class Person becomes class Person extends SJ_Serialize
      val cd = ClassDef.copy(classDef)(
        name = classDef.name,
        constr = classDef.constructor,
        parents = classDef.parents :+ TypeTree.of[SJ_Serialize],  // SJ_Serialize is a trait having methods
        selfOpt = classDef.self,
        body = classDef.body
      )
      val newCd = cd.asInstanceOf[dotty.tools.dotc.ast.tpd.Tree]
      println(QuotesImpl.showDecompiledTree(newCd)) // see if class modified successfully
      newCd
    else
      tree

}
```

When I look at the printed class (newCd) I see that it shows as now mixing in SJ_Serialize.  Great!  But not so great...

This phase happens early in the flow.  I see that programmer-written mixin traits have their methods copied into the target class at some point later in the flow.  I expected that to happen with my new added trait, but it did not. (SJ_Serialize has implemented methods that should be callable on the target class after mixing in.)

Makes me wonder if there's other machinery I need to connect to make this parent addition work properly?

What else am I missing to make this work, and how would I actually do it?

Body:
I have this phase:

class ExpPhase extends PluginPhase {
  import tpd._

  val phaseName = "expPhase"

  override val runsAfter = Set("typer")

  override def transformTypeDef(tree: TypeDef)(implicit ctx: Context): Tree =
    if tree.isClassDef && !tree.rhs.symbol.isStatic then  // only look at classes & traits, not objects
      val c2 = QuotesCache.init(ctx.fresh)
      implicit val quotes = scala.quoted.runtime.impl.QuotesImpl()(using c2)
      import quotes.reflect.*

      // Add new parent, SJ_Serialize, so class Person becomes class Person extends SJ_Serialize
      val cd = ClassDef.copy(classDef)(
        name = classDef.name,
        constr = classDef.constructor,
        parents = classDef.parents :+ TypeTree.of[SJ_Serialize],  // SJ_Serialize is a trait having methods
        selfOpt = classDef.self,
        body = classDef.body
      )
      val newCd = cd.asInstanceOf[dotty.tools.dotc.ast.tpd.Tree]
      println(QuotesImpl.showDecompiledTree(newCd)) // see if class modified successfully
      newCd
    else
      tree

}

When I look at the printed class (newCd) I see that it shows as now mixing in SJ_Serialize.  Great!  But not so great...

This phase happens early in the flow.  I see that programmer-written mixin traits have their methods copied into the target class at some point later in the flow.  I expected that to happen with my new added trait, but it did not. (SJ_Serialize has implemented methods that should be callable on the target class after mixing in.)

Makes me wonder if there's other machinery I need to connect to make this parent addition work properly?

What else am I missing to make this work, and how would I actually do it?


问:
Importing a CSV file in Java
I am creating a marketplace that users can import products into. I need to be able to import the CSV file through a network I/O so with a client-server functionality.

Currently when I import the CSV filepath the GUI (program) freezes and I believe it is trying to read something that is not there or something along those lines.

Client:

```<code>public void importFromCSV(String path) {

    try {
        writer.write(path);
        writer.flush();
        int bytes = 0;
        File file = new File(path);
        FileInputStream fis = new FileInputStream(path);

        // send file size
        dos.writeLong(file.length());
        // break file into chunks
        byte[] buffer = new byte[4 * 1024];
        while ((bytes = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, bytes);
            dos.flush();
        }
        fis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

Server:

```<code>public static void importCSV(Store store) {
    try {
        int bytes = 0;
        System.out.println("about to read path");
        String path = reader.readLine();
        System.out.println("read path");

        FileOutputStream fos = new FileOutputStream(path);

        long size = dis.readLong();     // read file size
        byte[] buffer = new byte[4*1024];
        while (size > 0 && (bytes = dis.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1) {
            fos.write(buffer, 0, bytes);
            size -= bytes;      // read upto file size
        }
        fos.close();

        store.setProducts(CSVFileWork.CSVToProducts(path));
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(store.getProducts().size());
}
</code>```

Title: Importing a CSV file in Java

Body:
I am creating a marketplace that users can import products into. I need to be able to import the CSV file through a network I/O so with a client-server functionality.

Currently when I import the CSV filepath the GUI (program) freezes and I believe it is trying to read something that is not there or something along those lines.

Client:

public void importFromCSV(String path) {

    try {
        writer.write(path);
        writer.flush();
        int bytes = 0;
        File file = new File(path);
        FileInputStream fis = new FileInputStream(path);

        // send file size
        dos.writeLong(file.length());
        // break file into chunks
        byte[] buffer = new byte[4 * 1024];
        while ((bytes = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, bytes);
            dos.flush();
        }
        fis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Server:

public static void importCSV(Store store) {
    try {
        int bytes = 0;
        System.out.println("about to read path");
        String path = reader.readLine();
        System.out.println("read path");

        FileOutputStream fos = new FileOutputStream(path);

        long size = dis.readLong();     // read file size
        byte[] buffer = new byte[4*1024];
        while (size > 0 && (bytes = dis.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1) {
            fos.write(buffer, 0, bytes);
            size -= bytes;      // read upto file size
        }
        fos.close();

        store.setProducts(CSVFileWork.CSVToProducts(path));
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(store.getProducts().size());
}


问:
Creative Data API Pull
In our API we are pulling Creative data and for 2 campaigns, the “creative.name” is pulling in the “creative.id”. For all other campaigns, the correct “creative.name” is populating.

Is there a reason this would happen, such as a modification made to the campaign during its run or the creative.name/text being added after the start of the campaign?

Additionally is there a LinkedIn Creatives API cheatsheet you can share?

(shared above already)

Title: Creative Data API Pull


问:
Doxygen UML is not properly display (version 1.9.5)

Hello,
I have a issue with UML_LOOK in doxygen.

Is anybody having same issue with UML_LOOk on 1.9.5
I have tried to find why is this working weird but have no idea...

my configuration setting is

```<code>CLASS_GRAPH            = YES
COLLABORATION_GRAPH    = YES
GROUP_GRAPHS           = YES
UML_LOOK               = YES
UML_LIMIT_NUM_FIELDS   = 10
DOT_UML_DETAILS        = NO
DOT_WRAP_THRESHOLD     = 17
TEMPLATE_RELATIONS     = YES
INCLUDE_GRAPH          = YES
INCLUDED_BY_GRAPH      = YES
CALL_GRAPH             = YES
CALLER_GRAPH           = YES
GRAPHICAL_HIERARCHY    = YES
DIRECTORY_GRAPH        = YES
DIR_GRAPH_MAX_DEPTH    = 1
DOT_IMAGE_FORMAT       = png
INTERACTIVE_SVG        = NO
DOT_PATH               = "C:/Program Files/Graphviz/bin"
</code>```

I couldn't find "CLASS_DIAGRAM=YES"..
there are no option in "Expert-->Dot" section

Class members are correctly display in UML.

Find solution to fix this issue with changing config.

Body:
Hello,
I have a issue with UML_LOOK in doxygen.

Is anybody having same issue with UML_LOOk on 1.9.5
I have tried to find why is this working weird but have no idea...

my configuration setting is

CLASS_GRAPH            = YES
COLLABORATION_GRAPH    = YES
GROUP_GRAPHS           = YES
UML_LOOK               = YES
UML_LIMIT_NUM_FIELDS   = 10
DOT_UML_DETAILS        = NO
DOT_WRAP_THRESHOLD     = 17
TEMPLATE_RELATIONS     = YES
INCLUDE_GRAPH          = YES
INCLUDED_BY_GRAPH      = YES
CALL_GRAPH             = YES
CALLER_GRAPH           = YES
GRAPHICAL_HIERARCHY    = YES
DIRECTORY_GRAPH        = YES
DIR_GRAPH_MAX_DEPTH    = 1
DOT_IMAGE_FORMAT       = png
INTERACTIVE_SVG        = NO
DOT_PATH               = "C:/Program Files/Graphviz/bin"

I couldn't find "CLASS_DIAGRAM=YES"..
there are no option in "Expert-->Dot" section

Class members are correctly display in UML.

Find solution to fix this issue with changing config.


问:
How to show Flutter Spinkit when a button is pressed?
I have a button that checks for login credentials and if they were correct, navigates the user to another page. I want to use Flutter Spinkit. I have the following code for the button:

```<code>onPressed: () async {
  const SpinKitWave(
    color: Colors.white, type: SpinKitWaveType.start);
  var service = Services();
  var response =
    await service.login(username.text, password.text);
  if (response.statusCode == 200) {
    SharedPreferences prefs =
      await SharedPreferences.getInstance();
    prefs.setString('myUsername', username.text);
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) =>
        const HomePage(),
      ));
  }
},
</code>```

When I press the button, the Flutter Spinkit does not show anything.

Body:
I have a button that checks for login credentials and if they were correct, navigates the user to another page. I want to use Flutter Spinkit. I have the following code for the button:

onPressed: () async {
  const SpinKitWave(
    color: Colors.white, type: SpinKitWaveType.start);
  var service = Services();
  var response =
    await service.login(username.text, password.text);
  if (response.statusCode == 200) {
    SharedPreferences prefs =
      await SharedPreferences.getInstance();
    prefs.setString('myUsername', username.text);
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) =>
        const HomePage(),
      ));
  }
},

When I press the button, the Flutter Spinkit does not show anything.


问:
Recursuve calls in c working even though its not returned to its parent call in stack
I was lookin for a code to implement the LCM of two numbers using recursion. Here is the code i found:

```<code>#include<stdio.h>
int lcm(int a, int b)
{
    static int common = 1;

    if (common % a == 0 && common % b == 0)
    {
        return common;
    }
    common++;
    lcm(a, b);  //call the function lcm recursively.
}
void main()
{
    int a=5;
    int b=6;
    int c= lcm(a,b);
    printf("\n%d",c);
}
</code>```

I understand everything but the last line in the lcm(int a, intb) function

lcm(a,b);

According to me, for lets say input values 5,2 there will be 10 recursive calls made in the stack after which our base condition is reached. Now for the statement:

return common;

where does it return the value to? we are not really saving it anywhere in the 9th recursive call in the stack. How is it getting passed down the hierarchy and making its way to void main. If the recursive call was written as-

return lcm(a,b);

I understand how this works- we return the 10th recursive function call to 9th and then to 8th and so on... until it makes it way to void main when we return from the first time function was called.

Body:
I was lookin for a code to implement the LCM of two numbers using recursion. Here is the code i found:

#include<stdio.h>
int lcm(int a, int b)
{
    static int common = 1;

    if (common % a == 0 && common % b == 0)
    {
        return common;
    }
    common++;
    lcm(a, b);  //call the function lcm recursively.
}
void main()
{
    int a=5;
    int b=6;
    int c= lcm(a,b);
    printf("\n%d",c);
}

I understand everything but the last line in the lcm(int a, intb) function

lcm(a,b);

According to me, for lets say input values 5,2 there will be 10 recursive calls made in the stack after which our base condition is reached. Now for the statement:

return common;

where does it return the value to? we are not really saving it anywhere in the 9th recursive call in the stack. How is it getting passed down the hierarchy and making its way to void main. If the recursive call was written as-

return lcm(a,b);

I understand how this works- we return the 10th recursive function call to 9th and then to 8th and so on... until it makes it way to void main when we return from the first time function was called.


问:
Can't show transparent image in php
I'm creating a minecraft skin generator, but the php code doesn't show me the transparent image:

This is what it shows me:
image: https://i.imgur.com/L3vA3n8.png

I can't put the images to show

It shows me the black background and what I'm trying to achieve is to make it transparent (white color)

Thus:
image:
https://i.imgur.com/Gyq5NqG.png
I can't put the images to show

This is the code I'm using:

```<code><?php
// Crear instancias de imágenes
$origen = imagecreatefrompng("https://jose89fcb.es/SkinMinecraftVistaPreviaDiscord/navidad/Traje_entero.png");
$destino = imagecreatefrompng("http://textures.minecraft.net/texture/3084a678ada05e08058555c11383be71bf8419fa0c2fc89b5aa0be8d00aeb9a0");
$contenedor = imagecreatetruecolor(imagesx($destino), imagesy($destino));

//ver el tamaño de la original
// Copiar
imagecopy($contenedor, $destino, 0, 0, 0, 0, imagesx($destino), imagesy($destino));
imagecopy($contenedor, $origen, 0, 0, 0, 0, imagesx($origen), imagesy($origen));

// Imprimir y liberar memoria
header('Content-Type: image/png');
imagepng($contenedor);

imagedestroy($destino);
imagedestroy($origen);
imagedestroy($contenedor);
?>
</code>```

These two images should be displayed in the same image:
https://textures.minecraft.net/texture/3084a678ada05e08058555c11383be71bf8419fa0c2fc89b5aa0be8d00aeb9a0

https://jose89fcb.es/SkinMinecraftVistaPreviaDiscord/navidad/Traje_entero.png

Remaining the images like this:
https://i.imgur.com/R2H1Px4.png

Where is the problem?

Thank you very much in advance!

Can someone help me, thank you very much

Title: Can't show transparent image in php

Body:
I'm creating a minecraft skin generator, but the php code doesn't show me the transparent image:

This is what it shows me:
image: https://i.imgur.com/L3vA3n8.png

I can't put the images to show

It shows me the black background and what I'm trying to achieve is to make it transparent (white color)

Thus:
image:
https://i.imgur.com/Gyq5NqG.png
I can't put the images to show

This is the code I'm using:

<?php
// Crear instancias de imágenes
$origen = imagecreatefrompng("https://jose89fcb.es/SkinMinecraftVistaPreviaDiscord/navidad/Traje_entero.png");
$destino = imagecreatefrompng("http://textures.minecraft.net/texture/3084a678ada05e08058555c11383be71bf8419fa0c2fc89b5aa0be8d00aeb9a0");
$contenedor = imagecreatetruecolor(imagesx($destino), imagesy($destino));

//ver el tamaño de la original
// Copiar
imagecopy($contenedor, $destino, 0, 0, 0, 0, imagesx($destino), imagesy($destino));
imagecopy($contenedor, $origen, 0, 0, 0, 0, imagesx($origen), imagesy($origen));

// Imprimir y liberar memoria
header('Content-Type: image/png');
imagepng($contenedor);

imagedestroy($destino);
imagedestroy($origen);
imagedestroy($contenedor);
?>

These two images should be displayed in the same image:
https://textures.minecraft.net/texture/3084a678ada05e08058555c11383be71bf8419fa0c2fc89b5aa0be8d00aeb9a0

https://jose89fcb.es/SkinMinecraftVistaPreviaDiscord/navidad/Traje_entero.png

Remaining the images like this:
https://i.imgur.com/R2H1Px4.png

Where is the problem?

Thank you very much in advance!

Can someone help me, thank you very much


问:
How to resolve SSL error while connecting to REDCap
I am running into the following error when making an API call to REDCap through R. The error only occurs on the server while it works fine on my laptop. I have downloaded the certificate in the same directory where my code is.

```<code>Error in curl::curl_fetch_memory(url, handle = handle) :
  SSL certificate problem: unable to get local issuer certificate
Calls: redcap_report ... request_fetch -> request_fetch.write_memory -> <Anonymous>
Execution halted
</code>```

Here is my code

```<code>library(REDCapR)
my_uri <-'https://redcap-qi.xxx.xxx.xxx/xxx/xxx/API/'
my_token <- 'xxxxxxxxxxxxxxxxx'

my_data <-
  redcap_report(redcap_uri = my_uri,
                token = my_token,
                report_id = 12345)$data
</code>```

Adding the following resolved my issue

```<code>new_config <- httr::config(ssl_verifypeer = FALSE)
httr::set_config(new_config, override = FALSE)
</code>```

Body:
I am running into the following error when making an API call to REDCap through R. The error only occurs on the server while it works fine on my laptop. I have downloaded the certificate in the same directory where my code is.

Error in curl::curl_fetch_memory(url, handle = handle) :
  SSL certificate problem: unable to get local issuer certificate
Calls: redcap_report ... request_fetch -> request_fetch.write_memory -> <Anonymous>
Execution halted

Here is my code

library(REDCapR)
my_uri <-'https://redcap-qi.xxx.xxx.xxx/xxx/xxx/API/'
my_token <- 'xxxxxxxxxxxxxxxxx'

my_data <-
  redcap_report(redcap_uri = my_uri,
                token = my_token,
                report_id = 12345)$data

Adding the following resolved my issue

new_config <- httr::config(ssl_verifypeer = FALSE)
httr::set_config(new_config, override = FALSE)


问:
Generate a new variable based on two unequal data frames having similar item/value
I have two unequal data frames. Lets say

A <- data.frame(x = 1:15, y=letters[1:15]) and

B <- data.frame(k = 1:4, w=letters[1:4])

I want to generate a new variable (Z) that equals 1, if y=w' otherwise zero(0)`. that is want to generate a new variable that is equal to 1 if any text/description in the column "w" of data frame B, can be found in the column "y" of data frame A. Z will then be appended to data frame A. there are no common identifiers for the two datasets. I have this code and others and not working

```<code>A <- A %>%
  mutate(
    Z = if_else(
      y %in% B$w,
      '1',
      '0'
    )
  )
</code>```

Body:
I have two unequal data frames. Lets say

A <- data.frame(x = 1:15, y=letters[1:15]) and

B <- data.frame(k = 1:4, w=letters[1:4])

I want to generate a new variable (Z) that equals 1, if y=w' otherwise zero(0)`. that is want to generate a new variable that is equal to 1 if any text/description in the column "w" of data frame B, can be found in the column "y" of data frame A. Z will then be appended to data frame A. there are no common identifiers for the two datasets. I have this code and others and not working

A <- A %>%
  mutate(
    Z = if_else(
      y %in% B$w,
      '1',
      '0'
    )
  )


问:
Append list of logged in users to a log file using crontab?
I need to create a basic log file through the use of a crontab job that appends a timestamp, followed by a list of logged in users. It must be at 23:59 each night.
(I have used 18 18 * * * as an example to make sure the job works for now)

So far, I have;

```<code>!#/bin/bash
59 23 * * * (date ; who) >> /root/userlogfile.txt
</code>```

for my crontab script, the output;

```<code>Fri Dec 9 18:18:01 UTC 2022
root console 00:00 Dec 9 18:15:15
</code>```

My required output is something similar to;

```<code>Fri 09 Dec 23:59:00 GMT 2022

user1   tty2    2017-11-30 22:00 (:0)

user5   pts/1   2017-11-30 20:35 (192.168.1.1)
</code>```

How would I go about this?

Body:
I need to create a basic log file through the use of a crontab job that appends a timestamp, followed by a list of logged in users. It must be at 23:59 each night.
(I have used 18 18 * * * as an example to make sure the job works for now)

So far, I have;

!#/bin/bash
59 23 * * * (date ; who) >> /root/userlogfile.txt

for my crontab script, the output;

Fri Dec 9 18:18:01 UTC 2022
root console 00:00 Dec 9 18:15:15

My required output is something similar to;

Fri 09 Dec 23:59:00 GMT 2022

user1   tty2    2017-11-30 22:00 (:0)

user5   pts/1   2017-11-30 20:35 (192.168.1.1)

How would I go about this?


问:
ArgumentException when using USB to connect to Android phone with C#
I want to have an Android app communicate with a UWP C# program via USB. I have my phone showing up in Device Manager as an ADB interface with the winusb.sys driver. To communicate with it, I want to put the phone into Accessory mode, for which I need to send a USB control packet (https://source.android.com/docs/core/interaction/accessories/aoa?hl=en#attempt-to-start-in-accessory-mode). But whenever I try to send it, I get an ArgumentException.

I wrote the following code in C#:

```<code>//vendor id and product id of phone
uint vid = 0x1004;
uint pid = 0x633E;
string aqs = UsbDevice.GetDeviceSelector(vid, pid);

DeviceInformationCollection devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs);

UsbDevice usbDevice = await UsbDevice.FromIdAsync(devices[0].Id); // get UsbDevice

if (usbDevice != null)
{

    byte[] bytes = new byte[2];
    IBuffer buf = bytes.AsBuffer();

    UsbSetupPacket initSetupPacket = new UsbSetupPacket()
    {
        RequestType = new UsbControlRequestType()
        {
            Direction = UsbTransferDirection.In,
            Recipient = UsbControlRecipient.Device,
            ControlTransferType = UsbControlTransferType.Vendor,
        },
        Request = 51,
        Value = 0,
        Index = 0,
        Length = 2
    };

    IBuffer result = await usbDevice.SendControlInTransferAsync(initSetupPacket, buf);
}
</code>```

My problem is that an ArgumentException ('Value does not fall within the expected range.') is thrown when calling usbDevice.SendControlInTransferAsync and I don't know why.

Body:
I want to have an Android app communicate with a UWP C# program via USB. I have my phone showing up in Device Manager as an ADB interface with the winusb.sys driver. To communicate with it, I want to put the phone into Accessory mode, for which I need to send a USB control packet (https://source.android.com/docs/core/interaction/accessories/aoa?hl=en#attempt-to-start-in-accessory-mode). But whenever I try to send it, I get an ArgumentException.

I wrote the following code in C#:

//vendor id and product id of phone
uint vid = 0x1004;
uint pid = 0x633E;
string aqs = UsbDevice.GetDeviceSelector(vid, pid);

DeviceInformationCollection devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs);

UsbDevice usbDevice = await UsbDevice.FromIdAsync(devices[0].Id); // get UsbDevice

if (usbDevice != null)
{

    byte[] bytes = new byte[2];
    IBuffer buf = bytes.AsBuffer();

    UsbSetupPacket initSetupPacket = new UsbSetupPacket()
    {
        RequestType = new UsbControlRequestType()
        {
            Direction = UsbTransferDirection.In,
            Recipient = UsbControlRecipient.Device,
            ControlTransferType = UsbControlTransferType.Vendor,
        },
        Request = 51,
        Value = 0,
        Index = 0,
        Length = 2
    };

    IBuffer result = await usbDevice.SendControlInTransferAsync(initSetupPacket, buf);
}

My problem is that an ArgumentException ('Value does not fall within the expected range.') is thrown when calling usbDevice.SendControlInTransferAsync and I don't know why.


问:
Bash script gives psycopg2 error: symbol not found in flat namespace (_PQbackendPID)?
I am using Apple M1. Here is the bash script I wrote.

```<code>#!/bin/sh

# Open Activity Tracker website
python -m webbrowser http://127.0.0.1:8000/

# Activate virtual environment
. dj-env/bin/activate

# Navigate to Activity Tracker project folder
cd dj_activity_tracker

# Run Django local development server
python manage.py runserver
</code>```

When you run manually are you doing that in the same virtualenv? Yes.

Are you doing the installs into the virtualenv? Yes.

What version of psycopg? Within my virtual environment, I run "pip show psycopg2-binary". It outputs "Version: 2.9.5".

When I run these commands on my terminal manually without the script, it works. However, when I use this script, I get the error:

```<code>
File "/Users/doge/Desktop/dj-env/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 28, in \<module\>
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/doge/Desktop/dj-env/lib/python3.11/site-packages/psycopg2/\_psycopg.cpython-311-darwin.so, 0x0002): symbol not found in flat namespace (\_PQbackendPID)

</code>```

Things I have tried:

Uninstall/reinstall psycopg2

brew install postgresql

I am stumped on how this is working manually but not when I run the script. What could be the issue? I appreciate your support.

Body:
I am using Apple M1. Here is the bash script I wrote.

#!/bin/sh

# Open Activity Tracker website
python -m webbrowser http://127.0.0.1:8000/

# Activate virtual environment
. dj-env/bin/activate

# Navigate to Activity Tracker project folder
cd dj_activity_tracker

# Run Django local development server
python manage.py runserver

When you run manually are you doing that in the same virtualenv? Yes.

Are you doing the installs into the virtualenv? Yes.

What version of psycopg? Within my virtual environment, I run "pip show psycopg2-binary". It outputs "Version: 2.9.5".

When I run these commands on my terminal manually without the script, it works. However, when I use this script, I get the error:

File "/Users/doge/Desktop/dj-env/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 28, in \<module\>
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/doge/Desktop/dj-env/lib/python3.11/site-packages/psycopg2/\_psycopg.cpython-311-darwin.so, 0x0002): symbol not found in flat namespace (\_PQbackendPID)

Things I have tried:

Uninstall/reinstall psycopg2

brew install postgresql

I am stumped on how this is working manually but not when I run the script. What could be the issue? I appreciate your support.


问:
SELECT name, val FROM wp_wfConfig WHERE autoload = 'yes'
I have got a report by my webhost and he told me that there is a key or something in the database that creates many many thousands of queries. I dont know how to understand this report. Maybe someone can help me? I think it has to do with wordfence plugin somehow.

Queries reported are:

SELECT name, val FROM wp_wfConfig WHERE autoload = 'yes'

SELECT post_id, meta_key, meta_value FROM wp_postmeta WHERE post_id IN (2,12,13,14,19,91,133,626,3775,7034,7755,9559,10298,11588,13049,13133,13142,13146,15298,15300,15365,15761,17185,18530,20989,21046,23394,25343,25357,29136) ORDER BY meta_id ASC

SELECT post_id, meta_key, meta_value FROM wp_postmeta WHERE post_id IN (2,12,13,14,19,91,133,626,3775,7034,7755,9559,10298,11588,13049,13133,13142,13146,15298,15300,15365,15761,17185,18530,20989,21046,23394,25343,25357,29136) ORDER BY meta_id ASC

SELECT name, val FROM wp_wfConfig WHERE autoload = 'yes'

I uninstalled wordfence and have deleted all the tables with wordfence assistant to make sure, all settings and tables are deleted. But the term "autoload" is still cryptical for me.


问:
How to allow external access from VisualStudio for private azure devops nuget feeds without providing user credentials
We have implemented product using several private nugets (Azure DevOps feed) which worked very well.

Now the development is completed and delivered. As part of the agreement, the client wants the source code. When the client tried to compile the source code in VisualStudio, they couldn't restore the nugets as they are in our organization's private feed. Although the PAT is is given in the nuget.config file, the Azure Credential Authentication window asks for the username and password of our organization, which we cannot provide to the client.

Is there any solution for this issue? How usually project code base with private nugets are delivered?

Any suggestions will be greatly appreciated.

Thanks in advance.

We don't want to create a stalkholder user account for anyone in client organization. So the solution provided here will not work.

I am thinking of two options:

Remove the reference to nuget and add the latest dlls of those libraries directly to the projects

Add the private nuget projects into the solution( provide code base for private nugets as well)

Any other way? How can we resolve it using PAT(personal access token)?


问:
Get a single TIFF using multiple TIFFs and masks
I'm working with satellite imagery (from Sentinel-2), in particular with cloud detection and cloud cleaning.

I got a batch of images of the same area, but in different periods:

From these images, you can see that the position of the clouds is always different.

I also have the mask for each image, where the black areas represent clouds:

These masks are not perfect, but this is not a problem.

What I want to do is to use the mask to cut all the white portions (so get the land and exclude the clouds), and then fill these cuts with a black portion of another image (fill the "hole" in the image with a part of another image without clouds).

Imagery is in TIFF format, while masks are in JPG format.

I'm using Python with libraries like Rasterio, numpy and scikit-image, so a Pythonic solution would be appreciated.


问:
Adding dollar sign in front of variable name in arguments of Powershell script
I am working on pipeline where I am passing arguments in the powershell script as below. I want to append ServiceName and Environment.Name with a $ sign.

arguments: '-ServiceDisplayName "$(ServiceDisplayName)" -ServiceName
"$(ServiceName)$(Environment.Name)" -ServiceDirectory
"$(ServiceFolder)" -UserName "$(ServiceUserAccount)"'

Tried -ServiceName "$(ServiceName)`$$(Environment.Name)"


问:
How to create a Keycloak user using the keycloak admin api with only a phone number?
I'm trying to develop a mobile application where users can register by entering only their phone number. The client application is a native iOS Application which communicates with a Spring Boot backend via REST.

I already implemented a Spring Boot backend as ressource server and a keycloak instance as authorization server.

Registering users by using their username/password combination already works perfectly fine but i can't figure out how to create a user with only the phone number as username and password both are required.

I have already found out how to add a phone number as attribute to the user. So my minimal create user request body becomes this:

```<code>{
    "username": "Test",
    "credentials": [{
        "type": "password",
        "value": "testpwd"
    }],
    "enabled" : true,
    "attributes": {
        "phoneNumber": "123456"
    }
}
</code>```

The phone number also appears in the access token because I already added it in the client scope.
The decoded access token looks like this:

```<code>...
  "scope": "phone",
  "phone_number": "123456"
</code>```

Body:
I'm trying to develop a mobile application where users can register by entering only their phone number. The client application is a native iOS Application which communicates with a Spring Boot backend via REST.

I already implemented a Spring Boot backend as ressource server and a keycloak instance as authorization server.

Registering users by using their username/password combination already works perfectly fine but i can't figure out how to create a user with only the phone number as username and password both are required.

I have already found out how to add a phone number as attribute to the user. So my minimal create user request body becomes this:

{
    "username": "Test",
    "credentials": [{
        "type": "password",
        "value": "testpwd"
    }],
    "enabled" : true,
    "attributes": {
        "phoneNumber": "123456"
    }
}

The phone number also appears in the access token because I already added it in the client scope.
The decoded access token looks like this:

...
  "scope": "phone",
  "phone_number": "123456"


问:
FastAPI and Pydantic - Can't get JSON returned due to validation errors
I'm trying to run FastAPI to query a database when given URL params for id, first name, and last name. The items in the database have multiple attributes in addition to the ones that need to be queried. This is what I have so far:

database.py: (the actual code has proper names and not user[x])

```<code>import os
from sqlalchemy import MetaData, Table, Integer, Column, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

host = "localhost"
user = "postgres"
databaseName = "postgres"
password = "password"
dbtype = "postgresql"

DATABASE_PATH = f"{dbtype}://{user}:{password }@{host}/{databaseName}"

engine = create_engine(DATABASE_PATH)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

meta = MetaData()
users = Table(
    'users', meta,
    Column('id', Integer, primary_key = True),
    Column('username', String),
    Column('first_name', String),
    Column('last_name', String),
    Column('email', String),
    Column('phone_number', String),)
meta.create_all(engine)

engine.execute('''DELETE FROM users''')

engine.execute(users.insert(), id=1, username='user1', first_name='user1',
    last_name='user1', email='user1@gmail.com', phone_number='(123)-456-7890');
engine.execute(users.insert(), id=2, username='user2', first_name='user2',
    last_name='user2', email='user2@gmail.com', phone_number='(223)-456-7890');
engine.execute(users.insert(), id=3, username='user3', first_name='user3',
    last_name='user3', email='user3@gmail.com', phone_number='(323)-456-7890');
engine.execute(users.insert(), id=4, username='user4', first_name='user4',
    last_name='user4', email='user4@gmail.com', phone_number='(423)-456-7890');
</code>```

models.py:

```<code>from sqlalchemy import MetaData, Table, Integer, Column, String, create_engine
from .database import engine, Base
from typing import TypedDict

meta = MetaData()

class UserDict(TypedDict):
    id: int
    username: str
    first_name: str
    last_name: str
    email: str
    phone_number: str
    class Config:
        orm_mode=True

class UsersClass(Base):

    __tablename__ = "users"

    id = Column(Integer, primary_key = True)
    username = Column(String)
    first_name = Column(String)
    last_name = Column(String)
    email = Column(String)
    phone_number = Column(String)

    def __init__(self, id: int, username: str, first_name: str, last_name: str, email:str, phone_number:str):
        self.id = id
        self.username = username
        self.first_name = first_name
        self.last_name = last_name
        self.email = email

    def __repr__(self) -> str:
        return f"<UsersClass {self.name}>"

    def serialize(self) -> UserDict:
        return {"id": self.id, "username": self.username, "first_name": self.first_name,
            "last_name": self.last_name, "email": self.email, "phone_number": self.phone_number}

</code>```

crud.py:

```<code>from sqlalchemy.orm import Session
from .models import UsersClass

def getUserByName(session: Session, name: str) -> UsersClass:
    return session.query(UsersClass).filter(UsersClass.first_name == name or UsersClass.last_name == name)

def getUserByNames(session: Session, first_name: str, last_name: str) -> UsersClass:
    return session.query(UsersClass).filter(UsersClass.first_name == first_name and UsersClass.last_name == last_name)

def getUserByID(session:Session, id:int) -> UsersClass:
    return session.query(UsersClass).filter(UsersClass.id == id)

def getUserByIDAndName(session: Session, id:int, name:str) -> UsersClass:
    return session.query(UsersClass).filter(UsersClass.id == id and (UsersClass.first_name == name or UsersClass.last_name == name))

def getUserByIDAndNames(session: Session, id:int, first_name:str, last_name:str) -> UsersClass:
    return session.query(UsersClass).filter(UsersClass.id == id and UsersClass.first_name == name and UsersClass.last_name == name)
</code>```

schemas.py:

```<code>from pydantic import BaseModel
from typing import Union

class UsersBase(BaseModel):
    id: Union[int, None]
    username: Union[str, None]
    first_name: Union[str, None]
    last_name: Union[str, None]
    email: Union[str, None]
    phone_number: Union[str, None]

</code>```

routers.py:

```<code>from typing import List, Union
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from . import crud, models
from .database import SessionLocal, engine
from .schemas import UsersBase

#models.Base.metadata.create_all(bind=engine)
userrouter = APIRouter()

def get_session():
    session = SessionLocal()
    try:
        yield session
    finally:
        session.close()

@userrouter.get("/people/", response_model=UsersBase)
async def read_query(
    id: Union[int, None] = None, first_name: Union[str, None] = None,
    last_name:Union[str, None] = None, session: Session = Depends(get_session)):

    if(id and not first_name and not last_name):
        userToReturn = crud.getUserByID(session=session, id=id)
        if userToReturn is None:
            raise HTTPException(status_code=404, detail = "Item not found")
        return userToReturn

    elif (id and first_name and not last_name):
        userToReturn = crud.getUserByIDAndName(session=session, id=id, first_name=first_name)
        if userToReturn is None:
            raise HTTPException(status_code=404, detail = "Item not found")
        return userToReturn.serialize

    elif(id and first_name and last_name):
        userToReturn = crud.getUserByIDAndNames(session=session, id=id, first_name=first_name, last_name=last_name)
        if userToReturn is None:
            raise HTTPException(status_code=404, detail = "Item not found")
        return userToReturn.serialize

    elif(not id and first_name and not last_name):
        userToReturn = crud.getUserByName(session=session, name=first_name)
        if userToReturn is None:
            raise HTTPException(status_code=404, detail = "Item not found")
        return userToReturn.serialize

    elif(not id and first_name and last_name):
        userToReturn = crud.getUserByNames(session=session, first_name=first_name, last_name=last_name)
        if userToReturn is None:
            raise HTTPException(status_code=404, detail = "Item not found")
        return userToReturn.serialize

    userToReturn = {"id": id, "first_name" : first_name, "last_name" : last_name}
    return userToReturn
</code>```

main.py

```<code>from fastapi import FastAPI
from .routers import userrouter

app = FastAPI()
app.include_router(userrouter)

@app.get("/")
async def root():
    return{"message": "main page"}
</code>```

When the user has the uvicorn server up they should be able to go to something like "localhost/people/?first_name=Jane&last_name=Doe" and retrieve a JSON result. It needs to be able to query by id, first name, last name, and any combination of those 3.

I've been error-chasing all morning but my most recent is

```<code>pydantic.error_wrappers.ValidationError: 1 validation error for UsersBase
response
  value is not a valid dict (type=type_error.dict)
</code>```

I've verified the database is up and running and storing the data properly

It's probably clear this is my first time doing something like this lol. I followed this tutorial and changed it to fit my requirements. It feels like it's almost there, I just keep getting internal server errors. Please help!

Body:
I'm trying to run FastAPI to query a database when given URL params for id, first name, and last name. The items in the database have multiple attributes in addition to the ones that need to be queried. This is what I have so far:

database.py: (the actual code has proper names and not user[x])

import os
from sqlalchemy import MetaData, Table, Integer, Column, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

host = "localhost"
user = "postgres"
databaseName = "postgres"
password = "password"
dbtype = "postgresql"

DATABASE_PATH = f"{dbtype}://{user}:{password }@{host}/{databaseName}"

engine = create_engine(DATABASE_PATH)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

meta = MetaData()
users = Table(
    'users', meta,
    Column('id', Integer, primary_key = True),
    Column('username', String),
    Column('first_name', String),
    Column('last_name', String),
    Column('email', String),
    Column('phone_number', String),)
meta.create_all(engine)

engine.execute('''DELETE FROM users''')

engine.execute(users.insert(), id=1, username='user1', first_name='user1',
    last_name='user1', email='user1@gmail.com', phone_number='(123)-456-7890');
engine.execute(users.insert(), id=2, username='user2', first_name='user2',
    last_name='user2', email='user2@gmail.com', phone_number='(223)-456-7890');
engine.execute(users.insert(), id=3, username='user3', first_name='user3',
    last_name='user3', email='user3@gmail.com', phone_number='(323)-456-7890');
engine.execute(users.insert(), id=4, username='user4', first_name='user4',
    last_name='user4', email='user4@gmail.com', phone_number='(423)-456-7890');

models.py:

from sqlalchemy import MetaData, Table, Integer, Column, String, create_engine
from .database import engine, Base
from typing import TypedDict

meta = MetaData()

class UserDict(TypedDict):
    id: int
    username: str
    first_name: str
    last_name: str
    email: str
    phone_number: str
    class Config:
        orm_mode=True

class UsersClass(Base):

    __tablename__ = "users"

    id = Column(Integer, primary_key = True)
    username = Column(String)
    first_name = Column(String)
    last_name = Column(String)
    email = Column(String)
    phone_number = Column(String)

    def __init__(self, id: int, username: str, first_name: str, last_name: str, email:str, phone_number:str):
        self.id = id
        self.username = username
        self.first_name = first_name
        self.last_name = last_name
        self.email = email

    def __repr__(self) -> str:
        return f"<UsersClass {self.name}>"

    def serialize(self) -> UserDict:
        return {"id": self.id, "username": self.username, "first_name": self.first_name,
            "last_name": self.last_name, "email": self.email, "phone_number": self.phone_number}

crud.py:

from sqlalchemy.orm import Session
from .models import UsersClass

def getUserByName(session: Session, name: str) -> UsersClass:
    return session.query(UsersClass).filter(UsersClass.first_name == name or UsersClass.last_name == name)

def getUserByNames(session: Session, first_name: str, last_name: str) -> UsersClass:
    return session.query(UsersClass).filter(UsersClass.first_name == first_name and UsersClass.last_name == last_name)

def getUserByID(session:Session, id:int) -> UsersClass:
    return session.query(UsersClass).filter(UsersClass.id == id)

def getUserByIDAndName(session: Session, id:int, name:str) -> UsersClass:
    return session.query(UsersClass).filter(UsersClass.id == id and (UsersClass.first_name == name or UsersClass.last_name == name))

def getUserByIDAndNames(session: Session, id:int, first_name:str, last_name:str) -> UsersClass:
    return session.query(UsersClass).filter(UsersClass.id == id and UsersClass.first_name == name and UsersClass.last_name == name)

schemas.py:

from pydantic import BaseModel
from typing import Union

class UsersBase(BaseModel):
    id: Union[int, None]
    username: Union[str, None]
    first_name: Union[str, None]
    last_name: Union[str, None]
    email: Union[str, None]
    phone_number: Union[str, None]

routers.py:

from typing import List, Union
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from . import crud, models
from .database import SessionLocal, engine
from .schemas import UsersBase

#models.Base.metadata.create_all(bind=engine)
userrouter = APIRouter()

def get_session():
    session = SessionLocal()
    try:
        yield session
    finally:
        session.close()

@userrouter.get("/people/", response_model=UsersBase)
async def read_query(
    id: Union[int, None] = None, first_name: Union[str, None] = None,
    last_name:Union[str, None] = None, session: Session = Depends(get_session)):

    if(id and not first_name and not last_name):
        userToReturn = crud.getUserByID(session=session, id=id)
        if userToReturn is None:
            raise HTTPException(status_code=404, detail = "Item not found")
        return userToReturn

    elif (id and first_name and not last_name):
        userToReturn = crud.getUserByIDAndName(session=session, id=id, first_name=first_name)
        if userToReturn is None:
            raise HTTPException(status_code=404, detail = "Item not found")
        return userToReturn.serialize

    elif(id and first_name and last_name):
        userToReturn = crud.getUserByIDAndNames(session=session, id=id, first_name=first_name, last_name=last_name)
        if userToReturn is None:
            raise HTTPException(status_code=404, detail = "Item not found")
        return userToReturn.serialize

    elif(not id and first_name and not last_name):
        userToReturn = crud.getUserByName(session=session, name=first_name)
        if userToReturn is None:
            raise HTTPException(status_code=404, detail = "Item not found")
        return userToReturn.serialize

    elif(not id and first_name and last_name):
        userToReturn = crud.getUserByNames(session=session, first_name=first_name, last_name=last_name)
        if userToReturn is None:
            raise HTTPException(status_code=404, detail = "Item not found")
        return userToReturn.serialize

    userToReturn = {"id": id, "first_name" : first_name, "last_name" : last_name}
    return userToReturn

main.py

from fastapi import FastAPI
from .routers import userrouter

app = FastAPI()
app.include_router(userrouter)

@app.get("/")
async def root():
    return{"message": "main page"}

When the user has the uvicorn server up they should be able to go to something like "localhost/people/?first_name=Jane&last_name=Doe" and retrieve a JSON result. It needs to be able to query by id, first name, last name, and any combination of those 3.

I've been error-chasing all morning but my most recent is

pydantic.error_wrappers.ValidationError: 1 validation error for UsersBase
response
  value is not a valid dict (type=type_error.dict)

I've verified the database is up and running and storing the data properly

It's probably clear this is my first time doing something like this lol. I followed this tutorial and changed it to fit my requirements. It feels like it's almost there, I just keep getting internal server errors. Please help!


问:
Writing 3D array in c++ and reading with numpy (without using reshape)
I'm debugging some volumetric data in c++ and would like to visualise it.

Say I have a double array in c++, how can I write it as a binary file and read it from numpy as a 3D array? I'd like to stick to the standard c++ library.

```<code>double myArr[1000];
// ...Set values of myArr

std::ofstream outFile;
std::open("myfile.bin");
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        for (int k = 0; k < 10; k++) {
            outFile << myArr[k + j*10 + i*100];
        }
        outFile << "some way to declare the next slice";
    }
    outFile << "some way to declare the next slice";
}
outFile.close();
</code>```

In python I would like to read this array like this so it would appear as a 3D array:

```<code>numpy.fromfile("myfile.bin", dtype=np.float)
</code>```

I read this Writing binary in c++ and read in python which works for 1d int but not sure how to create 3D double. ie. what do I need to write to the array to tell it to shift by 1 along each dimension? I don't want to use numpy to reshape the array as the dimension output by c++ can vary.

Body:
I'm debugging some volumetric data in c++ and would like to visualise it.

Say I have a double array in c++, how can I write it as a binary file and read it from numpy as a 3D array? I'd like to stick to the standard c++ library.

double myArr[1000];
// ...Set values of myArr

std::ofstream outFile;
std::open("myfile.bin");
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        for (int k = 0; k < 10; k++) {
            outFile << myArr[k + j*10 + i*100];
        }
        outFile << "some way to declare the next slice";
    }
    outFile << "some way to declare the next slice";
}
outFile.close();

In python I would like to read this array like this so it would appear as a 3D array:

numpy.fromfile("myfile.bin", dtype=np.float)

I read this Writing binary in c++ and read in python which works for 1d int but not sure how to create 3D double. ie. what do I need to write to the array to tell it to shift by 1 along each dimension? I don't want to use numpy to reshape the array as the dimension output by c++ can vary.


问:
How to disable scroll-based lazy loading of thumbnails on youtube?
I hate this feature, I'm using firefox and I wish it to be gone. Userscript, addon, anything.

The code has:


问:
How many comparisons required by following algorithms to arrange the A array in decreasingorder? Insertion sort, Quick sort, Selection sort, Heap Sort
Suppose you are given an array A of 'n' integers in increasing order. How many comparisons required by the following algorithms to arrange the A array in decreasing order? Insertion sort, Quick sort, Selection sort, Heap Sort.

I was just thinking that insertion sort can not be done because it arranges the elements in increase order.

HELP ME SENPAI:-(


问:
R matrix transpose (2 into 1 column) many separate files and merge into one .csv
I have ~217 identical .csv files in a folder, each represents one individual, and has 2 columns (header: x, y) and 180 rows of data.

I need to transpose these into a single row (new headers:  x1:x180, continued into y1:y180), create an ID column with an abbreviated file name, and merge the separate files into one data frame of 217 rows and an ID columns, and 360 columns of data.

Here's example data from separate .csv files in the same folder, truncated to the first 6 rows:

```<code>#dataA_observer_date
          x          y
1 -2.100343 -0.2601952
2 -2.128320 -0.2805480
3 -2.152010 -0.3000733
4 -2.168258 -0.3170724
5 -2.174368 -0.3305717
6 -2.168887 -0.3403942
</code>```
```<code>#dataB_observer_date
          x          y
1 0.7577988 -0.1212715
2 0.7256039 -0.1344822
3 0.6933261 -0.1496408
4 0.6638619 -0.1657460
5 0.6409363 -0.1815894
6 0.6281463 -0.1960087
</code>```

I need the data to look like this, in one file:

```<code>head(dataA)
ID          [x1]     [x2]     [x3]      [x4]      [x5]      [x6]       [y1]      [y2]       [y3]       [y4]       [y5]       [y6]
dataA  -2.100343 -2.12832 -2.15201 -2.168258 -2.174368 -2.168887 -0.2601952 -0.280548 -0.3000733 -0.3170724 -0.3305717 -0.3403942

dataB
dataC...
...data217
</code>```

for transposing, I tried the following, which results in a different column ordersince it works by row through the 180 rows:

```<code>t_Image1 <- matrix(t(Image1Coords), nrow = 1)

x1    y1    x2   y2...
</code>```

I have the file names from the folder in a list using other help from https://stackoverflow.com/questions/31039269/combine-and-transpose-many-fixed-format-dataset-files-quickly

```<code>filenames <- list.files(path = "C:/Users/path_to_folder", pattern = "*.csv", full.names = FALSE)
require(data.table)
data_list <- lapply(filenames,read.csv)
</code>```

But I can't get it to come together. So far, with help from https://stackoverflow.com/questions/21530672/in-r-loop-through-matrix-files-transpose-and-save-with-new-name and several other places, to just transpose the files and resave them to be combined in another step:  But the exported file is hideous.  The matrix transpose into one row retains quotes and puts 2 data points in one cell, and I'm not sure what its doing as headers, but its all in the first cell

```<code>for (i in filenames) {
  mat <- matrix(t(read_table(i, col_names = TRUE, skip_empty_rows = TRUE)), nrow = 1)
  mat$ID <- tools::file_path_sans_ext(basename(filename))
  filename <- paste0("transposed_", i)
  write.table(mat, file = filename)
}
</code>```

I have not addressed shortening the file names and making an ID column yet.

Any help/advice would be greatly appreciated.

Body:
I have ~217 identical .csv files in a folder, each represents one individual, and has 2 columns (header: x, y) and 180 rows of data.

I need to transpose these into a single row (new headers:  x1:x180, continued into y1:y180), create an ID column with an abbreviated file name, and merge the separate files into one data frame of 217 rows and an ID columns, and 360 columns of data.

Here's example data from separate .csv files in the same folder, truncated to the first 6 rows:

#dataA_observer_date
          x          y
1 -2.100343 -0.2601952
2 -2.128320 -0.2805480
3 -2.152010 -0.3000733
4 -2.168258 -0.3170724
5 -2.174368 -0.3305717
6 -2.168887 -0.3403942

#dataB_observer_date
          x          y
1 0.7577988 -0.1212715
2 0.7256039 -0.1344822
3 0.6933261 -0.1496408
4 0.6638619 -0.1657460
5 0.6409363 -0.1815894
6 0.6281463 -0.1960087

I need the data to look like this, in one file:

head(dataA)
ID          [x1]     [x2]     [x3]      [x4]      [x5]      [x6]       [y1]      [y2]       [y3]       [y4]       [y5]       [y6]
dataA  -2.100343 -2.12832 -2.15201 -2.168258 -2.174368 -2.168887 -0.2601952 -0.280548 -0.3000733 -0.3170724 -0.3305717 -0.3403942

dataB
dataC...
...data217

for transposing, I tried the following, which results in a different column ordersince it works by row through the 180 rows:

t_Image1 <- matrix(t(Image1Coords), nrow = 1)

x1    y1    x2   y2...

I have the file names from the folder in a list using other help from https://stackoverflow.com/questions/31039269/combine-and-transpose-many-fixed-format-dataset-files-quickly

filenames <- list.files(path = "C:/Users/path_to_folder", pattern = "*.csv", full.names = FALSE)
require(data.table)
data_list <- lapply(filenames,read.csv)

But I can't get it to come together. So far, with help from https://stackoverflow.com/questions/21530672/in-r-loop-through-matrix-files-transpose-and-save-with-new-name and several other places, to just transpose the files and resave them to be combined in another step:  But the exported file is hideous.  The matrix transpose into one row retains quotes and puts 2 data points in one cell, and I'm not sure what its doing as headers, but its all in the first cell

for (i in filenames) {
  mat <- matrix(t(read_table(i, col_names = TRUE, skip_empty_rows = TRUE)), nrow = 1)
  mat$ID <- tools::file_path_sans_ext(basename(filename))
  filename <- paste0("transposed_", i)
  write.table(mat, file = filename)
}

I have not addressed shortening the file names and making an ID column yet.

Any help/advice would be greatly appreciated.


问:
Why do i need to input two times for the input to be recognized?
I have made a substring function that uses pointers, and I cannot get the input for inputString unless I input a string two times. Here is my code:

#include <stdio.h>
#include <string.h>

int sub_strings( const char* str1, const char* str2){
    int a = 0;
    const char* temp = str1;
    while (temp = strstr(temp, str2)){
        a++;
        temp++;
    }
    return a;

}

int main(){
    char inString[20];
    char outString[20];

    printf("Please Enter A String (no space)\n");
    scanf("%s\n", inString);
    printf("Please enter a substring\n");
    scanf("%s\n", outString);

    printf("%d", sub_strings(inString,outString));

    return 0;
}
```

Is it a problem with the pointers? Thanks for your help!

Body:
I have made a substring function that uses pointers, and I cannot get the input for inputString unless I input a string two times. Here is my code:

#include <stdio.h>
#include <string.h>

int sub_strings( const char* str1, const char* str2){
    int a = 0;
    const char* temp = str1;
    while (temp = strstr(temp, str2)){
        a++;
        temp++;
    }
    return a;

}

int main(){
    char inString[20];
    char outString[20];

    printf("Please Enter A String (no space)\n");
    scanf("%s\n", inString);
    printf("Please enter a substring\n");
    scanf("%s\n", outString);

    printf("%d", sub_strings(inString,outString));

    return 0;
}

Is it a problem with the pointers? Thanks for your help!


问:
Flutter/Dart: how to make text be hoverable when exceeding the width of its container
I have this list of artists and i put as subtitle the subgenres of the artist:

I would like that the extra part of the subtitle to be hoverable as [techno, rap ... and have the whole list shown only when hovering with the mouse at the subtitle.

Here is the list creation part

```<code>          Container(
            height: height,
            child: _foundUsers.isNotEmpty
                ? ListView.builder(
                    itemCount: _foundUsers.length,
                    itemBuilder: (context, index) => Card(
                        key: ValueKey(_foundUsers[index]["name"]),
                        color: Colors.blue,
                        // elevation: 1,
                        margin: const EdgeInsets.symmetric(vertical: 5.0),
                        child: Container(
                          height: height / _cardsPerScreen - 10,
                          child: _foundUsers.isNotEmpty
                              ? SingleChildScrollView(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      ListTile(
                                        leading: Text(
                                          _foundUsers[index]["id"].toString(),
                                          style: const TextStyle(
                                              fontSize: 24,
                                              color: Colors.white),
                                        ),
                                        title: Text(
                                            _foundUsers[index]['artist'].name,
                                            style:
                                                TextStyle(color: Colors.white)),
                                        subtitle: Text(
                                            '${_foundUsers[index]["artist"].subgenres.toString()}',
                                            style:
                                                TextStyle(color: Colors.white)),
                                      ),
                                    ],
                                  ),
                                )
                              : Container(),
                        )),
                  )
                : const Text(
                    'No results found',
                    style: TextStyle(fontSize: 24),
                  ),
          ),
</code>```

Body:
I have this list of artists and i put as subtitle the subgenres of the artist:

I would like that the extra part of the subtitle to be hoverable as [techno, rap ... and have the whole list shown only when hovering with the mouse at the subtitle.

Here is the list creation part

          Container(
            height: height,
            child: _foundUsers.isNotEmpty
                ? ListView.builder(
                    itemCount: _foundUsers.length,
                    itemBuilder: (context, index) => Card(
                        key: ValueKey(_foundUsers[index]["name"]),
                        color: Colors.blue,
                        // elevation: 1,
                        margin: const EdgeInsets.symmetric(vertical: 5.0),
                        child: Container(
                          height: height / _cardsPerScreen - 10,
                          child: _foundUsers.isNotEmpty
                              ? SingleChildScrollView(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      ListTile(
                                        leading: Text(
                                          _foundUsers[index]["id"].toString(),
                                          style: const TextStyle(
                                              fontSize: 24,
                                              color: Colors.white),
                                        ),
                                        title: Text(
                                            _foundUsers[index]['artist'].name,
                                            style:
                                                TextStyle(color: Colors.white)),
                                        subtitle: Text(
                                            '${_foundUsers[index]["artist"].subgenres.toString()}',
                                            style:
                                                TextStyle(color: Colors.white)),
                                      ),
                                    ],
                                  ),
                                )
                              : Container(),
                        )),
                  )
                : const Text(
                    'No results found',
                    style: TextStyle(fontSize: 24),
                  ),
          ),


问:
MySQL database values change lonely when I refresh my file in browser
I created a page allowing persons to click a button and it should change values within a database. However, when I refresh my php file in a browser, the values that were in the database suddenly change by themselves, without having to click that button. I'm new to coding and it frustrates me.

Here's the issue :

The code in the file named collection1.php

```<code><?php session_start();?>
<!doctype html>
<html>
        <title>
            Coming soon!
        </title>
        <meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="forme set.css">
        <script src="outter.js"></script>
    <head>
    </head>
    <body>
        <div>
            <button id="button1" class="button1" onclick="<?php
    $link=mysqli_connect("localhost", "root", "", "database");
    if(!isset($_SESSION['username'])){
        echo "linkerror()";
    } else {
        $username=$_SESSION['username'];
        $cardid="plot32";
        $already=mysqli_query($link, "SELECT cardid FROM cardscollection WHERE '".$cardid."' IN (cardid) AND '".$username."' IN (username)");
        if($already->num_rows!==0){
            $removeit=mysqli_query($link, "DELETE FROM cardscollection WHERE username='".$username."' AND cardid='".$cardid."'");
            $removecard=mysqli_query($link, "UPDATE accounts SET nbcards = nbcards - 1 WHERE username='".$username."'");
        } else {
            $addit=mysqli_query($link, "INSERT INTO cardscollection (username, cardid, series, subseries) VALUES ('".$username."', '".$cardid."', 'World Tourney', 'Tourney 2.2')");
            $addcard=mysqli_query($link, "UPDATE accounts SET nbcards = nbcards + 1 WHERE username='".$username."'");
        }
    }
?>"></button>
        </div>
   </body>
</code>```

The database tables look like this :

Table 'accounts'

username
nbcards

username1
1

Table 'cards collection'

username
cardid
series
subseries

username1
plot32
World Tourney
Tourney 2.2

Let's imagine I am username1 and click on that button. If the concerned values already are in the database, it should change the appropriate values right?
But if I refresh the php file in my browser to refresh the code I am working on (here localhost/collection1.php), the database will change to this by itself, without me clicking on the button :

Table 'accounts'

username
nbcards

username1
0

Table 'cards collection'

username
cardid
series
subseries

I probably misunderstand some php/sql exchanges as I have no idea why it occurs, knowing another account registering page works fine the same way.
Any help is appreciated, thanks!

No idea why it happens..

Body:
I created a page allowing persons to click a button and it should change values within a database. However, when I refresh my php file in a browser, the values that were in the database suddenly change by themselves, without having to click that button. I'm new to coding and it frustrates me.

Here's the issue :

The code in the file named collection1.php

<?php session_start();?>
<!doctype html>

        <title>
            Coming soon!
        </title>
        <meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="forme set.css">

            <button id="button1" class="button1" onclick="<?php
    $link=mysqli_connect("localhost", "root", "", "database");
    if(!isset($_SESSION['username'])){
        echo "linkerror()";
    } else {
        $username=$_SESSION['username'];
        $cardid="plot32";
        $already=mysqli_query($link, "SELECT cardid FROM cardscollection WHERE '".$cardid."' IN (cardid) AND '".$username."' IN (username)");
        if($already->num_rows!==0){
            $removeit=mysqli_query($link, "DELETE FROM cardscollection WHERE username='".$username."' AND cardid='".$cardid."'");
            $removecard=mysqli_query($link, "UPDATE accounts SET nbcards = nbcards - 1 WHERE username='".$username."'");
        } else {
            $addit=mysqli_query($link, "INSERT INTO cardscollection (username, cardid, series, subseries) VALUES ('".$username."', '".$cardid."', 'World Tourney', 'Tourney 2.2')");
            $addcard=mysqli_query($link, "UPDATE accounts SET nbcards = nbcards + 1 WHERE username='".$username."'");
        }
    }
?>"></button>

The database tables look like this :

Table 'accounts'

username
nbcards

username1
1

Table 'cards collection'

username
cardid
series
subseries

username1
plot32
World Tourney
Tourney 2.2

Let's imagine I am username1 and click on that button. If the concerned values already are in the database, it should change the appropriate values right?
But if I refresh the php file in my browser to refresh the code I am working on (here localhost/collection1.php), the database will change to this by itself, without me clicking on the button :

Table 'accounts'

username
nbcards

username1
0

Table 'cards collection'

username
cardid
series
subseries

I probably misunderstand some php/sql exchanges as I have no idea why it occurs, knowing another account registering page works fine the same way.
Any help is appreciated, thanks!

No idea why it happens..


问:
Div between text element characters
`I have a text element that is built when the user clicks a button. In the middle of that text, I want to add an input element but I could not find a way.
I actually made a lot of things but here are the important ones So, First I made an input element and a button when the user enter input and click the button what he wrote will be displayed in a h1 element with a random missing word I want to make an input element and I want it to be in the same place that the missing word should've been in.

```<code>    function myFunction() {
        var x = document.getElementById("input").value;
        var y=document.getElementById("inputed");
        x=x.substr(0, c)+x.substr(d, x.length);
//I want an input element to be between the charAt(c) and charAt(d) //this input element is t
        const t = document.createElement("input");
        document.body.appendChild(t);
        t.style.display="inline-block";
        t.style.color="gray";
        t.style.border= "2px solid";
        t.style.borderColor= "gray";
        t.style.borderRadius= "10px";
        t.style.outline= "none";
        t.style.fontSize= "x-large";
        t.style.height= "40px";
        t.style.width= "100px";
        y.innerHTML=x;
    }
</code>```

That is all!I will be extremly happy if someone helps me.

Title: Div between text element characters

Body:
`I have a text element that is built when the user clicks a button. In the middle of that text, I want to add an input element but I could not find a way.
I actually made a lot of things but here are the important ones So, First I made an input element and a button when the user enter input and click the button what he wrote will be displayed in a h1 element with a random missing word I want to make an input element and I want it to be in the same place that the missing word should've been in.

    function myFunction() {
        var x = document.getElementById("input").value;
        var y=document.getElementById("inputed");
        x=x.substr(0, c)+x.substr(d, x.length);
//I want an input element to be between the charAt(c) and charAt(d) //this input element is t
        const t = document.createElement("input");
        document.body.appendChild(t);
        t.style.display="inline-block";
        t.style.color="gray";
        t.style.border= "2px solid";
        t.style.borderColor= "gray";
        t.style.borderRadius= "10px";
        t.style.outline= "none";
        t.style.fontSize= "x-large";
        t.style.height= "40px";
        t.style.width= "100px";
        y.innerHTML=x;
    }

That is all!I will be extremly happy if someone helps me.


问:
How to validate a Youtube video & playlist url until they completely match or has a redirect to the video or playlist in Python?
I'm working on a small Youtube video & playlist downloader. However currently I'm facing a problem where I cannot validate the Youtube URL.

I bind "ReleaseKey" on the entrybox so everytime a user type, it checks if the url is valid or not and returns true or false. Here is how I implement the check:

```<code>req = requests.get(self.yt_url_string, allow_redirects=False)
if req.status_code == 200:
   print("True")
   return True
print("False")
return False
</code>```

This check is kind of working fine if the user completely paste an actual valid url, however  if the user pastes half of the link like this uncomplete link example it will still return true, then when the condition returns true it goes to pytube function which is
YouTube(url_from_the_user) and shows an error exception.

Is there any solution to validate the url or any other method to prevent from getting error exception message?

Body:
I'm working on a small Youtube video & playlist downloader. However currently I'm facing a problem where I cannot validate the Youtube URL.

I bind "ReleaseKey" on the entrybox so everytime a user type, it checks if the url is valid or not and returns true or false. Here is how I implement the check:

req = requests.get(self.yt_url_string, allow_redirects=False)
if req.status_code == 200:
   print("True")
   return True
print("False")
return False

This check is kind of working fine if the user completely paste an actual valid url, however  if the user pastes half of the link like this uncomplete link example it will still return true, then when the condition returns true it goes to pytube function which is
YouTube(url_from_the_user) and shows an error exception.

Is there any solution to validate the url or any other method to prevent from getting error exception message?