instruction
stringlengths
0
30k
Single loop and `break`-free version. ``` import random print('Welcome to the Higher or Lower game!') are_boundaries_fixed = False is_guessed = False while not (is_guessed and are_boundaries_fixed): if not are_boundaries_fixed: lowr = int(input('What would you like for your lower bound to be?: ')) upr = int(input('And your highest?: ')) if lowr >= upr: print('The lowest bound must not be higher than highest bound. Try again.') else: are_boundaries_fixed = True x = random.randint(lowr, upr) g = int(input(f'Great now guess a number between {lowr} and {upr}:')) else: if g > x: g = int(input('Nope. Too high, Guess another number: ')) elif g < x: g = int(input('Nope. Too small, Guess another number: ')) else: is_guessed = True print('You got it!') ``` Notice that `input` accepts a single parameter, the text to be displayed on the screen. So, `'Great now guess a number between', lowr, 'and', upr, ':'` will raise an error, use instead string formatting, for ex f-string.
If you create the plot in two steps, you can definitely retrieve the x aesthetic from the aesthetic object. One option is to create the aesthetic object first, then generate the plot and retrieve the x aesthetic from the aes object: my_aes<-aes( x = xval, y = after_stat(density) ) ggplot(data = df) + geom_histogram(mapping=my_aes, bins=bin_number(df[,as_label(my_aes$x)])) Another option is to map the aesthetics inside ggplot(), and again retrieve the x aesthetic when adding the geom_histogram layer: p<-ggplot(data=df, aes(x=xval, y=after_stat(density))) p+geom_histogram(bins=bin_number(df[,as_label(p$mapping$x)]))
``` import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Horizontal Buttons'), ), body: Column( mainAxisSize: MainAxisSize.min, children: [ Expanded( child: Row( children: [ Expanded( child: GestureDetector( onTap: () { // Action for button 1 }, child: Container( padding: EdgeInsets.all(12), color: Colors.blue, child: Center( child: Text( 'Button 1 with long text to test the wrapping', style: TextStyle(color: Colors.white), ), ), ), ), ), SizedBox(width: 16), // Spacer between the buttons Expanded( child: GestureDetector( onTap: () { // Action for button 2 }, child: Container( padding: EdgeInsets.all(12), color: Colors.green, child: Center( child: Text( 'Button 2 with long text to test the wrapping', style: TextStyle(color: Colors.white), ), ), ), ), ), ], ), ), ], ), ), ); } } ``` I want to increase only size of button vertically to adjust according to length of content.The above code is occupying screen both horizontally and vertically. i want vertical height to be occupied according to length of the content.Can any one help me pelase,Thank you. i want vertical height to be occupied according to length of the content.Can any one help me pelase,Thank you.
How to have control over height of container when container inside expanded
|flutter|
null
This is the column part which i have declared. ``` { title: 'Tags', key: 'tags', dataIndex: 'tags', render: (_,{tags})=>{ <> {tags.map((tag)=>{ return( <Tag key={tag}>{tag}</Tag> ); })} </> } } ``` I have tried the code too that is given in antd official site. why this way doesn't work?
{"OriginalQuestionIds":[71470236],"Voters":[{"Id":17865804,"DisplayName":"Chris","BindingReason":{"GoldTagBadge":"fastapi"}}]}
It is recommended to rewrite the DTO with a constructor applying the required parameters. If rewriting is not possible, implement a custom denormalization tool.Following approach ensures strict validation during deserialization. final class SimpleDtoDenormalizer implements DenormalizerInterface { public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed { if (!is_array($data)) { throw new \InvalidArgumentException('Expected an array, got ' . get_debug_type($data)); } $dto = new SimpleDto(); $dto->name = $data['name'] ?? throw new \InvalidArgumentException('Missing "name"'); $dto->value = $data['value'] ?? throw new \InvalidArgumentException('Missing "value"'); return $dto; } // Other methods as per Symfony documentation }
Records in the materialized view that have already been materialized are not refreshed following changes to the dimension table. See more details in the [documentation][1]: `Records in the view's source table (the fact table) are materialized only once. Updates to the dimension tables don't have any impact on records that have already been processed from the fact table.` [1]: https://learn.microsoft.com/en-us/azure/data-explorer/kusto/management/materialized-views/materialized-view-create#query-parameter
I am trying to create a structure "Student" which contains q substructures named Course. Each Course is a structure with a credit and point int value. How do I set up my Student structure to have an integer number of Course structures within it? Thanks ``` struct Student{ int q; Course course[q]; }; struct Course{ int credit; int point; }; ``` ``` struct Student{ int q; Course course[q]; }; struct Course{ int credit; int point; }; ``` I tried this but VSC is telling me it is wrong.
Define array of structure within a structure in C++
|c++|struct|
null
``` * What went wrong: A problem occuremphasized textred configuring project ':cloud_firestore'. > Could not resolve all files for configuration ':cloud_firestore:classpath'. > Could not download builder-7.0.2.jar (com.android.tools.build:builder:7.0.2) > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/builder/7.0.2/builder-7.0.2.jar'. > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/builder/7.0.2/builder-7.0.2.jar'. > The server may not support the client's requested TLS protocol versions: (TLSv1.2, TLSv1.3). You may need to configure the client to allow other protocols to be used. See: https://docs.gradle.org/7.4/userguide/build_environment.html#gradle_system_properties > Remote host terminated the handshake > Failed to notify project evaluation listener. > Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project. > Could not find method implementation() for arguments [project ':firebase_core'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. > Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project. ``` I try to upgrade the dependencies flutter pub upgrade
The following: ``` interface IThing { virtual string A => "A"; } ``` Is the so called [default interface method][1] and virtual as far as I can see actually does nothing because: > The `virtual` modifier may be used on a function member that would otherwise be implicitly `virtual` I.e. it just an implicit declaration of the fact that method is virtual since the team decided to not restrict such things. See also the [Virtual Modifier vs Sealed Modifier][2] part of the spec: > Decisions: Made in the LDM 2017-04-05: > - non-`virtual` should be explicitly expressed through `sealed` or `private`. > - `sealed` is the keyword to make interface instance members with bodies non-`virtual` > - We want to allow all modifiers in interfaces > - ... Note that default implemented `IThing.A` is not part of the `Thing`, hence you can't do `new Thing().A`, you need to cast to the interface first. If you want to override the `IThing.A` in the `Thing2` then you can implement the interface directly (another way would be declaring `public virtual string A` in the `Thing` so your current code works): ``` class Thing2: Thing, IThing { public string A => "!"; } Console.WriteLine(((IThing)new Thing()).A); // Prints "A" Console.WriteLine(((IThing)new Thing2()).A); // Prints "!" ``` [1]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods [2]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods#virtual-modifier-vs-sealed-modifier
{"Voters":[{"Id":1959108,"DisplayName":"jyao"}]}
- After set formatting with `.Font.Bold = True`, `InsertAfter` inserts the text with the same format. ```vb Set wdDoc = wdApp.Documents.Add Set WordRange = wdDoc.Content Const TXT = "Severity: " With WordRange .Text = TXT & Sheets("CleanSheet").Cells(2, 2).Value & vbCr Dim iEnd As Long: iEnd = Len(TXT) wdDoc.Range(0, iEnd-1).Font.Bold = True End With ``` --- - If you prefer to use `Selection` ```vb Set wdDoc = wdApp.Documents.Add Const wdCollapseEnd = 0 With wdApp.Selection .Font.Bold = True .Typetext "Severity: " .Collapse wdCollapseEnd .Font.Bold = False .Typetext Sheets("CleanSheet").Cells(2, 2).Value & vbCr End With ``` _Microsoft documentation:_ > [Range.Collapse method (Word)](https://learn.microsoft.com/en-us/office/vba/api/word.range.collapse?WT.mc_id=M365-MVP-33461&f1url=%3FappId%3DDev11IDEF1%26l%3Den-US%26k%3Dk(vbawd10.chm157155429)%3Bk(TargetFrameworkMoniker-Office.Version%3Dv16)%26rd%3Dtrue) > [Selection.TypeText method (Word)](https://learn.microsoft.com/en-us/office/vba/api/word.selection.typetext?WT.mc_id=M365-MVP-33461&f1url=%3FappId%3DDev11IDEF1%26l%3Den-US%26k%3Dk(vbawd10.chm158663163)%3Bk(TargetFrameworkMoniker-Office.Version%3Dv16)%26rd%3Dtrue) > [Selection object (Word)](https://learn.microsoft.com/en-us/office/vba/api/word.selection?WT.mc_id=M365-MVP-33461&f1url=%3FappId%3DDev11IDEF1%26l%3Den-US%26k%3Dk(vbawd10.chm2421)%3Bk(TargetFrameworkMoniker-Office.Version%3Dv16)%26rd%3Dtrue)
For `getBytes`, use `as_uchar4`: ```c uchar4 values = as_uchar4(imageToInt[col+width*row]); ``` and for `ToInt32`, use `as_int`: ```c int newValue = as_int(values); ``` So your kernel should look something like this: ```c __kernel void gaussianBlur(__global int* imageToInt, int width, int height, __global double* blurBuffer, int blurBufferSize, __global int* outputBuffer) { int col = get_global_id(0); int row = get_global_id(1); int maskSize = 1; double sum = 0.0f; for(int a = -maskSize; a < maskSize + 1; a++) { // Collect neighbor values and multiply with gaussian for(int b = -maskSize; b < maskSize + 1; b++) { sum += blurBuffer[a+1+(b+1)*2*maskSize] * imageToInt[col+width*row]; } } uchar4 values = as_uchar4(imageToInt[col+width*row]); int alpha = (int)values.s3; int alphasum = alpha * (int)sum; values.s3 = (uchar)alphasum; int newValue = as_int(values); outputBuffer[col+width*row] = newValue; } ``` ------------- These `as_...` functions come built-in with OpenCL C, and enable you to reinterpret the bits that make up a number, as long as the total number of bits remains the same. In your case, an `int` is made up of 4 bytes, just like the `uchar4` vector data type. With `uchar4`, you can address the individual bytes with `.s1`, `.s1`, `.s2`, `.s3`, or with `.x`, `.y`, `.z`, `.w`. The `as_...` functions can also be used to get the individual bits of a `float` number for example: ```c float x = 1.0f; int bits = as_int(x); ``` In plain C, you can also manually write such a function: ```c uint as_int(const float x) { return *(int*)&x; } ``` --------- OpenCL C comes packed with math functionality, more than most other languages. All of the built-in functions are listed in [this super helpful reference card][1]. [1]: https://www.khronos.org/files/opencl-1-2-quick-reference-card.pdf
My code keeps working for a couple inputs and then ends citing a segmentation fault. I do not do any dynamic memory allocation. It's supposed to be a game of reversi (aka othello). The include lab8part1 contains the stdbool and declares some of the functions. ``` #include <stdio.h> #include <stdlib.h> #include "lab8part1.h" void printBoard(char board[][26], int n); bool positionInBounds(int n, int row, int col); bool checkLegalInDirection(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol); bool validMove(char board[][26], int n, int row, int col, char colour); bool computerMove(char board[][26], int n, char colour, char row, char col); bool UserMove(char board[][26], int n, char colour, char row, char col); int checkBestMoves(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol); bool checkifmove(char board[][26], int n, char color); int main(void) { char board[26][26], color, row, col; printf("Enter the board dimension: "); int n; scanf(" %d", &n); int start = n / 2; for (int m = 0; m < n; m++){ for (int j = 0; j < n; j++){ if ((m == start - 1 && j == start - 1) || (m == start && j == start)) { board[m][j] = 'W'; } else if ((m == start - 1 && j == start) || (m == start && j == start - 1)) { board[m][j] = 'B'; } else { board[m][j] = 'U'; } } } printf("Computer plays (B/W): "); scanf(" %c", &color); char color1; if (color == 'B'){ color1 = 'W'; } else{ color1 = 'B'; } printBoard(board, n); printf("\n"); char turn = 'B'; bool validmove = true; while ((checkifmove(board, n, color) == true) || (checkifmove(board, n, color1) == true)){ validmove = true; if (turn == color){ validmove = computerMove(board, n, color, row, col); } else{ UserMove(board, n, color1, row, col); } if (validmove == false){ break; } if (turn == 'W'){ turn = 'B'; } else{ turn = 'W'; } } int whitwin = 0; int blacwin = 0; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ if (board[i][j] == 'W'){ whitwin += 1; } else{ blacwin += 1; } } } if (whitwin > blacwin){ printf("W player wins."); } else if (whitwin < blacwin){ printf("B player wins."); } else{ printf("Draw."); } return 0; } bool computerMove(char board[][26], int n, char colour, char row, char col){ int movesrow[100] = {0}; int movescol[100] = {0}; int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'U') { if (checkLegalInDirection(board, n, i, j, colour, -1, -1)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, -1, 0)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, -1, 1)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 0, -1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 0, 1)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, -1)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, 0)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, 1)) { movesrow[count] = i; movescol[count] = j; } } } count += 1; } int bestMoves[600] = {0}; int tracker = 0; int tot = 0; for (int i = 0; i < count; i++){ if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, -1); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 0); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 1); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, -1); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, 1); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, -1); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 0); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 1); if (tot != 0){ bestMoves[tracker] = tot; } } } // if computer runs out of moves if (bestMoves[0] == 0){ printf("%c player has no valid move.", colour); return false; } int counter = 0; int bigNum = bestMoves[0]; int duplicates[tracker]; for (int i = 1; i < tracker; i++) { if (bestMoves[i] > bigNum) { bigNum = bestMoves[i]; duplicates[0] = i; counter = 1; } else if (bestMoves[i] == bigNum) { duplicates[counter] = i; counter++; } } int rowtemp = 0, coltemp = 0; for (int i = 0; i < counter; i++){ for (int j = 0; j < n; j++){ if ((movesrow[duplicates[i]] < movesrow[duplicates[i + j ]]) && movescol[duplicates[i]] < movescol[duplicates[ i + j]]){ rowtemp = movesrow[duplicates[i]]; coltemp = movescol[duplicates[i]]; } else{ rowtemp = movesrow[duplicates[i + j]]; coltemp = movescol[duplicates[i + j]]; } } } row = rowtemp; col = coltemp; if (validMove(board, n, (row), (col), colour)){ board[row][col] = colour; printf("\nComputer places %c at %c%c\n", colour, (row +'a'), (col + 'a')); printBoard(board,n); return true; } else{ return false; } } bool UserMove(char board[][26], int n, char colour, char row, char col){ int movesrow[100] = {0}; int movescol[100] = {0}; int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'U') { if (checkLegalInDirection(board, n, i, j, colour, -1, -1)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, -1, 0)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, -1, 1)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 0, -1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 0, 1)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, -1)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, 0)){ movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, 1)) { movesrow[count] = i; movescol[count] = j; } } } count += 1; } int bestMoves[100] = {0}; int tracker = 0; int tot = 0; for (int i = 0; i < count; i++){ if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, -1); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 0); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 1); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, -1); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, 1); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, -1); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 0); if (tot != 0){ bestMoves[tracker] = tot; } } if (tot != 0){ tracker += 1; } tot = 0; for (int j = 0; j < count; j++){ tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 1); if (tot != 0){ bestMoves[tracker] = tot; } } } // if player runs out of moves if (bestMoves[0] == 0){ printf("%c player has no valid move.", colour); return false; } printf("\nEnter a move for colour %c (RowCol): ", colour); scanf(" %c%c", &row, &col); if (validMove(board, n, (row - 'a'), (col - 'a'), colour)){ board[row- 'a'][col-'a'] = colour; printBoard(board,n); } } bool validMove(char board[][26], int n, int row, int col, char colour){ int score = 0; if (checkLegalInDirection(board, n, row, col, colour, -1, -1)) { score++; int i = 1; while (board[row + (i * -1)][col + (i * -1)] != colour){ board[row + (i * -1)][col + (i * -1)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, -1, 0)) { score++; int i = 1; while (board[row + (i * -1)][col + (i * 0)] != colour){ board[row + (i * -1)][col + (i * 0)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, -1, 1)) { score++; int i = 1; while (board[row + (i * -1)][col + (i * 1)] != colour){ board[row + (i * -1)][col + (i * 1)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, 0, -1)) { score++; int i = 1; while (board[row + (i * 0)][col + (i * -1)] != colour){ board[row + (i * 0)][col + (i * -1)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, 0, 1)) { score++; int i = 1; while (board[row + (i * 0)][col + (i * 1)] != colour){ board[row + (i * 0)][col + (i * 1)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, 1, -1)) { score++; int i = 1; while (board[row + (i * 1)][col + (i * -1)] != colour){ board[row + (i * 1)][col + (i * -1)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, 1, 0)) { score++; int i = 1; while (board[row + (i * 1)][col + (i * 0)] != colour){ board[row + (i * 1)][col + (i * 0)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, 1, 1)) { score++; int i = 1; while (board[row + (i * 1)][col + (i * 1)] != colour){ board[row + (i * 1)][col + (i * 1)] = colour; i++; } } if (score > 0){ return true; } else { return false; } } void printBoard(char board[][26], int n) { printf(" "); for (int i = 0; i < n; i++){ printf("%c", 'a' + i); } for (int m = 0; m < n; m++){ printf("\n%c ", 'a' + m); for (int j = 0; j < n; j++){ printf("%c", board[m][j]); } } } bool positionInBounds(int n, int row, int col) { if (row >= 0 && row < n && col >= 0 && col < n){ return true; } else{ return false; } } bool checkLegalInDirection(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol) { if (positionInBounds(n,row,col) == false){ return false; } if (board[row][col] != 'U' ){ return false; } row += deltaRow; col += deltaCol; if (positionInBounds(n,row,col) == false){ return false; } if (board[row][col] == colour || board[row][col] == 'U') { return false; } while ((positionInBounds(n, row, col)) == true) { if (board[row][col] == colour) { return true; } if (board[row][col] == 'U') { return false; } row += deltaRow; col += deltaCol; } return false; } int checkBestMoves(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol) { int tiles = 0; if (positionInBounds(n,row,col) == false){ return false; } if (board[row][col] != 'U' ){ return false; } row += deltaRow; col += deltaCol; if (positionInBounds(n,row,col) == false){ return false; } if (board[row][col] == colour || board[row][col] == 'U') { return false; } while ((positionInBounds(n, row, col)) == true) { if (board[row][col] == colour) { return tiles; } if (board[row][col] == 'U') { return false; } tiles += 1; row += deltaRow; col += deltaCol; } return false; } bool checkifmove(char board[][26], int n, char color){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'U') { if (checkLegalInDirection(board, n, i, j, color, -1, -1) || checkLegalInDirection(board, n, i, j, color, -1, 0) || checkLegalInDirection(board, n, i, j, color, -1, 1) || checkLegalInDirection(board, n, i, j, color, 0, -1) || checkLegalInDirection(board, n, i, j, color, 0, 1) || checkLegalInDirection(board, n, i, j, color, 1, -1) || checkLegalInDirection(board, n, i, j, color, 1, 0) || checkLegalInDirection(board, n, i, j, color, 1, 1)) { return true; } } } } return false; } ``` I have messed with shortening and expanding the array sizes but nothing seems to be working. I also tried using malloc but encountered the same problem.
My code keeps failing with a segmentation fault but I don't allocate any memory
|c|segmentation-fault|
null
I am currently working on google charts and trying to implement custom tooltip. It is still showing the basic default tooltip. Documentation - https://developers.google.com/chart/interactive/docs/customizing_tooltip_content Link to the JSFiddle - https://jsfiddle.net/ritesh2627/wo6kb14e/1/ Here is the code: ` <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawVisualization); function createCustomHTMLContent() { return '<div>' + 'Jan 2023: <strong>1234 kWh</strong>'+ '</div>'; } function drawVisualization() { // Some raw data (not necessarily accurate) var data = new google.visualization.DataTable(); data.addColumn('string', 'sdfgadfg'); data.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}}); data.addColumn('number', '2023'); data.addColumn('number', '2024'); data.addRows([ ['Jan', createCustomHTMLContent(), 165, 614.6], ['Feb' ,createCustomHTMLContent(), 135, 682], ['Mar' ,createCustomHTMLContent(), 157, 623], ['Apr' ,createCustomHTMLContent(), 139, 609.4], ['May' ,createCustomHTMLContent(), 136, 569.6], ['Jun' ,createCustomHTMLContent(), 165, 614.6], ['Aug' ,createCustomHTMLContent(), 135, 682], ['Sep' ,createCustomHTMLContent(), 157, 623], ['Oct' ,createCustomHTMLContent(), 139, 609.4], ['Nov' ,createCustomHTMLContent(), 136, 569.6], ['Dec' ,createCustomHTMLContent(), 136, 569.6], ]); var options = { vAxis: {title: 'Usage in kWh',titleTextStyle : { fontName : "Oswald", italic : false, },}, hAxis: {title: 'Month', titleTextStyle : { fontName : "Oswald", italic : false, }}, seriesType: 'bars', series: {0: { color: '#1f6099' }, 1: {type: 'line',pointsVisible: true, color: '#2AB673'}}, legend: { position: 'bottom', alignment: 'center' }, tooltip: { isHtml: true }, }; var chart = new google.visualization.ComboChart(document.getElementById('chart_div')); chart.draw(data, options); } <!-- language: lang-html --> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div" style="width: 900px; height: 500px;"></div> <!-- end snippet --> `
Custom tooltip is not working (Google Charts)
|javascript|google-visualization|
Upon trying to output the roles on page ListRoles.cshtml with the admin account in this project it gives me System.NullReferenceException: 'Object reference not set to an instance of an object.'... I think the problem is in the Can anyone tell me how to fix it please! have tried some things but nothing worked. Here's the project: [https://github.com/bul-bbx/Rent_A_Car](https://github.com/bul-bbx/Rent_A_Car) and here's the whole error: NullReferenceException: Object reference not set to an instance of an object. AspNetCoreGeneratedDocument.Views_Role_Index.get_Model() AspNetCoreGeneratedDocument.Views_Role_Index.ExecuteAsync() in Index.cshtml @if (Model.Any()) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result) Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
If you want to count the lines, you could write the pattern as: (?:[\s\S]*^——$|\G(?!^))\R\K.+ The pattern matches: - `(?:` Non capture group - `[\s\S]*` Match all the way to the end of the file - `^——$` Match `——` on a single line - `|` Or - `\G(?!^)` Assert the current position at the end of the previous match, not at the start - `)` Close the non capture group - `\R\K` Match a newline and then forget what is matched so far - `.+` Match a whole line with one or more characters [Regex demo](https://regex101.com/r/At2M7O/1) Or if there can not be a single `——` at the bottom: (?:[\s\S]*^——$|\G(?!^))\R\K(?!^——$).+ [Regex demo](https://regex101.com/r/eDQzuB/1) For example in a tool like Notepad++: [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/MTvyO.png
From the docs ![](https://i.imgur.com/WQgtocU.png) Also read: https://www.brucebrotherton.com/blog/hyphens-on-the-web/ <hr> It is the browser in charge of rendering text, you have to analyze where text is rendered. With Canvas or SPAN Far from perfect. This one: * wraps each word in a ``<span>`` * calculates by ``offsetHeight`` if a SPAN spans multiple lines * of so it found a hyphened word * it then **removes** each _last_ character from the ``<span>`` to find when the word wrapped to a new line ![](https://i.imgur.com/zvCwk1H.png) The _Far from perfect_ is the word "demonstrate" which _**"fits"**_ when shortened to "demonstr" **-** "ate" But is not the English spelling ![](https://i.imgur.com/WtZTaiF.png) Needs some more JS voodoo <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> <style> .hyphen { background: pink } .remainder { background: lightblue } </style> <process-text lang="en" style="display:inline-block; overflow-wrap: word-break; hyphens: auto; zoom:1.2; width: 7em"> By using words like "incomprehensibilities", we can demonstrate word breaks. </process-text> <script> customElements.define('process-text', class extends HTMLElement { connectedCallback() { setTimeout(() => { let words = this.innerHTML.trim().split(/(\W+)/); let spanned = words.map(w => `<span>${w}</span>`).join(''); this.innerHTML = spanned; let spans = [...this.querySelectorAll("span")]; let defaultHeight = spans[0].offsetHeight; let hyphend = spans.map(span => { let hyphen = span.offsetHeight > defaultHeight; console.assert(span.offsetHeight == defaultHeight, span.innerText, span.offsetWidth); span.classList.toggle("hyphen", hyphen); if (hyphen) { let saved = span.innerText; while (span.innerText && span.offsetHeight > defaultHeight) { span.innerText = span.innerText.slice(0, -1); } let remainder = document.createElement("span"); remainder.innerText = saved.replace(span.innerText, ""); remainder.classList.add("remainder"); span.after(remainder); } }) console.log(this.querySelectorAll("span").length, "<SPAN> created" ); }) //setTimeout to read innerHTML } // connectedCallback }); </script> <!-- end snippet -->
|mysql|
null
How to only estimate neonatal mortality (nmr) using `syncmrates` in Stata? How to get the output that is nmr as binary variable using `syncmrates`? I can get under 5 mortatlity rates, imr, nmr and pmr using `syncmrates` command. However I need only nmr as it is my main outcome variable and I need it in a binary form to carry out regression.
How to only estimate neonatal mortality using syncmrates in Stata?
|python|nlp|openai-api|summarization|
My Android app uses Fragments and includes Google signin authorization via Firebase. After signing in, the following appears, overlaying the fragment underneath it: [![enter image description here][1]][1] When I touch the screen, the gray view disappears: [![enter image description here][2]][2] Has anyone here seen this problem or know what's causing it? [1]: https://i.stack.imgur.com/BW3MF.jpg [2]: https://i.stack.imgur.com/3WYsQ.jpg
Gray view with a white horizontal bar appearing after Google signin from my Android app
|android|android-fragments|google-signin|
|angular|primeng|
I make a program, two clients connect to a server, and one of the clients send msg to server, then the server resend this msg to another client.I use base_rdset as listen set, and rdset as ready set, clients' socket identifier storge in a array. When I start the server, sometimes it runs well, but sometimes it posts an error which is `select:Bad file descriptor`. waht happend to this program? ``` #include <55header.h> //该服务端最多可以连接的客户端个数 #define SIZE 3 int main(int argc,char*argv[]) { //./server 192.168.176.132 8080 //服务端绑定8080端口 //存储网络套接字的结构体 ARGS_CHECK(argc,3); //存储网络套接字的结构体 struct sockaddr_in addr; addr.sin_family=AF_INET;//ipv4 addr.sin_port=htons(atoi(argv[2]));//port addr.sin_addr.s_addr=inet_addr(argv[1]);//ip //创建socket文件对象 int socket_fd=socket(AF_INET,SOCK_STREAM,0); ERROR_CHECK(socket_fd,-1,"socket"); //绑定端口 int res_bind =bind(socket_fd,(struct sockaddr*)&addr,sizeof(a ERROR_CHECK(res_bind,-1,"bind"); //将socket文件对象改造成全连接队列,开始然后开始监听端口 int res_listen=listen(socket_fd,10); ERROR_CHECK(res_listen,-1,"listen"); //创建读监听集合 fd_set base_rdset; //创建读就绪集合 fd_set rdset; char buf[1024]; //存储用于和客户端通信的socket文件对象的文件描述符net_fd的集合 int net_fds[SIZE]={0}; //监听全连接队列,看是否有客户端发起连接 FD_SET(socket_fd,&base_rdset); while(1){ //用监听集合初始化就绪集合 FD_ZERO(&rdset); memcpy(&rdset,&base_rdset,sizeof(base_rdset)); int ready_num=select(10,&rdset,NULL,NULL,NULL); ERROR_CHECK(ready_num,-1,"select"); if(FD_ISSET(socket_fd,&rdset)){ //客户端发起了连接,把第一个可分配的文件描述符容器 //分配给发起连接的客户端的socket文件对象的文件描述符 for(int i=0;i<SIZE;i++){ if(net_fds[i]==0){ net_fds[i]=accept(socket_fd,NULL,NULL); FD_SET(net_fds[i],&base_rdset); break; } } } for(int i=0;i<SIZE;i++){ if(net_fds[i]==0){ continue; } if(FD_ISSET(net_fds[i],&rdset)){ memset(buf,0,sizeof(buf)); int count_chars=recv(net_fds[i],buf,sizeof(bu ERROR_CHECK(count_chars,-1,"recv"); if(count_chars==0){ //就绪了但是读到的字符个数为0,说明该客户 //将该客户端踢出监听集合,停止监听 close(net_fds[i]); FD_CLR(net_fds[i],&base_rdset); net_fds[i]=0; continue; } //该客户端发来了消息,进行消息转发 for(int j=0;j<SIZE;j++){ if(j==i||net_fds[j]==0){ //跳过未分配的文件描述符 //跳过自己,不能转发给自己 continue; } send(net_fds[j],buf,count_chars,0); } } } } return 0; } ``` [enter image description here](https://i.stack.imgur.com/9JRij.png) I add code that is`FD_ZERO(&base_rdset)`,this problem seems like be solved,but i am not sure,I want to know why does this error occered
The OP's problem qualifies perfectly for a solution of mainly 2 combined techniques ... 1) the [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) based creation of a list of [async function/s (expressions)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function), each function representing a delayed broadcast task. 2) the creation of an [async generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator) via an [async generator-function (expression)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function*), where the latter consumes / works upon the created list of delayed tasks, and where the async generator itself will be iterated via the [`for await...of` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of). In addition one needs to write kind of a `wait` function which can be achieved easily via an async function which returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) instance, where the latter resolves the promise via [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) and a customizable delay value. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const queueData = ["Sample Data 1", "Sample Data 2", "Sample Data 3"]; // create a list of async function based "delayed tasks". const delayedTasks = queueData .map(data => async () => { wss.broadcast( JSON.stringify({ data }) ); await wait(1500); return `successful broadcast of "${ data }"`; }); // create an async generator from the "delayed tasks". const scheduledTasksPool = (async function* (taskList) { let task; while (task = taskList.shift()) { yield await task(); } })(delayedTasks); // utilize the async generator of "delayed tasks". (async () => { for await (const result of scheduledTasksPool) { console.log({ result }); } })(); <!-- language: lang-css --> .as-console-wrapper { min-height: 100%!important; top: 0; } <!-- language: lang-html --> <script> const wss = { broadcast(payload) { console.log('broadcast of payload ...', payload); }, }; async function wait(timeInMsec = 1_000) { return new Promise(resolve => setTimeout(resolve, Math.max(0, Math.min(timeInMsec, 20_000))) ); } </script> <!-- end snippet -->
Here's the `docker-compose.yml` file: ``` version: "3" services: db_cassandra: container_name: db_cassandra image: custom.cassandra.image/builder-cassandra volumes: - "./common/cassandra:/lua/cassandra_setup:rw" environment: WORKSPACE: "/tmp" SERVICES_ROOT_DIR: "/services_root" healthcheck: test: ["CMD", "cqlsh", "-u", "cassandra", "-p", "cassandra" ] interval: 5s timeout: 5s retries: 60 ports: - "9042:9042" remote_cassandra: container_name: remote_cassandra build: context: ../. dockerfile: ./it/remote_cassandra/Dockerfile args: BASE_IMAGE: custom.cassandra.image/builder-cassandra depends_on: dd_cassandra: condition: service_healthy volumes: - "./common/cassandra:/lua/cassandra_setup:rw" environment: WORKSPACE: "/tmp" SERVICES_ROOT_DIR: "/services_root" ``` Here's the `remote_cassandra/Dockerfile`: ``` ARG BASE_IMAGE FROM ${BASE_IMAGE} COPY ./it/common/cassandra/cassandra-setup.sh / RUN chmod +x /cassandra-setup.sh CMD ["/cassandra-setup.sh", "db_cassandra"] ``` `remote_cassandra` remotely connects to the `db_cassandra` service and executes certain queries. Here's how the `cassandra-setup.sh` script looks like: ``` #!/bin/bash #code that creates schema.cql . . . DB_CONTAINER="$1" while ! cqlsh $DB_CONTAINER 9042 -e 'describe cluster' ; do echo "waiting for db_cassandra to be up..." sleep .5 done cqlsh $DB_CONTAINER 9042 -f "${WORKSPACE}/schema.cql" ``` When I pass the "dd_cassandra" as an argument to ENTRYPOINT, the docker containers are created and nothing happens after that, they keep waiting indefinitely. However, if I don't pass the argument and simply hardcode it in the `cassandra-setup.sh` script like this below, then things run smoothly: ``` #!/bin/bash #code that creates schema.cql . . . while ! cqlsh db_cassandra 9042 -e 'describe cluster' ; do echo "waiting for db_cassandra to be up..." sleep .5 done cqlsh db_cassandra 9042 -f "${WORKSPACE}/schema.cql" ``` I've also tried with: ``` ENTRYPOINT ["/cassandra-setup.sh"] CMD ["db_cassandra"] ``` and it doesn't work too.
I am new in R and I'm trying to run a code written by Feng et al., (2019). They already provide the code in their paper, and I prepared all the text files that are needed for it, but for some reason the code keeps running on the results the authors provide (the example data). I can't figure it out and I would appreciate any advise you can give me. Thanks for your time! The code: ### #get file folder dir_file<-system.file("extdata", package="ELISAtools") dir_file<-("C://Users//ElinD//OneDrive//Desktop//ELISAtools//extdata") #setwd(dir_file) batches<-loadData(file.path(dir_file,"mytextfile2.txt")) This is my data: > dput(File) structure(list(ExpID = c("Exp1", "Exp2", "Exp2", "Exp3"), FileName = c("plate1.txt", "plate2.txt", "plate3.txt", "plate4.txt"), Batch = c("Batch1", "Batch2", "Batch2", "Batch3"), Num_Plate = 1:4, Date = c("03/01/2024", "10/01/2024", "11/01/2024", "22/01/2024"), AnnotationFile = c("AnnotationfileVER4.txt", "AnnotationfileVER4.txt", "AnnotationfileVER4.txt", "AnnotationfileVER4.txt" ), Std_Conc = c("stdtextconc.txt", "stdtextconc.txt", "stdtextconc.txt", "stdtextconc.txt"), Dir_Annotation = c(NA, NA, NA, NA), Dir_StdConc = c(NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, -4L))
You can extend the `Error` class to create an error type whose constructor expects an argument of type `never`: ``` class NeverError extends Error { constructor(check: never) { super(`NeverError received unexpected value ${check}, type should have been never.`) this.name = 'NeverError' } } ``` Then you throw the error if the code is ever reached, and if `job` isn't `never` it'll also raise a compiler error: ``` if (job.type === 'add') { add(job) } else if (job.type === 'send') { send(job) } else { throw new NeverError(job) } ```
Non-www to www in Laravel php script Not Redirect Problem
{"OriginalQuestionIds":[67529371],"Voters":[{"Id":3959875,"DisplayName":"wOxxOm","BindingReason":{"GoldTagBadge":"google-chrome-extension"}}]}
here's a slightly cleaner code, ``` // choosing is based on the assumption // that the head is the last element in the body array // if not, you can simply reverse the conditions if (prev == /*last in body*/) { spriteName == "head_sprite"; } else if (prev == /*first in body*/) { spriteName = "tail_sprite"; } else if (next.x == prev.x || next.y == prev.y) { spriteName == "body_sprite"; } else { spriteName = "curved_sprite"; } // now rotate and reverse if (prev.x == next.x) { // rotate 90deg } else if (prev.x > next.x) { // reverse horizontally } if (prev.y > next.y) { // reverse vertically } ``` it's much more convenient to rotate/reverse the sprite than choosing individual sprites based on each case. i have selected from the snake_graphics.zip you attached those sprites > ["head_down", "tail_down", "body_vertical", "body_bottomright"] and renamed them to > ["head_sprite", "tail_sprite", "body_sprite", "curved_sprite" ] respectively. i possibly might have mistaken in rotating/reversing the sprite as i don't know for sure whether prev or next is the current ("assumed prev is"), but that's the basic idea
I am trying to create a structure "Student" which contains q substructures named Course. Each Course is a structure with a credit and point int value. How do I set up my Student structure to have an integer number of Course structures within it? Thanks ``` struct Student{ int q; Course course[q]; }; struct Course{ int credit; int point; }; ``` I tried this but VSC is telling me it is wrong.
In the following example I'm downloading MNIST myself and loading it through `reticulate` / `numpy`. Shouldn't make much difference. When you want to get a sample with `sample()`, you usually take a sample of indices you'll use for subsetting. To get a balanced sample, you might want to draw a specific number or proportion from each label group: ``` r library(reticulate) library(dplyr) # Download MNIST dataset as numpy npz, # load through reticulate, build something along the lines of keras::dataset_mnist() output np <- import("numpy") mnist_npz <- curl::curl_download("https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz", "mnist.npz") mnist_np <- np$load(mnist_npz) mnist_lst <- list( train = list( x = mnist_np[["x_train"]], y = mnist_np[["y_train"]] ), test = list( x = mnist_np[["x_test"]], y = mnist_np[["y_test"]] ) ) train_images <- mnist_lst$train$x train_labels <- mnist_lst$train$y test_images <- mnist_lst$test$x test_labels <- mnist_lst$test$y # sample row indices, # 100 per class to keep the dataset balanced sample_idx <- train_labels |> tibble(y = _) |> tibble::rowid_to_column("idx") |> slice_sample(n = 100, by = y ) |> arrange(idx) |> pull(idx) # use sample_idx for subsetting train_images_sample <- train_images[sample_idx,,] train_labels_sample <- train_labels[sample_idx] str(train_images_sample) #> int [1:1000, 1:28, 1:28] 0 0 0 0 0 0 0 0 0 0 ... str(train_labels_sample) #> int [1:1000(1d)] 9 7 5 6 8 7 7 5 2 9 ... # original label distribution table(train_labels) #> train_labels #> 0 1 2 3 4 5 6 7 8 9 #> 5923 6742 5958 6131 5842 5421 5918 6265 5851 5949 # sample distribution table(train_labels_sample) #> train_labels_sample #> 0 1 2 3 4 5 6 7 8 9 #> 100 100 100 100 100 100 100 100 100 100 ``` <sup>Created on 2024-03-29 with [reprex v2.1.0](https://reprex.tidyverse.org)</sup>
I want to create a python script, where I have a list of 14 digits and have to find the integer formed by a specific combination of all digits, with the requirement that the number of such combinations that are smaller than this integer exceeds the number of combinations that are greater than the integer by 5617961. [![My algorithm right now.][1]][1] This is what i've come up with. It should work but the obvious negative side is it's slow and inefficent. So I need help with coming up with a better algorithm. Also my code: from itertools import permutations def generate_combinations(lst, length): for combo in permutations(lst, length): yield ''.join(map(str, combo)) # List setup lst = [2, 2, 2, 2, 4, 4, 5, 5, 5, 6, 6, 6, 8, 8] length = 14 FiveLst = [] for combination in generate_combinations(lst, length): arv = [int(x) for x in str(combination)] if arv[0] == 5 and arv[1] == 8: print(combination) FiveLst.append(combination) for Fiveno in FiveLst: difmin = 0 difplus = 0 for combination in generate_combinations(lst, length): if combination > Fiveno: difplus += 1 else: difmin += 1 difference = difmin-difplus if difference == 5617961: print(f"Combination found!: {combination}") break print("Process complete!") exit() [1]: https://i.stack.imgur.com/smnrE.png
Passing arguments to ENTRYPOINT causes the container to start and run indefinitely
|docker-compose|cassandra|command-line-arguments|
[Example of the result I get right now][1]I'm using the LAG() function in SQL to calculate the difference between the current month's tips sum and the previous month's tips sum for each taxi driver. However, the LAG() function is returning 0 for every row, even though there should be previous rows to reference. This is the example of the query I am using now: SELECT td.taxi_id, td.year, td.month, td.tips_sum, (td.tips_sum - LAG(td.tips_sum, 1, 0) OVER (PARTITION BY td.taxi_id ORDER BY td.year, td.month) / NULLIF(LAG(td.tips_sum, 1, 0) OVER (PARTITION BY td.taxi_id ORDER BY td.year, td.month), 0) AS tips_change FROM tips_data td ORDER BY td.tips_sum DESC LIMIT 3 [1]: https://i.stack.imgur.com/IpMkl.png
|asynchronous|rust|async-await|rayon|
In this code char *line; line = strncpy(line, req, size); `line` is not explicitly initialized to a specific value; since it's an `auto` (local) variable, its initial value is *indeterminate*, meaning it could be literally anything. The behavior on writing through an invalid pointer is *undefined*, meaning that neither the compiler nor the runtime environment are required to handle the situation in any particular way. In this particular case that indeterminate initial value just happened to correspond to the address of a writable piece of memory, so your code *appeared* to work without any problems. However, there's no guarantee you didn't overwrite something important that would have caused a problem later on, or that another thread or process won't write over that memory while you're using it.
I'm using the LAG() function in SQL to calculate the difference between the current month's tips sum and the previous month's tips sum for each taxi driver. However, the LAG() function is returning 0 for every row, even though there should be previous rows to reference. This is the example of the query I am using now: SELECT td.taxi_id, td.year, td.month, td.tips_sum, (td.tips_sum - LAG(td.tips_sum, 1, 0) OVER (PARTITION BY td.taxi_id ORDER BY td.year, td.month) / NULLIF(LAG(td.tips_sum, 1, 0) OVER (PARTITION BY td.taxi_id ORDER BY td.year, td.month), 0) AS tips_change FROM tips_data td ORDER BY td.tips_sum DESC LIMIT 3 [1]: https://i.stack.imgur.com/IpMkl.png [Example of the result I get right now][1]
I wanted to ask that if we can give any default value in the props<>() just like we give a default value in function arguments ``` export const set = createAction( '[Counter] Set', props<{ value: number }>() ); ``` Here I want to give a default number to "value" property in props<{ value: number }>(). Is there any way of doing so? I tried adding the number similar to what we do in function arguments: ``` export const set = createAction( '[Counter] Set', props<{ value = 0 }>() ); ``` But it resulted in error!: ``` Operator '<' cannot be applied to types '<P extends SafeProps, SafeProps = NotAllowedInPropsCheck<P>>() => ActionCreatorProps<P>' and '{ value: number; }' ```
PHP has the `escapeshellcmd()` function which escapes dangerous commands from input fed into the the exec() system() functions. This will enable you to have the functionality you're looking for without introducing major security vulnerabilities. More about that [here](https://www.php.net/manual/en/function.escapeshellcmd.php).
I am developing a perfume review application using a React frontend and an Express/SQLite backend. My goal is to transition from using static data within a React component to fetching this data dynamically from my backend. **Project Architecture:** **Backend:** - **Models:** **`Parfum.js`** - Defines the perfume model. - **Controllers:** **`ParfumController.js`** - Contains logic to interact with the database. - **Database Management:** **`database.js`** - Manages SQLite database operations. - **API Setup:** **`app.js`** - Configures Express routes for the API. **Frontend (newfrontend directory):** - **React Component:** **`MainWindow.js`** - Displays perfume information. - **Styling:** **`MainWindow.css`** **Database:** - **SQLite Database:** **`database.db`** - Stores perfume data. The backend provides various endpoints, like **`/api/perfume-name/:id`**, for fetching perfume names. **Issue:** I need to fetch a list of perfumes from the backend dynamically instead of using static data within **`MainWindow.js`**. **Questions:** 1. How can I structure my API call within **`MainWindow.js`** to fetch and display perfumes? 2. Based on the provided database schema and Express routes, how can I update the React component's state with the fetched data? 3. What are the best practices for error handling in this scenario, especially for failed API calls or when no data is returned? **Attempts:** - Used axios in **`MainWindow.js`** with **`useEffect`** to fetch data on component mount. - Tested with hardcoded API endpoint URLs, which works fine with static data. Now seeking to implement dynamic data fetching. **Challenges:** - Encountering CORS errors and issues updating the component's state with fetched data. - Unsure how to handle the asynchronous nature of API calls within React effectively **Code Snippets:** ``` database.js: ``` ``` class Database { // Method to initialize database and tables _initializeDatabase() { // SQL table creation scripts } _Add_Perfume(Perfume) { // Add attributes of a Perfume object wich contains scraped data in a Perfume Object created in the Model and comming from the controller } // Example getter getPerfumeName(perfumeId) { // Implementation } // Additional getters and setters... } ``` ``` app.js backend setup: ``` ``` import express from 'express'; import cors from 'cors'; import { Database } from './database.js'; const app = express(); app.use(cors()); const port = 3001; app.get('/api/perfume-name/:id', (req, res) => { // Endpoint implementation }); // More routes... ``` **Desired Outcome:** I'm looking for guidance on fetching data from my Express backend into the MainWindow.js React component to replace the static data setup. Specifically, how to dynamically render this data in the component. **Current Static Setup in React (MainWindow.js):** Below is a snippet from my MainWindow.js component, showing how perfume data is currently hardcoded within the component's state. I aim to replace this static data setup with dynamic data fetched from my backend. ``` import React, { useState } from 'react'; import './MainWindow.css'; const MainWindow = () => { const [perfumes, setPerfumes] = useState([ { id: 1, name: 'Sauvage', brand: 'Dior', imageUrl: 'https://example.com/sauvage.jpg', genre: 'Men', // Additional perfume details... }, { id: 2, name: 'Chanel No 5', brand: 'Chanel', imageUrl: 'https://example.com/chanel-no-5.jpg', genre: 'Women', // Additional perfume details... }, // Additional perfumes... ]); // Component rendering logic... return ( <div className="perfume-container"> {perfumes.map(perfume => ( <div key={perfume.id} className="perfume-card"> <img src={perfume.imageUrl} alt={perfume.name} /> <h2>{perfume.name}</h2> <p>Brand: {perfume.brand}</p> {/* More perfume details */} </div> ))} </div> ); }; export default MainWindow; ```
Transitioning from Static to Dynamic Data in React with Express Backend
|reactjs|express|sqlite|axios|cors|
null
|java|docker|apache-kafka|docker-compose|spring-kafka|
I want all the lists in my application to look exactly the same and don't want to respecify all these settings over and over. I get the following error: Cannot find type 'Configuration' in scope. I currently have something like this: struct CustomListStyle: ListStyle { func makeBody(configuration: Configuration) -> some View { ScrollView { VStack(spacing: 10) { ForEach(configuration.data, id: \.self) { item in Text(item as? String ?? "") .foregroundColor(.blue) .padding(10) .background(Color.gray) .cornerRadius(10) } } .padding() } } } struct ContentView: View { var body: some View { List(0..<10, id: \.self) { index in Text("Item \(index)") } .listStyle(CustomListStyle()) } } Edit - 1 - Here is one for reference List( selection: $dm.someVar ) { Section( ) { LazyVGrid(columns: [ GridItem(.flexible(minimum: 120)), ], alignment: .leading, spacing: 10) { ForEach(0..<20, id: \.self) { index in Text("Column1 abcdef: \(index)") } } } }
null
null
null
null
**Yes, it's a common problem.** as long as you have used a `Container` and made some `clipping` customization for it, to appear looks like a `BottomNavigationBar`. it will but stills a container that have a clip path to be rendered. The problem occurs **when you realize that, the other part of the container you have clipped still exist**, *it hides any widget that get behind (Your problem).* > it's an advantage over another, good shape but hides the content > behind. So, i recommend the use of `BottomAppBar` and give it a `CircularNotchedRectangle` as a `shape`.
The best way to test more complex AWS lambda functions where development time and local infrastructure is the key. Is usage of their official [AWS Lambda docker image][1]. Simple Dockerfile example from documentation: ```Dockerfile FROM public.ecr.aws/lambda/nodejs:12 # Copy function code COPY app.js ${LAMBDA_TASK_ROOT} # Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile) CMD [ "app.handler" ] ``` [1]: https://hub.docker.com/r/amazon/aws-lambda-nodejs
Sometimes the program runs well, but sometimes the function select post an error that is Bad file descriptor
|c|
null
I am assuming you have the following questions: 1. Performance difference between not chaining the operations (Approach A in your question) vs chaining the operations (Approach B in your question)? 2. Performance difference between multiple `withColumn()` statements vs a single `select()` statement? Now answering the 2nd question is quite straightforward. As noted in the spark API reference for [`withColumn()`](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.withColumn.html#:~:text=or%20replaced%20column.-,Notes,-This%20method%20introduces): > This method introduces a projection internally. Therefore, calling it multiple times, for instance, via loops in order to add multiple columns can generate big plans which can cause performance issues and even *StackOverflowException*. To avoid this, use [`select()`](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.select.html#pyspark.sql.DataFrame.select) with multiple columns at once. I hope this makes it clear that in certain situations (for eg. loops) there can be a performance difference between `withColumn()` and `select()` and it's better to use the latter in general. You can read more on the hidden cost of `withColumn()` [here](https://medium.com/@manuzhang/the-hidden-cost-of-spark-withcolumn-8ffea517c015). Finally, coming to the 1st question: Short answer - Nope, there is no (negligible if any) performance difference between the two approaches. Maybe (correct me if I am wrong) your doubt is arising from the fact that not chaining the dataframe operations and using them separately is creating multiple intermediary dataframes which might be causing an overhead **but** the exact thing is happening while chaining as well. Therefore, they have the same physical plans and performance with negligible differences if any. So, the only difference that remains is readability.
{"Voters":[{"Id":635608,"DisplayName":"Mat"},{"Id":14853083,"DisplayName":"Tangentially Perpendicular"},{"Id":874188,"DisplayName":"tripleee"}],"SiteSpecificCloseReasonIds":[18]}
You can use Livewire and poll the orders table to get new orders on a controlled basis, or you can you the scheduling mechanism within Laravel to check for new orders. It appears they offer sub-minute task scheduling, but this probably isn't ideal really. You can also use the dispatch and event system. There are several methods already built into Laravel [Livewire][1] [Laravel Events][2] [1]: https://livewire.laravel.com/docs/quickstart [2]: https://laravel.com/docs/10.x/events#dispatching-events
It can be done in single animation starting at "`0` rotation" without stacking and without negative delay, and you were pretty close to that. (Welcome to SO, by the way!) You just had the easing functions set one frame later, but the progression (`ease-out` - `ease-in-out` - `ease-in`) was correct. For the POC demo I've changed the "thing" to resemble a pendulum, because I think it is slightly more illustrative for this purpose: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-css --> @keyframes swing { /* Starting at the bottom. */ 0% { transform: rotate(0turn); color: red; animation-timing-function: ease-out; } /* From the bottom to the right cusp: start full speed, end slow (ease-out). */ 25% { transform: rotate(-0.2turn); color: blue; animation-timing-function: ease-in-out; } /* From the right cusp to the left cusp: start slow, end slow (ease-in-out). It will effectively cross the bottom `0turn` point at 50% in full speed. */ 75% { transform: rotate(0.2turn); color: green; animation-timing-function: ease-in; } /* From the left cusp to the bottom: start slow, end full speed (ease-in). */ 100% { transform: rotate(0turn); color: yellow; animation-timing-function: step-end; } /* Back at the bottom. Arrived here at the full speed. Animation timing function has no effect here. */ } div { animation: swing; animation-duration: 3s; /* `animation-timing-function` is set explicitly (overridden) in concrete keyframes. */ animation-iteration-count: infinite; animation-direction: normal; /* `reverse` still obeys "reversed" timing functions from *previous* frames. */ animation-play-state: running; transform-origin: center top; margin: auto; width: 100px; display: flex; flex-direction: column; align-items: center; pointer-events: none; &::before, &::after { content: ''; background-color: currentcolor; } &::before { width: 1px; height: 100px; } &::after{ width: 50px; height: 50px; } } #reset:checked ~ div { animation: none; } #pause:checked ~ div { animation-play-state: paused; } <!-- language: lang-html --> <meta name="color-scheme" content="dark light"> <input type="checkbox" id="pause"><label for="pause">Pause animation</label>, <input type="checkbox" id="reset"><label for="reset">Remove animation</label>. <div></div> <!-- end snippet --> I must admit it never occurred to me that we can set different timing functions for each key frame, so such naturally looking multi-step animation with "bound" easing types is in fact achievable. Big takeaway for me is also information that easing function of the last (`to` / `100%`) key frame logically doesn't have any effect. Personally I'd go most probably with terser animation with only two key frames, `..direction: alternate` starting paused, and having negative delay shifting it's initial state to the middle, similar to that proposed in other answer here.
It would seem that a simple relationship exists between GPS and TG pages, given that some regions share numbering systems and some do not (Los Angeles + Orange Counties share, Riverside + San Bernardino Counties share but not with LA/OC, and so on). Since no one has an answer, I decided tht I wanted one, so I made one. Here's the trick: locate the very top-left of grid A1 of the first page in your particular county. Get the GPS for that point (I used Google Maps). Then calculate any two ponts on the same latitude line (it's helpful to find two streets on the same inner grid line), then two on the same longitude line. GPS both pairs, and calculate the distance (only the latitude distance for one pair, and only the longitude distance for the other pair). You will find that they are not the same (not a perfect square). I got: 0.03° latitude = 2.5 miles, or 0.01 miles per grid ↕ 0.03° longitude = 2.0 miles, or 0.01 miles per grid ↔ (correct, they are not the same, and both values are heavily rounded) Now, from there, knowing each page is 9 x 7 grids {^[A-HJ][1-7]$}, do: page = (top-left/starting page) + ( 30 * int( y` / 7 ) ) + int( x` / 9 ) because pages stack on top of each other vertically in LA/OC, my test bed, by jumps of 30) grid = 'A' + int( x` % 9 ), 1 + ( int( y` ) % 7 ) I'm still tweaking the mathl it's accurate about 70% of the time right now. I'll post the math when I get it perfected. Sadly, Rand McNally bought out and CLOSED Thomas Brothers maps (replacing them with their own product), but some states require first responders to still carry the Guides by law (including California), so you can still find a few editions ... for DOUBLE the price from the old days. If you can find an old Digital Edition online (circa 2004~2007), AND the serials to install them, AND a virtual machine to run them on Windows Xp or earlier (they malfunction on Vista, and were discontinued shortly thereafter), you can see the numbers yourself.
try use yarn lerna publish minor ----include-merged-tags
`OnClick` of `Checkbox` I want to `Show`/ `Hide` the HTML table. I tried like below **HTML** <tr id="trfeedback" runat="server" visible="false"> <td style="width: 5%"> </td> <td style="width: 90%"> <asp:CheckBox ID="chkFeedback" runat="server" Text="Send Feedback" Width="6%" onclick="toggleTable();" /> </td> <td style="width: 5%"> </td> </tr> <table id="trchkOptions" runat="server"> <tr> <td style="width: 5%"> </td> <td> <asp:CheckBox ID="chkOption1" runat="server" Width="5%" /> Option 1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;To&nbsp; RA 1,&nbsp; RA 2 </td> <td style="width: 5%"> </td> </tr> <tr> <td style="width: 5%"> </td> <td> <asp:CheckBox ID="chkOption2" runat="server" Width="5%" /> Option 2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;To&nbsp; HMS, VMS. </td> <td style="width: 5%"> </td> </tr> <tr> <td style="width: 5%"> </td> <td> <asp:CheckBox ID="chkOption3" runat="server" Width="5%" /> Option 3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;To, RA 1,&nbsp; RA 2. </td> <td style="width: 5%"> </td> </tr> </table> **JS** function toggleTable() { var lTable = document.getElementById("chkFeedback"); lTable.style.display = (lTable.style.display == "table") ? "none" : "table"; } but it is not working. I don't know where I am going wrong. The HTML is [in this Fiddle][1]. [1]: https://jsfiddle.net/h3y3zkuh/
{"Voters":[{"Id":16217248,"DisplayName":"CPlus"},{"Id":3730754,"DisplayName":"LoicTheAztec"},{"Id":17562044,"DisplayName":"Sunderam Dubey"}]}
{"Voters":[{"Id":2308683,"DisplayName":"OneCricketeer"},{"Id":2530121,"DisplayName":"L Tyrone"},{"Id":17562044,"DisplayName":"Sunderam Dubey"}]}
The data structure for this is a [Trie][1] (Prefix Tree): * Time Efficiency: Search, Insertion & Deletion: With a time complexity of **O(m)** where m is the length of the string. * Space Efficiency: Store the unique characters present in the strings. This can be a space advantage compared to storing the entire strings. ```php <?php class TrieNode { public $childNode = []; // Associative array to store child nodes public $endOfString = false; // Flag to indicate end of a string } class Trie { private $root; public function __construct() { $this->root = new TrieNode(); } public function insert($string) { if (!empty($string)) { $this->insertRecursive($this->root, $string); } } private function insertRecursive(&$node, $string) { if (empty($string)) { $node->endOfString = true; return; } $firstChar = $string[0]; $remainingString = substr($string, 1); if (!isset($node->childNode[$firstChar])) { $node->childNode[$firstChar] = new TrieNode(); } $this->insertRecursive($node->childNode[$firstChar], $remainingString); } public function commonPrefix() { $commonPrefix = ''; $this->commonPrefixRecursive($this->root, $commonPrefix); return $commonPrefix; } private function commonPrefixRecursive($node, &$commonPrefix) { if (count($node->childNode) !== 1 || $node->endOfString) { return; } $firstChar = array_key_first($node->childNode); $commonPrefix .= $firstChar; $this->commonPrefixRecursive($node->childNode[$firstChar], $commonPrefix); } } // Example usage $trie = new Trie(); $trie->insert("/home/texai/www/app/application/cron/logCron.log"); $trie->insert("/home/texai/www/app/application/jobs/logCron.log"); $trie->insert("/home/texai/www/app/var/log/application.log"); $trie->insert("/home/texai/www/app/public/imagick.log"); $trie->insert("/home/texai/www/app/public/status.log"); echo "Common prefix: " . $trie->commonPrefix() . PHP_EOL; ?> ``` Output: Common prefix: /home/texai/www/app/ [Demo][2] [1]: https://en.wikipedia.org/wiki/Trie [2]: https://onecompiler.com/php/428ve5e2h
{"Voters":[{"Id":2530121,"DisplayName":"L Tyrone"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":17562044,"DisplayName":"Sunderam Dubey"}]}
I have a function `def event(...)` in my `EventHandler` class which can be called at arbitrary intervals in my main code. It needs to put all the events that are coming in into a queue and process them one at a time. How do I do this? I've been trying to use the asyncio library to do this, but I have no clue how to do it. My problem is that if I make `event` async, then I get the error that it was never awaited. If I don't make it async, then I can't call the function that processes the next item in the queue. ``` async def _event(...): queue_item = await(self._queue.get()) ... ``` I need to be able to call event at any time, but the helper function `_event` needs to processes the next item in queue one at a time. How do I solve this? I tried making event synchronous ``` def event(...): """ When an event happens, this will add it to the queue. Multiple events can happen, and they will be executed one at a time, as they come in. Later on, we can change this. """ self._queue.put_nowait((flag, *args)) task = self._loop.create_task(self._event()) asyncio.ensure_future(task) ``` but then the error that comes up is that task was not awaited. Thanks for downvoting my question without saying anything! That really helps me out!
Ngrx props<>() method in createAction()
|javascript|angular|ngrx|ngrx-store|
null
I have a domain model of user where I store `original` user state and `current`. If property from current state doesn't match original - it needs to be updated in database and included in sql query. Creating similar compare methods for each property becomes repetitive and I wanted to know, is there a way to replace this compare methods with some generic shared one? [Playground][1] ``` #[derive(Debug, Clone)] struct UserProps { pub age: i32, pub name: String, } struct User { pub original: Option<UserProps>, pub current: UserProps, } impl User { // creating similar function for each property is burthersome // is there a way to create a generic one? pub fn age_changed(&self) -> bool { self.original .as_ref() .map_or(true, |val| val.age != self.current.age) } pub fn name_changed(&self) -> bool { self.original .as_ref() .map_or(true, |val| val.name != self.current.name) } } fn x() { let props = UserProps { age: 12, name: "x".to_owned(), }; let mut user = User { original: Some(props.clone()), current: props.clone(), }; user.current.age = 22; assert!(user.age_changed()); if user.age_changed() { // add property to sql query update operation } } ``` [1]: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=473af167f37d54769bc567797c15d9d1
Generic property compare
|rust|
What is missing is the LPSECURITY_ATTRIBUTES that you specify in the first parameter of the CreateEvent. This controls who can access the event and what they can do with it. With NULL as the first parameter, the event is created with with the default descriptor so that it is accessible to the system user only. Here is an example of creating the SECURITY_ATTRIBUTES. It will allow full control of the event to Administrators. No error checking or resource cleanup included. SECURITY_ATTRIBUTES sa {}; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = FALSE; ConvertStringSecurityDescriptorToSecurityDescriptor( TEXT("(A;OICI;GA;;;BA)"), SDDL_REVISION_1, &(sa.lpSecurityDescriptor), NULL);
I am having trouble reading a large .dat file into R. I am using ``` data<-read.table("...2018029_ascii/FRSS108PUF.dat", fill = TRUE) ``` This results in a large dataframe with V1, V2 as column names. I am using the ASCII file at this link: https://nces.ed.gov/pubsearch/pubsinfo.asp?pubid=2018029 "...nameoffolder/2018029_ascii/FRSS108PUF.dat"
loading .dat into R, no column names
|r|ascii|bigquery-public-datasets|
null
so I am new to Rust but recently came across a problem I don't know how to solve. It's to work with nested (and multi-dimensional) value-key pair arrays in Rust that is dynamically generated based on string splitting. The sample dataset looks something like the example below: `Species | Category Dog | Eukaryota, Animalia, Chordata, Mammalia, Carnivora, Canidae, Canis, C. familiaris Cat | Eukaryota, Animalia, Chordata, Mammalia, Carnivora, Feliformia, Felidae, Felinae, Felis, F. catus Bear. | Eukaryota, Animalia, Chordata, Mammalia, Carnivora, Ursoidea, Ursidae, Ursus ...` The goal would be to split the comma delimitation and a create a map or vector. Essentially, creating "layers" of nested keys (either as a Vector array or a key to a *final value*). From my understanding, Rust has a crate called "serde_json" which can be *used* to create key-value pairings like so: `let mut array = Map::new(); for (k, v) in data.into_iter() { array.insert(k, Value::String(v)); }` As for comma delimited string splitting, it might look something like this: `let categories = "a, b, c, d, e, f".split(", "); let category_data = categories.collect::<Vec<&str>>()` However, the end goal would be to create a recursively nested map or vector that follows the *Category* column for the array which can ultimately be serialised to a json output. How would this be implemented in Rust? In addition, while we might know the number of rows in the sample dataset, isn't it quite resource intensive to calculate all the "comma-delimited layers" in the *Category* column to know the final size of the array as required by Rust's memory safe design to "initialize" an array by a defined or specified size? Would this need to specifically implemented as way to know the maximum number of layers in order to be doable? Or can we implement an infinitely nested multi-dimensional array without having to specify or initialise a defined map or vector size? For further reference, in PHP, this might be implemented so: `$output_array = array(); foreach($data_rows as $data_row) { $temp =& $output_array; foreach(explode(', ', $data_row["Category"]) as $key) { $temp =& $temp[$key]; } // Check if array is already initialized, if not create new array with new data if(!isset($temp)) { $temp = array($data_row["Species"]); } else { array_push($temp, $data_row["Species"]); } }` How would a similar solution like this be implemented in Rust? Thanks in advance!
|android-studio|android-sqlite|blob|
null
Your code is failing for a couple of reasons: 1. You're drawing what's supposed to be the background image over the image you want to poke holes in (i.e. make the black pixels transparent). It should be the other way around - the remote image should go first, and then, on top of it, the uploaded image with its black pixels removed. 2. The other issue is that you're trying to load a remote resource which is not an image (despite the JPG extension). You actually need to work with [this](https://gcdnb.pbrd.co/images/VA1RxuEWqS4u.jpg) (obtained via right-clicking on the image loaded from your original link). 3. The third issue *might* be CORS, especially if you're testing your code locally (your computer, no local server running, etc). You can overcome this with a browser extension (I used [CORS Everywhere][1] - I am in no way affiliated with whoever made it, I just needed something to debug your code, and I settled on this). One way of addressing these issues is with the following modifications in your code. ``` // the true image URL - perhaps it's better to provide an input // and let the user set their own URL // then you'd also have some sort of error handling if the URL // is not that of an image const overlayImageUrl = 'https://gcdnb.pbrd.co/images/VA1RxuEWqS4u.jpg'; document.getElementById('file-input').addEventListener('change', function(event) { const file = event.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = function(e) { const img = new Image(); img.onload = function() { // this was done so that its meaning // it's easily recognizable later on const frameWidth = img.width; const frameHeight = img.height; // the top layer - from the locally loaded image const topLayer = document.createElement('canvas'); const topCtx = topLayer.getContext('2d'); topLayer.width = frameWidth; topLayer.height = frameHeight; // draw the top layer topCtx.drawImage(img, 0, 0); // Get the image data const imageData = topCtx.getImageData(0, 0, frameWidth, frameHeight); const data = imageData.data; // Remove black background (set alpha to 0 for black pixels) for (let i = 0; i < data.length; i += 4) { const r = data[i]; const g = data[i + 1]; const b = data[i + 2]; // Check if the pixel is black (you can adjust the threshold as needed) if (r < 30 && g < 30 && b < 30) { data[i + 3] = 0; // Set alpha to 0 } } // Put the modified image data back onto the canvas topCtx.putImageData(imageData, 0, 0); // Load the overlay image from the hosting website const overlayImg = new Image(); overlayImg.crossOrigin = 'anonymous'; overlayImg.src = overlayImageUrl; overlayImg.onload = function() { // the background layer - from the remotely loaded image // it's using its own canvas const bgLayer = document.createElement('canvas'); bgLayer.width = img.width; bgLayer.height = img.height; const bgCtx = bgLayer.getContext('2d'); bgCtx.drawImage(overlayImg, 0, 0, frameWidth, frameHeight); // the composite - here to host the background // and the top layer (the one we poked holes in) const compositeCanvas = document.createElement('canvas'); compositeCanvas.width = frameWidth; compositeCanvas.height = frameHeight; const composite = compositeCanvas.getContext('2d'); // first the background... composite.drawImage(bgLayer,0,0); // ... then the top layer - our uploaded image composite.drawImage(topLayer,0,0); // now the canvas holds two other canvases // Convert canvas to image and download the final image const finalImageUrl = compositeCanvas.toDataURL('image/png'); const downloadLink = document.createElement('a'); downloadLink.href = finalImageUrl; downloadLink.download = 'final_image.png'; downloadLink.click(); }; }; img.src = e.target.result; }; reader.readAsDataURL(file); }); ``` [1]: https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/
I need to learn how to use Swagger to document my code and I thought to learn from Node JS: API Development with Swagger in Udemy.com but I had a problem with getting the params from req.swagger.params.id.value for example and req.body to fix the problem with the body I found out that you needed to add app.use(bodyParser.json()); in the app.js file but when I did this I could not the req.swagger.params.id.value to work. var SwaggerExpress = require("swagger-express-mw"); var express = require("express"); var bodyParser = require("body-parser"); var app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); I started to look at this example to see how they have set up Swagger https://github.com/apigee-127/swagger-tools/blob/master/examples/2.0/index.js with this example, I can get both parameters. But And add this to make a page with the documentation for your AP: app.use("/docs", swaggerUI.serve, swaggerUI.setup(swaggerDoc)); Now I need to find out how to send a response to the like res.status(200) or res.status(204) but I will update when I find out