row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
43,272
|
In the first case there is a board with dimensions 2*2 with 4 squares inside it of 1*1 dimension. The first square is empty i.e. it is a missing square in the upper left corner, so the L-shaped arrangement for this case will be LR and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the lower right. Similarly, In the second case a missing square is there in the upper right corner so the L-shaped arrangement for this case will be LL and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the lower left, in the third case a missing square is there in the lower right corner so the L-shaped arrangement for this case will be UL and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the upper left and in the fourth case a missing square is there in the lower left corner so the L-shaped arrangement for this case will be UR and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the upper right
We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. import java.util.Scanner;
public class TrominoTiling {
private static String[][] board;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter size of board (need to be 2^n and 0 to quit): ");
int boardSize = scanner.nextInt();
if (boardSize == 0) {
scanner.close();
return;
}
System.out.print("Please enter coordinates of missing square (separated by a space): ");
int xMissing = scanner.nextInt();
int yMissing = scanner.nextInt();
// Initialize the board
initializeBoard(boardSize);
// Mark the initially missing square
board[yMissing][xMissing] = "MS";
// Fill the board with trominoes
fillBoard(0, 0, boardSize, xMissing, yMissing);
// Print the result
for (int y = boardSize - 1; y >= 0; y--) { // Start from the top for display
for (int x = 0; x < boardSize; x++) {
System.out.print(board[y][x] + "\t");
}
System.out.println();
}
scanner.close();
}
private static void initializeBoard(int boardSize) {
board = new String[boardSize][boardSize];
for (int i = 0; i < boardSize; i++) {
for (int j = 0; j < boardSize; j++) {
board[i][j] = " "; // Initialize with spaces
}
}
}
private static void fillBoard(int x, int y, int size, int xMissing, int yMissing) {
if (size == 2) {
// Place the trominoes around the missing square.
String trominoMarker = "UR"; // Default placement, adjust based on actual position of the missing tile.
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (x + i != xMissing || y + j != yMissing) {
if (xMissing == x && yMissing == y) trominoMarker = "LR"; // Lower Left
else if (xMissing == x + 1 && yMissing == y) trominoMarker = "LL"; // Lower Right
else if (xMissing == x && yMissing == y + 1) trominoMarker = "UR"; // Upper Left
else if (xMissing == x + 1 && yMissing == y + 1) trominoMarker = "UL"; // Upper Right
board[y + j][x + i] = trominoMarker;
}
}
}
return;
}
int halfSize = size / 2;
// Identify center for placing the tromino if the missing square is not in this quadrant.
int centerX = x + halfSize - 1;
int centerY = y + halfSize - 1;
// Determine in which quadrant the missing square resides.
boolean missingInLowerLeft = xMissing < x + halfSize && yMissing < y + halfSize;
boolean missingInLowerRight = xMissing >= x + halfSize && yMissing < y + halfSize;
boolean missingInUpperLeft = xMissing < x + halfSize && yMissing >= y + halfSize;
boolean missingInUpperRight = xMissing >= x + halfSize && yMissing >= y + halfSize;
// Place the center tromino based on the quadrant of the missing square.
if (!missingInLowerLeft) board[centerY][centerX] = "MS"; // Bottom-Left
if (!missingInLowerRight) board[centerY][centerX + 1] = "MS"; // Bottom-Right
if (!missingInUpperLeft) board[centerY + 1][centerX] = "MS"; // Top-Left
if (!missingInUpperRight) board[centerY + 1][centerX + 1] = "MS"; // Top-Right
// Recursively solve for each quadrant.
fillBoard(x, y, halfSize, missingInLowerLeft ? xMissing : centerX, missingInLowerLeft ? yMissing : centerY);
fillBoard(x + halfSize, y, halfSize, missingInLowerRight ? xMissing : centerX + 1, missingInLowerRight ? yMissing : centerY);
fillBoard(x, y + halfSize, halfSize, missingInUpperLeft ? xMissing : centerX, missingInUpperLeft ? yMissing : centerY + 1);
fillBoard(x + halfSize, y + halfSize, halfSize, missingInUpperRight ? xMissing : centerX + 1, missingInUpperRight ? yMissing : centerY + 1);
// Replace the "MS" used for simulations with correct tromino markers.
if (!missingInLowerLeft) board[centerY][centerX] = "LR"; // Center tromino facing Lower Right
if (!missingInLowerRight) board[centerY][centerX + 1] = "LL"; // Center tromino facing Lower Left
if (!missingInUpperLeft) board[centerY + 1][centerX] = "UR"; // Center tromino facing Upper Right
if (!missingInUpperRight) board[centerY + 1][centerX + 1] = "UL"; // Center tromino facing Upper Left
}
} Please enter size of board (need to be 2^n and 0 to quit): 4
Please enter coordinates of missing square (separated by a space): 1 3
UL MS LR LR
UL UL UL LR
UL LR LL UR
UL UL UR UR this is the output that i got and the expected output is Please enter size of board (need to be 2^n and 0 to quit): 4
Please enter coordinates of missing square (seperated by a space): 1 3
LL MS UR UR
LL LL LR UR
LL LR LR LR
LL LL LR LR
|
84fd10ca9f5e6996fc73c49e5f4d1331
|
{
"intermediate": 0.346184641122818,
"beginner": 0.44892674684524536,
"expert": 0.20488864183425903
}
|
43,273
|
import java.util.Scanner;
public class TrominoTiling {
private static String[][] board;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter size of board (need to be 2^n and 0 to quit): ");
int boardSize = scanner.nextInt();
if (boardSize == 0) {
scanner.close();
return;
}
System.out.print("Please enter coordinates of missing square (separated by a space): ");
int xMissing = scanner.nextInt();
int yMissing = scanner.nextInt();
// Initialize the board
initializeBoard(boardSize);
// Mark the initially missing square
board[yMissing][xMissing] = "MS";
// Fill the board with trominoes
fillBoard(0, 0, boardSize, xMissing, yMissing);
// Print the result
for (int y = boardSize - 1; y >= 0; y--) { // Start from the top for display
for (int x = 0; x < boardSize; x++) {
System.out.print(board[y][x] + "\t");
}
System.out.println();
}
scanner.close();
}
private static void initializeBoard(int boardSize) {
board = new String[boardSize][boardSize];
for (int i = 0; i < boardSize; i++) {
for (int j = 0; j < boardSize; j++) {
board[i][j] = " "; // Initialize with spaces
}
}
}
private static void fillBoard(int x, int y, int size, int xMissing, int yMissing) {
if (size == 2) {
// Directly place the tromino markers, adjusting based on the position of the missing square.
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (x + i != xMissing || y + j != yMissing) {
// Determine direction based on the missing square to correctly place the "L" tromino.
if (xMissing == x && yMissing == y) board[y + j][x + i] = "LR"; // Lower Left
else if (xMissing == x + 1 && yMissing == y) board[y + j][x + i] = "LL"; // Lower Right
else if (xMissing == x && yMissing == y + 1) board[y + j][x + i] = "UR"; // Upper Left
else if (xMissing == x + 1 && yMissing == y + 1) board[y + j][x + i] = "UL"; // Upper Right
}
}
}
return;
}
int halfSize = size / 2;
int centerX = x + halfSize;
int centerY = y + halfSize;
// Determine center square filler based on where the missing square is
if (xMissing < centerX && yMissing < centerY) { // Missing square in Lower Left quadrant
fillBoard(x, y, halfSize, xMissing, yMissing);
fillBoard(x, y + halfSize, halfSize, centerX - 1, centerY);
fillBoard(x + halfSize, y, halfSize, centerX, centerY - 1);
fillBoard(x + halfSize, y + halfSize, halfSize, centerX, centerY);
board[centerY - 1][centerX] = "LL"; // marker for the top-right to bottom-left tromino
board[centerY][centerX] = "LL";
board[centerY][centerX - 1] = "LL";
} else if (xMissing >= centerX && yMissing < centerY) { // Missing square in Lower Right quadrant
fillBoard(x, y, halfSize, centerX - 1, centerY - 1);
fillBoard(x, y + halfSize, halfSize, centerX - 1, centerY);
fillBoard(x + halfSize, y, halfSize, xMissing, yMissing);
fillBoard(x + halfSize, y + halfSize, halfSize, centerX, centerY);
board[centerY - 1][centerX - 1] = "LR"; // marker for the top-left to bottom-right tromino
board[centerY][centerX] = "LR";
board[centerY][centerX - 1] = "LR";
} else if (xMissing < centerX && yMissing >= centerY) { // Missing square in Upper Left quadrant
fillBoard(x, y, halfSize, centerX - 1, centerY - 1);
fillBoard(x, y + halfSize, halfSize, xMissing, yMissing);
fillBoard(x + halfSize, y, halfSize, centerX, centerY - 1);
fillBoard(x + halfSize, y + halfSize, halfSize, centerX, centerY);
board[centerY - 1][centerX] = "UR"; // marker for the bottom-right to top-left tromino
board[centerY - 1][centerX - 1] = "UR";
board[centerY][centerX] = "UR";
} else if (xMissing >= centerX && yMissing >= centerY) { // Missing square in Upper Right quadrant
fillBoard(x, y, halfSize, centerX - 1, centerY - 1);
fillBoard(x, y + halfSize, halfSize, centerX - 1, centerY);
fillBoard(x + halfSize, y, halfSize, centerX, centerY - 1);
fillBoard(x + halfSize, y + halfSize, halfSize, xMissing, yMissing);
board[centerY - 1][centerX - 1] = "UL"; // marker for the bottom-left to top-right tromino
board[centerY - 1][centerX] = "UL";
board[centerY][centerX - 1] = "UL";
}
}
} the output that i got after running the program is Please enter size of board (need to be 2^n and 0 to quit): 4
Please enter coordinates of missing square (separated by a space): 1 3
UL MS LR LR
UL UL UR LR
UL UR UR UR
UL UL UR UR but the expected output is Please enter size of board (need to be 2^n and 0 to quit): 4
Please enter coordinates of missing square (seperated by a space): 1 3
LL MS UR UR
LL LL LR UR
LL LR LR LR
LL LL LR LR
|
da22edce79e143d89053ac4da7b4fb92
|
{
"intermediate": 0.30533483624458313,
"beginner": 0.4863525629043579,
"expert": 0.20831255614757538
}
|
43,274
|
Write a dedicated server implementation for Mount and Blade Warband in Python
|
7154acf527a700620b0c2d9fa2106064
|
{
"intermediate": 0.5272433161735535,
"beginner": 0.15137097239494324,
"expert": 0.3213857114315033
}
|
43,275
|
User
based on this For answer aware question generation we usually need 3 models, first which will extract answer like spans, second model will generate question on that answer and third will be a QA model which will take the question and produce an answer, then we can compare the two answers to see if the generated question is correct or not.
Having 3 models for single task is lot of complexity, so goal is to create a multi-task model which can do all of these 3 tasks
1.extract answer like spans
2. generate question based on the answer
3. QA
rewrite this function
from datasets import load_dataset
def preprocess_for_question_generation(examples):
if examples["answer"] is None or examples["context"] is None:
return None
if not isinstance(examples["answer"], list) or not isinstance(examples["context"], list):
return None
if len(examples["answer"]) != len(examples["context"]):
return None
prepared_questions = []
prepared_input_texts = []
for context, answer in zip(examples["context"], examples["answer"]):
input_format = f"generate question: context: {context} answer: {answer}"
prepared_input_texts.append(input_format)
tokenized_inputs = tokenizer(
prepared_input_texts,
max_length=128,
padding="max_length",
truncation=True,
return_tensors="pt"
)
if "question" in examples:
tokenized_questions = tokenizer(
examples["question"],
max_length=64,
padding="max_length",
truncation=True,
return_tensors="pt"
)
tokenized_inputs["labels"] = tokenized_questions["input_ids"].clone()
# Convert tensors to NumPy arrays
tokenized_inputs_numpy = {}
for key, value in tokenized_inputs.items():
tokenized_inputs_numpy[key] = value.numpy()
return tokenized_inputs_numpy
# Apply preprocessing to datasets
tokenized_train_dataset = train_dataset.map(preprocess_for_question_generation, batched=True)
tokenized_val_dataset = val_dataset.map(preprocess_for_question_generation, batched=True)
tokenized_test_dataset = test_dataset.map(preprocess_for_question_generation, batched=True)
|
eaf7905365b206323a922f97cee5140d
|
{
"intermediate": 0.2584262788295746,
"beginner": 0.4441412091255188,
"expert": 0.2974325120449066
}
|
43,276
|
how to save cookies from session using requests in python. and then load them to session?
|
40a26b800ee287d88f9e8105d4d0eff6
|
{
"intermediate": 0.5711962580680847,
"beginner": 0.13820023834705353,
"expert": 0.2906034290790558
}
|
43,277
|
<?php
function main_code($unique_id,$event,$nr_args,$args)
{
$event=$args[0];
if($unique_id==0&&$event!=1&&$event!=2)
{
send_data_to_player($unique_id,[2,0]);//force log in
}else{
if($event==1)
{
//REGISTER ACCOUNT
//INPUT:arg1-username arg2-password
//OUTPUT:arg1- state arg2 -unique id
if(isset($args[1])&&isset($args[2]))
{
$username=$args[1];
$password=$args[2];
if(check_string($username) and check_string($password) and !(is_numeric($password)) and !(is_numeric($username)))
{
if(file_exists("accounts/".$username.".txt"))
{
send_data_to_player($unique_id,[1,0]);//the account already exists
}else{
$last_unique_id=read_file("server_vars/player.txt") + 1;
write_file("server_vars/player.txt",$last_unique_id);
write_file("username_id/".$username.".txt",$last_unique_id);
write_file("accounts/".$username.".txt",$password);
make_dir('players/'.$last_unique_id.'/');//create the id directory
init_player($last_unique_id,$username);
send_data_to_player($unique_id,[1,1,$last_unique_id]);//succesfull created account
}
}else{
send_data_to_player($unique_id,[1,4]);//invalid characters used
}
}
}
else if($event==2)
{
//LOG IN
//INPUT:arg1-username arg2-password
//OUTPUT:arg1- state arg2 -unique id arg3- local id
if(isset($args[1])&&isset($args[2]))
{
$username=$args[1];
$password=$args[2];
if(check_string($username) and check_string($password) and !(is_numeric($password)) and !(is_numeric($username)))
{
if(file_exists("accounts/".$username.".txt"))
{
$real_password=read_file("accounts/".$username.".txt");
if($real_password==$password)
{
$local_id_slot=find_local_id(0);
if($local_id_slot!=0)
{
if(file_exists("ip_login/".get_player_ip().".txt"))
{
$unique_id_real = get_unique_id_by_username($username);
send_data_to_player($unique_id,[2,2,$unique_id_real,get_local_id_by_ip()]);//succesfull log in
send_initial_players($unique_id_real);
}else{
$unique_id_real =get_unique_id_by_username($username);
write_file("ip_login/".get_player_ip().".txt",$local_id_slot);
write_file("local_id/".$local_id_slot.".txt",$unique_id_real);
write_file("players/".$unique_id_real."/active.txt",1);
write_file("players/".$unique_id_real."/last_time_active.txt",time());
write_file("players/".$unique_id_real."/ip.txt",get_player_ip());
write_file("players/".$unique_id_real."/local_id.txt",$local_id_slot);
write_file("players/".$unique_id_real."/ping.txt",0);
write_file("players/".$unique_id_real."/ping_var.txt",0);
send_data_to_player($unique_id,[2,2,$unique_id_real,$local_id_slot]);//succesfull log in
send_initial_players($unique_id);
ti_on_player_connect($unique_id_real);
}
}else{
send_data_to_player($unique_id,[2,3]);//the server is full
}
}else{
send_data_to_player($unique_id,[2,1]);//invalid user or pass
}
}else{
send_data_to_player($unique_id,[2,1]);//invalid user or pass
}
}else{
send_data_to_player($unique_id,[2,4]);//invalid characters used
}
}
}
else if($event==3)
{
//CHAT
//Input arg1 - message
if(isset($args[1]))
{
$message = $args[1];
if($message=='')
{
}else{
if(is_numeric($message))
{
$message = $message.' ';
}
$username=get_player_username($unique_id);
for($i=1;$i<=10;$i++)
{
$u_id = get_unique_id_by_local($i);
if($u_id!=0)
{
send_data_to_player($u_id,[3,$message,$username],2);
}
}
}
}
}
else if($event==4)
{
//SAVE PLAYER POSITION
//Input: arg1-x arg2-y arg3-rotation
//output:none
if(isset($args[1]) and isset($args[2]) and isset($args[3]))
{
$x=$args[1];
$y=$args[2];
$rot=$args[3];
global $allow_teleport;
if($allow_teleport)
{
set_position($unique_id,$x,$y,$rot);
}else{
$position=get_position($unique_id);
$old_x=$position[0];
$old_y=$position[1];
$old_rot=$position[2];
$distance=sqrt( pow($old_x - $x , 2) + pow($old_y - $y , 2) );
if($distance < 1000)
{
set_position($unique_id,$x,$y,$rot);
}
else
{
$to_send[0]=5;
$to_send[1]=$old_x;
$to_send[2]=$old_y;
$to_send[3]=$old_rot;
send_data_to_player($unique_id,$to_send);
// send_data_to_player($unique_id,[15," ".$distance,0xFF0000],1);
}
}
}
}
else if($event==6)
{
//SEND PLAYERS POSITION
//Input:none
//Output:arg1 - number of players arg2 - local player id arg3 - x arg4- y arg5 - rot arg6 -local player id ....
$number_of_players=0;
$to_send[0]=6;
$c=2;
for($i=1;$i<=10;$i++)
{
$u_id=get_unique_id_by_local($i);
if($u_id!=0 and $u_id!=$unique_id)
{
$number_of_players++;
$to_send[$c]=$i;
$c++;
$position=get_position($u_id);
$x=$position[0];
$y=$position[1];
$rot=$position[2];
$to_send[$c]=$x;
$c++;
$to_send[$c]=$y;
$c++;
$to_send[$c]=$rot;
$c++;
}
}
$c--;
$to_send[1]=$number_of_players;
send_data_to_player($unique_id,$to_send);
}
else if($event==9)
{
//PING
if(isset($args[1]))
{
if($args[1]==0)
{
write_file("players/".$unique_id."/ping_var.txt",round(microtime_float(), 2));
send_data_to_player($unique_id,[9,1]);
}else{
$time=read_file("players/".$unique_id."/ping_var.txt");
$ping=round(round(round(microtime_float(), 2) - round($time,2),2)*100);
write_file("players/".$unique_id."/ping.txt",$ping);
write_file("players/".$unique_id."/ping_var.txt",0);
$c=2;
$data[0]=9;
$data[1]=0;
for($i=1;$i<=10;$i++)
{
$u_id=get_unique_id_by_local($i);
if($u_id!=0)
{
$data[$c]=read_file("players/".$u_id."/ping.txt");
$c++;
}else{
$data[$c]=0;
$c++;
}
}
send_data_to_player($unique_id,$data);
}
}
}
else if($event==10)
{
//SEND PLAYER INVENTORY
$inv=read_file("players/".$unique_id."/inventory.txt");
$inv=explode("|",$inv);
$inv[0]=10;
send_data_to_player($unique_id,$inv);
}
else if($event==11)
{
//SEND PLAYER GOLD
send_data_to_player($unique_id,[11,get_gold($unique_id)]);
}
else if($event==14)
{
//SEND PLAYER TROOPS
$troops=read_file("players/".$unique_id."/troops.txt");
$troops=explode("|",$troops);
$nr=0;
foreach ($a as $troops)
{
if($a!=-1)
$nr++;
}
$troops[0]=14;
$troops[1]=$nr+2;//incrementing here, so we will not have to increment in the game
send_data_to_player($unique_id,$troops);
}
}
}
?>
Write that code on Python
|
851aaeed207adf1d71e4bb1884baf629
|
{
"intermediate": 0.31659311056137085,
"beginner": 0.4439292550086975,
"expert": 0.23947766423225403
}
|
43,278
|
function main_code($unique_id,$event,$nr_args,$args)
{
$event=$args[0];
if($unique_id==0&&$event!=1&&$event!=2)
{
send_data_to_player($unique_id,[2,0]);//force log in
}else{
if($event==1)
{
//REGISTER ACCOUNT
//INPUT:arg1-username arg2-password
//OUTPUT:arg1- state arg2 -unique id
if(isset($args[1])&&isset($args[2]))
{
$username=$args[1];
$password=$args[2];
if(check_string($username) and check_string($password) and !(is_numeric($password)) and !(is_numeric($username)))
{
if(file_exists("accounts/".$username.".txt"))
{
send_data_to_player($unique_id,[1,0]);//the account already exists
}else{
$last_unique_id=read_file("server_vars/player.txt") + 1;
write_file("server_vars/player.txt",$last_unique_id);
write_file("username_id/".$username.".txt",$last_unique_id);
write_file("accounts/".$username.".txt",$password);
make_dir('players/'.$last_unique_id.'/');//create the id directory
init_player($last_unique_id,$username);
send_data_to_player($unique_id,[1,1,$last_unique_id]);//succesfull created account
}
}else{
send_data_to_player($unique_id,[1,4]);//invalid characters used
}
}
}
else if($event==2)
{
//LOG IN
//INPUT:arg1-username arg2-password
//OUTPUT:arg1- state arg2 -unique id arg3- local id
if(isset($args[1])&&isset($args[2]))
{
$username=$args[1];
$password=$args[2];
if(check_string($username) and check_string($password) and !(is_numeric($password)) and !(is_numeric($username)))
{
if(file_exists("accounts/".$username.".txt"))
{
$real_password=read_file("accounts/".$username.".txt");
if($real_password==$password)
{
$local_id_slot=find_local_id(0);
if($local_id_slot!=0)
{
if(file_exists("ip_login/".get_player_ip().".txt"))
{
$unique_id_real = get_unique_id_by_username($username);
send_data_to_player($unique_id,[2,2,$unique_id_real,get_local_id_by_ip()]);//succesfull log in
send_initial_players($unique_id_real);
}else{
$unique_id_real =get_unique_id_by_username($username);
write_file("ip_login/".get_player_ip().".txt",$local_id_slot);
write_file("local_id/".$local_id_slot.".txt",$unique_id_real);
write_file("players/".$unique_id_real."/active.txt",1);
write_file("players/".$unique_id_real."/last_time_active.txt",time());
write_file("players/".$unique_id_real."/ip.txt",get_player_ip());
write_file("players/".$unique_id_real."/local_id.txt",$local_id_slot);
write_file("players/".$unique_id_real."/ping.txt",0);
write_file("players/".$unique_id_real."/ping_var.txt",0);
send_data_to_player($unique_id,[2,2,$unique_id_real,$local_id_slot]);//succesfull log in
send_initial_players($unique_id);
ti_on_player_connect($unique_id_real);
}
}else{
send_data_to_player($unique_id,[2,3]);//the server is full
}
}else{
send_data_to_player($unique_id,[2,1]);//invalid user or pass
}
}else{
send_data_to_player($unique_id,[2,1]);//invalid user or pass
}
}else{
send_data_to_player($unique_id,[2,4]);//invalid characters used
}
}
}
else if($event==3)
{
//CHAT
//Input arg1 - message
if(isset($args[1]))
{
$message = $args[1];
if($message=='')
{
}else{
if(is_numeric($message))
{
$message = $message.' ';
}
$username=get_player_username($unique_id);
for($i=1;$i<=10;$i++)
{
$u_id = get_unique_id_by_local($i);
if($u_id!=0)
{
send_data_to_player($u_id,[3,$message,$username],2);
}
}
}
}
}
else if($event==4)
{
//SAVE PLAYER POSITION
//Input: arg1-x arg2-y arg3-rotation
//output:none
if(isset($args[1]) and isset($args[2]) and isset($args[3]))
{
$x=$args[1];
$y=$args[2];
$rot=$args[3];
global $allow_teleport;
if($allow_teleport)
{
set_position($unique_id,$x,$y,$rot);
}else{
$position=get_position($unique_id);
$old_x=$position[0];
$old_y=$position[1];
$old_rot=$position[2];
$distance=sqrt( pow($old_x - $x , 2) + pow($old_y - $y , 2) );
if($distance < 1000)
{
set_position($unique_id,$x,$y,$rot);
}
else
{
$to_send[0]=5;
$to_send[1]=$old_x;
$to_send[2]=$old_y;
$to_send[3]=$old_rot;
send_data_to_player($unique_id,$to_send);
// send_data_to_player($unique_id,[15," ".$distance,0xFF0000],1);
}
}
}
}
else if($event==6)
{
//SEND PLAYERS POSITION
//Input:none
//Output:arg1 - number of players arg2 - local player id arg3 - x arg4- y arg5 - rot arg6 -local player id ....
$number_of_players=0;
$to_send[0]=6;
$c=2;
for($i=1;$i<=10;$i++)
{
$u_id=get_unique_id_by_local($i);
if($u_id!=0 and $u_id!=$unique_id)
{
$number_of_players++;
$to_send[$c]=$i;
$c++;
$position=get_position($u_id);
$x=$position[0];
$y=$position[1];
$rot=$position[2];
$to_send[$c]=$x;
$c++;
$to_send[$c]=$y;
$c++;
$to_send[$c]=$rot;
$c++;
}
}
$c--;
$to_send[1]=$number_of_players;
send_data_to_player($unique_id,$to_send);
}
else if($event==9)
{
//PING
if(isset($args[1]))
{
if($args[1]==0)
{
write_file("players/".$unique_id."/ping_var.txt",round(microtime_float(), 2));
send_data_to_player($unique_id,[9,1]);
}else{
$time=read_file("players/".$unique_id."/ping_var.txt");
$ping=round(round(round(microtime_float(), 2) - round($time,2),2)*100);
write_file("players/".$unique_id."/ping.txt",$ping);
write_file("players/".$unique_id."/ping_var.txt",0);
$c=2;
$data[0]=9;
$data[1]=0;
for($i=1;$i<=10;$i++)
{
$u_id=get_unique_id_by_local($i);
if($u_id!=0)
{
$data[$c]=read_file("players/".$u_id."/ping.txt");
$c++;
}else{
$data[$c]=0;
$c++;
}
}
send_data_to_player($unique_id,$data);
}
}
}
else if($event==10)
{
//SEND PLAYER INVENTORY
$inv=read_file("players/".$unique_id."/inventory.txt");
$inv=explode("|",$inv);
$inv[0]=10;
send_data_to_player($unique_id,$inv);
}
else if($event==11)
{
//SEND PLAYER GOLD
send_data_to_player($unique_id,[11,get_gold($unique_id)]);
}
else if($event==14)
{
//SEND PLAYER TROOPS
$troops=read_file("players/".$unique_id."/troops.txt");
$troops=explode("|",$troops);
$nr=0;
foreach ($a as $troops)
{
if($a!=-1)
$nr++;
}
$troops[0]=14;
$troops[1]=$nr+2;//incrementing here, so we will not have to increment in the game
send_data_to_player($unique_id,$troops);
}
}
}
Write that PHP code using Python
|
cd021b769eda62c905fc6d42351924dc
|
{
"intermediate": 0.2854423224925995,
"beginner": 0.46029508113861084,
"expert": 0.2542625665664673
}
|
43,279
|
traduce el siguiente text: My apologies for misunderstanding your initial question. Since you mentioned that you are experiencing this issue within Hugging Face Spaces, which runs on Google Colab, here's how you can try resolving this error:
First, let's create a new notebook cell at the beginning containing the following lines to import the required libraries and set up the environment:
|
0dfab15a452e1cd4599b0b48e0d7d6fb
|
{
"intermediate": 0.39410367608070374,
"beginner": 0.307159960269928,
"expert": 0.2987363636493683
}
|
43,280
|
In django, I have the following models:
class Product(models.Model):
name=models.CharField(max_length=200)
class Order(models.Model):
date=models.DateField()
invoice=models.CharField(max_length=200)
class OrderItem(models.Model):
order=models.ForeignKey(Order)
product=models.ForeignKey(Product)
count=models.IntegerField()
With these models, how do I create a form where I can fill in the date and invoice and a list of items. Each items is a dropdown with the possible products of which I can choose one. Then there is a field for the count, the number of items I want to order. After I have chosen an item and its count I should get a new dropdown so I can chose more items.
|
e0aec9afe6255e384d2525deea542e67
|
{
"intermediate": 0.6538017392158508,
"beginner": 0.18498963117599487,
"expert": 0.1612086445093155
}
|
43,281
|
rewrite this but make it easier to understand and simpler:
Monitors are high-level synchronization constructs used in concurrent programming to control access to shared resources by multiple threads, ensuring data integrity and preventing race conditions. Unlike semaphores and mutexes which are more primitive synchronization mechanisms, monitors offer a more abstract and easier-to-use solution for managing concurrent access to shared resources. They encapsulate both the data structure being protected and the operations (procedures/methods) that can be performed on the data, providing a mechanism to regulate which threads can access the shared resource at any given time.
|
f703748986f53be14ba1d5e94513d55d
|
{
"intermediate": 0.33301785588264465,
"beginner": 0.30706045031547546,
"expert": 0.3599216938018799
}
|
43,282
|
what is wrong here? i am trying to use monitors:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // for sleep function : waits for seconds
#include <semaphore.h>
#define prod 8
#define con 4
int count = 0;
int sum = 0;
int buffer[10];
pthread_cond_t producer;
pthread_cond_t consumer;
pthread_mutex_t lock;
void * producerFunc(void * param) {
pthread_mutex_lock(&lock);
while(count == 10) {
pthread_cond_wait(&producer, &lock);
}
buffer[sum] = 1;
sum = sum + 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&consumer);
pthread_exit(NULL);
}
void * consumerFunc(void * param) {
pthread_mutex_lock(&lock);
while(count == 0) {
pthread_cond_wait(&consumer, &lock);
}
sum = sum - 1;
buffer[sum] = 0;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&producer);
pthread_exit(NULL);
}
int main() {
producerFunc(NULL);
consumerFunc(NULL);
for (int i = 0; i < 10; i++) printf(“%d”, buffer[i]);
return 0;
}
|
a009e5d60307f7f8a9d4cf11b0168047
|
{
"intermediate": 0.36875343322753906,
"beginner": 0.5273294448852539,
"expert": 0.10391715914011002
}
|
43,283
|
what is wrong here? i am trying to use monitors:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // for sleep function : waits for seconds
#include <semaphore.h>
#define prod 8
#define con 4
int count = 0;
int sum = 0;
int buffer[10];
pthread_cond_t producer;
pthread_cond_t consumer;
pthread_mutex_t lock;
void * producerFunc(void * param) {
pthread_mutex_lock(&lock);
while(count == 10) {
pthread_cond_wait(&producer, &lock);
}
buffer[sum] = 1;
sum = sum + 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&consumer);
pthread_exit(NULL);
}
void * consumerFunc(void * param) {
pthread_mutex_lock(&lock);
while(count == 0) {
pthread_cond_wait(&consumer, &lock);
}
sum = sum - 1;
buffer[sum] = 0;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&producer);
pthread_exit(NULL);
}
int main() {
producerFunc(NULL);
consumerFunc(NULL);
for (int i = 0; i < 10; i++) printf(“%d”, buffer[i]);
return 0;
}
|
40245a3013f9639e23e42711157a5c7b
|
{
"intermediate": 0.36875343322753906,
"beginner": 0.5273294448852539,
"expert": 0.10391715914011002
}
|
43,284
|
.buttons-container {
display: flex;
text-decoration: none;
font-weight: 400;
}
.buttons-container a:hover {
color: white;
transition: color 0.3s;
}
.btn-goto-server {
width: 185px;
height: 60px;
color: black;
background-color: #eda34c;
border-radius: 5px;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
margin: 0 15px 0 0;
transition: color 0.3s;
}
.btn-create-account {
width: 160px;
height: 60px;
border: 3px solid #353534;
padding: 10px 20px;
color: #353534;
display: flex;
justify-content: center;
align-items: center;
border-radius: 5px;
font-size: 13px;
transition: color 0.3s;
}
как сделать лучше?
чтобы может быть не копировать?
|
32d8b3e0b02fecdde76cc362db9e7668
|
{
"intermediate": 0.4373995065689087,
"beginner": 0.2514629065990448,
"expert": 0.3111375868320465
}
|
43,285
|
Provide some more bs test cases
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import components.map.Map;
import components.map.Map.Pair;
import components.program.Program;
import components.simplereader.SimpleReader;
import components.simplereader.SimpleReader1L;
import components.statement.Statement;
/**
* JUnit test fixture for {@code Program}'s constructor and kernel methods.
*
* @author Wayne Heym
* @author Erich Boschert, Alex Zhang
*
*/
public abstract class ProgramTest {
/**
* The name of a file containing a BL program.
*/
private static final String FILE_NAME_1 = "data/program-sample.bl", FILE_NAME_2 = "data/program-sample2.bl",
FILE_NAME_3 = "data/program-sample3.bl", FILE_NAME_4 = "data/program-sample4.bl",
FILE_NAME_5 = "data/program-sample5.bl";
// TODO - define file names for additional test inputs
/**
* Invokes the {@code Program} constructor for the implementation under test and
* returns the result.
*
* @return the new program
* @ensures constructor = ("Unnamed", {}, compose((BLOCK, ?, ?), <>))
*/
protected abstract Program constructorTest();
/**
* Invokes the {@code Program} constructor for the reference implementation and
* returns the result.
*
* @return the new program
* @ensures constructor = ("Unnamed", {}, compose((BLOCK, ?, ?), <>))
*/
protected abstract Program constructorRef();
/**
*
* Creates and returns a {@code Program}, of the type of the implementation
* under test, from the file with the given name.
*
* @param filename the name of the file to be parsed to create the program
* @return the constructed program
* @ensures createFromFile = [the program as parsed from the file]
*/
private Program createFromFileTest(String filename) {
Program p = this.constructorTest();
SimpleReader file = new SimpleReader1L(filename);
p.parse(file);
file.close();
return p;
}
/**
*
* Creates and returns a {@code Program}, of the reference implementation type,
* from the file with the given name.
*
* @param filename the name of the file to be parsed to create the program
* @return the constructed program
* @ensures createFromFile = [the program as parsed from the file]
*/
private Program createFromFileRef(String filename) {
Program p = this.constructorRef();
SimpleReader file = new SimpleReader1L(filename);
p.parse(file);
file.close();
return p;
}
/**
* Test constructor.
*/
@Test
public final void testConstructor() {
/*
* Setup
*/
Program pRef = this.constructorRef();
/*
* The call
*/
Program pTest = this.constructorTest();
/*
* Evaluation
*/
assertEquals(pRef, pTest);
}
/**
* Test name.
*/
@Test
public final void testName() {
/*
* Setup
*/
Program pTest = this.createFromFileTest(FILE_NAME_1);
Program pRef = this.createFromFileRef(FILE_NAME_1);
/*
* The call
*/
String result = pTest.name();
/*
* Evaluation
*/
assertEquals(pRef, pTest);
assertEquals("Test", result);
}
/**
* Test setName.
*/
@Test
public final void testSetName() {
/*
* Setup
*/
Program pTest = this.createFromFileTest(FILE_NAME_1);
Program pRef = this.createFromFileRef(FILE_NAME_1);
String newName = "Replacement";
pRef.setName(newName);
/*
* The call
*/
pTest.setName(newName);
/*
* Evaluation
*/
assertEquals(pRef, pTest);
}
/**
* Test newContext.
*/
@Test
public final void testNewContext() {
/*
* Setup
*/
Program pTest = this.createFromFileTest(FILE_NAME_1);
Program pRef = this.createFromFileRef(FILE_NAME_1);
Map<String, Statement> cRef = pRef.newContext();
/*
* The call
*/
Map<String, Statement> cTest = pTest.newContext();
/*
* Evaluation
*/
assertEquals(pRef, pTest);
assertEquals(cRef, cTest);
}
/**
* Test swapContext.
*/
@Test
public final void testSwapContext() {
/*
* Setup
*/
Program pTest = this.createFromFileTest(FILE_NAME_1);
Program pRef = this.createFromFileRef(FILE_NAME_1);
Map<String, Statement> contextRef = pRef.newContext();
Map<String, Statement> contextTest = pTest.newContext();
String oneName = "one";
pRef.swapContext(contextRef);
Pair<String, Statement> oneRef = contextRef.remove(oneName);
/* contextRef now has just "two" */
pRef.swapContext(contextRef);
/* pRef's context now has just "two" */
contextRef.add(oneRef.key(), oneRef.value());
/* contextRef now has just "one" */
/* Make the reference call, replacing, in pRef, "one" with "two": */
pRef.swapContext(contextRef);
pTest.swapContext(contextTest);
Pair<String, Statement> oneTest = contextTest.remove(oneName);
/* contextTest now has just "two" */
pTest.swapContext(contextTest);
/* pTest's context now has just "two" */
contextTest.add(oneTest.key(), oneTest.value());
/* contextTest now has just "one" */
/*
* The call
*/
pTest.swapContext(contextTest);
/*
* Evaluation
*/
assertEquals(pRef, pTest);
assertEquals(contextRef, contextTest);
}
/**
* Test newBody.
*/
@Test
public final void testNewBody() {
/*
* Setup
*/
Program pTest = this.createFromFileTest(FILE_NAME_1);
Program pRef = this.createFromFileRef(FILE_NAME_1);
Statement bRef = pRef.newBody();
/*
* The call
*/
Statement bTest = pTest.newBody();
/*
* Evaluation
*/
assertEquals(pRef, pTest);
assertEquals(bRef, bTest);
}
/**
* Test swapBody.
*/
@Test
public final void testSwapBody() {
/*
* Setup
*/
Program pTest = this.createFromFileTest(FILE_NAME_1);
Program pRef = this.createFromFileRef(FILE_NAME_1);
Statement bodyRef = pRef.newBody();
Statement bodyTest = pTest.newBody();
pRef.swapBody(bodyRef);
Statement firstRef = bodyRef.removeFromBlock(0);
/* bodyRef now lacks the first statement */
pRef.swapBody(bodyRef);
/* pRef's body now lacks the first statement */
bodyRef.addToBlock(0, firstRef);
/* bodyRef now has just the first statement */
/* Make the reference call, replacing, in pRef, remaining with first: */
pRef.swapBody(bodyRef);
pTest.swapBody(bodyTest);
Statement firstTest = bodyTest.removeFromBlock(0);
/* bodyTest now lacks the first statement */
pTest.swapBody(bodyTest);
/* pTest's body now lacks the first statement */
bodyTest.addToBlock(0, firstTest);
/* bodyTest now has just the first statement */
/*
* The call
*/
pTest.swapBody(bodyTest);
/*
* Evaluation
*/
assertEquals(pRef, pTest);
assertEquals(bodyRef, bodyTest);
}
// TODO - provide additional test cases to thoroughly test ProgramKernel
}
|
8b8fc7fd4310475eb2a36e58471c50a7
|
{
"intermediate": 0.3950110971927643,
"beginner": 0.330659419298172,
"expert": 0.27432942390441895
}
|
43,286
|
--[[
@description Knobs: some knob components for your reaimgui projects
@version
0.0.1
@author Perken
@provides
./**/*.lua
@about
# Knobs
A port of imgui-rs-knobs
HOW TO USE:
|
03c68161af4fa4f279abe33f84fed63f
|
{
"intermediate": 0.42693567276000977,
"beginner": 0.2863596975803375,
"expert": 0.28670454025268555
}
|
43,287
|
i have a csv file that includes Date BTC ETH USDT BNB SOL XRP ADA DOGE Others
columns
in some parts some Dates are missing ,like:
3/4/2024 48.96 16.52 3.97 2.52 2.37 1.3 0.96 0.71 22.69
3/6/2024 50.7 17.24 4.03 2.45 2.24 1.31 0.98 0.9 20.15
3/8/2024 49.41 17.41 3.78 2.73 2.4 1.29 0.98 0.85 21.15
3/10/2024 49.26 17.21 3.73 2.76 2.35 1.25 0.96 0.94 21.54
...
which 3/5/2024,3/7/2024,3/9/2024, and... are missing
give me a proper python code so in place and fill missed rows by placing mean of top and bottom data
|
9d480f2a80566f6e5085aab5e8b45cdd
|
{
"intermediate": 0.46049368381500244,
"beginner": 0.3448759913444519,
"expert": 0.19463030993938446
}
|
43,288
|
Finish the arduino code, there are missing functions
#include <IRremote.h>
const int IR_RECEIVE_PIN = 2; // Define the pin number for the IR Sensor
String lastDecodedValue = ""; // Variable to store the last decoded value
void setup() {
Serial.begin(9600); // Start serial communication at 9600 baud rate
IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK); // Start the IR receiver
}
void loop() {
if (IrReceiver.decode()) {
String decodedValue = decodeKeyValue(IrReceiver.decodedIRData.command);
if (decodedValue != "ERROR" && decodedValue != lastDecodedValue) {
Serial.println(decodedValue);
lastDecodedValue = decodedValue; // Update the last decoded value
}
IrReceiver.resume(); // Enable receiving of the next value
}
}
|
6e03c70bd00f050773554ca6b1977c75
|
{
"intermediate": 0.32191306352615356,
"beginner": 0.5415002107620239,
"expert": 0.1365867555141449
}
|
43,289
|
save request session cookie jar to json in python
|
1232fe40ef898071cfae2bd6ecc11a82
|
{
"intermediate": 0.3928641676902771,
"beginner": 0.30268824100494385,
"expert": 0.3044475018978119
}
|
43,290
|
Refer to the datasheet (of a temperature DH11) provided in the SunFounder manual the sensor
returns the following bits:
• What is the purpose of the last 8 bits?
• Is this a valid reading?
• What is the temperature?
• What is humidity?
|
c568a0e7a56560f605c3bc8f7ea4bf1b
|
{
"intermediate": 0.44555583596229553,
"beginner": 0.343417227268219,
"expert": 0.21102690696716309
}
|
43,291
|
give me python code to download crypto market cap history as csv file
|
adf1c1893e93bb28e0084c69212ba3d0
|
{
"intermediate": 0.5529739856719971,
"beginner": 0.14922457933425903,
"expert": 0.2978014349937439
}
|
43,292
|
hi is this chatgpt 4
|
a91bed252cd2c0e81fa337a04bf59587
|
{
"intermediate": 0.3360641300678253,
"beginner": 0.25178489089012146,
"expert": 0.41215094923973083
}
|
43,293
|
explain pipes in computer systems based on this explanation:
Pipes : mechanism allowing two processes to communicate
Ø Very Old first Inter Process Communication (IPC) mechanisms in early UNIX, but exist
also in Windows
Ø Must a relationship (such as parent – child) exist between the communicating
processes?
Ø Can the pipes communicate over a network, or must the communicating processes
reside on the same machine?
Ø Pipes are unidirectional: you write at the write end, and read from the read end.
Ø For bidirectional communication, use a socket, or two pipes.
Ø You can use a pipe for bidirectional communication if both processes keep both ends of
the pipe open. You need to define a protocol for whose turn it is to talk. This is highly
impractical
|
2734e44750f3add84b88d9705456b09e
|
{
"intermediate": 0.3151293098926544,
"beginner": 0.27445659041404724,
"expert": 0.41041406989097595
}
|
43,294
|
i had made a youtube shorts from "MINDBLOWING - Modern Tools That Decode Mahabharata & Ramayana | Nilesh Nilkanth Oak" whose transcript is "Then you will go to the land of silver. That is the Thailand area. Then the Yavadvip. So Ropyadvip, Yavadvip. That is the land of Yava, the grains. That is the Java. The Java has come from Yava. Then he keeps on describing many islands. Then he says, after that, you will see the ocean. That is possibly many oceans, but the Pacific. Once you cross this, now this is when it gets extremely fascinating. Once you cross it, you are going to come to the area of Lord Ananta, Anantadev. And in that area, to mark the flag of Ananta, just like Arjuna has his own flag and Bhima has his own flag. That flag is inscribed on the surface of the stone, surface of the mountain. And he describes how that mountain is. I'm going to say this to you. I will split it. Like a trident. Shining like a gold. Yellow color. Like a pillar. Like a flag. Tal meaning like a pole." now make youtube shorts title , description and keywords to make it SEO strong
|
9cfd7dd78ff4e5c96e307220874ff82a
|
{
"intermediate": 0.37844985723495483,
"beginner": 0.2701428532600403,
"expert": 0.35140734910964966
}
|
43,295
|
I am studying for my upcoming final exam for my c++ computing class, after this text I will be pasting in a question and a correct answer to the question and i want you to explain why it is correct, and give me all the relevant information regarding the topic of the question. I want your reply to be very comprehensive and detailed, do you understand? I will tip you $100
|
eecd5d8250b357517de6e00f2c423cdf
|
{
"intermediate": 0.2967158555984497,
"beginner": 0.3634164035320282,
"expert": 0.3398677408695221
}
|
43,296
|
I am writing a program to move the robot in a virtual environment in Gazebo.
The code is shown below :"import rospy
from nav_msgs.msg import Odometry
from tf.transformations import euler_from_quaternion
from geometry_msgs.msg import Point, Twist
from math import atan2
x = 0.0
y = 0.0
theta = 0.0
def newOdom(msg):
global x
global y
global theta
x = msg.pose.pose.position.x
y = msg.pose.pose.position.y
rot_q = msg.pose.pose.orientation
(roll, pitch, theta) = euler_from_quaternion([rot_q.x, rot_q.y, rot_q.z, rot_q.w])
rospy.init_node("speed_controller")
sub = rospy.Subscriber("/odometry/filtered", Odometry, newOdom)
pub = rospy.Publisher("/cmd_vel", Twist, queue_size = 1)
speed = Twist()
r = rospy.Rate(4)
goal = Point()
goal.x = 5
goal.y = 5
while not rospy.is_shutdown():
inc_x = goal.x -x
inc_y = goal.y -y
angle_to_goal = atan2(inc_y, inc_x)
if abs(angle_to_goal - theta) > 0.1:
speed.linear.x = 0.0
speed.angular.z = 0.3
else:
speed.linear.x = 0.5
speed.angular.z = 0.0
pub.publish(speed)
r.sleep()"
How to modify the code to let the robot from a certain point to another point ?
|
f0a6fbc26ce19398f8a915fd5d9aa285
|
{
"intermediate": 0.49299705028533936,
"beginner": 0.2189294993877411,
"expert": 0.28807348012924194
}
|
43,297
|
I am writing a program to move the robot in a virtual environment in Gazebo.
The code is shown below :“To move the robot from A to B, we can apply a controller. Then we create a controller.py file under the src folder in the package with the following content.
import rospy
from nav_msgs.msg import Odometry
from tf.transformations import euler_from_quaternion
from geometry_msgs.msg import Point, Twist
from math import atan2
x = 0.0
y = 0.0
theta = 0.0
def newOdom(msg):
global x
global y
global theta
x = msg.pose.pose.position.x
y = msg.pose.pose.position.y
rot_q = msg.pose.pose.orientation
(roll, pitch, theta) = euler_from_quaternion([rot_q.x, rot_q.y, rot_q.z, rot_q.w])
rospy.init_node("speed_controller")
sub = rospy.Subscriber("/odometry/filtered", Odometry, newOdom)
pub = rospy.Publisher("/cmd_vel", Twist, queue_size = 1)
speed = Twist()
r = rospy.Rate(4)
goal = Point()
goal.x = 5
goal.y = 5
while not rospy.is_shutdown():
inc_x = goal.x -x
inc_y = goal.y -y
angle_to_goal = atan2(inc_y, inc_x)
if abs(angle_to_goal - theta) > 0.1:
speed.linear.x = 0.0
speed.angular.z = 0.3
else:
speed.linear.x = 0.5
speed.angular.z = 0.0
pub.publish(speed)
r.sleep() "
How to modify the code to let the robot from a certain point to another point ?
|
2be6ead3f2c302b0c53eb041190f5ceb
|
{
"intermediate": 0.4446580708026886,
"beginner": 0.27583369612693787,
"expert": 0.2795082926750183
}
|
43,298
|
An error occurred: HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url: /repos/MrKrit0/appius-adept_integration (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')))
|
c26b75101b23a78c69b0f351a3c10420
|
{
"intermediate": 0.38934019207954407,
"beginner": 0.17966030538082123,
"expert": 0.4309995472431183
}
|
43,299
|
r u GPT4?
|
083307625d0827520fbad36f9d5e2364
|
{
"intermediate": 0.30303189158439636,
"beginner": 0.21426834166049957,
"expert": 0.48269978165626526
}
|
43,300
|
Exercise B. What is the output of the following code segment?
num = 31
sum = 2
while num < 40:
sum = (num % 3)
num += sum
print(num, sum)
the question is on trace tables
the answer has 12 boxes, 2 wide 6 tall
|
4ddd4b6867f68e2a71472d7f6c7b1d2e
|
{
"intermediate": 0.27939462661743164,
"beginner": 0.5168867707252502,
"expert": 0.2037186175584793
}
|
43,301
|
in c++ how to know if a function has an O(1) time complexity
|
b1e3a20c8138827de8a7f1bded1db607
|
{
"intermediate": 0.2279047667980194,
"beginner": 0.40408435463905334,
"expert": 0.36801090836524963
}
|
43,302
|
how do I maintain a hashmap of coroutine jobs in Kotlin, that repeats every minute or whenever accessed
|
ca0360e55fc1637aed29b952d1922e9d
|
{
"intermediate": 0.6444565653800964,
"beginner": 0.1424279659986496,
"expert": 0.21311545372009277
}
|
43,303
|
how do I maintain a hashmap of coroutine jobs in Kotlin, that repeats every minute or whenever accessed
|
41403bc481b6e797275f33d0afa7e98d
|
{
"intermediate": 0.6444565653800964,
"beginner": 0.1424279659986496,
"expert": 0.21311545372009277
}
|
43,304
|
write a python script to fill custom data in page 4 of a pdf file. the file has clickable text fields and checkboxes.
|
f4b58ba913601996df9ef26278248ca7
|
{
"intermediate": 0.3631509244441986,
"beginner": 0.29594600200653076,
"expert": 0.34090304374694824
}
|
43,305
|
create a script for a logitec mouse to move cursor left and right 1 pixel recurring.
|
175b84e39c2d3675ceb965c4830bfd60
|
{
"intermediate": 0.3274843692779541,
"beginner": 0.1177324652671814,
"expert": 0.5547832250595093
}
|
43,306
|
//+------------------------------------------------------------------+
//| ProjectName |
//| Copyright 2020, CompanyName |
//| http://www.companyname.net |
//+------------------------------------------------------------------+
#include <Controls\Dialog.mqh>
#include <Controls\Button.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Controls\Label.mqh>
#include <Controls\Edit.mqh>
const string ID = "-1002113042792";
const string token = "7152618530:AAGJJC3zdkmCce3B7i11Dn2JDMh7GqpamyM";
const string IDToLicense = "-1002100526472";
#define INDENT_LEFT (11)
#define INDENT_TOP (11)
#define CONTROLS_GAP_X (5)
#define BUTTON_WIDTH (100)
#define BUTTON_HEIGHT (20)
CPositionInfo m_position;
CTrade m_trade;
CSymbolInfo m_symbol;
CLabel m_labelPipsToChange; // Метка для значения PipsToChange
CEdit m_editPipsToChange;
CLabel m_labelPipsToUpChange; // Метка для значения PipsToChange
CEdit m_editPipsToUpChange;
CLabel m_labelPipsToDownChange; // Метка для значения PipsToChange
CEdit m_editPipsToDownChange;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
class CAppWindowTwoButtons : public CAppDialog
{
private:
CButton m_button1; // the button object
CButton m_button2; // the button object
CLabel m_labelProfit;
public:
CAppWindowTwoButtons(void);
~CAppWindowTwoButtons(void);
//--- create
virtual bool Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);
//--- chart event handler
virtual bool OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam);
void UpdateProfitLabel(void);
void OnPipsToChangeEdit(void);
bool CreatePipsToChangeControls(void);
void OnPipsToDownChangeEdit(void);
bool CreatePipsToDownChangeControls(void);
void OnPipsToUpChangeEdit(void);
bool CreatePipsToUpChangeControls(void);
//--- create dependent controls
bool CreateButton1(void);
bool CreateButton2(void);
bool CreateProfitLabel(void);
//--- handlers of the dependent controls events
void OnClickButton1(void);
void OnClickButton2(void);
};
//+------------------------------------------------------------------+
//| Event Handling |
//+------------------------------------------------------------------+
EVENT_MAP_BEGIN(CAppWindowTwoButtons)
ON_EVENT(ON_CLICK,m_button1,OnClickButton1)
ON_EVENT(ON_CLICK,m_button2,OnClickButton2)
ON_EVENT(ON_CHANGE,m_editPipsToChange,OnPipsToChangeEdit)
ON_EVENT(ON_CHANGE,m_editPipsToDownChange,OnPipsToDownChangeEdit)
ON_EVENT(ON_CHANGE,m_editPipsToChange,OnPipsToChangeEdit)
EVENT_MAP_END(CAppDialog)
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
CAppWindowTwoButtons::CAppWindowTwoButtons(void)
{
}
//+------------------------------------------------------------------+
//| Destructor |
//+------------------------------------------------------------------+
CAppWindowTwoButtons::~CAppWindowTwoButtons(void)
{
}
//+------------------------------------------------------------------+
//| Create |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)
{
if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))
return(false);
//--- create dependent controls
if(!CreateButton1() || !CreateButton2() || !CreateProfitLabel() || !CreatePipsToChangeControls() || !CreatePipsToDownChangeControls() || !CreatePipsToUpChangeControls())
return(false);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Global Variable |
//+------------------------------------------------------------------+
CAppWindowTwoButtons ExtDialog;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreatePipsToUpChangeControls(void)
{
// Создание метки для PipsToChange
if(!m_labelPipsToUpChange.Create(0,"LabelPipsToUpChange",0,10,135,130,170))
return false;
m_labelPipsToUpChange.Text("Пункты на которые может поднятся цена:");
if(!Add(m_labelPipsToUpChange))
return(false);
// Создание поля для ввода PipsToChange
if(!m_editPipsToUpChange.Create(0,"EditPipsToUpChange",0,270,132,320,158))
return false;
if(!m_editPipsToUpChange.ReadOnly(false))
return(false);
m_editPipsToUpChange.Text(IntegerToString(PercentToUp));
if(!Add(m_editPipsToUpChange))
return(false);
return true;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::OnPipsToUpChangeEdit(void)
{
PercentToUp = StringToInteger(m_editPipsToUpChange.Text());
// Дополнительная валидация может потребоваться здесь
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreatePipsToDownChangeControls(void)
{
// Создание метки для PipsToChange
if(!m_labelPipsToDownChange.Create(0,"LabelPipsToDownChange",0,10,100,130,130))
return false;
m_labelPipsToDownChange.Text("Пункты на которые может упасть цена:");
if(!Add(m_labelPipsToDownChange))
return(false);
// Создание поля для ввода PipsToChange
if(!m_editPipsToDownChange.Create(0,"EditPipsToDownChange",0,255,97,305,123))
return false;
if(!m_editPipsToDownChange.ReadOnly(false))
return(false);
m_editPipsToDownChange.Text(IntegerToString(PercentToDown));
if(!Add(m_editPipsToDownChange))
return(false);
return true;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::OnPipsToDownChangeEdit(void)
{
PercentToDown = StringToInteger(m_editPipsToDownChange.Text());
// Дополнительная валидация может потребоваться здесь
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreatePipsToChangeControls(void)
{
// Создание метки для PipsToChange
if(!m_labelPipsToChange.Create(0,"LabelPipsToChange",0,10,65,100,10))
return false;
m_labelPipsToChange.Text("Количество пунктов изменения цены:");
if(!Add(m_labelPipsToChange))
return(false);
// Создание поля для ввода PipsToChange
if(!m_editPipsToChange.Create(0,"EditPipsToChange",0,240,62,290,88))
return false;
if(!m_editPipsToChange.ReadOnly(false))
return(false);
m_editPipsToChange.Text(IntegerToString(PipsToChange));
if(!Add(m_editPipsToChange))
return(false);
return true;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::OnPipsToChangeEdit(void)
{
PipsToChange = StringToInteger(m_editPipsToChange.Text());
// Дополнительная валидация может потребоваться здесь
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreateProfitLabel(void)
{
int x1=INDENT_LEFT;
int y1=INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X;
int x2=x1+INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X; // длина метки может быть больше, чтобы вместить текст
int y2=y1+BUTTON_HEIGHT;
if(!m_labelProfit.Create(0, "LabelProfit", 0, x1, y1, x2, y2))
return(false);
m_labelProfit.FontSize(10);
double profit = CalculateTotalProfit();
double TrueProfit = profit - g_initialProfit + g_closedTradesProfit + profitCloseSell + profitCloseBuy;
// Обновляем текст метки с прибылью
string profitText = StringFormat("Прибыль: %.2f", TrueProfit);
m_labelProfit.Text(profitText);
if(!Add(m_labelProfit))
return(false);
return(true);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreateButton1(void)
{
//--- coordinates
int x1=INDENT_LEFT; // x1 = 11 pixels
int y1=INDENT_TOP; // y1 = 11 pixels
int x2=x1+BUTTON_WIDTH; // x2 = 11 + 100 = 111 pixels
int y2=y1+BUTTON_HEIGHT; // y2 = 11 + 20 = 32 pixels
//--- create
if(!m_button1.Create(0,"Button1",0,x1,y1,x2,y2))
return(false);
if(!m_button1.Text("Закрыть sell"))
return(false);
if(!Add(m_button1))
return(false);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Create the "Button2" |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreateButton2(void)
{
//--- coordinates
int x1=INDENT_LEFT+120; // x1 = 11 + 2 * (100 + 5) = 221 pixels
int y1=INDENT_TOP; // y1 = 11 pixels
int x2=x1+BUTTON_WIDTH; // x2 = 221 + 100 = 321 pixels
int y2=y1+BUTTON_HEIGHT; // y2 = 11 + 20 = 31 pixels
//--- create
if(!m_button2.Create(0,"Button2",0,x1,y1,x2,y2))
return(false);
if(!m_button2.Text("Закрыть buy"))
return(false);
if(!Add(m_button2))
return(false);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::UpdateProfitLabel(void)
{
// Вычисляем текущую прибыль со всех открытых позиций
double profit = CalculateTotalProfit();
double TrueProfit = profit - g_initialProfit + g_closedTradesProfit + profitCloseSell + profitCloseBuy;
// Обновляем текст метки с прибылью
string profitText = StringFormat("Прибыль: %.2f", TrueProfit);
m_labelProfit.Text(profitText);
profitToSend = StringFormat("Прибыль: %.2f", TrueProfit);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
input double AboveCurrentPriceLevel = 2; // Уровень выше текущей цены для алерта
input double BelowCurrentPriceLevel = 1; // Уровень ниже текущей цены для алерта
input long PipsToChangeint = 5; // Количество пунктов изменения цены
input double InitialLots = 0.1; // Количество лотов для начальной сделки
input double LotChangePercent = 10.0; // Процент изменения количества лотов
input ENUM_TIMEFRAMES TimeFrame = PERIOD_M1;
input long PercentToDownInt = 3; //Пункты на которые может упасть цена после закртыия
input long PercentToUpInt = 3; //Пункты на которые может поднятся цена после закртыия
long PipsToChange = PipsToChangeint;
long PercentToDown = PercentToDownInt;
long PercentToUp = PercentToUpInt;
double PriceDown = 0;
double PriceUp = 10000000000;
double profitCloseSell = 0.0;
double profitCloseBuy = 0.0;
double g_closedTradesProfit = 0.0;
double g_initialProfit = 0.0;
double currentLots = InitialLots; // Текущее количество лотов
double lastPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID); // Последняя цена для отслеживания изменения на N пунктов
bool belowLevelAlerted = false; // Флаг отправки алерта для нижнего уровня
bool aboveLevelAlerted = false; // Флаг отправки алерта для верхнего уровня
bool close_s = false;
bool close_b = false;
bool start_b = false;
bool start_s = false;
bool send_b;
bool send_s;
string profitToSend;
bool close_all = false;
bool start = false;
datetime lastBarTime = 0;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int sendMessage(string text, string chatID, string botToken)
{
string baseUrl = "https://api.telegram.org";
string headers = "";
string requestURL = "";
string requestHeaders = "";
char resultData[];
char posData[];
int timeout = 200;
requestURL = StringFormat("%s/bot%s/sendmessage?chat_id=%s&text=%s",baseUrl,botToken,chatID,text);
int response = WebRequest("POST",requestURL,headers,timeout,posData,resultData,requestHeaders);
string resultMessage = CharArrayToString(resultData);
return response;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int getMessage(string chatID, string botToken)
{
string baseUrl = "https://api.telegram.org";
string headers = "";
string requestURL = "";
string requestHeaders = "";
char resultData[];
char posData[];
int timeout = 200;
string result[];
string sep = ",";
ushort sep_u = StringGetCharacter(sep,0);
string searchPattern = ("text");
string sep2 = "n";
ushort sep2_u = StringGetCharacter(sep2,0);
string result2[];
long accountNumber = AccountInfoInteger(ACCOUNT_LOGIN);
requestURL = StringFormat("%s/bot%s/getChat?chat_id=%s",baseUrl,botToken,chatID);
int response = WebRequest("GET",requestURL,headers,timeout,posData,resultData,requestHeaders);
string resultMessage = CharArrayToString(resultData);
int k = (StringSplit(resultMessage,sep_u,result));
if(k>0)
{
for(int i=0; i<k; i++)
{
if(StringFind(result[i], searchPattern) >= 0)
{
string res = StringSubstr(result[i],8,StringLen(result[i])-10);
int z = StringSplit(res,sep2_u,result2);
if(z>0)
{
for(int j=0; j<z; j++)
{
string finalResult;
int g = StringFind(result2[j],"\\",0);
if(g != -1)
{
finalResult = StringSubstr(result2[j],0,StringLen(result2[j])-1);
}
else
{
finalResult = result2[j];
}
if(finalResult == (string)accountNumber)
{
Print(accountNumber);
return true;
}
}
}
}
}
}
string wrongAccess = "Пытались торговать с счёта " + (string)accountNumber;
sendMessage(wrongAccess,ID,token);
return false;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double CalculateTotalProfit()
{
double totalProfit = 0.0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(m_position.SelectByIndex(i))
{
totalProfit += m_position.Profit();
}
}
return totalProfit;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int OnInit()
{
if(start != true)
{
g_initialProfit = CalculateTotalProfit();
}
if(!getMessage(IDToLicense,token))
return(INIT_FAILED);
if(!ExtDialog.Create(0,"Закрытие позиций и изменение вводных",0,15,100,350,300))
return(INIT_FAILED);
//--- run application
ExtDialog.Run();
MqlRates rates[];
if(CopyRates(_Symbol, TimeFrame, 0, 1, rates) > 0)
{
lastBarTime = rates[0].time;
}
else
{
Print("Ошибка при получении информации о барах: ", GetLastError());
return (INIT_FAILED);
}
if(aboveLevelAlerted == false && start_b == false)
{
while(send_b != true)
{
OpenOrder(ORDER_TYPE_BUY, currentLots, "B");
start_b = true;
}
}
if(belowLevelAlerted == false && start_s == false)
{
while(send_s != true)
{
OpenOrder(ORDER_TYPE_SELL, currentLots, "S");
start_s = true;
}
}
//ObjectCreate(0,"Нижняя линия",OBJ_HLINE,0,0,BelowCurrentPriceLevel);
//ObjectSetInteger(0, "Нижняя линия", OBJPROP_COLOR, clrBlue);
//ObjectCreate(0,"Верхняя линия",OBJ_HLINE,0,0,AboveCurrentPriceLevel);
if(start != true)
{
ENUM_TIMEFRAMES TimeInt = TimeFrame;
if(TimeInt > 16000)
{
TimeInt = (ENUM_TIMEFRAMES)((TimeInt - 16384) * 60);
}
string message = StringFormat(
"PipsToChange: %ld "
"InitialLots: %f "
"LotChangePercent: %f "
"TimeFrame: %d "
"PipsToDown: %ld "
"PipsToUp: %ld "
"Symbol: %s "
"Номер счета: %lld",
PipsToChangeint,
InitialLots,
LotChangePercent,
TimeInt,
PercentToDownInt,
PercentToUpInt,
_Symbol,
AccountInfoInteger(ACCOUNT_LOGIN));
sendMessage(message,ID,token);
start = true;
}
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Comment("");
//--- destroy dialog
ExtDialog.Destroy(reason);
//ObjectDelete(0,"Нижняя линия");
//ObjectDelete(0,"Верхняя линия");
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, // event ID
const long& lparam, // event parameter of the long type
const double& dparam, // event parameter of the double type
const string& sparam) // event parameter of the string type
{
ExtDialog.ChartEvent(id,lparam,dparam,sparam);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double NormalizeLot(double lot, double min_lot, double max_lot, double lot_step)
{
// Округление до ближайшего допустимого значения
lot = MathMax(min_lot, lot);
lot -= fmod(lot - min_lot, lot_step);
lot = MathMin(max_lot, lot);
return NormalizeDouble(lot, _Digits);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CalculateAndSetLotSize()
{
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
// Увеличение текущего размера лота на заданный процент
currentLots *= (1 + LotChangePercent / 100.0);
// Округление до ближайшего допустимого значения
currentLots = NormalizeLot(currentLots, min_lot, max_lot, lot_step);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double SubtractPointsDown(double price, long points)
{
// Получаем количество десятичных знаков и размер пункта
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Вычисляем изменение цены
double change = points * pointSize;
// Возвращаем результат
return NormalizeDouble(price - change, digits);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double SubtractPointsUp(double price, long points)
{
// Получаем количество десятичных знаков и размер пункта
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Вычисляем изменение цены
double change = points * pointSize;
// Возвращаем результат
return NormalizeDouble(price + change, digits);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::OnClickButton1(void)
{
for(int i=PositionsTotal()-1; i>=0; i--)
{
string symbol = PositionGetSymbol(i);
if(!PositionSelect(symbol))
continue;
if(m_position.SelectByIndex(i))
if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_SELL)
continue;
profitCloseSell += m_position.Profit();
m_trade.PositionClose(PositionGetInteger(POSITION_TICKET));
close_s = true;
}
PriceDown = SubtractPointsDown(SymbolInfoDouble(_Symbol, SYMBOL_BID),PercentToDown);
PriceUp = SubtractPointsUp(SymbolInfoDouble(_Symbol, SYMBOL_ASK),PercentToUp);
string messButt1 = "sell закрыты " + (string)AccountInfoInteger(ACCOUNT_LOGIN);
sendMessage(messButt1,ID,token);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::OnClickButton2(void)
{
int totalPositions = PositionsTotal();
for(int i = totalPositions - 1; i >= 0; i--)
{
string symbol = PositionGetSymbol(i);
if(!PositionSelect(symbol))
continue;
if(m_position.SelectByIndex(i))
if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_BUY)
continue;
profitCloseBuy += m_position.Profit();
m_trade.PositionClose(PositionGetInteger(POSITION_TICKET));
close_b = true;
}
PriceDown = SubtractPointsDown(SymbolInfoDouble(_Symbol, SYMBOL_BID),PercentToDown);
PriceUp = SubtractPointsUp(SymbolInfoDouble(_Symbol, SYMBOL_ASK),PercentToUp);
string messButt2 = "buy закрыты " + (string)AccountInfoInteger(ACCOUNT_LOGIN);
sendMessage(messButt2,ID,token);
}
#property indicator_chart_window
#property indicator_color1 Pink
//±-----------------------------------------------------------------+
//| Expert tick function |
//±-----------------------------------------------------------------+
long PipsToChangelast = PipsToChange;
long PercentToDownlast = PercentToDown;
long PercentToUplast = PercentToUp;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnTick()
{
send_b = false;
send_s = false;
ExtDialog.OnPipsToChangeEdit();
ExtDialog.UpdateProfitLabel();
ExtDialog.OnPipsToDownChangeEdit();
ExtDialog.OnPipsToUpChangeEdit();
if(PercentToDownlast != PercentToDown || PercentToUplast != PercentToUp || PipsToChangelast != PipsToChange)
{
string messChanges = StringFormat(
"PipsToChange: %ld "
"PipsToDown: %ld "
"PipsToUp: %ld "
"Номер счета: %lld",
PipsToChange,
PercentToDown,
PercentToUp,
AccountInfoInteger(ACCOUNT_LOGIN)
);
sendMessage(messChanges,ID,token);
PipsToChangelast = PipsToChange;
PercentToDownlast = PercentToDown;
PercentToUplast = PercentToUp;
}
double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
// Отправляем алерты при достижении указанных уровней
// if(!belowLevelAlerted && bidPrice <= BelowCurrentPriceLevel)
// {
// Alert("Цена достигла уровня BelowCurrentPriceLevel");
// belowLevelAlerted = true; // Отмечаем, что алерт был отправлен
// }
//
// if(!aboveLevelAlerted && askPrice >= AboveCurrentPriceLevel)
// {
// Alert("Цена достигла уровня AboveCurrentPriceLevel");
// aboveLevelAlerted = true; // Отмечаем, что алерт был отправлен
// }
datetime currentTime = TimeCurrent();
ENUM_TIMEFRAMES Time = TimeFrame;
if(Time > 16000)
{
Time = (ENUM_TIMEFRAMES)((Time - 16384) * 60);
}
if((SymbolInfoDouble(_Symbol, SYMBOL_ASK) > PriceUp || SymbolInfoDouble(_Symbol, SYMBOL_BID) < PriceDown) && close_all != true)
{
int totalPositions = PositionsTotal();
for(int i = totalPositions - 1; i >= 0; i--)
{
string symbol = PositionGetSymbol(i);
if(!PositionSelect(symbol))
continue;
profitCloseBuy += m_position.Profit();
m_trade.PositionClose(PositionGetInteger(POSITION_TICKET));
}
close_b = true;
close_s = true;
string closeMessage = "Бот закрыл все сделки " + (string)AccountInfoInteger(ACCOUNT_LOGIN);
sendMessage(closeMessage,ID,token);
sendMessage(profitToSend,ID,token);
close_all = true;
}
if(currentTime >= lastBarTime+Time*60)
{
if(MathAbs(bidPrice - lastPrice) > PipsToChange * _Point && )
{
// Подсчитаем новый размер лота
CalculateAndSetLotSize();
lastPrice = bidPrice; // Обновление последней цены
// Открываем новые ордера с новым размером лота
if(close_b == false)
{
while(send_b != true)
{
OpenOrder(ORDER_TYPE_BUY, currentLots, "B");
}
}
if(close_s == false)
{
while(send_s != true)
{
OpenOrder(ORDER_TYPE_SELL, currentLots, "S");
}
}
}
lastBarTime = lastBarTime+Time*60;
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OpenOrder(ENUM_ORDER_TYPE type, double lots, string orderMagic)
{
MqlTradeRequest request = {};
MqlTradeResult result = {};
// Заполнение полей структуры запроса на сделку
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lots;
request.type = type;
request.deviation = 5;
request.magic = StringToInteger(orderMagic + IntegerToString(GetTickCount()));
//request.comment = "Auto trade order";
if(type == ORDER_TYPE_BUY)
request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
else
if(type == ORDER_TYPE_SELL)
request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if(!OrderSend(request, result))
{
Print("OrderSend failed with error #", GetLastError());
Print("Details: symbol=", request.symbol, ", volume=", request.volume, ", type=", (request.type==ORDER_TYPE_BUY?"BUY":"SELL"), ", price=", request.price);
if(request.type == ORDER_TYPE_BUY)
{
send_b = false;
}
else
if(request.type == ORDER_TYPE_SELL)
{
send_s = false;
}
}
else
if(request.type == ORDER_TYPE_BUY)
{
send_b = true;
}
else
if(request.type == ORDER_TYPE_SELL)
{
send_s = true;
}
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
в 789 строку мне нужно добавить проверку после && что цена октрываемой сделки больше самой большой уже открытой или меньше самой маленькой уже открытой
|
20215ab1d49549092a47820d2fe707b6
|
{
"intermediate": 0.35756972432136536,
"beginner": 0.42062053084373474,
"expert": 0.2218097746372223
}
|
43,307
|
import React, {useEffect, useRef, useState} from 'react';
import {FlatList, StyleSheet, Text} from 'react-native';
import RNFS from 'react-native-fs';
import CardAyatList from '../../components/CardAyatList/CardAyatList.component';
import Loading from '../../components/loading/loading.component';
import {RootStackScreenProps} from '../../navigation/AppNavigator';
import {useAppSelector} from '../../store/hooks';
import {colors} from '../../themes/colors';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {Separator} from '../../components/separator/separator.component';
const QuranDetailScreen = ({
route: {
params: {id, data},
},
}: RootStackScreenProps<'QuranDetail'>) => {
// ---------------------------------------------------------------------------
// variables
// ---------------------------------------------------------------------------
const [isLoading, setIsLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const flatListRef = useRef<FlatList>(null);
const [scrollPosition, setScrollPosition] = useState(0);
const {error, loading, refreshing} = useAppSelector(state => state.quranList);
// ---------------------------------------------------------------------------
// useEffect
// ---------------------------------------------------------------------------
useEffect(() => {
const getScrollPosition = async () => {
const key = `scrollPosition_${data.id}`;
const position = await AsyncStorage.getItem(key);
if (position !== null) {
setScrollPosition(parseFloat(position));
}
};
getScrollPosition();
}, [id]);
useEffect(() => {
// Restore scroll position when component is mounted
if (flatListRef.current && scrollPosition) {
flatListRef.current.scrollToOffset({
offset: scrollPosition,
animated: false,
});
}
}, [scrollPosition]);
useEffect(() => {
const checkDiskSpace = async () => {
try {
const info = await RNFS.getFSInfo();
const {freeSpace} = info;
console.log('Free space on the device:', freeSpace);
} catch (error) {
console.log('Error checking disk space:', error);
}
};
checkDiskSpace();
}, []);
// ---------------------------------------------------------------------------
// functions
// ---------------------------------------------------------------------------
const itemsPerPage = 10;
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
// Save scroll position
// const handleScroll = (event: any) => {
// const yOffset = event.nativeEvent.contentOffset.y;
// const key = `scrollPosition_${id}`;
// AsyncStorage.setItem(key, yOffset.toString());
// };
const handleScroll = (event: any) => {
const yOffset = event.nativeEvent.contentOffset.y;
data.verses.forEach(async verse => {
const key = `scrollPosition_${verse.id}`;
console.log('key1:', key);
await AsyncStorage.setItem(key, yOffset.toString());
});
};
const loadMoreData = () => {
if (endIndex < data.verses.length) {
setCurrentPage(currentPage + 1);
}
};
const renderData = () => {
if (isLoading) {
return <Loading />;
}
if (!data) {
return <Text>No Data Found!</Text>;
}
return (
<FlatList
style={styles.container}
ref={flatListRef}
onScroll={handleScroll}
data={data.verses.slice(0, endIndex)}
renderItem={({item}) => (
<CardAyatList
data={{
...data,
verses: [item],
}}
onPress={() => {}}
/>
)}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={Separator}
onEndReached={loadMoreData}
onEndReachedThreshold={0.5}
scrollEventThrottle={16}
/>
);
};
// ---------------------------------------------------------------------------
return renderData();
};
export default QuranDetailScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.white,
},
});
import {createSlice, PayloadAction, createAsyncThunk} from '@reduxjs/toolkit';
import {persistReducer, persistStore} from 'redux-persist';
import RNFS, {writeFile, readFile} from 'react-native-fs';
import {RootState} from '../index';
import {SurahType} from '../../types/surah';
import surahData from '../../assets/quran-json/quran-ru.json';
interface initialStateInterface {
data: SurahType[];
error: boolean;
errorMessage: string;
loading: boolean;
refreshing: boolean;
position: number;
}
const initialState: initialStateInterface = {
data: [],
loading: true,
error: false,
errorMessage: '',
refreshing: false,
position: 0,
};
export const fetchQuranList = createAsyncThunk(
'quranList/fetchQuranList',
async () => {
const filePath = `${RNFS.DocumentDirectoryPath}/quranList.json`;
const fileExists = await RNFS.exists(filePath);
if (fileExists) {
const cachedData = await readFile(filePath, 'utf8');
return JSON.parse(cachedData);
} else {
const data = (surahData as SurahType[]).map(surah => ({
id: surah.id,
name: surah.name,
transliteration: surah.transliteration,
translation: surah.translation,
type: surah.type,
verses: surah.verses,
number_of_ayah: surah.number_of_ayah,
total_verses: surah.total_verses,
})) as SurahType[];
await writeFile(filePath, JSON.stringify(data), 'utf8');
return data;
}
},
);
export const quranListSlice = createSlice({
name: 'quranList',
initialState,
reducers: {
setQuranPosition: (state, action: PayloadAction<number>) => {
state.position = action.payload;
},
},
extraReducers: builder => {
builder
.addCase(fetchQuranList.pending, state => {
state.loading = true;
state.error = false;
state.errorMessage = '';
state.refreshing = true;
})
.addCase(fetchQuranList.fulfilled, (state, action) => {
state.data = action.payload;
state.loading = false;
state.refreshing = false;
})
.addCase(fetchQuranList.rejected, (state, action) => {
console.log('action.error', action.error);
state.loading = false;
state.error = true;
state.errorMessage = action.error.message ?? 'Something went wrong';
state.refreshing = false;
});
},
});
export const selectQuranData = (state: RootState) => state.quranList.data;
export const selectQuranError = (state: RootState) => state.quranList.error;
export const selectQuranLoading = (state: RootState) => state.quranList.loading;
export const selectQuranPosition = (state: RootState) =>
state.quranList.position;
export const {setQuranPosition} = quranListSlice.actions;
export default quranListSlice.reducer;
export type SurahType = {
id: number;
name: string;
name_translations: {
[key: string]: string;
};
transliteration: string;
translation: string;
number_of_ayah: number;
number_of_surah: number;
total_verses: number;
place: string;
type: string;
position: number;
verses: verse[];
tafsir: {
id: {
kemtjag: {
name: string;
source: string;
text: {
[key: string]: string;
};
};
};
};
};
export type verse = {
id: number;
introduction: string;
number: number;
text: string;
translation_tj: string;
translation: string;
};
I have problem with saving verses through id during scrolling. when i quit app and re-enter again it, should open from last place that I quit. How to implement it ?
|
003633b301dc2ac5c2cac098cad05282
|
{
"intermediate": 0.30461573600769043,
"beginner": 0.5182877779006958,
"expert": 0.17709653079509735
}
|
43,308
|
Structure and optimize the code, do a complete refactoring
import json
from data_sources.adapters import ConstructionAdapter
from data_sources.gateways import NeosintezGateway
from domain.repositories import ConstructionRepository
from domain.entities import Construction, Filter
from data_sources.adapters import ManufacturingDataAdapter
from domain.repositories import ManufacturingDataRepository
from domain.entities import ManufacturingData
from application.modules import ManufactureUpload
from data_sources.adapters import SetDataAdapter
from domain.repositories import SetDataRepository
from domain.entities import SetData
from application.modules import SetUpload
import os
import pandas as pd
import logging
from datetime import datetime
def load_json(file_path):
with open(file_path, 'r', encoding='utf-8-sig') as file:
return json.load(file, strict=False)
def load_xlsx (file_path: str) -> pd.DataFrame:
return pd.read_excel(file_path)
if __name__ == "__main__":
start_time = datetime.now()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler = logging.FileHandler(f"C:\python\logs\{datetime.now().strftime('%Y-%m-%d')}_milestone_and_set_uploader_log.txt", encoding='utf-8')
file_handler.setFormatter(formatter)
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
auth_data = load_json(r"C:\python\appius-neosintez_milestones_uploader\auth_data.json")
config = load_json(r"C:\python\appius-neosintez_milestones_uploader\config.json")
gateway = NeosintezGateway(**auth_data["neosintez"])
try:
manufacturing_data = load_xlsx(config['path']['milestone_path'])
os.rename(config["path"]["milestone_path"], f"prev_{datetime.now().strftime('%Y-%m-%d')}_{config['path']['milestone_path']}")
os.replace(f"prev_{datetime.now().strftime('%Y-%m-%d')}_{config['path']['milestone_path']}", config["path"]["prev_path"])
logger.info('Manufacturing data file is copied in prev folder')
except:
logger.warning('Manufacturing data file is not found')
try:
set_rd_data = load_xlsx(config['path']['set_path'])
os.rename(set_rd_data, f"prev_{datetime.now().strftime('%Y-%m-%d')}_{config['path']['set_path']}")
os.replace(f"prev_{datetime.now().strftime('%Y-%m-%d')}_{set_rd_data}", config["path"]["prev_path"])
logger.info('Set data file is copied in prev folder')
except:
logger.warning('Set data file is not found')
construction_adapter = ConstructionAdapter(gateway)
construction_repository = ConstructionRepository(construction_adapter)
df_id_exists = Filter("appius_ir_flag", "exist",)
constructions: list[Construction] = construction_repository.list(df_id_exists)
if constructions:
manufacturing_adapter = ManufacturingDataAdapter(gateway, manufacturing_data)
manufacturing_data_repository = ManufacturingDataRepository(manufacturing_adapter)
set_data_adapter = SetDataAdapter(gateway, set_rd_data)
set_data_repository = SetDataRepository(set_data_adapter)
for construction in constructions:
try:
id_di_check = Filter("mvz", "mvz", construction.mvz)
manufacturing_data_list: list[ManufacturingData] = manufacturing_data_repository.list(id_di_check)
if len(manufacturing_data_list) <= 0:
logging.warning('Manufacturing data file is empty')
id_df_count_by_mvz = manufacturing_adapter.count_id_df_per_mvz()
print(id_df_count_by_mvz)
manufacturing_upload = ManufactureUpload(gateway, construction, logger)
manufacturing_upload.execute(manufacturing_data, manufacturing_data_list, id_df_count_by_mvz)
id_di_check = Filter("mvz", "mvz", construction.mvz)
set_data_list: list[SetData] = set_data_repository.list(id_di_check)
uniq_df= sorted(set([item.df_code for item in set_data_list if item.df_code]))
uniq_stage = sorted(set([item.stage for item in set_data_list if item.stage]))
if len(set_data_list) <= 0:
logging.warning('Set data file is empty')
set_upload = SetUpload(gateway, construction, logger)
set_upload.execute(set_data_list)
except Exception as e:
logger.error(e)
logger.info(f"Время работы: {datetime.now() - start_time}")
import requests
import json
from domain.repositories import ManufacturingDataRepository
from domain.entities import Construction
from data_sources.gateways import NeosintezGateway
from data_sources.adapters import ManufacturingDataAdapter
from pprint import pprint
class ManufactureUpload:
manufacture_folder_class = "f581e310-d747-ee11-917e-005056b6948b"
mielstone_class = "f9232b4a-4046-ee11-917e-005056b6948b"
id_attr = "8f3be7b2-ff59-e911-8115-817c3f53a992"
guide_folder_id = "f8120300-1f59-ee11-9182-005056b6948b"
guide_mielstone_id = "64b97688-1c59-ee11-9182-005056b6948b"
base_folder_class = "0dd7d9f9-d259-e911-8115-817c3f53a992"
UPDATED_MILESTONE = 0
CREATED_MILESTONE = 0
MARK_AS_DELETED = 0
def __init__(self, gateway: NeosintezGateway, construction: Construction, logger) -> None:
self._gateway = gateway
self._construction = construction
self._construction_entity_id = construction.ns_entity_id
self._manufacture_folder_id = None
self._data_folder_id = None
self.logger = logger
self._id_df_folder_id = None
@property
def manufacture_folder_id(self):
if not self._manufacture_folder_id:
response: requests.Response = (
self._gateway.get_items_by_class_and_parent_folder(
class_id=self.manufacture_folder_class,
parent_folder_id=self._construction_entity_id,
)
)
if response.status_code == 200:
response_data = json.loads(response.text)
total = response_data["Total"]
if total == 1:
self._manufacture_folder_id = response_data["Result"][0]["Object"]["Id"]
return self._manufacture_folder_id
def id_df_folder_id(self, id_df):
if not self._id_df_folder_id:
self._id_df_folder_id = self._gateway.get_item_by_name_and_parent_folder(id_df ,self.base_folder_class, self.manufacture_folder_id)
return self._id_df_folder_id
def upload_data_to_folder(self, data, id_df_count_by_mvz):
if not self.manufacture_folder_id:
self.create_manufacture_folder()
self.set_id_attr_to_ns_entity(self.id_attr, self.manufacture_folder_id)
search_payload = {
"Filters": [
{"Type": 4, "Value": self.manufacture_folder_id}, # Фильтр по parent_folder_id
{"Type": 5, "Value": self.mielstone_class},
],
"Conditions": [
]}
for manufacturing_data in data:
search_response = self._gateway.search(search_payload)
if search_response.status_code != 200:
raise self.logger.error((f"Search error: {search_response.status_code} - {search_response.text}"))
search_data = json.loads(search_response.text)
match_found = False # флаг для отслеживания наличия совпадений
for item in search_data["Result"]:
if len(id_df_count_by_mvz[self._construction.mvz]) != 1:
parent = self._gateway.get_parent(item["Object"]["Id"]).split(" ")[3]
else:
parent = manufacturing_data.id_df
if item["Object"]["Attributes"]["fb0ba9a2-9653-ee11-9181-005056b6948b"]["Value"] == manufacturing_data.guid and manufacturing_data.id_df == int(parent):
match_found = True # нашли совпадение
guid = manufacturing_data.guid
end_index = guid.rindex("-0")
clean_guid = guid[:end_index]
item_id = item["Object"]["Id"]
self.update_milestone(item_id, manufacturing_data, update_payload=[])
self.UPDATED_MILESTONE += 1
if manufacturing_data.req_type == "Фактическая дата" and guid.endswith("-0"):
for item in search_data["Result"]:
if item["Object"]["Attributes"]["fb0ba9a2-9653-ee11-9181-005056b6948b"]["Value"] == clean_guid + "-1":
plan_date = item["Object"]["Attributes"]["78c6b7f2-4046-ee11-917e-005056b6948b"]["Value"]
update_payload = [{
"Name": 'forvalidation',
"Value": plan_date,
"Type": 3,
'Id': "78c6b7f2-4046-ee11-917e-005056b6948b"
}]
plan_number = item["Object"]["Attributes"]["87b8ab6c-4546-ee11-917e-005056b6948b"]["Value"]
update_payload.append({
"Name": 'forvalidation',
"Value": plan_number,
"Type": 1,
'Id': "87b8ab6c-4546-ee11-917e-005056b6948b"
})
self.update_milestone(item_id, manufacturing_data, update_payload=update_payload)
if not match_found:
guid = manufacturing_data.guid
if manufacturing_data.req_type == "Планируемая дата":
created_id = self.create_new_milestone(manufacturing_data, id_df_count_by_mvz)
self.update_milestone(created_id, manufacturing_data, update_payload=[])
self.CREATED_MILESTONE += 1
if manufacturing_data.req_type == "Фактическая дата" and guid.endswith("-1") or guid.endswith("-0"):
created_id = self.create_new_milestone(manufacturing_data, id_df_count_by_mvz)
self.update_milestone(created_id, manufacturing_data, update_payload=[])
self.CREATED_MILESTONE += 1
if manufacturing_data.req_type == "Фактическая дата":
self.check_last_fact(manufacturing_data, id_df_count_by_mvz)
def check_last_fact(self, manufacturing_data, id_df_count_by_mvz):
if manufacturing_data.guid:
search_payload = {
"Filters": [
{"Type": 4, "Value": self.guide_folder_id}, # Фильтр по parent_folder_id
{"Type": 5, "Value": self.guide_mielstone_id}, # Фильтр по class_id
],
"Conditions": [
]
}
search_response = self._gateway.search(search_payload)
if search_response.status_code != 200:
raise self.logger.warning(f"Search error: {search_response.status_code} - {search_response.text}")
search_data = json.loads(search_response.text)
for i, data in enumerate(search_data["Result"]):
try:
if data["Object"]["Attributes"]['cb78acd9-ddcb-ee11-9199-005056b6948b']["Value"] == manufacturing_data.guid:
manufacturing_data.guid = data["Object"]["Attributes"]['fb0ba9a2-9653-ee11-9181-005056b6948b']["Value"]
self.upload_data_to_folder([manufacturing_data], id_df_count_by_mvz)
except KeyError:
print("Error updating")
def update_milestone(self, item_id, manufacturing_data, update_payload=[]):
# Обновление существующей Вехи ПП
update_payload = update_payload
if manufacturing_data.guid:
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.guid,
"Type": 2,
'Id': "fb0ba9a2-9653-ee11-9181-005056b6948b"
})
if manufacturing_data.req_type == "Планируемая дата":
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.value,
"Type": 3,
'Id': "78c6b7f2-4046-ee11-917e-005056b6948b"
}
)
if manufacturing_data.req_type == "Планируемая дата":
if manufacturing_data.number_of_items:
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.number_of_items,
"Type": 1,
'Id': "87b8ab6c-4546-ee11-917e-005056b6948b"
})
if manufacturing_data.req_type == "Прогнозная дата":
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.value,
"Type": 3,
'Id': "2bbacfcf-4046-ee11-917e-005056b6948b"
})
if manufacturing_data.req_type == "Фактическая дата":
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.value,
"Type": 3,
'Id': "b07782b8-4046-ee11-917e-005056b6948b"
})
if manufacturing_data.req_type == "Фактическая дата":
if manufacturing_data.number_of_items:
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.number_of_items,
"Type": 1,
'Id': "58fd5c74-4546-ee11-917e-005056b6948b"
})
update_payload.append({
"Name": 'forvalidation',
"Value": {"Name": " "},
"Type": 8,
'Id': "7d39b7fb-b9eb-ec11-9131-005056b6948b"
})
self.update_milestone_by_guid(manufacturing_data, update_payload)
update_response = self._gateway.set_attr(item_id, update_payload)
if update_response.status_code != 200:
raise self.logger.warning(f"Update error: {update_response.status_code} - {update_response.text}")
def update_milestone_by_guid(self, manufacturing_data, update_payload):
if manufacturing_data.guid:
search_payload = {
"Filters": [
{"Type": 4, "Value": self.guide_folder_id}, # Фильтр по parent_folder_id
{"Type": 5, "Value": self.guide_mielstone_id}, # Фильтр по class_id
],
"Conditions": [
]
}
search_response = self._gateway.search(search_payload)
if search_response.status_code != 200:
raise self.logger.warning(f"Search error: {search_response.status_code} - {search_response.text}")
search_data = json.loads(search_response.text)
for i, data in enumerate(search_data["Result"]):
try:
if data["Object"]["Attributes"]['fb0ba9a2-9653-ee11-9181-005056b6948b']["Value"] == manufacturing_data.guid:
update_item_id = data["Object"]["Id"]
name = data["Object"]["Name"]
update_payload.append({
"Name": 'forvalidation',
"Type": 8,
'Id': "0303ada5-525b-ee11-9183-005056b6948b",
"Value": {"Id":update_item_id, "Name": name}
})
except KeyError:
print("Error updating")
return update_payload
def create_new_milestone(self, manufacturing_data, id_df_count_by_mvz):
if len(id_df_count_by_mvz[manufacturing_data.mvz]) == 1:
create_payload = {
"Id": "00000000-0000-0000-0000-000000000000",
"Name": manufacturing_data.section_pp,
"Entity": {"Id": self.mielstone_class, "Name": "forvalidation", },
}
create_response = self._gateway.create_item(self.manufacture_folder_id, create_payload)
if create_response.status_code != 200:
raise self.logger.warning(f"Creation error: {create_response.status_code} - {create_response.text}")
created_item_data = json.loads(create_response.text)
item_id = created_item_data["Id"]
return item_id
elif id_df_count_by_mvz[manufacturing_data.mvz]:
if not self.id_df_folder_id("ID Дф-16 - " + str(manufacturing_data.id_df)):
parent_id = self.create_id_df_folder("ID Дф-16 - " + str(manufacturing_data.id_df))
else:
parent_id = self.id_df_folder_id("ID Дф-16 - " + str(manufacturing_data.id_df))
create_payload = {
"Id": "00000000-0000-0000-0000-000000000000",
"Name": manufacturing_data.section_pp,
"Entity": {"Id": self.mielstone_class, "Name": "forvalidation", },
}
create_response = self._gateway.create_item(parent_id, create_payload)
if create_response.status_code != 200:
raise self.logger.warning(f"Creation error: {create_response.status_code} - {create_response.text}")
created_item_data = json.loads(create_response.text)
item_id = created_item_data["Id"]
self._id_df_folder_id = None
return item_id
def create_manufacture_folder(self):
data_folder_id = self._gateway.get_item_by_name_and_parent_folder("!Данные из информационных систем", self.base_folder_class, self._construction_entity_id)
create_payload = {
"Id": "00000000-0000-0000-0000-000000000000",
"Name": "Вехи ПП",
"Entity": {"Id": self.manufacture_folder_class, "Name": "forvalidation"},
}
create_response = self._gateway.create_item(data_folder_id, create_payload)
if create_response.status_code != 200:
self.logger.warning(f"Creation error: {create_response.status_code} - {create_response.text}")
created_folder_data = json.loads(create_response.text)
self._manufacture_folder_id = created_folder_data["Id"]
self.logger.info("Folder 'Вехи ПП' successfully created")
def create_id_df_folder(self, id_df):
create_payload = {
"Id": "00000000-0000-0000-0000-000000000000",
"Name": id_df,
"Entity": {"Id": self.base_folder_class, "Name": "forvalidation"},
}
create_response = self._gateway.create_item(self.manufacture_folder_id, create_payload)
if create_response.status_code != 200:
self.logger.warning(f"Creation error: {create_response.status_code} - {create_response.text}")
created_folder_data = json.loads(create_response.text)
self.logger.info(f"Folder {id_df} successfully created")
return created_folder_data["Id"]
def check_actual_data(self, manufacturing_data, id_df_count_by_mvz):
search_payload = {
"Filters": [
{"Type": 4, "Value": self.manufacture_folder_id},
{"Type": 5, "Value": self.mielstone_class},
],
"Conditions": [
{"Attribute": "7d39b7fb-b9eb-ec11-9131-005056b6948b", "Type": 1, 'Operator':8}
]
}
search_response = self._gateway.search(search_payload)
if search_response.status_code!= 200:
raise self.logger.warning(f"Search error: {search_response.status_code} - {search_response.text}")
search_data = json.loads(search_response.text)
manufacturing_data_for_delete = manufacturing_data.copy()
for item in reversed(manufacturing_data):
for i, data in enumerate(reversed(search_data["Result"])):
if len(id_df_count_by_mvz[self._construction.mvz]) != 1:
parent = self._gateway.get_parent(data["Object"]["Id"]).split(" ")[3]
else:
parent = item.id_df
if data["Object"]["Attributes"]['fb0ba9a2-9653-ee11-9181-005056b6948b']["Value"] == item.guid and item.id_df == int(parent):
search_data["Result"].pop(len(search_data["Result"]) - 1 - i)
for del_item in manufacturing_data_for_delete:
if del_item.guid == data["Object"]["Attributes"]['fb0ba9a2-9653-ee11-9181-005056b6948b']["Value"]:
manufacturing_data_for_delete.remove(del_item)
if len(search_data["Result"]) > 0:
for item in search_data["Result"]:
update_payload = [{
"Id": "7d39b7fb-b9eb-ec11-9131-005056b6948b",
"Name": "forvalidation",
"Type": 8,
"Value": {"Id" : "d5fa86ec-b9eb-ec11-9131-005056b6948b", "Name": "Удалить"}
}]
update_response = self._gateway.set_attr(item["Object"]["Id"], update_payload)
self.MARK_AS_DELETED += 1
if update_response.status_code!= 200:
raise self.logger.warning(f"Update error: {update_response.status_code} - {update_response.text}")
def set_id_attr_to_ns_entity(self, id_attr_value: str, entity_id: str,) -> requests.Response:
payload = [
{
"Id": self._manufacture_folder_id,
"Name": "forvalidation",
"Type": 2,
"Value": f"{self._construction.name}",
"Constraints": [],
}
]
return self._gateway.set_attr(entity_id, payload)
def execute(self, adapter: ManufacturingDataAdapter, data, id_df_count_by_mvz):
self.logger.info("-"*50)
self.logger.info(f"Manufacture Upload: Старт обработки объекта {self._construction.name}")
manufacturing_data_list = data
self.upload_data_to_folder(manufacturing_data_list, id_df_count_by_mvz)
self.check_actual_data(manufacturing_data_list, id_df_count_by_mvz)
self.logger.info(f"Updated {self.UPDATED_MILESTONE} milestones")
self.logger.info(f"Created {self.CREATED_MILESTONE} milestones")
self.logger.info(f"Mark as deleted {self.MARK_AS_DELETED} milestones")
self.logger.info("-"*50)
|
57b36e887fd061d1538d7e1ac39de95f
|
{
"intermediate": 0.3495648205280304,
"beginner": 0.3259044587612152,
"expert": 0.3245307207107544
}
|
43,309
|
make me a coding language using these characters:
[]-+/*%Δ,.<>!
|
2860a25af7b9ff769376ea6c41dac1dd
|
{
"intermediate": 0.27470463514328003,
"beginner": 0.3674711585044861,
"expert": 0.3578242063522339
}
|
43,310
|
Structure and optimize the code, do a complete refactoring
import json
from data_sources.adapters import ConstructionAdapter
from data_sources.gateways import NeosintezGateway
from domain.repositories import ConstructionRepository
from domain.entities import Construction, Filter
from data_sources.adapters import ManufacturingDataAdapter
from domain.repositories import ManufacturingDataRepository
from domain.entities import ManufacturingData
from application.modules import ManufactureUpload
from data_sources.adapters import SetDataAdapter
from domain.repositories import SetDataRepository
from domain.entities import SetData
from application.modules import SetUpload
import os
import pandas as pd
import logging
from datetime import datetime
def load_json(file_path):
with open(file_path, 'r', encoding='utf-8-sig') as file:
return json.load(file, strict=False)
def load_xlsx (file_path: str) -> pd.DataFrame:
return pd.read_excel(file_path)
if __name__ == "__main__":
start_time = datetime.now()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler = logging.FileHandler(f"C:\python\logs\{datetime.now().strftime('%Y-%m-%d')}_milestone_and_set_uploader_log.txt", encoding='utf-8')
file_handler.setFormatter(formatter)
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
auth_data = load_json(r"C:\python\appius-neosintez_milestones_uploader\auth_data.json")
config = load_json(r"C:\python\appius-neosintez_milestones_uploader\config.json")
gateway = NeosintezGateway(**auth_data["neosintez"])
try:
manufacturing_data = load_xlsx(config['path']['milestone_path'])
os.rename(config["path"]["milestone_path"], f"prev_{datetime.now().strftime('%Y-%m-%d')}_{config['path']['milestone_path']}")
os.replace(f"prev_{datetime.now().strftime('%Y-%m-%d')}_{config['path']['milestone_path']}", config["path"]["prev_path"])
logger.info('Manufacturing data file is copied in prev folder')
except:
logger.warning('Manufacturing data file is not found')
try:
set_rd_data = load_xlsx(config['path']['set_path'])
os.rename(set_rd_data, f"prev_{datetime.now().strftime('%Y-%m-%d')}_{config['path']['set_path']}")
os.replace(f"prev_{datetime.now().strftime('%Y-%m-%d')}_{set_rd_data}", config["path"]["prev_path"])
logger.info('Set data file is copied in prev folder')
except:
logger.warning('Set data file is not found')
construction_adapter = ConstructionAdapter(gateway)
construction_repository = ConstructionRepository(construction_adapter)
df_id_exists = Filter("appius_ir_flag", "exist",)
constructions: list[Construction] = construction_repository.list(df_id_exists)
if constructions:
manufacturing_adapter = ManufacturingDataAdapter(gateway, manufacturing_data)
manufacturing_data_repository = ManufacturingDataRepository(manufacturing_adapter)
set_data_adapter = SetDataAdapter(gateway, set_rd_data)
set_data_repository = SetDataRepository(set_data_adapter)
for construction in constructions:
try:
id_di_check = Filter("mvz", "mvz", construction.mvz)
manufacturing_data_list: list[ManufacturingData] = manufacturing_data_repository.list(id_di_check)
if len(manufacturing_data_list) <= 0:
logging.warning('Manufacturing data file is empty')
id_df_count_by_mvz = manufacturing_adapter.count_id_df_per_mvz()
print(id_df_count_by_mvz)
manufacturing_upload = ManufactureUpload(gateway, construction, logger)
manufacturing_upload.execute(manufacturing_data, manufacturing_data_list, id_df_count_by_mvz)
id_di_check = Filter("mvz", "mvz", construction.mvz)
set_data_list: list[SetData] = set_data_repository.list(id_di_check)
uniq_df= sorted(set([item.df_code for item in set_data_list if item.df_code]))
uniq_stage = sorted(set([item.stage for item in set_data_list if item.stage]))
if len(set_data_list) <= 0:
logging.warning('Set data file is empty')
set_upload = SetUpload(gateway, construction, logger)
set_upload.execute(set_data_list)
except Exception as e:
logger.error(e)
logger.info(f"Время работы: {datetime.now() - start_time}")
import requests
import json
from domain.repositories import ManufacturingDataRepository
from domain.entities import Construction
from data_sources.gateways import NeosintezGateway
from data_sources.adapters import ManufacturingDataAdapter
from pprint import pprint
class ManufactureUpload:
manufacture_folder_class = "f581e310-d747-ee11-917e-005056b6948b"
mielstone_class = "f9232b4a-4046-ee11-917e-005056b6948b"
id_attr = "8f3be7b2-ff59-e911-8115-817c3f53a992"
guide_folder_id = "f8120300-1f59-ee11-9182-005056b6948b"
guide_mielstone_id = "64b97688-1c59-ee11-9182-005056b6948b"
base_folder_class = "0dd7d9f9-d259-e911-8115-817c3f53a992"
UPDATED_MILESTONE = 0
CREATED_MILESTONE = 0
MARK_AS_DELETED = 0
def __init__(self, gateway: NeosintezGateway, construction: Construction, logger) -> None:
self._gateway = gateway
self._construction = construction
self._construction_entity_id = construction.ns_entity_id
self._manufacture_folder_id = None
self._data_folder_id = None
self.logger = logger
self._id_df_folder_id = None
@property
def manufacture_folder_id(self):
if not self._manufacture_folder_id:
response: requests.Response = (
self._gateway.get_items_by_class_and_parent_folder(
class_id=self.manufacture_folder_class,
parent_folder_id=self._construction_entity_id,
)
)
if response.status_code == 200:
response_data = json.loads(response.text)
total = response_data["Total"]
if total == 1:
self._manufacture_folder_id = response_data["Result"][0]["Object"]["Id"]
return self._manufacture_folder_id
def id_df_folder_id(self, id_df):
if not self._id_df_folder_id:
self._id_df_folder_id = self._gateway.get_item_by_name_and_parent_folder(id_df ,self.base_folder_class, self.manufacture_folder_id)
return self._id_df_folder_id
def upload_data_to_folder(self, data, id_df_count_by_mvz):
if not self.manufacture_folder_id:
self.create_manufacture_folder()
self.set_id_attr_to_ns_entity(self.id_attr, self.manufacture_folder_id)
search_payload = {
"Filters": [
{"Type": 4, "Value": self.manufacture_folder_id}, # Фильтр по parent_folder_id
{"Type": 5, "Value": self.mielstone_class},
],
"Conditions": [
]}
for manufacturing_data in data:
search_response = self._gateway.search(search_payload)
if search_response.status_code != 200:
raise self.logger.error((f"Search error: {search_response.status_code} - {search_response.text}"))
search_data = json.loads(search_response.text)
match_found = False # флаг для отслеживания наличия совпадений
for item in search_data["Result"]:
if len(id_df_count_by_mvz[self._construction.mvz]) != 1:
parent = self._gateway.get_parent(item["Object"]["Id"]).split(" ")[3]
else:
parent = manufacturing_data.id_df
if item["Object"]["Attributes"]["fb0ba9a2-9653-ee11-9181-005056b6948b"]["Value"] == manufacturing_data.guid and manufacturing_data.id_df == int(parent):
match_found = True # нашли совпадение
guid = manufacturing_data.guid
end_index = guid.rindex("-0")
clean_guid = guid[:end_index]
item_id = item["Object"]["Id"]
self.update_milestone(item_id, manufacturing_data, update_payload=[])
self.UPDATED_MILESTONE += 1
if manufacturing_data.req_type == "Фактическая дата" and guid.endswith("-0"):
for item in search_data["Result"]:
if item["Object"]["Attributes"]["fb0ba9a2-9653-ee11-9181-005056b6948b"]["Value"] == clean_guid + "-1":
plan_date = item["Object"]["Attributes"]["78c6b7f2-4046-ee11-917e-005056b6948b"]["Value"]
update_payload = [{
"Name": 'forvalidation',
"Value": plan_date,
"Type": 3,
'Id': "78c6b7f2-4046-ee11-917e-005056b6948b"
}]
plan_number = item["Object"]["Attributes"]["87b8ab6c-4546-ee11-917e-005056b6948b"]["Value"]
update_payload.append({
"Name": 'forvalidation',
"Value": plan_number,
"Type": 1,
'Id': "87b8ab6c-4546-ee11-917e-005056b6948b"
})
self.update_milestone(item_id, manufacturing_data, update_payload=update_payload)
if not match_found:
guid = manufacturing_data.guid
if manufacturing_data.req_type == "Планируемая дата":
created_id = self.create_new_milestone(manufacturing_data, id_df_count_by_mvz)
self.update_milestone(created_id, manufacturing_data, update_payload=[])
self.CREATED_MILESTONE += 1
if manufacturing_data.req_type == "Фактическая дата" and guid.endswith("-1") or guid.endswith("-0"):
created_id = self.create_new_milestone(manufacturing_data, id_df_count_by_mvz)
self.update_milestone(created_id, manufacturing_data, update_payload=[])
self.CREATED_MILESTONE += 1
if manufacturing_data.req_type == "Фактическая дата":
self.check_last_fact(manufacturing_data, id_df_count_by_mvz)
def check_last_fact(self, manufacturing_data, id_df_count_by_mvz):
if manufacturing_data.guid:
search_payload = {
"Filters": [
{"Type": 4, "Value": self.guide_folder_id}, # Фильтр по parent_folder_id
{"Type": 5, "Value": self.guide_mielstone_id}, # Фильтр по class_id
],
"Conditions": [
]
}
search_response = self._gateway.search(search_payload)
if search_response.status_code != 200:
raise self.logger.warning(f"Search error: {search_response.status_code} - {search_response.text}")
search_data = json.loads(search_response.text)
for i, data in enumerate(search_data["Result"]):
try:
if data["Object"]["Attributes"]['cb78acd9-ddcb-ee11-9199-005056b6948b']["Value"] == manufacturing_data.guid:
manufacturing_data.guid = data["Object"]["Attributes"]['fb0ba9a2-9653-ee11-9181-005056b6948b']["Value"]
self.upload_data_to_folder([manufacturing_data], id_df_count_by_mvz)
except KeyError:
print("Error updating")
def update_milestone(self, item_id, manufacturing_data, update_payload=[]):
# Обновление существующей Вехи ПП
update_payload = update_payload
if manufacturing_data.guid:
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.guid,
"Type": 2,
'Id': "fb0ba9a2-9653-ee11-9181-005056b6948b"
})
if manufacturing_data.req_type == "Планируемая дата":
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.value,
"Type": 3,
'Id': "78c6b7f2-4046-ee11-917e-005056b6948b"
}
)
if manufacturing_data.req_type == "Планируемая дата":
if manufacturing_data.number_of_items:
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.number_of_items,
"Type": 1,
'Id': "87b8ab6c-4546-ee11-917e-005056b6948b"
})
if manufacturing_data.req_type == "Прогнозная дата":
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.value,
"Type": 3,
'Id': "2bbacfcf-4046-ee11-917e-005056b6948b"
})
if manufacturing_data.req_type == "Фактическая дата":
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.value,
"Type": 3,
'Id': "b07782b8-4046-ee11-917e-005056b6948b"
})
if manufacturing_data.req_type == "Фактическая дата":
if manufacturing_data.number_of_items:
update_payload.append({
"Name": 'forvalidation',
"Value": manufacturing_data.number_of_items,
"Type": 1,
'Id': "58fd5c74-4546-ee11-917e-005056b6948b"
})
update_payload.append({
"Name": 'forvalidation',
"Value": {"Name": " "},
"Type": 8,
'Id': "7d39b7fb-b9eb-ec11-9131-005056b6948b"
})
self.update_milestone_by_guid(manufacturing_data, update_payload)
update_response = self._gateway.set_attr(item_id, update_payload)
if update_response.status_code != 200:
raise self.logger.warning(f"Update error: {update_response.status_code} - {update_response.text}")
def update_milestone_by_guid(self, manufacturing_data, update_payload):
if manufacturing_data.guid:
search_payload = {
"Filters": [
{"Type": 4, "Value": self.guide_folder_id}, # Фильтр по parent_folder_id
{"Type": 5, "Value": self.guide_mielstone_id}, # Фильтр по class_id
],
"Conditions": [
]
}
search_response = self._gateway.search(search_payload)
if search_response.status_code != 200:
raise self.logger.warning(f"Search error: {search_response.status_code} - {search_response.text}")
search_data = json.loads(search_response.text)
for i, data in enumerate(search_data["Result"]):
try:
if data["Object"]["Attributes"]['fb0ba9a2-9653-ee11-9181-005056b6948b']["Value"] == manufacturing_data.guid:
update_item_id = data["Object"]["Id"]
name = data["Object"]["Name"]
update_payload.append({
"Name": 'forvalidation',
"Type": 8,
'Id': "0303ada5-525b-ee11-9183-005056b6948b",
"Value": {"Id":update_item_id, "Name": name}
})
except KeyError:
print("Error updating")
return update_payload
def create_new_milestone(self, manufacturing_data, id_df_count_by_mvz):
if len(id_df_count_by_mvz[manufacturing_data.mvz]) == 1:
create_payload = {
"Id": "00000000-0000-0000-0000-000000000000",
"Name": manufacturing_data.section_pp,
"Entity": {"Id": self.mielstone_class, "Name": "forvalidation", },
}
create_response = self._gateway.create_item(self.manufacture_folder_id, create_payload)
if create_response.status_code != 200:
raise self.logger.warning(f"Creation error: {create_response.status_code} - {create_response.text}")
created_item_data = json.loads(create_response.text)
item_id = created_item_data["Id"]
return item_id
elif id_df_count_by_mvz[manufacturing_data.mvz]:
if not self.id_df_folder_id("ID Дф-16 - " + str(manufacturing_data.id_df)):
parent_id = self.create_id_df_folder("ID Дф-16 - " + str(manufacturing_data.id_df))
else:
parent_id = self.id_df_folder_id("ID Дф-16 - " + str(manufacturing_data.id_df))
create_payload = {
"Id": "00000000-0000-0000-0000-000000000000",
"Name": manufacturing_data.section_pp,
"Entity": {"Id": self.mielstone_class, "Name": "forvalidation", },
}
create_response = self._gateway.create_item(parent_id, create_payload)
if create_response.status_code != 200:
raise self.logger.warning(f"Creation error: {create_response.status_code} - {create_response.text}")
created_item_data = json.loads(create_response.text)
item_id = created_item_data["Id"]
self._id_df_folder_id = None
return item_id
def create_manufacture_folder(self):
data_folder_id = self._gateway.get_item_by_name_and_parent_folder("!Данные из информационных систем", self.base_folder_class, self._construction_entity_id)
create_payload = {
"Id": "00000000-0000-0000-0000-000000000000",
"Name": "Вехи ПП",
"Entity": {"Id": self.manufacture_folder_class, "Name": "forvalidation"},
}
create_response = self._gateway.create_item(data_folder_id, create_payload)
if create_response.status_code != 200:
self.logger.warning(f"Creation error: {create_response.status_code} - {create_response.text}")
created_folder_data = json.loads(create_response.text)
self._manufacture_folder_id = created_folder_data["Id"]
self.logger.info("Folder 'Вехи ПП' successfully created")
def create_id_df_folder(self, id_df):
create_payload = {
"Id": "00000000-0000-0000-0000-000000000000",
"Name": id_df,
"Entity": {"Id": self.base_folder_class, "Name": "forvalidation"},
}
create_response = self._gateway.create_item(self.manufacture_folder_id, create_payload)
if create_response.status_code != 200:
self.logger.warning(f"Creation error: {create_response.status_code} - {create_response.text}")
created_folder_data = json.loads(create_response.text)
self.logger.info(f"Folder {id_df} successfully created")
return created_folder_data["Id"]
def check_actual_data(self, manufacturing_data, id_df_count_by_mvz):
search_payload = {
"Filters": [
{"Type": 4, "Value": self.manufacture_folder_id},
{"Type": 5, "Value": self.mielstone_class},
],
"Conditions": [
{"Attribute": "7d39b7fb-b9eb-ec11-9131-005056b6948b", "Type": 1, 'Operator':8}
]
}
search_response = self._gateway.search(search_payload)
if search_response.status_code!= 200:
raise self.logger.warning(f"Search error: {search_response.status_code} - {search_response.text}")
search_data = json.loads(search_response.text)
manufacturing_data_for_delete = manufacturing_data.copy()
for item in reversed(manufacturing_data):
for i, data in enumerate(reversed(search_data["Result"])):
if len(id_df_count_by_mvz[self._construction.mvz]) != 1:
parent = self._gateway.get_parent(data["Object"]["Id"]).split(" ")[3]
else:
parent = item.id_df
if data["Object"]["Attributes"]['fb0ba9a2-9653-ee11-9181-005056b6948b']["Value"] == item.guid and item.id_df == int(parent):
search_data["Result"].pop(len(search_data["Result"]) - 1 - i)
for del_item in manufacturing_data_for_delete:
if del_item.guid == data["Object"]["Attributes"]['fb0ba9a2-9653-ee11-9181-005056b6948b']["Value"]:
manufacturing_data_for_delete.remove(del_item)
if len(search_data["Result"]) > 0:
for item in search_data["Result"]:
update_payload = [{
"Id": "7d39b7fb-b9eb-ec11-9131-005056b6948b",
"Name": "forvalidation",
"Type": 8,
"Value": {"Id" : "d5fa86ec-b9eb-ec11-9131-005056b6948b", "Name": "Удалить"}
}]
update_response = self._gateway.set_attr(item["Object"]["Id"], update_payload)
self.MARK_AS_DELETED += 1
if update_response.status_code!= 200:
raise self.logger.warning(f"Update error: {update_response.status_code} - {update_response.text}")
def set_id_attr_to_ns_entity(self, id_attr_value: str, entity_id: str,) -> requests.Response:
payload = [
{
"Id": self._manufacture_folder_id,
"Name": "forvalidation",
"Type": 2,
"Value": f"{self._construction.name}",
"Constraints": [],
}
]
return self._gateway.set_attr(entity_id, payload)
def execute(self, adapter: ManufacturingDataAdapter, data, id_df_count_by_mvz):
self.logger.info("-"*50)
self.logger.info(f"Manufacture Upload: Старт обработки объекта {self._construction.name}")
manufacturing_data_list = data
self.upload_data_to_folder(manufacturing_data_list, id_df_count_by_mvz)
self.check_actual_data(manufacturing_data_list, id_df_count_by_mvz)
self.logger.info(f"Updated {self.UPDATED_MILESTONE} milestones")
self.logger.info(f"Created {self.CREATED_MILESTONE} milestones")
self.logger.info(f"Mark as deleted {self.MARK_AS_DELETED} milestones")
self.logger.info("-"*50)
|
e0e924e5ae0462cee99d44be1426d53c
|
{
"intermediate": 0.3495648205280304,
"beginner": 0.3259044587612152,
"expert": 0.3245307207107544
}
|
43,311
|
In incident if a state is change from in progress to on hold hide the description field in servicenow
|
c2a96f64656da7df437582c9b0ba4e17
|
{
"intermediate": 0.45612967014312744,
"beginner": 0.27490705251693726,
"expert": 0.2689632773399353
}
|
43,312
|
based upon the PDF file https://www.purebasic.com/documentation/PureBasic.pdf, write a procedure to comment out unused procedures from a source code file with 4 spaces as the default code indentation
|
8fa4d51ddd269637401b2814e52c7041
|
{
"intermediate": 0.31124019622802734,
"beginner": 0.2605358362197876,
"expert": 0.42822393774986267
}
|
43,313
|
import React, {useEffect, useRef, useState} from 'react';
import {FlatList, StyleSheet, Text} from 'react-native';
import RNFS from 'react-native-fs';
import CardAyatList from '../../components/CardAyatList/CardAyatList.component';
import Loading from '../../components/loading/loading.component';
import {RootStackScreenProps} from '../../navigation/AppNavigator';
import {useAppSelector} from '../../store/hooks';
import {colors} from '../../themes/colors';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {Separator} from '../../components/separator/separator.component';
const QuranDetailScreen = ({
route: {
params: {id, data},
},
}: RootStackScreenProps<'QuranDetail'>) => {
// ---------------------------------------------------------------------------
// variables
// ---------------------------------------------------------------------------
const [isLoading, setIsLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const flatListRef = useRef<FlatList>(null);
const [scrollPosition, setScrollPosition] = useState(0);
const {error, loading, refreshing} = useAppSelector(state => state.quranList);
// ---------------------------------------------------------------------------
// useEffect
// ---------------------------------------------------------------------------
useEffect(() => {
const getScrollPosition = async () => {
const key = `scrollPosition_${data.id}`;
const position = await AsyncStorage.getItem(key);
if (position !== null) {
setScrollPosition(parseFloat(position));
}
};
getScrollPosition();
}, [id]);
useEffect(() => {
// Restore scroll position when component is mounted
if (flatListRef.current && scrollPosition) {
flatListRef.current.scrollToOffset({
offset: scrollPosition,
animated: false,
});
}
}, [data, scrollPosition]);
useEffect(() => {
const checkDiskSpace = async () => {
try {
const info = await RNFS.getFSInfo();
const {freeSpace} = info;
console.log('Free space on the device:', freeSpace);
} catch (error) {
console.log('Error checking disk space:', error);
}
};
checkDiskSpace();
}, []);
// ---------------------------------------------------------------------------
// functions
// ---------------------------------------------------------------------------
const itemsPerPage = 10;
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
// Save scroll position
// const handleScroll = (event: any) => {
// const yOffset = event.nativeEvent.contentOffset.y;
// const key = `scrollPosition_${id}`;
// AsyncStorage.setItem(key, yOffset.toString());
// };
const handleScroll = (event: any) => {
const yOffset = event.nativeEvent.contentOffset.y;
data.verses.forEach(async verse => {
const key = `scrollPosition_${verse.id}`;
console.log('key1:', key);
await AsyncStorage.setItem(key, yOffset.toString());
});
};
const loadMoreData = () => {
if (endIndex < data.verses.length) {
setCurrentPage(currentPage + 1);
}
};
const renderData = () => {
if (isLoading) {
return <Loading />;
}
if (!data) {
return <Text>No Data Found!</Text>;
}
return (
<FlatList
style={styles.container}
ref={flatListRef}
onScroll={handleScroll}
data={data.verses.slice(0, endIndex)}
renderItem={({item}) => (
<CardAyatList
data={{
...data,
verses: [item],
}}
onPress={() => {}}
/>
)}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={Separator}
onEndReached={loadMoreData}
onEndReachedThreshold={0.5}
scrollEventThrottle={16}
/>
);
};
// ---------------------------------------------------------------------------
return renderData();
};
export default QuranDetailScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.white,
},
});
Given that data.verses is an array and you want to save the scroll position for each verse specifically, you’ll need to adjust your strategy. Instead of trying to use a single scroll position for the entire detail screen, you should save and restore the scroll position more granitularly, potentially at the verse level or ensure you have a method to identify which verse was last in view or most relevant to the user’s last position. However, there’s a challenge with trying to save the scroll position for each data.verses.id directly—your FlatList displays a continuous scrollable view, not individual screens per verse, so it’s not straightforward to save a scroll position for each verse. Instead, you generally save the scroll position of the list view itself. One approach is to determine the verse that was at the top of the screen (or whichever verse is deemed significant according to your design) when the user last interacted with the list or when the user is leaving the screen. You then save the scroll position alongside the identifier for this particular verse, rather than saving a scroll position for every verse. Please implement it ?
|
b3d9739a042c6ba8888e437f5d704e33
|
{
"intermediate": 0.33149632811546326,
"beginner": 0.468942791223526,
"expert": 0.19956089556217194
}
|
43,314
|
in kotlin how do i check if a queue contains a property of an object
|
cb840c16fe3449648ec39e728c82c7ec
|
{
"intermediate": 0.5987741947174072,
"beginner": 0.13615699112415314,
"expert": 0.26506879925727844
}
|
43,315
|
Table: Flights
+-------------+------+
| Column Name | Type |
+-------------+------+
| flight_id | int |
| capacity | int |
+-------------+------+
flight_id is the column with unique values for this table.
Each row of this table contains flight id and its capacity.
Table: Passengers
+--------------+------+
| Column Name | Type |
+--------------+------+
| passenger_id | int |
| flight_id | int |
+--------------+------+
passenger_id is the column with unique values for this table.
Each row of this table contains passenger id and flight id.
Passengers book tickets for flights in advance. If a passenger books a ticket for a flight and there are still empty seats available on the flight, the passenger ticket will be confirmed. However, the passenger will be on a waitlist if the flight is already at full capacity.
Write a solution to report the number of passengers who successfully booked a flight (got a seat) and the number of passengers who are on the waitlist for each flight.下面的解法是否可行:with book_prep as (
select flight_id
, count(distinct passenger_id) as total_passengers
from passangers
group by 1
)
select f1.flight_id
, capacity
, total_passengers
, case when total_passengers > capacity then capacity
else total_passengers end as booked_cnt
, case when total_passengers > capacity then total_passengers - capacity
else 0 end as waitlist_cnt
from flights f1
left join book_prep b1 on f1.flight_id = b1.flight_id
|
7d1b11e29fd018a7aca068c9216ee075
|
{
"intermediate": 0.3236626982688904,
"beginner": 0.3084999918937683,
"expert": 0.3678372800350189
}
|
43,316
|
import PyPDF2
# Open the existing PDF file
with open("pdf.pdf", "rb") as pdf_file:
pdf_reader = PyPDF2.PdfReader(pdf_file)
# Access form fields
form_fields = pdf_reader.get_form_text_fields()
checkboxes = pdf_reader.get_fields()
for form_field in form_fields:
print(form_field)
# # Modify text fields
form_fields["Patient First Name"] = "John Doe"
# # Set checkmarks (if applicable)
# checkboxes["checkbox_name"] = True # Checked
pdf_writer = PyPDF2.PdfWriter()
# # Add the modified page(s) to the new PDF
for page_num in range(len(pdf_reader.pages)):
pdf_writer.add_page(pdf_reader.pages[page_num])
# # Save the new PDF
with open("modified_file.pdf", "wb") as output_file:
pdf_writer.write(output_file)
the new file doesnt have john doe in it anywhere
|
7e20a748e24694f19c5f0fd9460d86d6
|
{
"intermediate": 0.47119879722595215,
"beginner": 0.2993858754634857,
"expert": 0.22941537201404572
}
|
43,317
|
I have two reference fields Field A and Field B where if I enter user in field A, the same user shouldn't be populated in user B and vice versa. If user is selected in field B it should not be populated in field A. Can anyone help me with the script
|
f3d0465031c3d4fb87992e485cfb2ff4
|
{
"intermediate": 0.400649756193161,
"beginner": 0.23980110883712769,
"expert": 0.3595491349697113
}
|
43,318
|
I have two reference fields Field A and Field B where if I enter user in field A, the same user shouldn’t be populated in user B and vice versa. If user is selected in field B it should not be populated in field A. Can anyone help me with the script servicenow
|
2622192955f8a118a97bdf3fa04bdf3d
|
{
"intermediate": 0.46079909801483154,
"beginner": 0.2516922354698181,
"expert": 0.28750869631767273
}
|
43,319
|
Item* newptr = new Item;
newptr->val = x; newptr->next = nullptr;
head = newptr; // set head to newptr
tail = head; // or newptr
the code above in c++ attempt to add a new node to an empty list (head = nullptr), why it set it val to x and it next to nullptr but doesnt set it prev to nullptr?
|
9a15b06aee8358d1185fc6847d5d761b
|
{
"intermediate": 0.45725491642951965,
"beginner": 0.39860799908638,
"expert": 0.14413709938526154
}
|
43,320
|
I want to analyze a huge amount of data from a questionnaire. This data is mostly composed of quantitative data, from 10 years ago and current. I have to make light of trends and changes that happened in this time period. How can I do?
|
8d691ca8c5ca625e99bc7fa5b580a73d
|
{
"intermediate": 0.4303620755672455,
"beginner": 0.28812405467033386,
"expert": 0.2815138101577759
}
|
43,321
|
//+------------------------------------------------------------------+
//| ProjectName |
//| Copyright 2020, CompanyName |
//| http://www.companyname.net |
//+------------------------------------------------------------------+
#include <Controls\Dialog.mqh>
#include <Controls\Button.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Controls\Label.mqh>
#include <Controls\Edit.mqh>
const string ID = "-1002113042792";
const string token = "7152618530:AAGJJC3zdkmCce3B7i11Dn2JDMh7GqpamyM";
const string IDToLicense = "-1002100526472";
#define INDENT_LEFT (11)
#define INDENT_TOP (11)
#define CONTROLS_GAP_X (5)
#define BUTTON_WIDTH (100)
#define BUTTON_HEIGHT (20)
CPositionInfo m_position;
CTrade m_trade;
CSymbolInfo m_symbol;
CLabel m_labelPipsToChange; // Метка для значения PipsToChange
CEdit m_editPipsToChange;
CLabel m_labelPipsToUpChange; // Метка для значения PipsToChange
CEdit m_editPipsToUpChange;
CLabel m_labelPipsToDownChange; // Метка для значения PipsToChange
CEdit m_editPipsToDownChange;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
class CAppWindowTwoButtons : public CAppDialog
{
private:
CButton m_button1; // the button object
CButton m_button2; // the button object
CLabel m_labelProfit;
public:
CAppWindowTwoButtons(void);
~CAppWindowTwoButtons(void);
//--- create
virtual bool Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);
//--- chart event handler
virtual bool OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam);
void UpdateProfitLabel(void);
void OnPipsToChangeEdit(void);
bool CreatePipsToChangeControls(void);
void OnPipsToDownChangeEdit(void);
bool CreatePipsToDownChangeControls(void);
void OnPipsToUpChangeEdit(void);
bool CreatePipsToUpChangeControls(void);
//--- create dependent controls
bool CreateButton1(void);
bool CreateButton2(void);
bool CreateProfitLabel(void);
//--- handlers of the dependent controls events
void OnClickButton1(void);
void OnClickButton2(void);
};
//+------------------------------------------------------------------+
//| Event Handling |
//+------------------------------------------------------------------+
EVENT_MAP_BEGIN(CAppWindowTwoButtons)
ON_EVENT(ON_CLICK,m_button1,OnClickButton1)
ON_EVENT(ON_CLICK,m_button2,OnClickButton2)
ON_EVENT(ON_CHANGE,m_editPipsToChange,OnPipsToChangeEdit)
ON_EVENT(ON_CHANGE,m_editPipsToDownChange,OnPipsToDownChangeEdit)
ON_EVENT(ON_CHANGE,m_editPipsToChange,OnPipsToChangeEdit)
EVENT_MAP_END(CAppDialog)
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
CAppWindowTwoButtons::CAppWindowTwoButtons(void)
{
}
//+------------------------------------------------------------------+
//| Destructor |
//+------------------------------------------------------------------+
CAppWindowTwoButtons::~CAppWindowTwoButtons(void)
{
}
//+------------------------------------------------------------------+
//| Create |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)
{
if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))
return(false);
//--- create dependent controls
if(!CreateButton1() || !CreateButton2() || !CreateProfitLabel() || !CreatePipsToChangeControls() || !CreatePipsToDownChangeControls() || !CreatePipsToUpChangeControls())
return(false);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Global Variable |
//+------------------------------------------------------------------+
CAppWindowTwoButtons ExtDialog;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreatePipsToUpChangeControls(void)
{
// Создание метки для PipsToChange
if(!m_labelPipsToUpChange.Create(0,"LabelPipsToUpChange",0,10,135,130,170))
return false;
m_labelPipsToUpChange.Text("Пункты на которые может поднятся цена:");
if(!Add(m_labelPipsToUpChange))
return(false);
// Создание поля для ввода PipsToChange
if(!m_editPipsToUpChange.Create(0,"EditPipsToUpChange",0,270,132,320,158))
return false;
if(!m_editPipsToUpChange.ReadOnly(false))
return(false);
m_editPipsToUpChange.Text(IntegerToString(PercentToUp));
if(!Add(m_editPipsToUpChange))
return(false);
return true;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::OnPipsToUpChangeEdit(void)
{
PercentToUp = StringToInteger(m_editPipsToUpChange.Text());
// Дополнительная валидация может потребоваться здесь
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreatePipsToDownChangeControls(void)
{
// Создание метки для PipsToChange
if(!m_labelPipsToDownChange.Create(0,"LabelPipsToDownChange",0,10,100,130,130))
return false;
m_labelPipsToDownChange.Text("Пункты на которые может упасть цена:");
if(!Add(m_labelPipsToDownChange))
return(false);
// Создание поля для ввода PipsToChange
if(!m_editPipsToDownChange.Create(0,"EditPipsToDownChange",0,255,97,305,123))
return false;
if(!m_editPipsToDownChange.ReadOnly(false))
return(false);
m_editPipsToDownChange.Text(IntegerToString(PercentToDown));
if(!Add(m_editPipsToDownChange))
return(false);
return true;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::OnPipsToDownChangeEdit(void)
{
PercentToDown = StringToInteger(m_editPipsToDownChange.Text());
// Дополнительная валидация может потребоваться здесь
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreatePipsToChangeControls(void)
{
// Создание метки для PipsToChange
if(!m_labelPipsToChange.Create(0,"LabelPipsToChange",0,10,65,100,10))
return false;
m_labelPipsToChange.Text("Количество пунктов изменения цены:");
if(!Add(m_labelPipsToChange))
return(false);
// Создание поля для ввода PipsToChange
if(!m_editPipsToChange.Create(0,"EditPipsToChange",0,240,62,290,88))
return false;
if(!m_editPipsToChange.ReadOnly(false))
return(false);
m_editPipsToChange.Text(IntegerToString(PipsToChange));
if(!Add(m_editPipsToChange))
return(false);
return true;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::OnPipsToChangeEdit(void)
{
PipsToChange = StringToInteger(m_editPipsToChange.Text());
// Дополнительная валидация может потребоваться здесь
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreateProfitLabel(void)
{
int x1=INDENT_LEFT;
int y1=INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X;
int x2=x1+INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X; // длина метки может быть больше, чтобы вместить текст
int y2=y1+BUTTON_HEIGHT;
if(!m_labelProfit.Create(0, "LabelProfit", 0, x1, y1, x2, y2))
return(false);
m_labelProfit.FontSize(10);
double profit = CalculateTotalProfit();
double TrueProfit = profit - g_initialProfit + g_closedTradesProfit + profitCloseSell + profitCloseBuy;
// Обновляем текст метки с прибылью
string profitText = StringFormat("Прибыль: %.2f", TrueProfit);
m_labelProfit.Text(profitText);
if(!Add(m_labelProfit))
return(false);
return(true);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreateButton1(void)
{
//--- coordinates
int x1=INDENT_LEFT; // x1 = 11 pixels
int y1=INDENT_TOP; // y1 = 11 pixels
int x2=x1+BUTTON_WIDTH; // x2 = 11 + 100 = 111 pixels
int y2=y1+BUTTON_HEIGHT; // y2 = 11 + 20 = 32 pixels
//--- create
if(!m_button1.Create(0,"Button1",0,x1,y1,x2,y2))
return(false);
if(!m_button1.Text("Закрыть sell"))
return(false);
if(!Add(m_button1))
return(false);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Create the "Button2" |
//+------------------------------------------------------------------+
bool CAppWindowTwoButtons::CreateButton2(void)
{
//--- coordinates
int x1=INDENT_LEFT+120; // x1 = 11 + 2 * (100 + 5) = 221 pixels
int y1=INDENT_TOP; // y1 = 11 pixels
int x2=x1+BUTTON_WIDTH; // x2 = 221 + 100 = 321 pixels
int y2=y1+BUTTON_HEIGHT; // y2 = 11 + 20 = 31 pixels
//--- create
if(!m_button2.Create(0,"Button2",0,x1,y1,x2,y2))
return(false);
if(!m_button2.Text("Закрыть buy"))
return(false);
if(!Add(m_button2))
return(false);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::UpdateProfitLabel(void)
{
// Вычисляем текущую прибыль со всех открытых позиций
double profit = CalculateTotalProfit();
double TrueProfit = profit - g_initialProfit + g_closedTradesProfit + profitCloseSell + profitCloseBuy;
// Обновляем текст метки с прибылью
string profitText = StringFormat("Прибыль: %.2f", TrueProfit);
m_labelProfit.Text(profitText);
profitToSend = StringFormat("Прибыль: %.2f", TrueProfit);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
input long PipsToChangeint = 5; // Количество пунктов изменения цены
input double InitialLots = 0.1; // Количество лотов для начальной сделки
input double LotChangePercent = 10.0; // Процент изменения количества лотов
input ENUM_TIMEFRAMES TimeFrame = PERIOD_M1;
input long PercentToDownInt = 3; //Пункты на которые может упасть цена после закртыия
input long PercentToUpInt = 3; //Пункты на которые может поднятся цена после закртыия
long PipsToChange = PipsToChangeint;
long PercentToDown = PercentToDownInt;
long PercentToUp = PercentToUpInt;
double PriceDown = 0;
double PriceUp = 10000000000;
double profitCloseSell = 0.0;
double profitCloseBuy = 0.0;
double g_closedTradesProfit = 0.0;
double g_initialProfit = 0.0;
double currentLots = InitialLots; // Текущее количество лотов
double lastPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID); // Последняя цена для отслеживания изменения на N пунктов
bool belowLevelAlerted = false; // Флаг отправки алерта для нижнего уровня
bool aboveLevelAlerted = false; // Флаг отправки алерта для верхнего уровня
bool close_s = false;
bool close_b = false;
bool start_b = false;
bool start_s = false;
bool send_b;
bool send_s;
string profitToSend;
bool close_all = false;
bool start = false;
datetime lastBarTime = 0;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int sendMessage(string text, string chatID, string botToken)
{
string baseUrl = "https://api.telegram.org";
string headers = "";
string requestURL = "";
string requestHeaders = "";
char resultData[];
char posData[];
int timeout = 200;
requestURL = StringFormat("%s/bot%s/sendmessage?chat_id=%s&text=%s",baseUrl,botToken,chatID,text);
int response = WebRequest("POST",requestURL,headers,timeout,posData,resultData,requestHeaders);
string resultMessage = CharArrayToString(resultData);
return response;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int getMessage(string chatID, string botToken)
{
string baseUrl = "https://api.telegram.org";
string headers = "";
string requestURL = "";
string requestHeaders = "";
char resultData[];
char posData[];
int timeout = 200;
string result[];
string sep = ",";
ushort sep_u = StringGetCharacter(sep,0);
string searchPattern = ("text");
string sep2 = "n";
ushort sep2_u = StringGetCharacter(sep2,0);
string result2[];
long accountNumber = AccountInfoInteger(ACCOUNT_LOGIN);
requestURL = StringFormat("%s/bot%s/getChat?chat_id=%s",baseUrl,botToken,chatID);
int response = WebRequest("GET",requestURL,headers,timeout,posData,resultData,requestHeaders);
string resultMessage = CharArrayToString(resultData);
int k = (StringSplit(resultMessage,sep_u,result));
if(k>0)
{
for(int i=0; i<k; i++)
{
if(StringFind(result[i], searchPattern) >= 0)
{
string res = StringSubstr(result[i],8,StringLen(result[i])-10);
int z = StringSplit(res,sep2_u,result2);
if(z>0)
{
for(int j=0; j<z; j++)
{
string finalResult;
int g = StringFind(result2[j],"\\",0);
if(g != -1)
{
finalResult = StringSubstr(result2[j],0,StringLen(result2[j])-1);
}
else
{
finalResult = result2[j];
}
if(finalResult == (string)accountNumber)
{
Print(accountNumber);
return true;
}
}
}
}
}
}
string wrongAccess = "Пытались торговать с счёта " + (string)accountNumber;
sendMessage(wrongAccess,ID,token);
return false;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double CalculateTotalProfit()
{
double totalProfit = 0.0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(m_position.SelectByIndex(i))
{
totalProfit += m_position.Profit();
}
}
return totalProfit;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int OnInit()
{
if(start != true)
{
g_initialProfit = CalculateTotalProfit();
}
if(!getMessage(IDToLicense,token))
return(INIT_FAILED);
if(!ExtDialog.Create(0,"Закрытие позиций и изменение вводных",0,15,100,350,300))
return(INIT_FAILED);
//--- run application
ExtDialog.Run();
MqlRates rates[];
if(CopyRates(_Symbol, TimeFrame, 0, 1, rates) > 0)
{
lastBarTime = rates[0].time;
}
else
{
Print("Ошибка при получении информации о барах: ", GetLastError());
return (INIT_FAILED);
}
if(start_b == false)
{
while(send_b != true)
{
OpenOrder(ORDER_TYPE_BUY, currentLots, "B");
start_b = true;
}
}
if(start_s == false)
{
while(send_s != true)
{
OpenOrder(ORDER_TYPE_SELL, currentLots, "S");
start_s = true;
}
}
//ObjectCreate(0,"Нижняя линия",OBJ_HLINE,0,0,BelowCurrentPriceLevel);
//ObjectSetInteger(0, "Нижняя линия", OBJPROP_COLOR, clrBlue);
//ObjectCreate(0,"Верхняя линия",OBJ_HLINE,0,0,AboveCurrentPriceLevel);
if(start != true)
{
ENUM_TIMEFRAMES TimeInt = TimeFrame;
if(TimeInt > 16000)
{
TimeInt = (ENUM_TIMEFRAMES)((TimeInt - 16384) * 60);
}
string message = StringFormat(
"PipsToChange: %ld "
"InitialLots: %f "
"LotChangePercent: %f "
"TimeFrame: %d "
"PipsToDown: %ld "
"PipsToUp: %ld "
"Symbol: %s "
"Номер счета: %lld",
PipsToChangeint,
InitialLots,
LotChangePercent,
TimeInt,
PercentToDownInt,
PercentToUpInt,
_Symbol,
AccountInfoInteger(ACCOUNT_LOGIN));
sendMessage(message,ID,token);
start = true;
}
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Comment("");
//--- destroy dialog
ExtDialog.Destroy(reason);
//ObjectDelete(0,"Нижняя линия");
//ObjectDelete(0,"Верхняя линия");
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, // event ID
const long& lparam, // event parameter of the long type
const double& dparam, // event parameter of the double type
const string& sparam) // event parameter of the string type
{
ExtDialog.ChartEvent(id,lparam,dparam,sparam);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double NormalizeLot(double lot, double min_lot, double max_lot, double lot_step)
{
// Округление до ближайшего допустимого значения
lot = MathMax(min_lot, lot);
lot -= fmod(lot - min_lot, lot_step);
lot = MathMin(max_lot, lot);
return NormalizeDouble(lot, _Digits);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CalculateAndSetLotSize()
{
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
// Увеличение текущего размера лота на заданный процент
currentLots *= (1 + LotChangePercent / 100.0);
// Округление до ближайшего допустимого значения
currentLots = NormalizeLot(currentLots, min_lot, max_lot, lot_step);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double SubtractPointsDown(double price, long points)
{
// Получаем количество десятичных знаков и размер пункта
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Вычисляем изменение цены
double change = points * pointSize;
// Возвращаем результат
return NormalizeDouble(price - change, digits);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double SubtractPointsUp(double price, long points)
{
// Получаем количество десятичных знаков и размер пункта
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Вычисляем изменение цены
double change = points * pointSize;
// Возвращаем результат
return NormalizeDouble(price + change, digits);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::OnClickButton1(void)
{
for(int i=PositionsTotal()-1; i>=0; i--)
{
string symbol = PositionGetSymbol(i);
if(!PositionSelect(symbol))
continue;
if(m_position.SelectByIndex(i))
if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_SELL)
continue;
profitCloseSell += m_position.Profit();
m_trade.PositionClose(PositionGetInteger(POSITION_TICKET));
close_s = true;
}
PriceDown = SubtractPointsDown(SymbolInfoDouble(_Symbol, SYMBOL_BID),PercentToDown);
PriceUp = SubtractPointsUp(SymbolInfoDouble(_Symbol, SYMBOL_ASK),PercentToUp);
string messButt1 = "sell закрыты " + (string)AccountInfoInteger(ACCOUNT_LOGIN);
sendMessage(messButt1,ID,token);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CAppWindowTwoButtons::OnClickButton2(void)
{
int totalPositions = PositionsTotal();
for(int i = totalPositions - 1; i >= 0; i--)
{
string symbol = PositionGetSymbol(i);
if(!PositionSelect(symbol))
continue;
if(m_position.SelectByIndex(i))
if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_BUY)
continue;
profitCloseBuy += m_position.Profit();
m_trade.PositionClose(PositionGetInteger(POSITION_TICKET));
close_b = true;
}
PriceDown = SubtractPointsDown(SymbolInfoDouble(_Symbol, SYMBOL_BID),PercentToDown);
PriceUp = SubtractPointsUp(SymbolInfoDouble(_Symbol, SYMBOL_ASK),PercentToUp);
string messButt2 = "buy закрыты " + (string)AccountInfoInteger(ACCOUNT_LOGIN);
sendMessage(messButt2,ID,token);
}
#property indicator_chart_window
#property indicator_color1 Pink
//±-----------------------------------------------------------------+
//| Expert tick function |
//±-----------------------------------------------------------------+
long PipsToChangelast = PipsToChange;
long PercentToDownlast = PercentToDown;
long PercentToUplast = PercentToUp;
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double GetMaxOpenPrice()
{
double maxPrice = 0.0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(m_position.SelectByIndex(i))
{
double openPrice = m_position.PriceOpen();
if(openPrice > maxPrice)
maxPrice = openPrice;
}
}
return maxPrice;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double GetMinOpenPrice()
{
double minPrice = DBL_MAX;
for(int i = PositionsTotal() - 1; i >= 0; --i)
{
if(m_position.SelectByIndex(i))
{
double openPrice = m_position.PriceOpen();
if(openPrice < minPrice)
minPrice = openPrice;
}
}
return minPrice;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnTick()
{
send_b = false;
send_s = false;
ExtDialog.OnPipsToChangeEdit();
ExtDialog.UpdateProfitLabel();
ExtDialog.OnPipsToDownChangeEdit();
ExtDialog.OnPipsToUpChangeEdit();
if(PercentToDownlast != PercentToDown || PercentToUplast != PercentToUp || PipsToChangelast != PipsToChange)
{
string messChanges = StringFormat(
"PipsToChange: %ld "
"PipsToDown: %ld "
"PipsToUp: %ld "
"Номер счета: %lld",
PipsToChange,
PercentToDown,
PercentToUp,
AccountInfoInteger(ACCOUNT_LOGIN)
);
sendMessage(messChanges,ID,token);
PipsToChangelast = PipsToChange;
PercentToDownlast = PercentToDown;
PercentToUplast = PercentToUp;
}
double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
datetime currentTime = TimeCurrent();
ENUM_TIMEFRAMES Time = TimeFrame;
if(Time > 16000)
{
Time = (ENUM_TIMEFRAMES)((Time - 16384) * 60);
}
if((SymbolInfoDouble(_Symbol, SYMBOL_ASK) > PriceUp || SymbolInfoDouble(_Symbol, SYMBOL_BID) < PriceDown) && close_all != true)
{
int totalPositions = PositionsTotal();
for(int i = totalPositions - 1; i >= 0; i--)
{
string symbol = PositionGetSymbol(i);
if(!PositionSelect(symbol))
continue;
profitCloseBuy += m_position.Profit();
m_trade.PositionClose(PositionGetInteger(POSITION_TICKET));
}
close_b = true;
close_s = true;
string closeMessage = "Бот закрыл все сделки " + (string)AccountInfoInteger(ACCOUNT_LOGIN);
sendMessage(closeMessage,ID,token);
sendMessage(profitToSend,ID,token);
close_all = true;
}
double maxOpenPrice = GetMaxOpenPrice();
double minOpenPrice = GetMinOpenPrice();
if(currentTime >= lastBarTime+Time*60)
{
if(bidPrice - maxOpenPrice > PipsToChange * _Point || minOpenPrice - askPrice > PipsToChange * _Point)
{
// Подсчитаем новый размер лота
CalculateAndSetLotSize();
lastPrice = bidPrice; // Обновление последней цены
// Открываем новые ордера с новым размером лота
if(close_b == false)
{
while(send_b != true)
{
OpenOrder(ORDER_TYPE_BUY, currentLots, "B");
}
}
if(close_s == false)
{
while(send_s != true)
{
OpenOrder(ORDER_TYPE_SELL, currentLots, "S");
}
}
}
lastBarTime = lastBarTime+Time*60;
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OpenOrder(ENUM_ORDER_TYPE type, double lots, string orderMagic)
{
MqlTradeRequest request = {};
MqlTradeResult result = {};
// Заполнение полей структуры запроса на сделку
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.volume = lots;
request.type = type;
request.deviation = 5;
request.magic = StringToInteger(orderMagic + IntegerToString(GetTickCount()));
//request.comment = "Auto trade order";
if(type == ORDER_TYPE_BUY)
request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
else
if(type == ORDER_TYPE_SELL)
request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if(!OrderSend(request, result))
{
Print("OrderSend failed with error #", GetLastError());
Print("Details: symbol=", request.symbol, ", volume=", request.volume, ", type=", (request.type==ORDER_TYPE_BUY?"BUY":"SELL"), ", price=", request.price);
if(request.type == ORDER_TYPE_BUY)
{
send_b = false;
}
else
if(request.type == ORDER_TYPE_SELL)
{
send_s = false;
}
}
else
if(request.type == ORDER_TYPE_BUY)
{
send_b = true;
}
else
if(request.type == ORDER_TYPE_SELL)
{
send_s = true;
}
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
в эту программу нужно добавить расчет безубытка после нажатия одной из кнопок
|
cb7b1d62f2219568df20938d34081452
|
{
"intermediate": 0.35756972432136536,
"beginner": 0.42062053084373474,
"expert": 0.2218097746372223
}
|
43,322
|
React library rc-select has a prop called showAction. Can you post an example of the code that will render a select and and an icon and if you will click the icon the dropdown menu will render without clicking on select itself?
|
d30577db224ee0e4fc2c60cd518ac5dd
|
{
"intermediate": 0.8516186475753784,
"beginner": 0.05654977262020111,
"expert": 0.09183154255151749
}
|
43,323
|
How to determine The Optimal Number Of Clusters for a data clustering in R, using data from an Excel spreadsheet?
|
dce9eec321908c9203c10ac64967dc5f
|
{
"intermediate": 0.3663434684276581,
"beginner": 0.1163717657327652,
"expert": 0.5172847509384155
}
|
43,324
|
I want you to act as a Code Review Helper for beginner and intermediate programmers working with Python language. I will provide you with short code snippets, and you are to analyze these snippets for efficiency, readability, and adherence to Python coding standards (PEP 8). Your feedback should include suggestions for improvements, identifications of potential bugs or errors, and recommendations for best practices. Please avoid overly technical jargon unless it’s necessary for the explanation. My first code snippet is “def sum(a, b): return a + b”.
|
f1e550c8ec95e20ed5ffe708323cabac
|
{
"intermediate": 0.2946285903453827,
"beginner": 0.35270971059799194,
"expert": 0.35266169905662537
}
|
43,325
|
convert the following R code to python achieving the same functionality :
DT_STRUCTURE$NumericOrder <- as.numeric(gsub("\\D", "", DT_STRUCTURE$STRUCTURE))
DT_STRUCTURE <- DT_STRUCTURE[order(DT_STRUCTURE$NumericOrder), ]
DT_STRUCTURE_casted <- lapply(X = split(DT_STRUCTURE, with(DT_STRUCTURE, list(NumericOrder))),
FUN = dcast,
formula = STRUCTURE + ELEMENT.STRUCTURE ~ VARIABLE,
value.var = "VALEUR")
names(DT_STRUCTURE_casted) <- paste0("ST", names(DT_STRUCTURE_casted))
|
fa89d5f69cbb25106879ac502c79933c
|
{
"intermediate": 0.36867377161979675,
"beginner": 0.39312440156936646,
"expert": 0.2382018268108368
}
|
43,326
|
hey
|
9437fa62afac4857701750b3a635825f
|
{
"intermediate": 0.33180856704711914,
"beginner": 0.2916048467159271,
"expert": 0.3765866458415985
}
|
43,327
|
convert the following to python code achieving the same functionality using pandas,vaex and polars versions :
DT_STRUCTURE$NumericOrder <- as.numeric(gsub("\\D", "", DT_STRUCTURE$STRUCTURE))
DT_STRUCTURE <- DT_STRUCTURE[order(DT_STRUCTURE$NumericOrder), ]
DT_STRUCTURE_casted <- lapply(X = split(DT_STRUCTURE, with(DT_STRUCTURE, list(NumericOrder))),
FUN = dcast,
formula = STRUCTURE + ELEMENT.STRUCTURE ~ VARIABLE,
value.var = "VALEUR")
names(DT_STRUCTURE_casted) <- paste0("ST", names(DT_STRUCTURE_casted))
|
7ab5ce7ef3cb5a85ae64baee5be7d9f5
|
{
"intermediate": 0.4862310290336609,
"beginner": 0.2725541889667511,
"expert": 0.24121473729610443
}
|
43,328
|
convert the following to python code achieving the same functionality :
''' DT_STRUCTURE$NumericOrder <- as.numeric(gsub("\\D", "", DT_STRUCTURE$STRUCTURE))
DT_STRUCTURE <- DT_STRUCTURE[order(DT_STRUCTURE$NumericOrder), ]
DT_STRUCTURE_casted <- lapply(X = split(DT_STRUCTURE, with(DT_STRUCTURE, list(NumericOrder))),
FUN = dcast,
formula = STRUCTURE + ELEMENT.STRUCTURE ~ VARIABLE,
value.var = "VALEUR")
names(DT_STRUCTURE_casted) <- paste0("ST", names(DT_STRUCTURE_casted))
'''
|
6d22b23af0014c38e400f4fd4ebc5252
|
{
"intermediate": 0.3573226034641266,
"beginner": 0.3210632801055908,
"expert": 0.3216141164302826
}
|
43,329
|
convert the following to python code achieving the same functionality using pandas , polars and vaex
|
d8ea291bad2d4146f7de7fe892574833
|
{
"intermediate": 0.5316212177276611,
"beginner": 0.1742071956396103,
"expert": 0.29417160153388977
}
|
43,330
|
import pandas as pd
# Assuming DT_STRUCTURE is a pandas DataFrame
# Convert STRUCTURE column to numeric by removing non-numeric characters
DT_STRUCTURE['NumericOrder'] = pd.to_numeric(DT_STRUCTURE['STRUCTURE'].str.replace(r'\D', ''))
# Sort DataFrame by NumericOrder column
DT_STRUCTURE_sorted = DT_STRUCTURE.sort_values(by='NumericOrder')
# Perform the cast operation using groupby and pivot_table
DT_STRUCTURE_casted = DT_STRUCTURE_sorted.groupby('NumericOrder').apply(
lambda x: x.pivot_table(index=['STRUCTURE', 'ELEMENT.STRUCTURE'], columns='VARIABLE', values='VALEUR')
)
# Rename the resulting DataFrame columns
DT_STRUCTURE_casted.columns = ['ST' + str(col) for col in DT_STRUCTURE_casted.columns]
|
36be7165319114a297b38cb701413aa3
|
{
"intermediate": 0.46791523694992065,
"beginner": 0.27062737941741943,
"expert": 0.2614573538303375
}
|
43,331
|
Hi there, I need help with an API of one of the AI providers.
The AI provider that I'm using has paths for the endpoint like "/v1/completions" and "/v1/chat/completions" for compatibility with OpenAI's API, but it doesn't have the "/v1/models" endpoint to fetch the models.
The problem is that the app that I'm using has support for OpenAI-compatible APIs, but it REQUIRES "/v1/models" endpoint to fetch the list of available models, but my AI provider's API has it at "/api/models" instead.
Is there a way for me to "fake" that endpoint by making my own API that would mostly redirect to theirs, except for "/v1/models" path, which would redirect to "/api/models" instead, all that using Python? Remember that EVERYTHING else should redirect to the API, so even streaming data would work.
|
e945a699ed042c6d0938d7e57869f160
|
{
"intermediate": 0.7805008888244629,
"beginner": 0.08073563873767853,
"expert": 0.1387633979320526
}
|
43,332
|
I want to do data clustering from excel data imported to R. How to do?
|
930404f63e53faab39db2c334b3a9efe
|
{
"intermediate": 0.506978452205658,
"beginner": 0.13338543474674225,
"expert": 0.3596360981464386
}
|
43,333
|
Привет! Мне нужно добавить в бота кнопку "Купить аккаунты", которая будет выводить текст "Чтобы купить почты, обратитесь к администратору. \n\n Нажмите на кнопку ниже, чтобы перейти в диалог." с кнопкой с ссылкой t.me/Ih92seeucry. Вот код бота:
import aiosqlite
import logging
import asyncio
import time
import re
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiosqlite import connect
import imaplib
import email
from email.parser import BytesParser
from email.policy import default
from aiogram.dispatcher import FSMContext
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters.state import State, StatesGroup
API_TOKEN = '7134249973:AAFtQLdZFv4aBS9LUM785ZRdm0dlmT2NGJ4'
DATABASE = 'emails.db'
ADMINS = [989037374]
almaz = [400086083]
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
dp.middleware.setup(LoggingMiddleware())
# Создание таблицы при запуске бота
async def on_startup(dispatcher):
async with aiosqlite.connect(DATABASE) as db:
await db.execute("""
CREATE TABLE IF NOT EXISTS emails (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL
)
""")
await db.commit()
class EmailStates(StatesGroup):
waiting_for_email_data = State()
# Добавление почты и пароля в БД
async def add_email_to_db(user_id, email, password):
async with aiosqlite.connect(DATABASE) as db:
await db.execute("INSERT INTO emails (user_id, email, password) VALUES (?, ?, ?)", (user_id, email, password,))
await db.commit()
# Обработчик начального сообщения /start
@dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message):
keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add("Получить письма", "Купить аккаунты")
await message.answer("Привет! Чтобы начать, нажми одну из кнопок.", reply_markup=keyboard)
# Обработчик добавления почты
@dp.message_handler(commands=['add'])
async def request_email_data(message: types.Message):
if (message.from_user.id in ADMINS) or (message.from_user.id in almaz):
await EmailStates.waiting_for_email_data.set()
await message.answer("Введите адреса электронной почты и пароли в формате mail:pass, каждый с новой строки.")
else:
await message.answer("Извините, но только администраторы могут добавлять почты.")
# Обработка сообщений с данными почты от пользователя
@dp.message_handler(state=EmailStates.waiting_for_email_data)
async def add_email(message: types.Message, state: FSMContext):
# Обрабатываем входящее сообщение с почтами
lines = message.text.strip().split('\n')
error_lines = [] # Список строк с ошибками
for line in lines:
try:
email, password = line.split(':')
# Сохраняем в БД
await add_email_to_db(message.from_user.id, email, password)
except ValueError:
error_lines.append(line)
if error_lines:
error_message = "Некорректный формат в строках: \n" + "\n".join(error_lines)
error_message += "\nИспользуйте формат mail:password."
await message.answer(error_message)
else:
await message.answer(f"Почты добавлены в БД.")
# Завершаем состояние приема данных о почте
await state.finish()
async def extract_code_from_email(email_body):
match = re.search(r'\b\d{6}\b', email_body)
return match.group(0) if match else None
# Функция для попытки получить код
async def try_to_get_code(message, state, user_id, user_email):
timeout = 120 # Таймаут в секундах
end_time = time.time() + timeout
success = False
while time.time() < end_time:
emails_messages = await get_user_emails(user_id, user_email)
if isinstance(emails_messages, str):
await asyncio.sleep(10) # Ошибка IMAP - повторяем через 10 секунд
continue
if emails_messages:
# Получаем последнее письмо
last_email_body = emails_messages[-1].get_body(preferencelist=('plain', 'html')).get_content()
code = await extract_code_from_email(last_email_body)
if code:
await message.answer(f"Ваш код: {code}")
success = True
break
await asyncio.sleep(10) # Перерыв на 10 секунд
if not success:
await message.answer("Не удалось получить код в течение заданного времени.")
await state.finish()
async def send_long_message(message: types.Message, long_text: str, part_length: int = 4096):
for part in [long_text[i:i + part_length] for i in range(0, len(long_text), part_length)]:
await message.answer(part)
# Метод для получения писем пользователя
async def get_user_emails(user_id, email):
async with aiosqlite.connect(DATABASE) as db:
async with db.execute("SELECT email, password FROM emails WHERE user_id = ? AND email = ?", (user_id, email)) as cursor:
user_email = await cursor.fetchone()
if user_email:
mail_server = imaplib.IMAP4_SSL('imap.rambler.ru', 993)
try:
mail_server.login(user_email[0], user_email[1])
mail_server.select('inbox')
# поиск и возврат uid последних 5 писем
result, data = mail_server.uid('search', None, "ALL")
if result == 'OK':
emails = data[0].split()[-2:]
return await fetch_emails_from_uids(mail_server, emails)
except imaplib.IMAP4.error as e:
return f"Ошибка IMAP: {str(e)}"
finally:
mail_server.logout()
else:
return "Не удалось найти данные для этой почты в БД."
# Получение писем по их UID
async def fetch_emails_from_uids(mail_server, email_uids):
email_messages = []
parser = BytesParser(policy=default)
for email_uid in email_uids:
result, data = mail_server.uid('fetch', email_uid, '(RFC822)')
if result == 'OK':
email_data = data[0][1]
msg = parser.parsebytes(email_data)
email_messages.append(msg)
return email_messages
class EmailStates(StatesGroup):
waiting_for_email_data = State()
waiting_for_email_to_fetch = State()
# Обработчик команды "Получить письма", который запрашивает данные
@dp.message_handler(lambda message: message.text == "Получить письма", state="*")
async def request_to_fetch_emails(message: types.Message):
await EmailStates.waiting_for_email_to_fetch.set()
await message.answer("Введите адрес электронной почты, чтобы получить последние письма.")
# Обработчик получения адреса электронной почты для получения писем
@dp.message_handler(state=EmailStates.waiting_for_email_to_fetch)
async def fetch_emails_handler(message: types.Message, state: FSMContext):
user_email = message.text.strip()
# Отправляем сообщение пользователю о начале поиска кода
await message.answer("Ищем код в вашей почте, это может занять до двух минут…")
asyncio.create_task(try_to_get_code(message, state, message.from_user.id, user_email))
if __name__ == '__main__':
# Запуск бота
executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
|
18748d99893e25128375c92f30042df8
|
{
"intermediate": 0.3692317008972168,
"beginner": 0.4316059350967407,
"expert": 0.1991623491048813
}
|
43,334
|
I imported into R an excel database to perform data clustering. However, my data is stored as character strings. How do I convert those characters strings into numbers? (the data is composed of numbers read as characters)
|
a793a65dbe69228bdccc79a9ad6ba11f
|
{
"intermediate": 0.5352957844734192,
"beginner": 0.11623871326446533,
"expert": 0.3484654724597931
}
|
43,335
|
I imported Excel data into R. I want to delete the first row
|
e1cdbf0125db2f61c29939bb9beb3ed6
|
{
"intermediate": 0.43775901198387146,
"beginner": 0.2574644982814789,
"expert": 0.30477648973464966
}
|
43,336
|
elasticsearch give me get request on array of ids, but with projection on a a"hash_content" field
|
012bd6ccde88ce29e3914edd3167fde2
|
{
"intermediate": 0.4195346534252167,
"beginner": 0.1567719280719757,
"expert": 0.42369335889816284
}
|
43,337
|
You are an helpful assistant that analyses recipes and enhance them with better quality data and analysis of allergens and intoleration ingedients. You receive recipe as a plain text and you are reworking it into unified form that follows RelyonRecipe class bellow. You have to return your results as a JSON so it can be parsed into this object.
export class RelyonRecipe {
@Expose() @Transform(({ key, obj }) => obj[key])
_id?: string | undefined;
@Expose()
name!: string;
@Expose()
instructions!: string[];
@Expose()
thumbnail!: string;
@Expose()
video?: string;
@Expose()
ingredients!: {
image: string;
name: string,
measure: string,
}[];
@Expose()
engineSource!: FoodDataSources;
@Expose()
tags?: string[];
@Expose() @Type(() => RelyonAllergen)
allergens?: RelyonAllergen[];
}
Other Classes used in above RelyonRecipe:
export interface RelyonAllergen {
_id?: string;
name: string;
icon?: string;
iconURL?: URL;
lowercase: string;
preDefined: boolean;
author?: string;
status?: 'intolerant' | 'tolerant' | 'connection';
}
|
1f8e07758d7a9de8323c2f8c20ee0f62
|
{
"intermediate": 0.2294759303331375,
"beginner": 0.6194360256195068,
"expert": 0.15108798444271088
}
|
43,338
|
есть две страницы tilda.ru и tilda.cc
что нужно поменять в данном коде чтобы он работал на обоих страницах?
// ==UserScript==
// @name Tilda Publishing Helper
// @namespace https://roman-kosov.ru/donate
// @homepage https://roman-kosov.ru
// @version 55.0.10
// @description Тильда Хелпер: вспомогательные фичи, апгрейд Zero блока
// @author Roman Kosov
// @copyright 2017 - 2077, Roman Kosov (https://greasyfork.org/users/167647)
// @match https://tilda.cc/page/?pageid=*
// @match https://tilda.cc/projects/?projectid=*
// @match https://tilda.cc/projects/favicons/?projectid=
// @match https://tilda.cc/projects/payments/?projectid=*
// @match https://tilda.cc/projects/settings/?projectid=*
// @match https://tilda.cc/domains/*
// @match https://tilda.cc/identity/
// @match https://tilda.cc/identity/plan/
// @match https://tilda.cc/identity/courses/
// @match https://tilda.cc/identity/promocode/
// @match https://tilda.cc/identity/deleteaccount/
// @exclude https://tilda.cc/identity/apikeys/*
// @exclude https://tilda.cc/identity/changepassword/*
// @match https://tilda.ru/page/?pageid=*
// @match https://tilda.ru/projects/?projectid=*
// @match https://tilda.ru/projects/favicons/?projectid=
// @match https://tilda.ru/projects/payments/?projectid=*
// @match https://tilda.ru/projects/settings/?projectid=*
// @match https://tilda.ru/domains/*
// @match https://tilda.ru/identity/
// @match https://tilda.ru/identity/plan/
// @match https://tilda.ru/identity/courses/
// @match https://tilda.ru/identity/promocode/
// @match https://tilda.ru/identity/deleteaccount/
// @exclude https://tilda.ru/identity/apikeys/*
// @exclude https://tilda.ru/identity/changepassword/*
// @exclude https://tilda.ru
// @exclude https://tilda.cc
// @run-at document-idle
// @icon https://www.google.com/s2/favicons?domain=https://madeontilda.ru
// @downloadURL https://update.greasyfork.org/scripts/37669/Tilda%20Publishing%20Helper.user.js
// @updateURL https://update.greasyfork.org/scripts/37669/Tilda%20Publishing%20Helper.meta.js
// ==/UserScript==
(async function (window) {
'use strict';
/* Делаем редирект, если страница недоступна для редактирования */
const textBody =
document.querySelector('body').textContent || document.querySelector('body').innerText;
const search = new URLSearchParams(window.location.search);
let projectid = '';
if (search.get('projectid') !== null) {
projectid = search.get('projectid');
}
let pageid = '';
if (search.get('pageid') !== null) {
pageid = search.get('pageid');
}
let url = '';
if ((
textBody === "You can't edit this project.." ||
textBody === 'You can not edit this project...' ||
textBody === "This page belongs to another account, so you can't see or edit it... Please re-login" ||
textBody === "This page belongs to another account, so you can't see or edit it. Please re-login" ||
textBody === "This project belongs to another account, so you can't see or edit it. Please re-login" ||
textBody === "This project belongs to another account, so you can't see or edit it... Please re-login") && projectid) {
url = `https://project${parseInt(projectid, 10)}.tilda.ws/`;
if (pageid) {
url += `page${parseInt(pageid, 10)}.html`;
}
window.location.href = url;
return;
} else if (
textBody === 'Error 404: Page not found' ||
textBody ===
'System errorSomething is going wrong. If you see this message, please email us <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS> and describe the problem.'
) {
return;
} else if (
window.location.pathname === '/identity/apikeys/'
) {
return;
} else {
(function (factory) {
// eslint-disable-next-line no-undef
if (typeof define === 'function' && define.amd) {
/* AMD. Register as an anonymous module. */
// eslint-disable-next-line no-undef
define(['jquery'], factory);
} else if (typeof exports === 'object') {
/* Node/CommonJS */
module.exports = factory(require('jquery'));
} else {
/* Browser globals */
factory(jQuery);
}
})(function ($) {
setTimeout(() => {
if (projectid === '') {
projectid = window.$projectid || window.tildaprojectid || window.projectid || 0;
}
const returnTo2008 = [
1613433,
3976932,
5497750,
6688176,
7973007,
9122176,
10263672,
11483550,
12177330,
26403648,
26216918,
28470022,
30862545,
25762800,
].some((el, i) => parseInt(projectid, 10) === el / (i + 3)) ?
1 :
0;
if (returnTo2008 || localStorage.getItem('returnTo2008') !== null) {
localStorage.setItem('returnTo2008', 1);
return;
}
/* Заносим все новые стили в переменную */
let styleBody = `
.ui-sortable-handle > td:nth-child(1) {
padding-right: 20px;
}
/* Меняем расстояние между кнопками «Закрыть» и «Сохранить изменения» */
.td-popup-window__bottom-right .td-popup-btn {
margin: 0 0 0 15px !important;
}
/* Делаем кнопку «Домой» интерактивной */
.td-page__ico-home:hover {
filter: opacity(.5); !important;
}
/* Меняем текст в попапе при публикации страницы */
.js-publish-noteunderbutton {
width: 92% !important;
color: #333 !important;
font-family: unset !important;
}
.modal-body {
font-weight: 300;
}
.js-publish-noteunderbutton a,
.pub-left-bottom-link a {
text-decoration: underline;
}
#referralpopup {
z-index: 1 !important;
}`;
/* Заносим все внешние функции в переменную */
let scriptBody = '';
/* Переменная для вывода текста */
let text = '';
/* Опреляем язык по чёрному меню сверху */
let lang = 'RU';
if (typeof $("a[href$='/identity/'].t-menu__item:first").val() !== 'undefined') {
if ($("a[href$='/identity/'].t-menu__item:first").text() === 'Профиль') {
lang = 'RU';
} else {
lang = 'EN';
}
}
const isEmpty = (obj) => {
if (obj == null) return true;
if (obj.length > 0) return false;
if (obj.length === 0) return true;
if (typeof obj !== 'object') return true;
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) return false;
}
return true;
};
const addRecIDs = () => {
$('div.record').each((i, el) => {
if (
$(el)
.children('div#mainleft')
.children('.tp-record-edit-icons-left__wrapper')
.children('.tp-record-edit-icons-left__one:last-child[data-tilda-helper]')
.length < 1
) {
const rid = $(el).attr('recordid');
const recid = `#rec${rid}`;
const recordid = `#record${rid}`;
const copy = `let t = $('<input>'); $('body').append(t); t.val('#rec${rid}').select(); document.execCommand('copy'); t.remove()`;
const mainleft = $(el).children('div#mainleft').children('div');
if ($(el).height() <= 50) {
$(el).find('.recordediticons').css('display', 'block').css('z-index', '999');
}
$(mainleft).append(
'<div class="tp-record-edit-icons-left__one-right-space"></div>',
);
if (!$(`${recordid} > div:nth-child(1)`).hasClass('mainright')) {
$(mainleft).append(
$(`${recordid} > div:nth-child(1):not(.mainright)`)
.removeClass()
.css('padding', '7px 15px'),
)
.append(
'<div class="tp-record-edit-icons-left__one-right-space"></div>',
);
}
$(mainleft).append(`
<div class="tp-record-edit-icons-left__one" data-tilda-helper="true" style="cursor: pointer">
<div class="tp-record-edit-icons-left__item-title" data-title="Скопировать id этого блока">
<span onclick="${copy}" class="tp-record-edit-icons-left__item-tplcod" style="font-weight: 400">${recid}</span>
</div>
</div>`);
}
});
};
if (window.location.pathname === '/identity/plan/') {
$('body').append(
'<script async src="/tpl/js/new_ti-profile-all.min.js"></script>',
);
$('body').append(`
<script>
$(document).ready(function () {
var ts = Date.now();
var data = {};
data['comm'] = 'getidentity';
if (typeof window.xhr_getprojects != 'undefined') window.xhr_getprojects.abort();
window.xhr_getprojects = $.ajax({
type: "POST",
url: "/identity/get/getprofile/",
data: data,
dataType: "text",
success: function (datastr) {
check_logout(datastr);
if (datastr == '') {} else {
var obj = JSON.parse(datastr);
if (typeof obj == 'object') {
if (obj === null) obj = {};
$("[name='paybox']").before(\`<div style="font-size: 26px; font-weight: 600; background-color: #eee; padding: 30px; margin-top: -40px; margin-bottom: 15px">Email: $\{obj.useremail}</div>\`);
showmore_prices();
}
}
},
timeout: 1000 * 10
});
});
</script>`);
}
if (
window.location.pathname === '/identity/' ||
window.location.pathname === '/identity/deleteaccount/' ||
window.location.pathname === '/identity/promocode/'
) {
/* Добавляем ссылку на удаление аккаунта */
$("[href='/identity/changepassword/']").after(
`<a href="/identity/deleteaccount/" style="float: right; font-size: 16px; opacity: 0.3">${
lang === 'RU' ? 'Удалить аккаунт' : 'Delete Account'
}</a>`,
);
/* Исправляем слишком длинную кнопку в Профиле */
$('button.btn.btn-primary')
.css('padding-left', '0')
.css('padding-right', '0')
.css('min-width', '180px')
.css('margin', '-1px');
$('input.form-control')
.css('padding-left', '0')
.css('padding-right', '0')
.css('box-shadow', 'unset')
.css('border-radius', 'unset')
.addClass('td-input');
}
if (
window.location.pathname === '/domains/' ||
window.location.pathname === '/identity/courses/'
) {
/* Исправляем отступ слева у кнопки в Доменах */
$('center > a > table > tbody > tr > td').css('padding-left', '0');
}
if (window.location.search.includes('addnewpage=yes')) {
/* Перемещаем «Указать ID шаблона» */
if (typeof $('#welcome-middle').val() !== 'undefined') {
$('#previewprojex').append(`
<span>Или укажите номер шаблона</span>
`);
$('#welcome-middle').next().next().after($('#welcome-middle'));
}
}
styleBody += `
.td-welcome-bottom {
font-size: 18px;
padding-bottom: 25px;
}`;
if (window.location.pathname === '/page/') {
/* Добавляем recid для каждого блока на странице */
addRecIDs();
/* Упрощаем вид блока T803 */
$('.t803__multi-datablock center').append(
'<br><br><div class="t803__multi-data-bg" style="max-width: 370px; text-align: left"></div><br>',
);
$('.t803__multi-datablock').each((i, el) => {
$(el)
.find('center .t803__multi-data-bg')
.append(
$(el).find('.t803__multi-data-0 .t803__label')[0],
$(el).find('.t803__multi-data-0 .t803__multi-key'),
$(el).find('.t803__multi-data-0 .t803__label')[1],
$(el).find('.t803__multi-data-0 .t803__multi-default'),
);
});
$('.t803__multi-data-0').prepend(
$($('center .t803__multi-data-bg .t803__label')[0]).clone(),
$($('center .t803__multi-data-bg .t803__multi-key')[0]).clone(),
$($('center .t803__multi-data-bg .t803__label')[1]).clone(),
$($('center .t803__multi-data-bg .t803__multi-default')[0]).clone(),
);
/* Другая подсказка после публикации страницы */
if (typeof $('#page_menu_publishlink').val() !== 'undefined') {
$('#page_menu_publishlink').click(() => {
setTimeout(() => {
if (lang === 'RU') {
$('.js-publish-noteunderbutton').html(
'Ваш браузер может сохранять старую версию страницы.<br><a href="https://yandex.ru/support/common/browsers-settings/cache.html" rel="noopener noreferrer" target="_blank">Как очистить кэш в браузере.</a>',
);
} else {
$('.js-publish-noteunderbutton').html(
'Note: Following the link, please refresh the page twice to see the changes. Your browser may store the old version of the page.',
);
}
}, 2000);
});
}
/* Предупреждение в Настройках блока */
if (typeof $('.tp-record-edit-icons-left__two').val() !== 'undefined') {
$('.tp-record-edit-icons-left__two').click(() => {
setTimeout(() => {
/* Предупреждение для полей, в которых должно быть px, но юзер это упустил */
$("input[placeholder*='px']").each((i, el) => {
const value = $(el).val();
if (
!value.includes('px') &&
value !== '' &&
$(el).css('border-color') != 'rgb(255, 0, 0)'
) {
$(el)
.css('border', '1px solid red')
.before(
'<span style="color: red">В этом поле нужно указать значение с "px"</span>',
);
}
});
/* Предупреждение для поля «SEO для Заголовка» */
const field = $('[data-tpl-field="title_tag"]');
const titleTag = field.find('[name="title_tag"]');
if (!isEmpty(titleTag.val())) {
const id = $('[data-rec-id').attr('data-rec-id');
const title = $(`#rec${id}`).find('[field="title"]').text() || $(`#rec${id}`).find('.t-title').text();
if (!title) {
$(titleTag).css('border', '1px solid red').parent().before('<span style="color: red">Тег не применится, т.к. нет не заполнено поле «Заголовок» в Контенте блока</span> <img src="/tpl/img/page/pe-help.svg" class="tilda-helper-tooltip" style="display:inline-block;opacity:0.2;width:16px;padding-bottom:3px">');
$(field).find('.tilda-helper-tooltip').tooltipster({
theme: 'pe-tooltip__tooltipster-noir',
contentAsHTML: true,
content: 'Данная подсказка появилась, т.к. вы установили <a href="https://greasyfork.org/ru/scripts/37669-tilda-publishing-helper" target="_blank">Tilda Helper</a>'
});
}
}
}, 1000);
});
}
/* Предупреждение в Контенте блока */
if (typeof $('.tp-record-edit-icons-left__three').val() !== 'undefined') {
$('.tp-record-edit-icons-left__three').click(() => {
setTimeout(() => {
/* Предупреждение о ссылках с кавычкой */
$("input[name*='link']").each((i, el) => {
if ($(el).parent().children('span').length == 0 &&$(el).val().includes('"')) {
$(el).css('border', '1px solid red').before('<span style="color: red">Уберите кавычки из этого поля — они могут привести к проблеме. Напишите, пожалуйста, об этом блоке в поддержку <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS></span>');
}
});
$("input[name='zoom']").each((i, el) => {
if (($(el).parent().children('span').length == 0 && parseInt($(el).val(), 10) > 20) || parseInt($(el).val(), 10) < 0) {
$(el).css('border', '1px solid red').before('<span style="color: red">Значение в поле Zoom должно быть от 0 до 17 (для Яндекс.Карты) или от 1 до 20 (для Google Maps).</span>');
}
});
/* Если нет Header и Footer, то проверяем корректная ли ссылка на попап */
if (typeof $('.headerfooterpagearea').val() === 'undefined') {
$("input[name*='link'][value^='#popup']").each((i, el) => {
if ($(el).parent().children('span').length == 0 && !$('#allrecords').text().includes($(el).val()) && $(el).parents('[data-rec-tplid]').attr('data-rec-tplid') != '868') {
$(el).css('border', '1px solid red').before('<span style="color: red">Ссылка для открытия попапа недействительна. Такой попап отсутствует на этой странице</span>');
}
});
$("input[name*='link'][value^='#rec']").each((i, el) => {
if ($(el).parent().children('span').length == 0 && typeof $('#allrecords').find($($("input[name*='link'][value^='#rec']").val())).val() === 'undefined') {
$(el).css('border', '1px solid red').before('<span style="color: red">Якорная ссылка недействительна. Такой блок отсутствует на этой странице</span>');
}
});
}
/* Добавлем быстрые ссылки на якори */
$("input[name*='link']").each((i, el) => {
let option = '';
const name = $(el).attr('name');
$("#allrecords .record:not([data-record-type='875'], [data-record-type='360']) .r center b").each((i, el) => {
let value = $(el).text();
/* Если блок T173 Якорная ссылка */
if ($(el).parents("[data-record-type='215']").length) {
value = `#${value}`;
}
option += `<span onclick="$('[name=${name}]').val('${value}')" style="padding: 0 8px 0 8px; cursor: context-menu; display: inline-block" title="Нажмите, чтобы вставить ссылку">${value}</span>`;
});
if (!isEmpty(option)) {
$(el)
.parent()
.parent()
.find('.pe-hint')
.after(
`<div class="pe-field-link-more" style="margin-top: 10px; font-size: 11px"><span style="display: inline-block">${
lang === 'RU'
? 'Быстрое заполнение поля'
: 'Quick field filling'
}:</span>${option}</div>`,
);
}
});
/* Делаем проверку поля с ключом в блоке T803 */
$("input[name='cont']").each((i, el) => {
const value = $(el).val();
if (value.includes('%')) {
$(el)
.css('border', '1px solid red')
.before(
'<span style="color: red">Уберите % из этого поля. В этом поле нужно указать лишь имя ключа, двойные проценты (%%ключ%%) подставятся автоматически.</span>',
);
}
if (value.includes(' ')) {
$(el)
.css('border', '1px solid red')
.before(
'<span style="color: red">Уберите лишние пробелы из этого поля. В этом поле нужно указать лишь имя ключа без пробелов.</span>',
);
}
});
}, 2000);
});
}
/* Показываем результаты тестов в блоках BF918 */
if (typeof $("[data-record-type='806'] .tp-record-edit-icons-left__three", ).val() !== 'undefined') {
$('[data-vote-id]').each((i, el) => {
const voteid = $(el).attr('data-vote-id');
$.ajax({
type: 'GET',
url: `https://vote.tildacdn.com/vote/2/getresult/?voteid=${voteid}&host=https%3A%2F%2Ftilda.cc`,
}).done((data) => {
const json = JSON.parse(
JSON.stringify(data).replace(/-[0-9]+-[0-9]+/g, ''),
)[0];
const question = Object.keys(json);
let sumCount = 0;
question.forEach((id) => {
sumCount = 0;
$(`[data-question-id='${id}']`)
.find('[data-answer-id]')
.each((i, el) => {
const count = parseInt(
Object.values(json[`${id}`])[i] || 0,
10,
);
sumCount += count;
$(el)
.find('.t-vote__btn-res')
.prepend(`<span>${count}</span>`);
});
});
$(el).append(
`<div style="padding-top: 25px;">Тест прошли: ${sumCount} раз${
sumCount % 10 >= 2 && sumCount % 10 <= 4 ? 'а' : ''
}</div>`,
);
});
});
styleBody += `
.t806__answers .t806__answer .t-vote__btn-res {
opacity: 1 !important;
}
.t806__btn_next {
display: block !important;
}
.t806__details {
display: block !important;
opacity: .4 !important;
}
.t-vote__btn-res__percent.js-vote-percent:before {
content: '(';
}
.t-vote__btn-res__percent.js-vote-percent:after {
content: ')';
}`;
}
/* Отмена overflow:visible для Zero блоков, которые могут перекрывать своим контентом соседние */
$('body').on('mouseover', '.record', function () {
var t396 = '.record[data-record-cod="T396"]';
$(this).prev(t396).css('overflow', 'hidden');
$(this).next(t396).css('overflow', 'hidden');
$(this).css('overflow', '');
});
/* Добавить кнопку для активации сетки */
$('#guidesmenubutton').attr('data-tilda-helper', 'true');
$('#guidesmenubutton > a').text('▦').css('font-size', '18px').attr('title', 'В Тильде используется 12-колоночная сетка. Эта кнопка де-/активирует показ сетки');
styleBody += `
#guidesmenubutton {
display: block !important;
}`;
/* Работа с блоками */
const document_records = document.querySelector('#allrecords');
const recordsObserver = new MutationObserver(() => {
addRecIDs();
});
recordsObserver.observe(document_records, {
childList: true,
});
/* Апгрейд типографа */
const replaceTypograph = (el) => {
const html = $(el).html();
const replaced = html.replace(/#nbsp;/g, '⦁').replace(/#shy;/g, '╍');
if (html !== replaced) {
$(el).html(replaced);
$(el).on('click', function () {
$(el).html(html);
$(el).off('click');
});
}
};
$('.tn-atom, .t-title, .t-uptitle, .t-text, .t-descr').each(function (i, el) {
replaceTypograph(el);
});
const recordsFieldsObserver = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
if ($(mutation.removedNodes[0]).hasClass('editinplacefield')) {
$(mutation.target)
.parent()
.find('.tn-atom, .t-title, .t-uptitle, .t-text, .t-descr')
.each(function (i, el) {
replaceTypograph(el);
});
}
}
}
});
recordsFieldsObserver.observe(document_records, {
childList: true,
subtree: true,
});
styleBody += `
[data-record-type="360"] .tp-record-edit-icons-left__three {
pointer-events: none;
}
/* Меняем фон на менее прозрачный, очень бесит прозрачность (0.92), когда редактируешь Настройки у бокового меню ME901 */
#editforms {
background-color: rgba(255, 255, 255, 0.99) !important;
}
/* Меняем жёлтую плашку */
div[style*='position:fixed;background-color:yellow;'] {
right: 15px !important;
bottom: 15px !important;
width: auto !important;
}
/* Делаем полоску светлеее в Настройках и Контенте блоков */
.editrecordcontent_container hr,
.panel-body hr {
border-top: 1px solid #dedede !important;
}
/* Всплывающая подсказка около ID блока */
.tp-record-edit-icons-left__one .tp-record-edit-icons-left__item-title[data-title]:hover:after {
background: #ffffff;
border-radius: 5px;
bottom: -30px;
right: -100px;
box-shadow: 0 0 10px #3d3d3d;
box-shadow: 0 0 10px rgba(61, 61, 61, .5);
box-sizing: border-box;
color: #3d3d3d;
content: attr(data-title);
font-size: 12px;
font-weight: 400;
min-width: 125px;
padding: 5px 10px;
position: absolute;
text-align: center;
z-index: 3;
width: auto;
white-space: nowrap;
overflow: visible;
}
.tp-record-edit-icons-left__one .tp-record-edit-icons-left__item-title[data-title]:hover:before {
border: solid;
border-color: #ffffff transparent;
border-width: 6px 6px 0 6px;
bottom: -5px;
right: 36px;
content: "";
position: absolute;
z-index: 4;
overflow: visible;
transform: rotate(180deg);
}
/* Убираем лишние значения в блоке T803 */
.t803__multi-data-column .t803__label:nth-of-type(1),
.t803__multi-data-column .t803__multi-key,
.t803__multi-data-column .t803__label:nth-of-type(2),
.t803__multi-data-column .t803__multi-default {
display: none !important;
}`;
}
if (window.location.pathname === '/projects/settings/') {
/* Делаем боковое меню плавающим */
if ($("[data-menu-item='#ss_menu_fonts']")) {
styleBody += `
/* Красная обводка для подсказки о перепубликации страниц */
#ss_menu_analytics .t265-wrapper {
border: 2px red dashed;
}
#ss_menu_analytics .ss-btn,
#ss_menu_seo .ss-btn {
border: 1px solid #ccc !important;
}
/* Подсказка под полями Google Analytics, GTM и Яндекс.Метрикой */
span.js-ga-localinput,
span.js-metrika-localinput,
span.js-gtm-localinput {
opacity: 0.75;
padding-top: 15px;
margin-top: 15px;
font-weight: 300;
font-size: 14px;
}
#checkdns {
margin-top: 30px;
border: 1px solid #d9d9d9;
padding: 25px 15px 15px 15px;
}
#checkdns h4 {
text-align: center;
padding: 0 0 15px 0;
}
#checkdns table {
margin: 20px auto;
}
#checkdns table th:first-child {
width: 170px;
}
#checkdns table img {
width: 30px;
}
#checkdns table td:first-child {
padding: 10px 0;
}
#checkdns table td:last-child {
vertical-align: middle;
}
#checkdns table+a{
position: absolute;
bottom: 10px;
right: 10px;
color: #d9d9d9;
}
.isTildaIP {
border: 0;
box-shadow: none;
background: url(/tpl/img/popups/all-icons.svg) no-repeat -71px -327px;
width: 36px;
height: 35px;
display: inline-block;
transform: scale(0.6);
vertical-align: middle;
margin: -5px 0 0 -2px;
}`;
}
/* Убираем подсказу из Настроек сайта → Ещё */
if (typeof $('#ss_menu_more').val() !== 'undefined') {
$(
'#ss_menu_more > div:nth-child(2) .ss-upload-button, #ss_menu_more > div:nth-child(2) img, #ss_menu_more > div:nth-child(2) br',
).remove();
$('#ss_menu_more > div:nth-child(2) .ss-form-group__hint').html(
`${
lang === 'RU'
? 'Загрузить иконку можно в разделе'
: 'Upload favicon you can in'
} SEO → <a href="${$('a[href^="/projects/favicons/?projectid="]').attr(
'href',
)}">${
lang === 'RU'
? 'Настройка иконок для сайта'
: 'Settings icons for sites'
}</a>`,
);
}
$('#ss_menu_seo .ss-btn, #ss_menu_analytics .ss-btn').addClass('ss-btn-white');
/* Скролл по пунктам в Настройках сайта плавным */
if (typeof $('li[data-menu-item]').val() !== 'undefined') {
$('li[data-menu-item]').click(() => {
$('html,body').animate({
scrollTop: $('body').offset().top + 105,
},
300,
);
});
}
/* Предупреждение для поля Google Analytics */
let value = $('input.js-ga-localinput').val();
if (typeof value !== 'undefined') {
if (
value.match(new RegExp('^(UA-([0-9]+){6,}-[0-9]+)$')) == null &&
value !== ''
) {
$('input.js-ga-localinput')
.css('border', '1px solid red')
.before(
"<span style='color: red'>В этом поле нужно только номер счётчика</span>",
);
}
}
/* Предупреждение для поля Яндекс.Метрика */
value = $('input.js-metrika-localinput').val();
if (typeof value !== 'undefined') {
if (value.match(new RegExp('^(([0-9]+){4,})$')) == null && value !== '') {
$('input.js-metrika-localinput')
.css('border', '1px solid red')
.before(
"<span style='color: red'>В этом поле нужно только номер счётчика</span>",
);
}
}
/* Предупреждение для поля субдомен */
value = $('input#ss-input-alias').val();
if (typeof value !== 'undefined') {
if (value.includes('_') && value !== '') {
$('input#ss-input-alias')
.css('border', '1px solid red')
.parent()
.parent()
.parent()
.parent()
.before(
"<span style='color: red'>Использование знака подчёркивания может привести к проблемам в некоторых сервисах (например, Инстаграм)</span>",
);
}
}
/* Предупреждение для css link */
value = $("[name='customcssfile']").val();
if (typeof value !== 'undefined') {
if (value.includes('rel=stylesheet') && value !== '') {
$("[name='customcssfile']")
.css('border', '1px solid red')
.parent()
.before(
"<span style='color: red'>Некорректная ссылка на файл. Уберите, пожалуйста, в конце «rel=stylesheet»</span>",
);
}
}
/* Подсказка под полями счётчиков */
text = 'Добавьте только номер счётчика';
if (typeof $('.js-ga-localinput').val() !== 'undefined') {
$('.js-ga-localinput')
.attr('placeholder', 'UA-56581111-1')
.after(
`<span class='js-ga-localinput' style='display: none'>${text}<span>`,
);
}
if (typeof $('.js-metrika-localinput').val() !== 'undefined') {
$('.js-metrika-localinput')
.attr('placeholder', '25981111')
.after(
`<span class='js-metrika-localinput' style='display: none'>${text}<span>`,
);
}
if (typeof $("[name='googletmid']").val() !== 'undefined') {
$("[name='googletmid']")
.attr('placeholder', 'GTM-N111GS')
.after(`<span class='js-gtm-localinput'>${text}<span>`);
}
/* Просим кнопки больше не исчезать, когда юзер нажимает на «вручную» */
$('.js-yandexmetrika-connect').removeClass('js-yandexmetrika-connect');
$('.js-ga-connect').removeClass('js-ga-connect');
/* Делаем проверку IP адреса у домена */
// if (typeof $('#checkdns').val() === 'undefined') {
// const domain = $("[name='customdomain']").val();
// if (!isEmpty(domain)) {
// $("[name='customdomain']").parent().append('<div id="checkdns"></div>');
// $.ajax(`https://static.roman-kosov.ru/getdns/?url=${domain}`).done(
// (data) => {
// $('#checkdns').empty();
// let result =
// '<h4>Проверка IP адреса домена из разных стран</h4><table><thead><tr><th>Местонахождение</th><th>Результат</th></tr></thead><tbody>';
// const json = JSON.parse(data);
// for (const i in json) {
// if (json[i] !== null) {
// let flag = i.slice(0, 2);
// if (flag === 'uk') flag = 'gb';
// const ip = json[i][0].A;
// const isTildaIP = [
// '185.165.123.36',
// '185.165.123.206',
// '185.203.72.17',
// '77.220.207.191',
// ].some((i) => ip.includes(i)) ?
// 'isTildaIP' :
// '';
// result += `<tr><td><img src="/files/flags/${flag}.png"> ${flag.toLocaleUpperCase()}</td><td>${ip} <div class="${isTildaIP}"></div></td></tr>`;
// }
// }
// result +=
// '</tbody></table><a href="https://roman-kosov.ru/helper/?dns" target="_blank"> Tilda Helper </a>';
// $('#checkdns').append(result);
// },
// );
// }
// }
/* Добавляем подсказку по валютам */
if (typeof $('[name=currency_txt] + div').val() !== 'undefined') {
$('[name=currency_txt] + div').text(
lang === 'RU' ? 'Знаки: ₽, $, €, ¥, руб.' : 'Signs: ₽, $, €, ¥.',
);
}
/* Исправляем дизайн у выпадающего списка валют */
$('.js-currency-selector')
.addClass('ss-input ss-select')
.parent()
.addClass('ss-select');
}
if (window.location.pathname === '/projects/payments/') {
/* Делаем более заметней галочку «Выключить тестовый режим» */
if (typeof $("[name^='testmodeoff']").val() !== 'undefined') {
$("[name='testmodeoff-cb']")
.parent()
.parent()
.after(
'<br><span style="font-weight: 300">По умолчанию тестовый режим активен. Поставьте галочку, если вы уже протестировали оплату и вам нужен «боевой» режим</span>.',
);
$("[name='testmodeoff-cb']")
.parents('.ss-form-group')
.css('outline', '1px red solid')
.css('outline-offset', '8px');
}
}
if (window.location.pathname === '/projects/') {
$('body').css('background-color', '#f0f0f0');
/* Создаём дополнительные ссылки в карточках проектов */
$('.td-sites-grid__cell').each((i, el) => {
const projectid = $(el).attr('id');
if (typeof projectid !== 'undefined') {
const id = projectid.replace('project', '');
const buttons = $(el).find('.td-site__settings');
const link = $(el).find(
"a[href^='/projects/?projectid=']:not(.td-site__section-one)",
);
let leads = '';
if (lang === 'RU') {
leads = 'Заявки';
$(link).html('Редактировать');
} else if (lang === 'EN') {
leads = 'Leads';
$(link).html('EDIT');
} else {
return;
}
/* Удаляем https:// у проектов без доменов */
$('.td-site__url-link a').each((i, el) => {
$(el).text($(el).text().replace('https://project', 'project'));
});
/* Пункты заявка и настройки */
$(`
<table class="td-site__settings">
<tbody>
<tr>
<td>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 28" width="20px" height="14px">
<path class="st0" d="M9 .9H5v5H0v4h5v5h4v-5h5v-4H9zM16 5.9h24v4H16zM16 13.9h24v4H16zM16 21.9h24v4H16z"></path>
</svg>
</td>
<td class="td-site__settings-title">
<a href="./leads/?projectid=${id}">${leads}</a>
</td>
</tr>
</tbody>
</table>
`).appendTo($(buttons).parent());
}
});
fetch('https://tilda.cc/identity/get/getplan/', {
credentials: 'include',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: 'comm=getplan',
method: 'POST',
mode: 'cors',
})
.then((response) => response.json())
.then((data) => {
if (data.endsubscription !== null && data.subscription_nextchargedate == null) {
const diff = Math.ceil((parseInt(data.endsubscription * 1000, 10) - new Date().getTime()) / (1000 * 3600 * 24));
let text = '';
if (diff < 14 && diff > 3) {
if (data.userpay !== null) {
if (data.userpay === '') {
text = 'Пробный тариф';
} else {
text = 'Тариф';
}
}
text += ` закончится через ${diff} д. Пожалуйста, не забудьте <a href="/identity/plan/" style="background-color:rgba(0,0,0,.2);padding:6px 10px;color:#fff;font-weight:600">оплатить</a>`;
if (text !== '') {
$('.td-maincontainer').prepend(`<div style="position:relative; padding:30px 60px; background-color: #f4846b; text-align:center; font-size:18px"><a href="https://roman-kosov.ru/helper" target="_blank" style="opacity:.4; position:absolute; bottom:5px; right:5px; font-size:14px; color:#fff">Tilda Helper</a><div style="max-width: 1180px; margin: 0 auto"><spn style="font-weight: 500; color: #fff">${text}</span></div></div>`);
}
}
}
});
const identityGo = [{
href: 'crm',
value: 'CRM',
},
{
href: 'experts',
value: 'Experts',
},
{
href: 'education',
value: 'Education',
},
{
href: 'news',
value: 'Каналы новостей',
},
{
href: 'upwidget',
value: 'Сервисы хранения файлов',
},
];
const dom = identityGo.map((obj) => {
return `<a href="https://tilda.cc/identity/go${obj.href}" style="color:#777">${obj.value}</a> `;
});
$('.td-sites-grid').after(
`<center style="font-size:16px">${dom.join('')}</center>`,
);
styleBody += `
/* Добавляем кнопку заявок к карточкам проектов */
.td-site__settings {
margin-right: 15px;
}
.td-site__settings-title {
font-size: 12px;
}
.td-site__url-link {
font-size: 14px;
}
.td-site__section-two {
padding: 0 30px;
}`;
}
if (
window.location.pathname === '/projects/' ||
window.location.pathname.includes('/identity/') ||
window.location.pathname.includes('/domains/')
) {
/* Попытка разместить чёрный плашку внизу на больших экрана как можно ниже */
let footer = '.td-footercontainer';
if ($('.td-footercontainer').length !== 1) {
footer = 'footer';
$('body').append('<footer></footer>');
$('#rec271198, #rec266148, #rec103634, body > .t-row').appendTo('footer');
}
if ($(window).height() > $('body').height()) {
$(footer).css('position', 'fixed').css('bottom', '0').css('width', '100%');
} else {
$(footer).css('position', 'relative');
}
styleBody += `
#rec271198 > div > div > div {
float: unset !important;
text-align: center;
}
.t142__wrapone {
right: unset !important;
text-align: center !important;
float: unset !important;
}
.t142__wraptwo {
right: unset !important;
}`;
}
if (
window.location.pathname === '/projects/' &&
window.location.search.includes('?projectid=')
) {
/* Определяем есть ли список страниц */
projectid = $('#pagesortable').attr('data-projectid');
if (typeof projectid !== 'undefined') {
/* Добавляем ссылку на «Главную страницу» для иконки домика */
$('.td-page__td-title')
.has('.td-page__ico-home')
.prepend(
`<a href='https://tilda.cc/projects/settings/?projectid=${projectid}#tab=ss_menu_index'></a>`,
);
$(
".td-page__td-title > a[href^='https://tilda.cc/projects/settings/?projectid=']",
).append($("[src='/tpl/img/td-icon-home.png']"));
if ($('.td-project-uppanel__wrapper > a, .td-project-uppanel__wrapper > div').length > 6) {
$('.td-project-uppanel__url-span').remove();
}
fetch('https://tilda.cc/projects/get/getleadserrors/', {
credentials: 'include',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: `comm=getleadserrors&projectid=${projectid}`,
method: 'POST',
mode: 'cors',
})
.then((response) => response.json())
.then((data) => {
if (data.errors !== null) {
const count = data.errors.length;
if (count > 0) {
$('.td-project-uppanel__wrapper')
.find("a[href^='/projects/leads/?projectid=']")
.find('.td-project-uppanel__title')
.after(`<span style="background: red;border-radius: 50%;color: #fff;text-align: center;width: 1em;height: 1em;font-size: 1em;line-height: 1em;margin-left: 5px;padding: 3px" title="Присутствуют заявки с ошибками">${count}</span>`);
}
}
});
fetch('https://tilda.cc/projects/submit/leads/', {
credentials: 'include',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: `comm=getleads&projectid=${projectid}`,
method: 'POST',
mode: 'cors',
})
.then((response) => response.json())
.then((data) => {
if (data.leads !== null) {
const count = data.leads.length;
if (count > 0) {
const title = $('.td-project-uppanel__wrapper')
.find("a[href^='/projects/leads/?projectid=']")
.find('.td-project-uppanel__title');
const text = title.text();
title.text(`${text} (${count})`);
}
}
});
$('.td-page').each((i, el) => {
let pageid = $(el).attr('id');
if (pageid.includes('page')) {
pageid = pageid.replace('page', '');
// дополнительные кнопки: дублировать, переместить, снять с публикации
const duplicate = `td__pagesettings__dublicatePage(${pageid})`;
const move = `https://tilda.cc/projects/pagemove/?pageid=${pageid}`;
const unpublish = `unpublish(${projectid}, ${pageid})`;
$(el)
.find('.td-page__buttons-td:last')
.attr('data-tilda-helper', 'true')
.attr('title', 'Удалить страницу')
.find('.td-page__button-title')
.remove();
$(el).find('.td-page__buttons-spacer:last').css('width', '20px');
$(el).find('.td-page__buttons-table tr').append(
$(`<td data-tilda-helper="true" class="td-page__buttons-spacer" style="width: 10px"></td><td data-tilda-helper="true" title="Дублировать страницу (создать копию)" class="td-page__buttons-td" style="height: 14px; top: 3px; position: relative;"><a onclick="${duplicate}"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 22 25" style="height: 14px"><path fill="#000" d="M20.416 24.985H4.418c-.365 0-.715-.132-.973-.366a1.195 1.195 0 01-.402-.884c0-.331.144-.65.402-.884.258-.234.608-.366.973-.366h14.78V6.41c0-.332.145-.65.403-.884.258-.234.608-.366.972-.366.365 0 .715.132.973.366.257.235.402.552.402.884v17.183c0 .767-.687 1.392-1.532 1.392z"/><path fill="#000" d="M16.264 20.978H1.807c-.816 0-1.48-.664-1.48-1.48V2.403c0-.815.664-1.479 1.48-1.479h14.457c.816 0 1.48.664 1.48 1.48v17.094c0 .816-.664 1.48-1.48 1.48zm-13.436-2.5h12.416V3.423H2.828v15.055z"/></svg></a></td>`),
);
$(el).find('.td-page__buttons-table tr').append(
$(`<td data-tilda-helper="true" class="td-page__buttons-spacer" style="width: 10px"></td><td data-tilda-helper="true" title="Перенести страницу (в другой проект)" class="td-page__buttons-td" style="height: 14px; position: relative;"><a href="${move}"><div style="width: 27px; height: 23px; background: url(/tpl/img/popups/all-icons.svg) no-repeat -322px -276px; transform: scale(0.6, 0.6)"></div></a></td>`),
);
if ($(el).find('.td-page__note').text() === '') {
$(el).find('.td-page__buttons-table tr').append(
$(`<td data-tilda-helper="true" class="td-page__buttons-spacer" style="width: 10px"></td><td data-tilda-helper="true" title="Снять страницу с публикации" class="td-page__buttons-td"><a onclick="${unpublish}"><img src="/tpl/img/td-icon-publish-black.png" width="14px" class="td-page__button-ico" style="transform: rotate(180deg); padding: 0; margin-top: -3px"></a></td>`),
);
}
}
});
/* Функция распубликации страницы */
scriptBody = `
function unpublish(projectid, pageid) {
if (confirm('Вы точно уверены, что хотите снять страницу с публикации?')) {
let csrf = getCSRF();
$.ajax({
type: 'POST',
url: '/page/unpublish/',
data: {
pageid: pageid,
csrf: csrf
}
}).done(() => {
window.location.reload()
});
}
};`;
const site = $('.td-project-uppanel__url-link a[href]').attr('href');
/* Добавляем «Сайт закрыт от индексации» под ссылкой на сайт */
$.ajax({
type: 'GET',
url: `https://static.roman-kosov.ru/get-dom/?url=${site}/robots.txt`,
}).done((text) => {
if (text !== null) {
/* Стоит ли пароль на сайт */
const auth = text.match(
new RegExp('<b>Authorization Required.</b>'),
);
if (!isEmpty(auth)) {
$('.td-project-uppanel__url tbody').append(`
<tr>
<td>
</td>
<td class="td-project-uppanel__url">
<span style="font-size: 12px">
На весь сайт стоит пароль.
<a href="https://tilda.cc/projects/settings/?projectid=${projectid}#tab=ss_menu_privacy" style="color: #f4846b; text-decoration: underline; font-weight: 400">Снять</a>.
</span>
</td>
</tr>`);
}
/* Стоит ли запрет на идексацию сайта */
const index = text.match(new RegExp('Disallow: /\\n'));
if (!isEmpty(index)) {
$('.td-project-uppanel__url tbody').append(`
<tr>
<td>
</td>
<td class="td-project-uppanel__url">
<span style="font-size: 12px">
Сайт закрыт от индексации.
<a href="https://tilda.cc/projects/settings/?projectid=${projectid}#tab=ss_menu_seo" style="color: #f4846b; text-decoration: underline; font-weight: 400">Открыть</a>.
</span>
</td>
</tr>`);
}
}
});
}
}
if (window.location.pathname === '/projects/favicons/') {
/* Есть ли на странице иконка */
if (typeof $('#preview16icon').val() !== 'undefined') {
const url = $('.ss-menu-pane__title:last')
.text()
.trim()
.match(/(\b[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/gi);
$('.ss-tl__page-container tbody').prepend(`
<tr valign="top">
<td>
<img src="https://favicon.yandex.net/favicon/${url}?size=32" style="width: 32px; height: 32px">
</td>
<td style="padding-left: 20px">
<div class="ss-form-group">
<label class="ss-label">Иконка в Яндекс.Поиске</label>
<div class="ss-form-group__hint">
Фавиконка — это небольшая картинка, которая отображается в сниппете в результатах поиска Яндекса, рядом с адресом сайта в адресной строке браузера, около названия сайта в Избранном или в Закладках браузера.
<br>
Если иконка не соответствует той, что загружена в формате .ico, то <b>проверьте, пожалуйста, что загруженная вами иконка дейсвительно размером 32×32</b> и прошло больше 1 недели.
<br>
Подробная инструкция <a href="https://yandex.ru/support/webmaster/search-results/favicon.html" target="_blank" noopener nofollow>здесь</a>.
</div>
</div>
</td>
</tr>`);
styleBody += `
/* Убираем отступ сверху у иконок */
#preview16icon,
#preview152icon,
#preview270icon {
padding-top: 0 !important;
}`;
}
}
if (window.location.pathname === '/identity/payments/') {
styleBody += `
/* Убираем отступ сверху у иконок */
.t-container a {
text-decoration: underline !important;
}`;
}
$('body').append(`<script>${scriptBody}</script>`);
/* Добавляем новые стили к body */
$('body').append(`<style>${styleBody}</style>`);
// eslint-disable-next-line no-undef
}, window.location.pathname === '/page/' ? 500 : 2000);
});
}
})(window);
|
53cdc75f53ae82ce6ba415a626e352c0
|
{
"intermediate": 0.33248451352119446,
"beginner": 0.4285094439983368,
"expert": 0.23900601267814636
}
|
43,339
|
Привет! я встретил несколько проблем в своем боте:
1) Код с добавленной почты может получить только тот юзер, который ее добавил. Нужно исправить это, код должны иметь возможность получить все пользователи, т.к. почты добавляет администратор.
2) Проверка на подписку на канал не работает.
Вот код бота:
import aiosqlite
import logging
import asyncio
import time
import re
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiosqlite import connect
import imaplib
import email
from email.parser import BytesParser
from email.policy import default
from aiogram.dispatcher import FSMContext
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.utils.exceptions import MessageNotModified
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ParseMode
from aiogram import types
from aiogram.dispatcher.middlewares import BaseMiddleware
from aiogram.dispatcher.handler import CancelHandler
API_TOKEN = '6306133720:AAH0dO6nwIlnQ7Hbts6RfGs0eI73EKwx-hE'
DATABASE = 'emails.db'
ADMINS = [989037374]
almaz = [400086083]
CHANNEL_ID = "-1002014105263"
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
dp.middleware.setup(LoggingMiddleware())
# Создание таблицы при запуске бота
async def on_startup(dispatcher):
async with aiosqlite.connect(DATABASE) as db:
await db.execute("""
CREATE TABLE IF NOT EXISTS emails (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL
)
""")
await db.commit()
async def generate_invite_link(chat_id):
try:
chat_invite_link = await bot.create_chat_invite_link(chat_id, expire_date=int(time.time()) + 900) # на 15 минут
return chat_invite_link.invite_link
except Exception as e:
logging.error(e)
return None
async def is_user_subscribed(chat_id, user_id):
try:
member = await bot.get_chat_member(chat_id, user_id)
return member.status not in ["left", "kicked"]
except Exception as e:
logging.error(e)
return False # По умолчанию считаем, что пользователь не подписан, если возникла ошибка
class SubscriptionCheckMiddleware(BaseMiddleware):
def __init__(self, channel_id):
super().__init__()
self.channel_id = channel_id
async def on_process_message(self, message: types.Message, data: dict):
member = await bot.get_chat_member(self.channel_id, message.from_user.id)
if member.status not in ["member", "administrator", "creator"]:
invite_link = await generate_invite_link(self.channel_id)
if invite_link:
keyboard = InlineKeyboardMarkup().add(
InlineKeyboardButton("🔗 Подписаться на канал", url=invite_link)
)
await message.answer(
f"🔒 Для продолжения работы с ботом *необходимо подписаться на наш новостной канал\.*\n\n👌 Если вы уже подписались на канал, нажмите /start",
parse_mode="MarkdownV2",
reply_markup=keyboard
)
# прерываем обработку следующих хэндлеров
raise CancelHandler()
async def post_process(self, obj, data, *args):
pass
class EmailStates(StatesGroup):
waiting_for_email_data = State()
# Добавление почты и пароля в БД
async def add_email_to_db(user_id, email, password):
async with aiosqlite.connect(DATABASE) as db:
await db.execute("INSERT INTO emails (user_id, email, password) VALUES (?, ?, ?)", (user_id, email, password,))
await db.commit()
# Обработчик начального сообщения /start
@dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message):
keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add("📩 Получить код")
keyboard.row("💸 Купить аккаунты", "🖼 Уникализатор")
await message.answer(
"Привет! Это - бот для приема писем с кодом от TikTok.\n\nНаш уникализатор фонов - @YandexTTBot - самая удобная автозамена фонов в ваших креативах.",
reply_markup=keyboard)
@dp.message_handler(lambda message: message.text == "💸 Купить аккаунты")
async def buy_accounts(message: types.Message):
keyboard = types.InlineKeyboardMarkup()
url_button = types.InlineKeyboardButton(text="👨💻 Администратор", url="https://t.me/Ih82seeucry")
keyboard.add(url_button)
await message.answer(
"💵 Чтобы купить почты, обратитесь к администратору. Пожалуйста, бронируйте аккаунты за сутки, так как их может просто не быть в наличии.\n\n Нажмите на кнопку ниже, чтобы перейти в диалог.",
reply_markup=keyboard)
@dp.message_handler(lambda message: message.text == "🖼 Уникализатор")
async def buy_accounts(message: types.Message):
keyboard = types.InlineKeyboardMarkup()
url_button = types.InlineKeyboardButton(text="🔗 Уникализатор от Яндекса", url="https://t.me/YandexTTBot")
keyboard.add(url_button)
await message.answer(
"🖼 Лучший уникализатор ваших креативов - Яндекс.Фоны. \n\n Нажмите на кнопку ниже, чтобы перейти бота.",
reply_markup=keyboard)
# Обработчик добавления почты
@dp.message_handler(commands=['add'])
async def request_email_data(message: types.Message):
if (message.from_user.id in ADMINS) or (message.from_user.id in almaz):
await EmailStates.waiting_for_email_data.set()
await message.answer("Введите адреса электронной почты и пароли в формате mail:pass, каждый с новой строки.")
else:
await message.answer("Извините, но только администраторы могут добавлять почты.")
# Обработка сообщений с данными почты от пользователя
@dp.message_handler(state=EmailStates.waiting_for_email_data)
async def add_email(message: types.Message, state: FSMContext):
# Обрабатываем входящее сообщение с почтами
lines = message.text.strip().split('\n')
error_lines = [] # Список строк с ошибками
for line in lines:
try:
email, password = line.split(':')
# Сохраняем в БД
await add_email_to_db(message.from_user.id, email, password)
except ValueError:
error_lines.append(line)
if error_lines:
error_message = "Некорректный формат в строках: \n" + "\n".join(error_lines)
error_message += "\nИспользуйте формат mail:password."
await message.answer(error_message)
else:
await message.answer(f"Почты добавлены в БД.")
# Завершаем состояние приема данных о почте
await state.finish()
async def extract_code_from_email(email_body):
match = re.search(r'\b\d{6}\b', email_body)
return match.group(0) if match else None
# Функция для попытки получить код
async def try_to_get_code(message, state, user_id, user_email):
timeout = 120 # Таймаут в секундах
end_time = time.time() + timeout
success = False
while time.time() < end_time:
emails_messages = await get_user_emails(user_id, user_email)
if isinstance(emails_messages, str):
await asyncio.sleep(10) # Ошибка IMAP - повторяем через 10 секунд
continue
if emails_messages:
# Получаем последнее письмо
last_email_body = emails_messages[-1].get_body(preferencelist=('plain', 'html')).get_content()
code = await extract_code_from_email(last_email_body)
if code:
await message.answer(f"Ваш код: {code}")
success = True
break
await asyncio.sleep(10) # Перерыв на 10 секунд
if not success:
await message.answer("Не удалось получить код в течение заданного времени.")
await state.finish()
async def send_long_message(message: types.Message, long_text: str, part_length: int = 4096):
for part in [long_text[i:i + part_length] for i in range(0, len(long_text), part_length)]:
await message.answer(part)
# Метод для получения писем пользователя
async def get_user_emails(user_id, email):
async with aiosqlite.connect(DATABASE) as db:
async with db.execute("SELECT email, password FROM emails WHERE user_id = ? AND email = ?",
(user_id, email)) as cursor:
user_email = await cursor.fetchone()
if user_email:
mail_server = imaplib.IMAP4_SSL('imap.rambler.ru', 993)
try:
mail_server.login(user_email[0], user_email[1])
mail_server.select('inbox')
# поиск и возврат uid последних 5 писем
result, data = mail_server.uid('search', None, "ALL")
if result == 'OK':
emails = data[0].split()[-2:]
return await fetch_emails_from_uids(mail_server, emails)
except imaplib.IMAP4.error as e:
return f"Ошибка IMAP: {str(e)}"
finally:
mail_server.logout()
else:
return "Не удалось найти данные для этой почты в БД."
# Получение писем по их UID
async def fetch_emails_from_uids(mail_server, email_uids):
email_messages = []
parser = BytesParser(policy=default)
for email_uid in email_uids:
result, data = mail_server.uid('fetch', email_uid, '(RFC822)')
if result == 'OK':
email_data = data[0][1]
msg = parser.parsebytes(email_data)
email_messages.append(msg)
return email_messages
class EmailStates(StatesGroup):
waiting_for_email_data = State()
waiting_for_email_to_fetch = State()
@dp.message_handler(lambda message: message.text == "📩 Получить код", state="*")
async def request_to_fetch_emails(message: types.Message):
await EmailStates.waiting_for_email_to_fetch.set()
await message.answer("Введите адрес электронной почты, чтобы получить код. Убедитесь, что TikTok уже выслал код.")
async def check_email_exists(user_email):
async with aiosqlite.connect(DATABASE) as db:
async with db.execute("SELECT id FROM emails WHERE email = ?", (user_email,)) as cursor:
# Если запрос вернул какие-либо строки, значит почта существует
result = await cursor.fetchone()
return result is not None
# Обработчик получения адреса электронной почты для получения писем
@dp.message_handler(state=EmailStates.waiting_for_email_to_fetch)
async def fetch_emails_handler(message: types.Message, state: FSMContext):
user_email = message.text.strip()
if not await check_email_exists(user_email):
await message.answer(
"Указанная почта не найдена в базе данных.")
await state.finish()
return
# Отправляем сообщение пользователю о начале поиска кода
await message.answer("Ищем код в вашей почте, это может занять до двух минут…")
asyncio.create_task(try_to_get_code(message, state, message.from_user.id, user_email))
if __name__ == '__main__':
# Запуск бота
executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
|
24e90c40f6c1ba813290792d1ccda62b
|
{
"intermediate": 0.28667065501213074,
"beginner": 0.5421425700187683,
"expert": 0.17118676006793976
}
|
43,340
|
You are an helpful assistant that analyses recipes and enhance them with better quality data and analysis of allergens and intoleration ingedients. You receive recipe as a structured JSON text and you are reworking it into unified form that follows RelyonRecipe class bellow. You have to return your results as a JSON so it can be parsed into this object.
export class RelyonRecipe {
@Expose() @Transform(({ key, obj }) => obj[key])
_id?: string | undefined;
@Expose()
name!: string;
@Expose()
instructions!: string[];
@Expose()
thumbnail!: string;
@Expose()
video?: string;
@Expose()
ingredients!: {
image: string;
name: string,
measure: string,
}[];
@Expose()
engineSource!: FoodDataSources;
@Expose()
tags?: string[];
@Expose() @Type(() => RelyonAllergen)
allergens?: RelyonAllergen[];
}
Other Classes used in above RelyonRecipe:
export interface RelyonAllergen {
_id?: string;
name: string;
icon?: string;
iconURL?: URL;
lowercase: string;
preDefined: boolean;
author?: string;
status?: 'intolerant' | 'tolerant' | 'connection';
}
Here is your first recipe:
{"meals":[{"idMeal":"52771","strMeal":"Spicy Arrabiata Penne","strDrinkAlternate":null,"strCategory":"Vegetarian","strArea":"Italian","strInstructions":"Bring a large pot of water to a boil. Add kosher salt to the boiling water, then add the pasta. Cook according to the package instructions, about 9 minutes.\r\nIn a large skillet over medium-high heat, add the olive oil and heat until the oil starts to shimmer. Add the garlic and cook, stirring, until fragrant, 1 to 2 minutes. Add the chopped tomatoes, red chile flakes, Italian seasoning and salt and pepper to taste. Bring to a boil and cook for 5 minutes. Remove from the heat and add the chopped basil.\r\nDrain the pasta and add it to the sauce. Garnish with Parmigiano-Reggiano flakes and more basil and serve warm.","strMealThumb":"https:\/\/www.themealdb.com\/images\/media\/meals\/ustsqw1468250014.jpg","strTags":"Pasta,Curry","strYoutube":"https:\/\/www.youtube.com\/watch?v=1IszT_guI08","strIngredient1":"penne rigate","strIngredient2":"olive oil","strIngredient3":"garlic","strIngredient4":"chopped tomatoes","strIngredient5":"red chile flakes","strIngredient6":"italian seasoning","strIngredient7":"basil","strIngredient8":"Parmigiano-Reggiano","strIngredient9":"","strIngredient10":"","strIngredient11":"","strIngredient12":"","strIngredient13":"","strIngredient14":"","strIngredient15":"","strIngredient16":null,"strIngredient17":null,"strIngredient18":null,"strIngredient19":null,"strIngredient20":null,"strMeasure1":"1 pound","strMeasure2":"1\/4 cup","strMeasure3":"3 cloves","strMeasure4":"1 tin ","strMeasure5":"1\/2 teaspoon","strMeasure6":"1\/2 teaspoon","strMeasure7":"6 leaves","strMeasure8":"spinkling","strMeasure9":"","strMeasure10":"","strMeasure11":"","strMeasure12":"","strMeasure13":"","strMeasure14":"","strMeasure15":"","strMeasure16":null,"strMeasure17":null,"strMeasure18":null,"strMeasure19":null,"strMeasure20":null,"strSource":null,"strImageSource":null,"strCreativeCommonsConfirmed":null,"dateModified":null}]}
|
c3e25d6a8e26fe1374389d355f3b7b33
|
{
"intermediate": 0.33451277017593384,
"beginner": 0.37991464138031006,
"expert": 0.2855726182460785
}
|
43,341
|
Show me only the partition column name and ranges for below ddl:
CREATE SET TABLE CDMTDFMGR.sample_WA_sales_csv_multipartition_order ,FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL,
CHECKSUM = DEFAULT,
DEFAULT MERGEBLOCKRATIO,
MAP = TD_MAP1
(
product_id INTEGER,
Seller_Country VARCHAR(14) CHARACTER SET LATIN NOT CASESPECIFIC,
Channel_Type VARCHAR(11) CHARACTER SET LATIN NOT CASESPECIFIC,
Store_Type VARCHAR(22) CHARACTER SET LATIN NOT CASESPECIFIC,
Product_Category VARCHAR(24) CHARACTER SET LATIN NOT CASESPECIFIC,
Product_Line VARCHAR(20) CHARACTER SET LATIN NOT CASESPECIFIC,
Product VARCHAR(33) CHARACTER SET LATIN NOT CASESPECIFIC,
Years INTEGER,
Quarter VARCHAR(7) CHARACTER SET LATIN NOT CASESPECIFIC,
Sales_Value FLOAT,
Units_Sold INTEGER,
Margin FLOAT)
PRIMARY INDEX ( product_id )
PARTITION BY CASE_N(
Years > 2013 ,
Years > 2012 ,
Years > 2011 ,
NO CASE, UNKNOWN);
|
d7fa298ba33aac730b25d8e6f4912941
|
{
"intermediate": 0.30961787700653076,
"beginner": 0.2662965655326843,
"expert": 0.4240855872631073
}
|
43,342
|
write a vs code settings file ( provide the hierchy ) to ignore missing imports on mypy linter , set linter severity to information , and add max line 200 to black formatter , i only install mypy via extensions and i have an empty .vscode folder
|
7d729fbd2f680ea70cb890bd35187bb0
|
{
"intermediate": 0.47465717792510986,
"beginner": 0.2645406723022461,
"expert": 0.2608022391796112
}
|
43,343
|
ignore a specific flake8 error from settinfs.json vscode
|
856e1091f3dd2e724d427c33d6bb402c
|
{
"intermediate": 0.40642431378364563,
"beginner": 0.2859998345375061,
"expert": 0.30757588148117065
}
|
43,344
|
You are an helpful assistant that analyses recipes and enhance them with better quality data and analysis of allergens and intoleration ingedients. It is very important to unify the data you will return into unified form and also, very important step is add Allergens of this meal. You receive recipe as a structured JSON text and you are reworking it into unified form that follows RelyonRecipe class bellow. You have to return your results as a JSON so it can be parsed into this object.
export class RelyonRecipe {
@Expose() @Transform(({ key, obj }) => obj[key])
_id?: string | undefined;
@Expose()
name!: string;
@Expose()
instructions!: string[];
@Expose()
thumbnail!: string;
@Expose()
video?: string;
@Expose()
ingredients!: {
image: string;
name: string,
measure: string,
}[];
@Expose()
engineSource!: FoodDataSources;
@Expose()
tags?: string[];
@Expose() @Type(() => RelyonAllergen)
allergens?: {
name: string;
type: string;
lowercase: string;
llm_processed: boolean;
}[];
}
Here is your first recipe:
{"meals":[{"idMeal":"52771","strMeal":"Spicy Arrabiata Penne","strDrinkAlternate":null,"strCategory":"Vegetarian","strArea":"Italian","strInstructions":"Bring a large pot of water to a boil. Add kosher salt to the boiling water, then add the pasta. Cook according to the package instructions, about 9 minutes.\r\nIn a large skillet over medium-high heat, add the olive oil and heat until the oil starts to shimmer. Add the garlic and cook, stirring, until fragrant, 1 to 2 minutes. Add the chopped tomatoes, red chile flakes, Italian seasoning and salt and pepper to taste. Bring to a boil and cook for 5 minutes. Remove from the heat and add the chopped basil.\r\nDrain the pasta and add it to the sauce. Garnish with Parmigiano-Reggiano flakes and more basil and serve warm.","strMealThumb":"https:\/\/www.themealdb.com\/images\/media\/meals\/ustsqw1468250014.jpg","strTags":"Pasta,Curry","strYoutube":"https:\/\/www.youtube.com\/watch?v=1IszT_guI08","strIngredient1":"penne rigate","strIngredient2":"olive oil","strIngredient3":"garlic","strIngredient4":"chopped tomatoes","strIngredient5":"red chile flakes","strIngredient6":"italian seasoning","strIngredient7":"basil","strIngredient8":"Parmigiano-Reggiano","strIngredient9":"","strIngredient10":"","strIngredient11":"","strIngredient12":"","strIngredient13":"","strIngredient14":"","strIngredient15":"","strIngredient16":null,"strIngredient17":null,"strIngredient18":null,"strIngredient19":null,"strIngredient20":null,"strMeasure1":"1 pound","strMeasure2":"1\/4 cup","strMeasure3":"3 cloves","strMeasure4":"1 tin ","strMeasure5":"1\/2 teaspoon","strMeasure6":"1\/2 teaspoon","strMeasure7":"6 leaves","strMeasure8":"spinkling","strMeasure9":"","strMeasure10":"","strMeasure11":"","strMeasure12":"","strMeasure13":"","strMeasure14":"","strMeasure15":"","strMeasure16":null,"strMeasure17":null,"strMeasure18":null,"strMeasure19":null,"strMeasure20":null,"strSource":null,"strImageSource":null,"strCreativeCommonsConfirmed":null,"dateModified":null}]}
|
9311dee3e420f93d5855811ace1fdfab
|
{
"intermediate": 0.3131539225578308,
"beginner": 0.3244114816188812,
"expert": 0.3624345660209656
}
|
43,345
|
Explain this and give me possible output of tags:
response is like this:
{
'Tags': [
{
'Key': 'string',
'Value': 'string'
},
]
}
tags = [{d["Key"]: d["Value"]} for d in response["Tags"]]
json_tags = {}
for tag in tags:
json_tags.update(tag)
|
fa124890b2fc7fb307327bbd32b08da0
|
{
"intermediate": 0.37568891048431396,
"beginner": 0.3064013123512268,
"expert": 0.31790977716445923
}
|
43,346
|
Find the partition from below Teradata DDL:
CREATE MULTISET TABLE CDMTDFMGR.FLGT_RSPPI ,FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL,
CHECKSUM = DEFAULT,
DEFAULT MERGEBLOCKRATIO,
MAP = TD_MAP1
(
FLGT_NO VARCHAR(10) CHARACTER SET LATIN CASESPECIFIC NOT NULL,
ARLN_DESG_CD VARCHAR(15) CHARACTER SET LATIN CASESPECIFIC,
FLGT_TYPE_CD CHAR(1) CHARACTER SET LATIN CASESPECIFIC NOT NULL,
FLGT_STYP_CD CHAR(3) CHARACTER SET LATIN CASESPECIFIC,
FLGT_STS_TYPE_CD CHAR(1) CHARACTER SET LATIN CASESPECIFIC,
CD_SHRE_IND CHAR(1) CHARACTER SET LATIN CASESPECIFIC,
FRST_DPRT_ARPT_CD CHAR(2) CHARACTER SET LATIN CASESPECIFIC,
FINL_ARRV_ARPT_CD CHAR(2) CHARACTER SET LATIN CASESPECIFIC,
DPRT_TS TIMESTAMP(0),
ARRV_TS TIMESTAMP(0),
OPEN_DT DATE FORMAT 'YYYY-MM-DD' NOT NULL,
CLOSE_DT DATE FORMAT 'YYYY-MM-DD' NOT NULL)
PRIMARY INDEX ( FLGT_NO ,OPEN_DT )
PARTITION BY RANGE_N(OPEN_DT BETWEEN '2020-01-01' AND '2025-01-01' EACH INTERVAL '1' YEAR ,
NO RANGE, UNKNOWN)
INDEX ( FRST_DPRT_ARPT_CD )
INDEX ( FINL_ARRV_ARPT_CD );
|
3d7bf54999156ebe5be1ca7140a32982
|
{
"intermediate": 0.34052592515945435,
"beginner": 0.32844632863998413,
"expert": 0.3310277462005615
}
|
43,347
|
current code:
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbAddressInsideEmiratesId"
).get_by_role("link", name="-- Select -- ").click()
page.locator("li").filter(has_text="DUBAI").click()
wanted code implemetation:
order_sent = page.locator("#order-sent")
order_sent.wait_for()
convert current code to what i want
|
4cbf2e02a37acff72ba5831c12651dcd
|
{
"intermediate": 0.405465692281723,
"beginner": 0.2659420371055603,
"expert": 0.32859230041503906
}
|
43,348
|
i have 2 folder of svd files
i want to check if a file is in folder one and is not in folder 2 ,move it to folder 3
give e the proper python code
|
cd3720d767267aae200bbef57128d29e
|
{
"intermediate": 0.3927435874938965,
"beginner": 0.36334988474845886,
"expert": 0.24390655755996704
}
|
43,349
|
How can I write a pyramid chart in SAPUI5?
|
8ada922ab09813e5152a5e93699fa3da
|
{
"intermediate": 0.5339683890342712,
"beginner": 0.13330353796482086,
"expert": 0.3327280879020691
}
|
43,350
|
what gpt model are you
|
b897a4d96933596bfc0655a2efa9c1da
|
{
"intermediate": 0.18948110938072205,
"beginner": 0.1530706286430359,
"expert": 0.6574482321739197
}
|
43,351
|
<mvc:View xmlns=“sap.m” xmlns:mvc=“sap.ui.core.mvc” controllerName=“your.namespace.PyramidChart”>
<Page title=“Pyramid Chart”>
<content>
<FlexBox alignItems=“Center” justifyContent=“Center”>
<svg width=“400” height=“300” xmlns=“http://www.w3.org/2000/svg”>
<!-- Top level -->
<polygon points=“200,50 150,150 250,150” style=“fill:lightblue;stroke:black;stroke-width:2” />
<!-- Middle level -->
<polygon points=“150,150 100,250 200,250 250,150” style=“fill:lightgreen;stroke:black;stroke-width:2” />
<!-- Bottom level -->
<polygon points=“100,250 50,350 150,350 200,250” style=“fill:lightpink;stroke:black;stroke-width:2” />
<text x=“200” y=“200” text-anchor=“middle” fill=“black” font-size=“16”>Text above Pyramid</text>
</svg>
</FlexBox>
</content>
</Page>
</mvc:View>
|
678c85bcad66ad846706904076d301fc
|
{
"intermediate": 0.32891958951950073,
"beginner": 0.28319984674453735,
"expert": 0.3878805637359619
}
|
43,352
|
comment gérez le fait que si le personnage est déjà dans mes favoris le coeur passe a coeur_filled pour le bouton ajouter au favoris et sinon le coeur est creux : // Instantiate API
import PersonnagesProvider from "../../services/PersonnagesProvider.js";
import FavoriteManager from '../../services/FavoriteManager.js';
export default class Home {
async render() {
let personnages = await PersonnagesProvider.FetchPersonnages();
let html = personnages
.map(
(personnage) => /*html*/ `
<div class="col">
<div class="card shadow-sm">
<svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">${personnage.nom}</text></svg>
<div class="card-body">
<p class="card-text">${personnage.nom}</p>
<p>Force: ${personnage.statistiques.force}</p>
<p>Dextérité: ${personnage.statistiques.dextérité}</p>
<p>Intelligence: ${personnage.statistiques.intelligence}</p>
<p>Santé: ${personnage.statistiques.santé}</p>
<p>Mana: ${personnage.statistiques.mana}</p>
<p>Defense: ${personnage.statistiques.defense}</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<a href="#/personnage/${personnage.id}" class="btn btn-sm btn-outline-secondary">+ détail sur ${personnage.nom}</a>
</div>
<small class="text-body-secondary">${personnage.id}</small>
<a onclick="FavoriteManager.addToFavorites('${personnage.id}');">Ajouter en favoris</a>
</div>
</div>
</div>
</div>
`
)
.join("\n ");
return /*html*/ `
<nav>
<ul>
<div class="left-part">
<li><a href="/">Personnages</a></li>
<li><a href="#/armes">Armes</a></li>
<li><a href="#/armures">Armures</a></li>
</div>
<li>Mes favoris</li>
</ul>
<nav>
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
${html}
</div>
`;
}
}
class FavoriteManager {
static addToFavorites(id) {
let favorites = JSON.parse(localStorage.getItem('favorites')) || [];
console.log(favorites);
if (!favorites.includes(id)) {
favorites.push(id);
localStorage.setItem("favorites", JSON.stringify(favorites));
}
}
}
window.FavoriteManager = FavoriteManager;
export default FavoriteManager;
|
5044911b2bff2812afa063eef49eaf9a
|
{
"intermediate": 0.3886544406414032,
"beginner": 0.4596412479877472,
"expert": 0.15170429646968842
}
|
43,353
|
comment gérez le fait que si le personnage est déjà dans mes favoris le coeur passe a coeur_filled pour le bouton ajouter au favoris et sinon le coeur est creux : // Instantiate API
import PersonnagesProvider from “…/…/services/PersonnagesProvider.js”;
import FavoriteManager from ‘…/…/services/FavoriteManager.js’;
export default class Home {
async render() {
let personnages = await PersonnagesProvider.FetchPersonnages();
let html = personnages
.map(
(personnage) => /html/ <br/> <div class="col"><br/> <div class="card shadow-sm"><br/> <svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">${personnage.nom}</text></svg><br/> <div class="card-body"><br/> <p class="card-text">${personnage.nom}</p><br/> <p>Force: ${personnage.statistiques.force}</p><br/> <p>Dextérité: ${personnage.statistiques.dextérité}</p><br/> <p>Intelligence: ${personnage.statistiques.intelligence}</p><br/> <p>Santé: ${personnage.statistiques.santé}</p><br/> <p>Mana: ${personnage.statistiques.mana}</p><br/> <p>Defense: ${personnage.statistiques.defense}</p><br/> <div class="d-flex justify-content-between align-items-center"><br/> <div class="btn-group"><br/> <a href="#/personnage/${personnage.id}" class="btn btn-sm btn-outline-secondary">+ détail sur ${personnage.nom}</a><br/> </div><br/> <small class="text-body-secondary">${personnage.id}</small><br/> <a onclick="FavoriteManager.addToFavorites('${personnage.id}');">Ajouter en favoris</a><br/> </div><br/> </div><br/> </div><br/> </div><br/>
)
.join("\n ");
return /html/ <br/> <nav><br/> <ul><br/> <div class="left-part"><br/> <li><a href="/">Personnages</a></li><br/> <li><a href="#/armes">Armes</a></li><br/> <li><a href="#/armures">Armures</a></li><br/> </div><br/> <li>Mes favoris</li><br/> </ul><br/> <nav><br/> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"><br/> ${html}<br/> </div><br/> ;
}
}
class FavoriteManager {
static addToFavorites(id) {
let favorites = JSON.parse(localStorage.getItem(‘favorites’)) || [];
console.log(favorites);
if (!favorites.includes(id)) {
favorites.push(id);
localStorage.setItem(“favorites”, JSON.stringify(favorites));
}
}
}
window.FavoriteManager = FavoriteManager;
|
25c0c5194bef54258055e4e2870c44a5
|
{
"intermediate": 0.291574627161026,
"beginner": 0.4475085139274597,
"expert": 0.26091691851615906
}
|
43,354
|
comment gérez le fait que si le personnage est déjà dans mes favoris le coeur passe a coeur_filled pour le bouton ajouter au favoris et sinon le coeur est creux : // Instantiate API
import PersonnagesProvider from “…/…/services/PersonnagesProvider.js”;
import FavoriteManager from ‘…/…/services/FavoriteManager.js’;
export default class Home {
async render() {
let personnages = await PersonnagesProvider.FetchPersonnages();
let html = personnages
.map(
(personnage) => /html/ <br/> <div class="col"><br/> <div class="card shadow-sm"><br/> <svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">${personnage.nom}</text></svg><br/> <div class="card-body"><br/> <p class="card-text">${personnage.nom}</p><br/> <p>Force: ${personnage.statistiques.force}</p><br/> <p>Dextérité: ${personnage.statistiques.dextérité}</p><br/> <p>Intelligence: ${personnage.statistiques.intelligence}</p><br/> <p>Santé: ${personnage.statistiques.santé}</p><br/> <p>Mana: ${personnage.statistiques.mana}</p><br/> <p>Defense: ${personnage.statistiques.defense}</p><br/> <div class="d-flex justify-content-between align-items-center"><br/> <div class="btn-group"><br/> <a href="#/personnage/${personnage.id}" class="btn btn-sm btn-outline-secondary">+ détail sur ${personnage.nom}</a><br/> </div><br/> <small class="text-body-secondary">${personnage.id}</small><br/> <a onclick="FavoriteManager.addToFavorites('${personnage.id}');">Ajouter en favoris</a><br/> </div><br/> </div><br/> </div><br/> </div><br/>
)
.join("\n ");
return /html/ <br/> <nav><br/> <ul><br/> <div class="left-part"><br/> <li><a href="/">Personnages</a></li><br/> <li><a href="#/armes">Armes</a></li><br/> <li><a href="#/armures">Armures</a></li><br/> </div><br/> <li>Mes favoris</li><br/> </ul><br/> <nav><br/> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"><br/> ${html}<br/> </div><br/> ;
}
}
class FavoriteManager {
static addToFavorites(id) {
let favorites = JSON.parse(localStorage.getItem(‘favorites’)) || [];
console.log(favorites);
if (!favorites.includes(id)) {
favorites.push(id);
localStorage.setItem(“favorites”, JSON.stringify(favorites));
}
}
}
window.FavoriteManager = FavoriteManager;
|
a1a51679cb590e3c1bd814f418ee6327
|
{
"intermediate": 0.291574627161026,
"beginner": 0.4475085139274597,
"expert": 0.26091691851615906
}
|
43,355
|
current code:
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbAddressInsideEmiratesId"
).get_by_role("link", name="-- Select -- ").click()
page.locator("li").filter(has_text="DUBAI").click()
wanted code implemetation:
order_sent = page.locator("#order-sent")
order_sent.wait_for()
convert current code to what i want. i want to wait till dubai is present in the dropdown then click it
|
ac0ee467b64410007f2fa5c537e33b55
|
{
"intermediate": 0.440218061208725,
"beginner": 0.2554798126220703,
"expert": 0.3043020963668823
}
|
43,356
|
Hi , Please be a senior JS developer and help to solve my questions with working code.
|
5435eef102fae277f57a42728baadc77
|
{
"intermediate": 0.4089697003364563,
"beginner": 0.314665824174881,
"expert": 0.2763645052909851
}
|
43,357
|
How can I bind text data from a model to a svg in xml?
|
f3081df7b77fb9f8b51c4bc1d01ccfa7
|
{
"intermediate": 0.5369636416435242,
"beginner": 0.11977648735046387,
"expert": 0.34325990080833435
}
|
43,358
|
how to install this :
moondream
a tiny vision language model that kicks ass and runs anywhere
Website | Hugging Face | Demo
Benchmarks
moondream2 is a 1.86B parameter model initialized with weights from SigLIP and Phi 1.5.
Model VQAv2 GQA TextVQA TallyQA (simple) TallyQA (full)
moondream1 74.7 57.9 35.6 - -
moondream2 (latest) 76.8 60.6 46.4 79.6 73.3
Examples
Image Example
What is the girl doing?
The girl is eating a hamburger.
What color is the girl's hair?
The girl's hair is white.
What is this?
This is a computer server rack, specifically designed for holding multiple computer processors and other components. The rack has multiple shelves or tiers, each holding several processors, and it is placed on a carpeted floor. The rack is filled with various computer parts, including processors, wires, and other electronic devices.
What is behind the stand?
There is a brick wall behind the stand.
Usage
Using transformers (recommended)
pip install transformers timm einops
from transformers import AutoModelForCausalLM, AutoTokenizer
from PIL import Image
model_id = "vikhyatk/moondream2"
revision = "2024-03-13"
model = AutoModelForCausalLM.from_pretrained(
model_id, trust_remote_code=True, revision=revision
)
tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
image = Image.open('<IMAGE_PATH>')
enc_image = model.encode_image(image)
print(model.answer_question(enc_image, "Describe this image.", tokenizer))
The model is updated regularly, so we recommend pinning the model version to a specific release as shown above.
To enable Flash Attention on the text model, pass in attn_implementation="flash_attention_2" when instantiating the model.
model = AutoModelForCausalLM.from_pretrained(
model_id, trust_remote_code=True, revision=revision,
torch_dtype=torch.float16, attn_implementation="flash_attention_2"
).to("cuda")
Batch inference is also supported.
answers = moondream.batch_answer(
images=[Image.open('<IMAGE_PATH_1>'), Image.open('<IMAGE_PATH_2>')],
prompts=["Describe this image.", "Are there people in this image?"],
tokenizer=tokenizer,
)
Using this repository
Clone this repository and install dependencies.
pip install -r requirements.txt
sample.py provides a CLI interface for running the model. When the --prompt argument is not provided, the script will allow you to ask questions interactively.
python sample.py --image [IMAGE_PATH] --prompt [PROMPT]
Use gradio_demo.py script to start a Gradio interface for the model.
python gradio_demo.py
webcam_gradio_demo.py provides a Gradio interface for the model that uses your webcam as input and performs inference in real-time.
python webcam_gradio_demo.py
Limitations
The model may generate inaccurate statements, and struggle to understand intricate or nuanced instructions.
The model may not be free from societal biases. Users should be aware of this and exercise caution and critical thinking when using the model.
The model may generate offensive, inappropriate, or hurtful content if it is prompted to do so.
|
815302608a5e9f22188ea2d9f470ce0d
|
{
"intermediate": 0.35037267208099365,
"beginner": 0.4024195969104767,
"expert": 0.24720782041549683
}
|
43,359
|
Hi!
|
d1dc47913eed096d62243badccb965be
|
{
"intermediate": 0.3230988085269928,
"beginner": 0.2665199935436249,
"expert": 0.4103812277317047
}
|
43,360
|
there are three dropdowns a,b,c. dropdown b is dependent on the element clicked in dropdown a and dropdown c is dependent on the element clicked in dropdown b. i want to click an element in a then check if a certain element is present in b. if it is present in b then click on dropdown b and click the element we were waiting for. same process for c. implement this logic using playwright in python. i will enter the ids manually later
|
c8d4956018be88989f4bff1a2c93f6df
|
{
"intermediate": 0.553117036819458,
"beginner": 0.17525580525398254,
"expert": 0.27162715792655945
}
|
43,361
|
能不能帮我写一个pine脚本,功能是同时使用Volatility Oscillator指标、Bollinger Bands指标、Normalized MACD指标。Volatility Oscillator指标、Normalized MACD指标我会提供,Bollinger Bands指标直接调用tradingview的就行,设置保持默认。代码如下Volatility Oscillator指标
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © veryfid
//@version=4
study("Volatility Oscillator", resolution = "")
length = input(100)
spike = close - open
x = stdev(spike,length)
y = stdev(spike,length) * -1
plot(spike, color = color.white, linewidth = 2, title = "Spike Linel")
p1 = plot(x, "Upper Line")
p2 = plot(y, "Lower Line")
plot(0, color= color.gray, title= "Zero Line")
plot(spike, color= color.blue, style=plot.style_area, transp=80, title = "Spike Fill")
osc2 = spike
lbR = 5
lbL = 5
rangeUpper =60
rangeLower = 5
plotBull = input(title="Plot Bullish", defval=true)
plotHiddenBull = input(title="Plot Hidden Bullish", defval=false)
plotBear = input(title="Plot Bearish", defval=true)
plotHiddenBear = input(title="Plot Hidden Bearish", defval=false)
delay_plot_til_closed = input(title="Delay diversion plot until candle is closed (don't repaint)", defval=false)
bearColor = color.red
bullColor = color.green
hiddenBullColor = color.new(color.green, 80)
hiddenBearColor = color.new(color.red, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
repaint = (not(delay_plot_til_closed) or barstate.ishistory or barstate.isconfirmed)
plFound = na(pivotlow(osc2, lbL, lbR)) ? false : true
phFound = na(pivothigh(osc2, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL = osc2[lbR] > valuewhen(plFound, osc2[lbR], 1) and _inRange(plFound[1])
// Price: Lower Low
priceLL = low[lbR] < valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound and repaint
plotshape(
bullCond ? osc2[lbR] : na,
offset=-lbR,
title="Regular Bullish Label",
text="R",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
transp=0
)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL = osc2[lbR] < valuewhen(plFound, osc2[lbR], 1) and _inRange(plFound[1])
// Price: Higher Low
priceHL = low[lbR] > valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound and repaint
plotshape(
hiddenBullCond ? osc2[lbR] : na,
offset=-lbR,
title="Hidden Bullish Label",
text="H",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
transp=0
)
//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
oscLH = osc2[lbR] < valuewhen(phFound, osc2[lbR], 1) and _inRange(phFound[1])
// Price: Higher High
priceHH = high[lbR] > valuewhen(phFound, high[lbR], 1)
bearCond = plotBear and priceHH and oscLH and phFound and repaint
plotshape(
bearCond ? osc2[lbR] : na,
offset=-lbR,
title="Regular Bearish Label",
text="R",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
transp=0
)
//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High
oscHH = osc2[lbR] > valuewhen(phFound, osc2[lbR], 1) and _inRange(phFound[1])
// Price: Lower High
priceLH = high[lbR] < valuewhen(phFound, high[lbR], 1)
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound and repaint
plotshape(
hiddenBearCond ? osc2[lbR] : na,
offset=-lbR,
title="Hidden Bearish Label",
text="H",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
transp=0
)
//barcolor(color = spike > 0 ? color.green : color.red )
Normalized MACD指标
study("Normalized MACD",shorttitle='N MACD')
sma = input(13,title='Fast MA')
lma = input(21,title='Slow MA')
tsp = input(9,title='Trigger')
np = input(50,title='Normalize')
h=input(true,title='Histogram')
docol = input(false,title="Color Change")
dofill=input(false,title="Fill")
type = input(1,minval=1,maxval=3,title="1=Ema, 2=Wma, 3=Sma")
sh = type == 1 ? ema(close,sma)
: type == 2 ? wma(close, sma)
: sma(close, sma)
lon=type == 1 ? ema(close,lma)
: type == 2 ? wma(close, lma)
: sma(close, lma)
ratio = min(sh,lon)/max(sh,lon)
Mac = (iff(sh>lon,2-ratio,ratio)-1)
MacNorm = ((Mac-lowest(Mac, np)) /(highest(Mac, np)-lowest(Mac, np)+.000001)*2)- 1
MacNorm2 = iff(np<2,Mac,MacNorm)
Trigger = wma(MacNorm2, tsp)
Hist = (MacNorm2-Trigger)
Hist2 = Hist>1?1:Hist<-1?-1:Hist
swap=Hist2>Hist2[1]?green:red
swap2 = docol ? MacNorm2 > MacNorm2[1] ? #0094FF : #FF006E : red
plot(h?Hist2:na,color=swap,style=columns,title='Hist',histbase=0)
plot(MacNorm2,color=swap2,title='MacNorm')
plot(dofill?MacNorm2:na,color=MacNorm2>0?green:red,style=columns)
plot(Trigger,color=black,title='Trigger')
hline(0)
|
5cb90037dd7ff6764177ef49c7d8bc04
|
{
"intermediate": 0.3027285039424896,
"beginner": 0.3870060443878174,
"expert": 0.3102653920650482
}
|
43,362
|
comment gérez des évènements autrement que la vérification lorsque la page charge, je m'explique, lorsque j'ajoute un personnage au favoris le problème c'est que l'état du coeur remplit est actualisé après refresh et je veux voir le coeur changez de couleur sans refresh : j'ai des repertoires models, services et view. Je veux avoir une architecture clean, j'ai penser a mettre une balise script dans le return du html mais je me demande si d'autre pratique sont plus clean : // Instantiate API
import PersonnagesProvider from "../../services/PersonnagesProvider.js";
import FavoriteManager from '../../services/FavoriteManager.js';
export default class Home {
async render() {
let personnages = await PersonnagesProvider.FetchPersonnages();
let html = personnages
.map(
(personnage) => /*html*/ `
<div class="col">
<div class="card shadow-sm">
<svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">${personnage.nom}</text></svg>
<div class="card-body">
<p class="card-text">${personnage.nom}</p>
<p>Force: ${personnage.statistiques.force}</p>
<p>Dextérité: ${personnage.statistiques.dextérité}</p>
<p>Intelligence: ${personnage.statistiques.intelligence}</p>
<p>Santé: ${personnage.statistiques.santé}</p>
<p>Mana: ${personnage.statistiques.mana}</p>
<p>Defense: ${personnage.statistiques.defense}</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<a href="#/personnage/${personnage.id}" class="btn btn-sm btn-outline-secondary">+ détail sur ${personnage.nom}</a>
</div>
<small class="text-body-secondary">${personnage.id}</small>
<a onclick="FavoriteManager.toggleFavorites('${personnage.id}');">
${FavoriteManager.isFavorite(personnage.id) ?
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart-fill" viewBox="0 0 16 16"><path d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/></svg>' :
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16"><path d="M8 2.748l-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z"/></svg>'}
</a>
</div>
</div>
</div>
</div>
`
)
.join("\n ");
return /*html*/ `
<nav>
<ul>
<div class="left-part">
<li><a href="/">Personnages</a></li>
<li><a href="#/armes">Armes</a></li>
<li><a href="#/armures">Armures</a></li>
</div>
<li>Mes favoris</li>
</ul>
<nav>
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
${html}
</div>
`;
}
}
import PersonnagesProvider from "../../services/PersonnagesProvider.js";
import Utils from "../../services/Utils.js";
export default class Personnage{
async render(){
let request = Utils.parseRequestURL();
let personnage = await PersonnagesProvider.getPersonnages(request.id);
personnage.map(p => {
personnage = p;
})
return /*html*/`
<script>
function testt(){
console.log("test");
}
</script>
<section class="section">
<h1> Nom : ${personnage.nom}</h1>
<p> Classe : ${personnage.classe} </p>
<p> Note : ${personnage.note} </p>
<p> Niveau : ${personnage.niveau} </p>
</section>
<p><a href="">+ 100 expériences</a></p>
<a onclick="testt();">Ajouter en favoris</a>
<p><a href="/">Retour</a></p>
`
}
}const Utils = {
// --------------------------------
// Parse a url and break it into resource, id and verb
// --------------------------------
parseRequestURL : () => {
let url = location.hash.slice(1).toLowerCase() || '/';
let r = url.split("/")
let request = {
resource : null,
id : null,
verb : null
}
request.resource = r[1]
request.id = r[2]
request.verb = r[3]
return request
}
// --------------------------------
// Simple sleep implementation
// --------------------------------
, sleep: (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
export default Utils;
|
363e4a0cdc1f6fb524c9918fa9fe0aaf
|
{
"intermediate": 0.4585869014263153,
"beginner": 0.38574305176734924,
"expert": 0.15567010641098022
}
|
43,363
|
In sapui5,how can I set background picture for a flexbox
|
facabc914cf047b892eb201a37022ddb
|
{
"intermediate": 0.3983733355998993,
"beginner": 0.33576685190200806,
"expert": 0.26585978269577026
}
|
43,364
|
In sapui5,how can I set background picture for a flexbox
|
e3ac00830a89675d7865124171330201
|
{
"intermediate": 0.3983733355998993,
"beginner": 0.33576685190200806,
"expert": 0.26585978269577026
}
|
43,365
|
I have a code understand the code. Basically which is reading csv file which is ocr textract of an invoice which is in image format. That contains these columns (page_num,block_num,line_num,word_num,left,right,top,bottom,width,height,conf,text,image_height,image_width,skewness,orientation)
Modify the code to calculate the conf (confidence score) of bounding boxes which is the output of process_single_token_entity and process_multi_token_enetity. In case of multi token entity calculate the combined or average value of all the bounding box.
import cv2
import pandas as pd
import json
from thefuzz import fuzz
from itertools import product
class BoundingBoxFinder:
def __init__(self):
print("Initializing used_bounding_boxes")
self.used_bounding_boxes = {}
def preprocess_entity(self, entity):
try:
token = entity.replace(",", "").strip()
return token
except:
pass
def calculate_proximity_score(self, box_a, box_b):
vertical_overlap = max(0, min(box_a["bottom"], box_b["bottom"]) - max(box_a["top"], box_b["top"]))
vertical_distance = 0 if vertical_overlap > 0 else min(abs(box_a["top"] - box_b["bottom"]), abs(box_a["bottom"] - box_b["top"]))
horizontal_overlap = max(0, min(box_a["right"], box_b["right"]) - max(box_a["left"], box_b["left"]))
horizontal_distance = 0 if horizontal_overlap > 0 else abs(box_a["right"] - box_b["left"])
return horizontal_distance + 2 * vertical_distance
def is_nearby(self, box_a, box_b, max_line_difference=5, max_distance=100):
return self.calculate_proximity_score(box_a, box_b) <= max_distance + 2 * max_line_difference
def merge_boxes(self, boxes):
min_left = min(box["left"] for box in boxes)
max_right = max(box["right"] for box in boxes)
min_top = min(box["top"] for box in boxes)
max_bottom = max(box["bottom"] for box in boxes)
return {"left": min_left, "right": max_right, "top": min_top, "bottom": max_bottom}
def find_potential_matches(self, dataframe, token, threshold=75):
potential_matches = []
for _, row in dataframe.iterrows():
ocr_text = self.preprocess_entity(row["text"])
score = fuzz.ratio(token, ocr_text)
if score > threshold:
potential_matches.append({
"box": {"left": row["left"], "right": row["right"], "top": row["top"], "bottom": row["bottom"]},
"score": score
})
return potential_matches
def find_best_sequence_heuristic(self, matches_list):
if not matches_list or len(matches_list[0]) == 0:
return []
best_sequence = [min(matches_list[0], key=lambda match: match["score"])]
for next_matches in matches_list[1:]:
current_box = best_sequence[-1]["box"]
next_best_match = min(next_matches, key=lambda match: self.calculate_proximity_score(current_box, match["box"]))
best_sequence.append(next_best_match)
return best_sequence
def process_single_token_entity(self, dataframe, entity, threshold=75):
best_match = None
best_score = threshold
entity = self.preprocess_entity(entity)
if entity not in self.used_bounding_boxes:
self.used_bounding_boxes[entity] = []
for _, row in dataframe.iterrows():
ocr_text = self.preprocess_entity(row["text"])
score = fuzz.ratio(entity, ocr_text)
current_box = {"left": row["left"], "right": row["right"], "top": row["top"], "bottom": row["bottom"]}
if score > best_score and current_box not in self.used_bounding_boxes[entity]:
best_score = score
best_match = current_box
if best_match:
self.used_bounding_boxes[entity].append(best_match)
return best_match
def box_overlap(self, box1, box2):
"""Check if there"s any overlap in any coordinate between two boxes."""
return box1["left"] == box2["left"] or box1["right"] == box2["right"]
def all_boxes_unique(self, sequence_boxes, used_boxes):
"""Ensure no part of the boxes in sequence_boxes overlaps with any box in used_boxes."""
for seq_box in sequence_boxes:
for used_box in used_boxes:
if self.box_overlap(seq_box, used_box):
return False
return True
def get_next_best_sequence(self, all_potential_matches, previous_matches, entity):
"""
Try to find the next best sequence of matches that hasn"t used any part of the bounding boxes.
"""
# Flatten the list of used boxes for easier comparison.
used_boxes = [box for sequence in previous_matches.get(entity, []) for box in sequence]
for sequence in product(*all_potential_matches):
sequence_boxes = [match["box"] for match in sequence]
if self.all_boxes_unique(sequence_boxes, used_boxes):
return sequence # Found a sequence where no box part has been used before
return None # No unique sequence found
def process_multi_token_entity(self, dataframe, entity, threshold=75, max_distance=100, max_line_difference=3):
tokens = entity.split()
all_potential_matches = [self.find_potential_matches(dataframe, token, threshold) for token in tokens]
if not all(matches for matches in all_potential_matches):
return None
if entity not in self.used_bounding_boxes:
self.used_bounding_boxes[entity] = []
previous_matches = self.used_bounding_boxes.get(entity, [])
all_sequences = list(product(*all_potential_matches)) # Create all possible sequences
valid_sequences = [] # List to hold sequences that meet the is_nearby condition
for sequence in all_sequences:
sequence_boxes = [match["box"] for match in sequence]
sequence_is_valid = True
for i in range(len(sequence_boxes) - 1):
if not self.is_nearby(sequence_boxes[i], sequence_boxes[i + 1], max_line_difference, max_distance):
sequence_is_valid = False
break
if sequence_is_valid:
valid_sequences.append(sequence)
# Sort valid sequences by their cumulative proximity score, to prioritize those with boxes closer together
valid_sequences = sorted(valid_sequences, key=lambda seq: sum(self.calculate_proximity_score(seq[i]["box"], seq[i+1]["box"]) for i in range(len(seq) - 1)))
next_best_sequence = None
for sequence in valid_sequences:
sequence_boxes = [match["box"] for match in sequence]
if self.all_boxes_unique(sequence_boxes, [box for sublist in previous_matches for box in sublist]):
next_best_sequence = sequence
break
if next_best_sequence:
new_boxes_sequence = [match["box"] for match in next_best_sequence]
merged_box = self.merge_boxes(new_boxes_sequence)
self.used_bounding_boxes[entity].append(new_boxes_sequence)
return merged_box
return None
def draw_bounding_boxes(self, image_path, bounding_boxes, entity_names):
image = cv2.imread(image_path)
font = cv2.FONT_HERSHEY_SIMPLEX
for box, name in zip(bounding_boxes, entity_names):
if box:
cv2.rectangle(image, (box["left"], box["top"]), (box["right"], box["bottom"]), (0, 255, 0), 2)
cv2.putText(image, name, (box["left"], max(box["top"] - 10, 0)), font, 0.5, (0, 0, 255), 2)
cv2.imwrite("annotated_imagecls.jpg", image)
def process_data(self, json_path, csv_path, image_path):
with open(json_path, "r") as f:
data = json.load(f)
dataframe = pd.read_csv(csv_path)
bounding_boxes = []
entity_names = []
# Existing processing for non-special sections
special_sections = ["amounts_and_tax", "Payment Details"] # Define special handling cases here
for section in ["invoice_details", "Payment Details", "amounts_and_tax"]:
entities = data.get(section, {})
# Check if the current section needs special handling
if section not in special_sections:
for entity_name, entity_value in entities.items():
entity_value_no_comma = self.preprocess_entity(entity_value)
if " " in entity_value_no_comma:
box = self.process_multi_token_entity(dataframe, entity_value_no_comma)
else:
box = self.process_single_token_entity(dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
else:
# Special handling for "amounts_and_tax" section
reversed_dataframe = dataframe.iloc[::-1].reset_index(drop=True) # Reverse the dataframe
for entity_name, entity_value in entities.items():
entity_value_no_comma = self.preprocess_entity(entity_value)
if " " in entity_value_no_comma:
# Use the reversed_dataframe for multi-token entities
box = self.process_multi_token_entity(reversed_dataframe, entity_value_no_comma)
else:
# Use the reversed_dataframe for single-token entities
box = self.process_single_token_entity(reversed_dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
self.draw_bounding_boxes(image_path, bounding_boxes, entity_names)
# Example usage
if __name__ == "__main__":
bbox_finder = BoundingBoxFinder()
bbox_finder.process_data("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
# bbox_finder.main("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
|
6f26ea1f5ecad8814515972558d2891e
|
{
"intermediate": 0.3291004002094269,
"beginner": 0.5358304977416992,
"expert": 0.13506914675235748
}
|
43,366
|
in operating systems what is the quantum of a process
|
a8d1cdeadbbd6eae0c3d2f166d9a16fc
|
{
"intermediate": 0.2588794231414795,
"beginner": 0.212467759847641,
"expert": 0.5286527872085571
}
|
43,367
|
write a program for parallel processing in python
|
a6e430567c4881f2b9e5ad70e2e3cd2e
|
{
"intermediate": 0.23306502401828766,
"beginner": 0.0939156636595726,
"expert": 0.673019289970398
}
|
43,368
|
write a python library allowing no git knowledgable python devs to manage there code with git within the project and its collaborators via python
|
62a35efed9eb149d9a802cfbc9c355d0
|
{
"intermediate": 0.7987408638000488,
"beginner": 0.07891777902841568,
"expert": 0.12234135717153549
}
|
43,369
|
organise mon code en 2 parties avec ce snippet : <form class="vehicle-form space-y-4 w-full md:w-2/3 mx-auto" [formGroup]="vehicleForm">
<div class="grid sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<!-- Constructeur -->
<div class="sm:col-span-1">
<div class="mb-2 block">
<label class="font-medium mb-1">Constructeur</label>
<select
(change)="getModele($event)"
id="constructeur" name="constructeur" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" formControlName="Libelle">
<option *ngFor="let constructeur of constructeurs " [value]="constructeur.Id">{{ constructeur.Libelle }}</option>
</select>
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('Libelle')?.hasError('required') && (vehicleForm.get('Libelle')?.dirty || vehicleForm.get('Libelle')?.touched)">
Ce champs est requis
</small>
</div>
</div>
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="model" class="font-medium mb-1">Modèle</label>
<select
id="model" name="model" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" formControlName="Libelle">
<option *ngFor="let modele of modeles" [value]="modele.Id">{{ modele.Libelle }}</option>
</select>
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('Libelle')?.hasError('required') && (vehicleForm.get('Libelle')?.dirty || vehicleForm.get('Libelle')?.touched)">
Ce champs est requis
</small>
</div>
</div>
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="date_mise_en_circulation" class="font-medium mb-1">Date de mise en circulation</label>
<input type="date" id="date_mise_en_circulation" name="date_mise_en_circulation" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" formControlName="DateMiseEnCirculation">
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('DateMiseEnCirculation')?.hasError('required') && (vehicleForm.get('DateMiseEnCirculation')?.dirty || vehicleForm.get('DateMiseEnCirculation')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<!-- Number Plate -->
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="numberplate" class="font-medium mb-1">Numéro de série</label>
<input type="text" id="numberplate" name="numberplate" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" placeholder="Numéro de série" formControlName="NumeroSerie">
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('NumeroSerie')?.hasError('invalidSerialNumber') && (vehicleForm.get('NumeroSerie')?.dirty || vehicleForm.get('NumeroSerie')?.touched)">
Le format du numéro de série n’est pas valide.
</small>
</div>
</div>
<!-- Registration Date -->
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="registration_date" class="font-medium mb-1">Immatriculation</label>
<input type="text" id="registration_date" name="registration_date" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 fo
cus:border-blue-500 block w-full p-2.5" placeholder="Immatriculation" formControlName="Immatriculation">
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('Immatriculation')?.hasError('invalidRegistrationNumber') && (vehicleForm.get('Immatriculation')?.dirty || vehicleForm.get('Immatriculation')?.touched)">
Le format de l’immatriculation n’est pas valide.
</small>
</div>
</div>
<!-- Kilometerage -->
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="kilometrage" class="font-medium mb-1">Kilométrage</label>
<input type="number" id="kilometrage" name="kilometrage" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" placeholder="Kilométrage" formControlName="Kilometrage">
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('Kilometrage')?.hasError('required') && (vehicleForm.get('Kilometrage')?.dirty || vehicleForm.get('Kilometrage')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="critair" class="font-medium mb-1">Critair</label>
<select id="critair" name="critair" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" formControlName="VignetteCritair">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('VignetteCritair')?.hasError('required') && (vehicleForm.get('VignetteCritair')?.dirty || vehicleForm.get('VignetteCritair')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<!-- Validity of Critair Stickers-->
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="validitycritair" class="font-medium mb-1">Validité Crit'Air</label>
<input type="date" id="validitycritair" name="validitycritair" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" formControlName="ValiditeCritair">
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('ValiditeCritair')?.hasError('required') && (vehicleForm.get('ValiditeCritair')?.dirty || vehicleForm.get('ValiditeCritair')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<!-- Acquisition Date -->
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="DateAchat" class="font-medium mb-1">Date d'acquisition</label>
<input type="date" id="DateAchat" name="DateAchat" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" formControlName="DateAchat">
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('DateAchat')?.hasError('required') && (vehicleForm.get('DateAchat')?.dirty || vehicleForm.get('DateAchat')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<!-- Vehicle Type -->
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="vehicle_type" class="font-medium mb-1">Type de véhicule</label>
<select id="vehicle_type" name="vehicle_type" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" formControlName="TypeVehicule">
<option value="Voiture">Voiture</option>
<option value="Moto">Moto</option>
</select>
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('TypeVehicule')?.hasError('required') && (vehicleForm.get('TypeVehicule')?.dirty || vehicleForm.get('TypeVehicule')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="numeroassurance" class="font-medium mb-1">Numéro d'assurance</label>
<input type="text" id="numeroassurance" name="numeroassurance" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" placeholder="Numéro d'assurance" formControlName="NumeroAssurance">
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('NumeroAssurance')?.hasError('required') && (vehicleForm.get('NumeroAssurance')?.dirty || vehicleForm.get('NumeroAssurance')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="consommation" class="font-medium mb-1">Consommation moyenne</label>
<input type="number" id="consommation" name="consommation" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" placeholder="Consommation moyenne" formControlName="ConsommationMoyenne">
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('ConsommationMoyenne')?.hasError('required') && (vehicleForm.get('ConsommationMoyenne')?.dirty || vehicleForm.get('ConsommationMoyenne')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="prixAchat" class="font-medium mb-1">Prix d'achat</label>
<input type="number" id="prixAchat" name="prixAchat" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" placeholder="Prix d'achat" formControlName="PrixAchat">
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('PrixAchat')?.hasError('required') && (vehicleForm.get('PrixAchat')?.dirty || vehicleForm.get('PrixAchat')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<!-- Driver -->
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="driver" class="font-medium mb-1">Chauffeur associé</label>
<select id="driver" name="driver" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" formControlName="IdConducteur">
<option *ngFor="let driver of drivers" [value]="driver.Id">{{ driver.Nom }}</option>
</select>
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('IdConducteur')?.hasError('required') && (vehicleForm.get('IdConducteur')?.dirty || vehicleForm.get('IdConducteur')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<!-- Acquisition Status -->
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="Achat" class="font-medium mb-1">Achat</label>
<select id="Achat" name="Achat" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-border-blue-500 block w-full p-2.5" formControlName="Achat">
<option value="Oui">Oui</option>
<option value="Non">Non</option>
</select>
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('Achat')?.hasError('required') && (vehicleForm.get('Achat')?.dirty || vehicleForm.get('Achat')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<div class="sm:col-span-1">
<div class="mb-2 block">
<label for="location" class="font-medium mb-1">Location</label>
<select id="location" name="location" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" formControlName="Location">
<option value="Oui">Oui</option>
<option value="Non">Non</option>
</select>
<small class="text-red-600 mt-1" *ngIf="vehicleForm.get('Location')?.hasError('required') && (vehicleForm.get('Location')?.dirty || vehicleForm.get('Location')?.touched)">
Ce champs est requis.
</small>
</div>
</div>
<div class="max-w-2xl mx-auto">
<aside class="flex flex-col items-center justify-center mb-5" aria-label="Sidebar">
<div class="px-3 py-4 overflow-y-auto rounded-2xl bg-gray-50 dark:bg-gray-800">
<ul class="space-y-2">
<h2 class="text-lg font-semibold text-gray-800 dark:text-gray-200">Modèle caractéristique du véhicule</h2>
<!-- Category -->
<div class="sm:col-span-1">
<div class="mb-2 block" *ngFor="let modelecarac of modelecaracteristique ">
<label class="font-medium mb-1">Segment : </label>
{{modelecarac.Segment }}
</div>
</div>
<!-- Capacity -->
<div class="sm:col-span-1">
<div class="mb-2 block" *ngFor="let modelecarac of modelecaracteristique ">
<label class="font-medium mb-1">Nombre de places :</label>
{{modelecarac.NombrePlaces }}
</div>
</div>
<!-- Engine Size -->
<div class="sm:col-span-1">
<div class="mb-2 block" *ngFor="let modelecarac of modelecaracteristique ">
<label class="font-medium mb-1">Cylindrée :</label>
{{modelecarac.Cylindree}}
</div>
</div>
<!-- Weight -->
<div class="sm:col-span-1">
<div class="mb-2 block" *ngFor="let modelecarac of modelecaracteristique ">
<label class="font-medium mb-1" >Poids :</label>
{{modelecarac.Poids}}
</div>
</div>
<!-- Carbon Emissions -->
<div class="sm:col-span-1">
<div class="mb-2 block" *ngFor="let modelecarac of modelecaracteristique ">
<label class="font-medium mb-1">Emission de CO2 :</label>
{{modelecarac.EmissionCO2}}
</div>
</div>
<!-- Fuel Type -->
<div class="sm:col-span-1">
<div class="mb-2 block" *ngFor="let modelecarac of modelecaracteristique ">
<label class="font-medium mb-1" formControlName="TypeCarburant">Type de carburant :</label>
{{modelecarac.TypeCarburant}}
</div>
</div>
<!-- Transmission Type -->
<div class="sm:col-span-1">
<div class="mb-2 block" *ngFor="let modelecarac of modelecaracteristique ">
<label class="font-medium mb-1" formControlName="TypeBoiteVitesse">Type de transmission :</label>
{{modelecarac.TypeBoiteVitesse}}
</div>
</div>
<!-- Power to weight Ratio -->
<div class="sm:col-span-1">
<div class="mb-2 block" *ngFor="let modelecarac of modelecaracteristique ">
<label class="font-medium mb-1">Rapport Poids Puissance :</label>
{{modelecarac.RapportPoidsPuissance}}
</div>
</div>
</ul>
</div>
</aside>
</div>
</div>
<div class="sm:col-start-1 sm:col-end-3 flex items-center justify-center pt-8">
<button type="submit" class="btn btn-primary mr-4" (click)="onSubmitVehicule()">Enregistrer</button>
<button type="reset" class="btn btn-secondary" (click)="resetForm()">Annuler</button>
</div>
</form>
<form class="space-y-4 w-full md:w-2/3 mx-auto" [formGroup]="optionService.optionForm">
<div class="grid sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<!-- Select element for type of options -->
<div class="mt-4">
<label for="options" class="block font-medium mb-1">Type d'options</label>
<select id="options" name="options" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-40 p-2.5">
<option *ngFor="let option of options" [value]="option.name">{{option.name}}</option>
</select>
</div>
<!-- Select element for choosing a vehicle -->
<div class="mt-4">
<label for="vehicules" class="block font-medium mb-1">Choisir un véhicule</label>
<select id="vehicules" name="vehicules" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-40 p-2.5" formControlName="IdVehicule">
<option *ngFor="let vehicule of vehicules" [value]="vehicule.Id">{{vehicule.Constructeur}} {{vehicule.Modele}} {{vehicule.Immatriculation}}</option>
</select>
</div>
</div>
<div class="sm:col-start-1 sm:col-end-3 flex items-center justify-center pt-8">
<button type="submit" class="btn btn-primary mr-4" (click)="onSubmitOption()">Enregistrer</button>
<button type="reset" class="btn btn-secondary" (click)="resetForm()">Annuler</button>
</div>
</form>
|
ada9ef2939669c1b02dd6f84164a0c45
|
{
"intermediate": 0.30618804693222046,
"beginner": 0.423441618680954,
"expert": 0.27037033438682556
}
|
43,370
|
const username = "God";
const godUser = await strapi.query('plugin::users-permissions.user').findOne({
where: { username },
populate: ['decks', 'decks.cards.card'],
});
const allUsers = await strapi.query('plugin::users-permissions.user').findMany({});
console.log(allUsers); 如何对获取 user的所有deck 卡组的卡,然后去重,
|
e52cd32c8a2c9770e41fc59c477ad446
|
{
"intermediate": 0.33153027296066284,
"beginner": 0.37910550832748413,
"expert": 0.28936418890953064
}
|
43,371
|
functions.php
|
99e3144e9fc82fdafd6dc5c964ca15be
|
{
"intermediate": 0.3651163876056671,
"beginner": 0.3150182068347931,
"expert": 0.3198654353618622
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.