instruction stringlengths 0 30k ⌀ |
|---|
### Summary
There is a difference between `any` in type parameter and `any` in regular function parameter. Your case is the former one for generics. So you need to instantiate `T`(decide `T`'s concrete type) first when assigning it to the concrete variables
Ref1. https://stackoverflow.com/questions/71274361/go-error-cannot-use-generic-type-without-instantiation
Ref2. https://stackoverflow.com/questions/71628061/difference-between-any-interface-as-constraint-vs-type-of-argument
### In detail
[Type definition spec](https://tip.golang.org/ref/spec#Type_definitions)
> If the type definition specifies type parameters, the type name denotes a generic type. Generic types must be instantiated when they are used.
[Instantiations spec](https://tip.golang.org/ref/spec#Instantiations)
> A generic function or type is instantiated by substituting type arguments for the type parameters. [...]
It's because in `GetAllProducts`, type `T` is not decided yet. So it is impossible to assign `[]models.Products` to `T`.
```golang
func (db *DbConnection[T]) GetAllProducts() {
var re []models.Products
re, _ = db.GetAll()
}
```
But you can assign `models.Products` to `T` if `T` is decided as `models.Products`, like this.
```golang
db := DbConnection[models.Products]{}
var re []models.Products
re, _ = db.GetAll()
```
I reproduce your problem in the simplified version(https://go.dev/play/p/GHkDThFLOKG). You can find the same error `GetAllProducts()` but in the main code, it works. |
I have a very large text file (58 million lines) that I want to process using Cython. It looks like this:
262.000 1.000 2.2900
263.000 1.000 -2.1562
264.000 1.000 -1.7201
265.000 1.000 1.1220
266.000 1.000 -0.0108
267.000 1.000 0.4371
268.000 1.000 -0.1519
269.000 1.000 0.1389
And so on. I need to go line-by-line and get the three values; the first two should be converted to integers, then the last one remains a float. I use a dictionary (c++ map) to convert the first two numbers to two new numbers, then use those new numbers as indices to a 2D array and at that position, add the absolute value of the third value.
By far my biggest bottleneck is just processing the data. The fastest algorithm that I have been able to write uses Pandas to read in the file and converts it to a Numpy array, but this still takes about 30 seconds, with the whole script taking about 35 seconds.
The code for this implementation is below:
@cython.boundscheck(False)
@cython.wraparound(False)
def GetInteractionMatrices(self, path: str) -> np.ndarray:
cdef:
np.ndarray[np.float64_t, ndim=2] res_res
np.ndarray[np.float64_t, ndim=2] data
int length
int i
int atomResidue_i
int atomResidue_j
double value
res_res = np.zeros((self.numResidues,self.numResidues), dtype=np.float64)
data = np.abs(pd.read_csv(path, sep="\s+", header=None, skiprows=1).to_numpy())
length = data.shape[0]
# Needed to ensure the data is contigious in memory
res_res = res_res.copy(order='C')
data = data.copy(order='C')
cdef np.float64_t[:, ::1] res_resView = res_res
cdef double[:, ::1] dataView = data
for i in range(length):
atomResidue_i = self.atomResidueDict[<int>dataView[i, 0]]
atomResidue_j = self.atomResidueDict[<int>dataView[i, 1]]
if atomResidue_i == atomResidue_j: continue
value = dataView[i, 2]
res_resView[atomResidue_i, atomResidue_j] += value
return res_res
But some more consideration of the algorithm led to me realize that I don't really need to read the data in memory at all, and I can just process it as a data stream. However, my best implementation of this is about 2x slower than the above code, taking about 55 seconds.
@cython.boundscheck(False)
@cython.wraparound(False)
def GetInteractionMatrices(self, path: str) -> np.ndarray:
cdef:
np.ndarray[np.float64_t, ndim=2] res_res
np.ndarray[np.float64_t, ndim=1] dataTemp
int i
int atomResidue_i
int atomResidue_j
double value
FILE* p
char *token
char line[50]
char path_c[100]
res_res = np.zeros((self.numResidues,self.numResidues), dtype=np.float64)
dataTemp = np.zeros(3, dtype=np.float64)
# Needed to ensure the data is contigious in memory
res_res = res_res.copy(order='C')
cdef np.float64_t[:, ::1] res_resView = res_res
cdef double[:] dataTempView = dataTemp
strncpy(path_c, path.encode('utf-8'), sizeof(path_c)-1)
path_c[sizeof(path_c)-1] = b'\0'
p = fopen(<char*>path_c, "r")
if p is NULL:
PyErr_SetFromErrnoWithFilenameObject(OSError, <char*>path_c)
fseek(p, 0, SEEK_SET) # Move to the beginning of the file
while fgets(line, 50, p) != NULL:
i=0
token = strtok(line, ' ')
while token != NULL and i < 3:
dataTempView[i] = atof(token)
token = strtok(NULL, ' ')
i += 1
atomResidue_i = self.atomResidueDict[<int>dataTempView[0]]
atomResidue_j = self.atomResidueDict[<int>dataTempView[1]]
if atomResidue_i == atomResidue_j: continue
res_resView[atomResidue_i, atomResidue_j] += np.abs(dataTempView[2])
return res_res
Surprising, using numpy to get the absolute value alone adds 30 additional seconds to the process, which I think is probably the only advantage of reading the data into memory.
I still think this has the potential to be faster, I suspect an additional inefficiency is with the nested while loops and splitting the string based on spaces, though at this point I'm not sure how I could further optimize it.
**-----EDIT 1-----**
I took some suggestions and made the following changes:
* Replaced `np.abs` with `abs` which Cython optimizes
* Converted my dictionary to a Numpy array
This managed to bring the time down from 55 seconds to only 14!
I then tried to implement my own parsing function using knowledge of the specific format of the file, but I seem to have made it worse. If anyone would like to take a look at it, I'd love some feedback on it:
cdef ParseLine(bytes line):
cdef:
int i = 0
int num1 = 0
int num2 = 0
double num3 = 0
# Ignore leading spaces
while line[i] == 32:
i += 1
# Build first number
while 48 <= line[i] <= 57:
num1 = line[i] - 48 + num1 * 10
i += 1
# Ignore decimal point and any trailing zeros
i += 4
# Ignore spaces
while line[i] == 32:
i += 1
# Build second number
while 48 <= line[i] <= 57:
num2 = line[i] - 48 + num2 * 10
i += 1
# Ignore decimal point and any trailing zeros
i += 4
# Ignore spaces or sign (we would've taken abs anyway)
while line[i] == 32 or line[i] == 45:
i += 1
# Build third number
while 48 <= line[i] <= 57:
num3 = line[i] - 48 + num3 * 10
i += 1
# Ignore decimal point
num3 = num3 + (line[i+1] - 48) * 0.1
num3 = num3 + (line[i+2] - 48) * 0.01
num3 = num3 + (line[i+3] - 48) * 0.001
num3 = num3 + (line[i+4] - 48) * 0.0001
return num1, num2, num3
This feels inefficient, but from what I've been able to find, this is basically how `atoi` and `atof` are implemented. Though this is about 50 seconds slower, so there must be some optimizations somewhere.
**-----EDIT 2-----**
If anyone else is in the position, changing the function signature from `cdef ParseLine(bytes line)` to `cdef (int, int, double) ParseLine(char* line)` (note `char*` rather than `bytes`) sped up the code from ~60 seconds to ~3 seconds! I think it's because `bytes` is a Python object which has a large access overhead, and `char*` is a C object, which is optimized by Cython. |
|java|reference|pass-by-reference|call-by-value| |
{"Voters":[{"Id":770830,"DisplayName":"bereal"},{"Id":1902010,"DisplayName":"ceejayoz"},{"Id":238704,"DisplayName":"President James K. Polk"}]} |
I searched online but could not find an answer. I know i+=1 in Python is equivalent to i++ in C/C++. But what about ++i? when I want to increment first and then assign. Is it never used in Python and why it is not needed?
I searched online for an answer but could not find one. |
how to write "++i" in Python? |
|python|python-3.x| |
null |
The code below uses a **background callback** (plotly/dash) to retrieve a value.
[![enter image description here][1]][1]
Every 3 seconds, `update_event(event, shared_value)` sets an `event` and define a `value`. In parallel, `listening_process(set_progress)` waits for the `event`.
This seems to work nicely when the waiting time is low (say a few seconds). When the waiting time is below 1 second (say 500ms), `listening_process(set_progress)` is missing values.
Is there a way for the **background callback** to refresh faster ?
It looks like the server updates with a delay of a few hundreds of ms, independently of the rate at which I set the `event`.
```
import time
from uuid import uuid4
import diskcache
import dash_bootstrap_components as dbc
from dash import Dash, html, DiskcacheManager, Input, Output
from multiprocessing import Event, Value, Process
from datetime import datetime
import random
# Background callbacks require a cache manager + a unique identifier
launch_uid = uuid4()
cache = diskcache.Cache("./cache")
background_callback_manager = DiskcacheManager(
cache, cache_by=[lambda: launch_uid], expire=60,
)
# Creating an event
event = Event()
# Creating a shared value
shared_value = Value('i', 0) # 'i' denotes an integer type
# Updating the event
# This will run in a different process using multiprocessing
def update_event(event, shared_value):
while True:
event.set()
with shared_value.get_lock(): # ensure safe access to shared value
shared_value.value = random.randint(1, 100) # generate a random integer between 1 and 100
print("Updating event...", datetime.now().time(), "Shared value:", shared_value.value)
time.sleep(3)
app = Dash(__name__, background_callback_manager=background_callback_manager)
app.layout = html.Div([
html.Button('Run Process', id='run-button'),
dbc.Row(children=[
dbc.Col(
children=[
# Component sets up the string with % progress
html.P(None, id="progress-component")
]
),
]
),
html.Div(id='output')
])
# Listening for the event and generating a random process
def listening_process(set_progress):
while True:
event.wait()
event.clear()
print("Receiving event...", datetime.now().time())
with shared_value.get_lock(): # ensure safe access to shared value
value = shared_value.value # read the shared value
set_progress(value)
@app.callback(
[
Output('run-button', 'style', {'display': 'none'}),
Output("progress-component", "children"),
],
Input('run-button', 'n_clicks'),
prevent_initial_call=True,
background=True,
running=[
(Output("run-button", "disabled"), True, False)],
progress=[
Output("progress-component", "children"),
],
)
def run_process(set_progress, n_clicks):
if n_clicks is None:
return False, None
elif n_clicks > 0:
p = Process(target=update_event, args=(event,shared_value))
p.start()
listening_process(set_progress)
return True, None
if __name__ == '__main__':
app.run(debug=True, port=8050)
```
EDIT : found a solution using `interval`.
```
@app.callback(
[
Output('run-button', 'style', {'display': 'none'}),
Output("progress-component", "children"),
],
Input('run-button', 'n_clicks'),
prevent_initial_call=True,
interval= 100, #### **THIS IS NEW**
background=True,
running=[
(Output("run-button", "disabled"), True, False)],
progress=[
Output("progress-component", "children"),
],
)
```
But then, what is the advantage of this approach over a `dcc.interval` ? In both cases, there is polling. The only advantage I can see is that the consumer receives the updated value at the *exact* same time it is produced.
[1]: https://i.stack.imgur.com/jqJ5v.gif |
I have a relatively large PostgreSQL (v12) table storing JSONB data that has unintentional duplicate data (based on a composite unique index on two columns, `aCol` and `bCol`). In order to create that index, I have to first delete all of the accidental duplicates from the DB. This works fine in 2/3 of our DB servers (servers for different environments, i.e. Dev and Prod, all with the same DB schema), but in the 3rd the query will just never finish, and I've let it run for up to 2 hours (in the other environments it takes a matter of minutes).
I've tried configuring the resources and configuration settings to be the same in all environments; for example, the RAM, disk size and ops, CPU, `effective_io_concurrency`, etc. I've also compared the sizes of the tables and I don't think that's the issue, because one of the servers that does complete has ~2 million records for a total of ~9 GB while the one that fails has ~400,000 records for a total of ~2 GB.
The query in question is:
```sql
DELETE FROM aTable t1 USING aTable t2
WHERE t1.aCol = t2.aCol
AND t1.bCol = t2.bCol
AND t1.id != t2.id
AND t1.created_at <= t2.created_at
```
I'm not a DBA or SQL expert by any means so I would definitely appreciate any insight into what else might be causing this query to hang in 1 specific environment, or whether there is a more efficient way to achieve what I'm trying to do that could potentially bypass the issue. Thanks in advance
**Edit:** In response to the comments, here are the explain plans for the queries in the two environments.
Working environment:
```
Delete on aTable a (cost=800504.63..5706702.06 rows=72439076 width=12)
-> Merge Join (cost=800504.63..5706702.06 rows=72439076 width=12)
Merge Cond: ((a.aCol = b.aCol) AND (a.bCol = b.bCol))
Join Filter: ((a.id <> b.id) AND (a.created_at <= b.created_at))
-> Sort (cost=400252.31..404391.52 rows=1655683 width=50)
Sort Key: a.aCol, a.bCol
-> Seq Scan on aTable a (cost=0.00..184763.83 rows=1655683 width=50)
-> Materialize (cost=400252.31..408530.73 rows=1655683 width=50)
-> Sort (cost=400252.31..404391.52 rows=1655683 width=50)
Sort Key: b.aCol, b.bCol
-> Seq Scan on aTable b (cost=0.00..184763.83 rows=1655683 width=50)
```
Failing environment:
```
Delete on aTable a (cost=0.00..1794266.00 rows=59613596 width=12)
-> Nested Loop (cost=0.00..1794266.00 rows=59613596 width=12)
-> Seq Scan on aTable a (cost=0.00..40365.00 rows=395600 width=50)
-> Index Scan using idx_aTable_aCol on aTable b (cost=0.00..4.42 rows=1 width=50)
Index Cond: (aCol = a.aCol)
Filter: ((a.id <> id) AND (a.created_at <= created_at) AND (a.bCol = bCol))
```
I notice that the failing table seems to be trying to use an index on `aCol`, though the tables in both environments have that exact same index. Not really sure what to make of that |
The result of dereferencing a deleted pointer is undefined. That means anything can happen, including having a program appear to work.
There is no promise that an exception will be thrown, or that an error message will be displayed. |
**UPDATE**
I reread your question and understand now, that it's more about understanding the `styled` function, which I can't really help, sorry. But still, for a reusable approach of actually getting the tooltip to not wrap, I leave my answer here.
**TL;DR**: `useTheme` + `useMemo` + 'stylesOverrides'
I ran into a similar problem. The `styled` function applies its styles to the root of the component, but not to child- or pseudo-elements, which the tooltip is one of.
This leaves us with the `sx` prop, which you don't want to use or with `stylesOverrides`. To make the latter reusable, you can provide a speed dial actions theme provider, which overrides the tooltip styles.
**EXAMPLE**
Following is a similar speed dial component to what I use, so you may need to adapt it to your use case:
```ts
import FileCopyIcon from '@mui/icons-material/FileCopyOutlined';
import SpeedDial from '@mui/material/SpeedDial';
import SpeedDialAction from '@mui/material/SpeedDialAction';
import SpeedDialIcon from '@mui/material/SpeedDialIcon';
import { createTheme, ThemeOptions, ThemeProvider, useTheme } from '@mui/material/styles';
import { useMemo } from 'react';
const speedDialActionOverrides: ThemeOptions = {
components: {
MuiSpeedDialAction: {
styleOverrides: {
staticTooltipLabel: {
whiteSpace: 'nowrap',
},
},
},
},
};
const TestDial = () => {
// extend the existing theme with some overrides
const existingTheme = useTheme();
const theme = useMemo(() => createTheme(existingTheme, speedDialActionOverrides), [existingTheme]);
return (
<ThemeProvider theme={theme}>
{/* apply the extended theme to this speed dial */}
<SpeedDial ariaLabel="Example Speed Dial" icon={<SpeedDialIcon />}>
<SpeedDialAction icon={<FileCopyIcon />} tooltipTitle="Copy the File" tooltipOpen />
</SpeedDial>
</ThemeProvider>
);
};
export default TestDial;
``` |
A quick aside, we can cast to-and-fro from one table type to another, with restrictions:
/** create a TYPE **/
CREATE TYPE tyNewNames AS ( a int, b int , c int ) ;
SELECT
/** note: order, type & # of columns must match exactly**/
ROW((rec).*)::tyNewNames AS "rec newNames" -- f1,f2,f3 --> a,b,c
, (ROW((rec).*)::tyNewNames).* -- expand the new names
,'<new vs. old>' AS "<new vs. old>"
,*
FROM
(
SELECT
/** inspecting rec: PG assigned stand-in names f1, f2, f3, etc... **/
rec /* a record*/
,(rec).* -- expanded fields f1, f2, f3
FROM (
SELECT ( 1, 2, 3 ) AS rec -- an anon type record
) cte0
)cte1
;
+---------+-+-+-++------------+--------+--+--+--+
|rec |rec |
|newnames |a|b|c|<new vs. old>|oldnames|f1|f2|f3|
+---------+-+-+-++------------+--------+--+--+--+
|(1,2,3) |1|2|3|<new vs. old>|(1,2,3) |1 |2 |3 |
+---------+-+-+-++------------+--------+--+--+--+
A compressed example of this code might look like this:
SELECT ( ( ROW( (rec).* ) )::tyNewNames ).* ;
db fiddle(uk)
[https://dbfiddle.uk/dlTxd8Y3][1]
However as Erwin points out, with the exception of a few cases, ROW() is a noise word. It's also possible to simply recast the record on-the-fly with the new field names, and without the nested CTE's:
/** create a TYPE **/
CREATE TYPE tyNewNames AS ( a int, b int , c int ) ;
SELECT ( 1, 2, 3 ) -- an anon type record
, (ROW( 1, 2, 3 )).* -- anon field names f1, f2, f3 with ROW() wrapper
, ( ( 1, 2, 3 )).* -- anon field names f1, f2, f3 w/out ROW() wrapper
/** cast to new names OTF , f1,f2,f3 --> a,b,c **/
, ( ROW( 1 ,2 ,3 )::tyNewNames ).* -- row() wrapper
, ( ( 1 ,2 ,3 )::tyNewNames ).* -- no row() wrapper
;
[https://dbfiddle.uk/OPJcuzs7][2]
[1]: https://dbfiddle.uk/dlTxd8Y3
[2]: https://dbfiddle.uk/OPJcuzs7 |
null |
When I run the command npm run build (webpack), webpack builds a folder with all of the static files bundled together in bundle.js. Then, when I run the command npm run dev (webpack serve), it opens html file located in the build folder in the browser. But when I look at the source folder using chrome dev tools, the bundle.js that is being loaded is very different (a lot longer) than the bundle.js file created and stored in the project directory. This is the case in both production mode and development mode. The consequence of this is that when I try to use the app without the command webpack serve, like by clicking on the html file and selecting open in default browser, the application doesn't work because the bundle.js file isn't the actual bundle.js file. React components don't get rendered. I don't know if I've explained this well at all, but I'm wondering how I can get the bundle.js file that webpack dev server uses to be the file generated in the build folder. I want the actual completed application to live in the build folder.
If it helps, here is my webpack.config.js file:
```
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: {
bundle: path.resolve(__dirname, 'src/client/index.jsx')
},
output: {
path: path.resolve(__dirname, 'build'),
filename: '[name].js'
},
devServer: {
static: {
directory: path.resolve(__dirname, 'build')
},
port: 3000,
hot: true,
open: true
},
module: {
rules: [
{
test: /\.jsx$/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
}
},
exclude: /node_modules/
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: "Netflix Comments",
filename: 'index.html',
template: 'src/template.html'
})
]
}
```
And package.json
```
{
"name": "netflix-comments",
"version": "1.0.0",
"description": "A chrome extension that adds a comment section to Netflix * Automatically injects a comment icon to the playback control bar that opens a comment section on the right hand side of the screen when clicked (either overlays the show or shrinks the screen) * Users can create an account or post anonymously * Comment will display username/anonymous and time posted * Show a little animation to other people in the comment section when another user is typing * Users will be able to see their comment history * Users will be able to reply to other comments * Season/series comment section",
"main": "webpack.config.js",
"scripts": {
"build": "webpack --mode development",
"dev": "webpack serve"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.24.3",
"@babel/preset-env": "^7.24.3",
"@babel/preset-react": "^7.24.1",
"babel-loader": "^9.1.3",
"html-webpack-plugin": "^5.6.0",
"webpack": "^5.91.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.3"
}
}
```
Thanks in advance!
|
The webpack bundle created and stored in the project directory is different than the one used to run the application with webpack-dev-server |
<!-- language-all: sh -->
> Why is PowerShell failing when redirecting the output?
The reason is that `python` (which underlies `html2text`) - like many other Windows CLIs - modifies its output behavior based on whether the output target is a *console (terminal)* or is _redirected_:
* In the *former* case, such CLIs use the _Unicode_ version of the WinAPI [`WriteConsole`](https://learn.microsoft.com/en-us/windows/console/writeconsole) function, meaning that _any_ character from the global [Unicode](https://en.wikipedia.org/wiki/Unicode) alphabet is accepted.
* This means that character-encoding problems do _not_ surface in this case, and the output usually _prints_ properly to the console (terminal) - that said, *exotic* Unicode characters may not print properly, necessitating switching to a different _font_.
* In the *latter* case, CLIs must _encode_ their output, and are expected to respect the legacy Windows _OEM code page_ associated with the current console window, as reflected in the output from `chchp.com` and - by default - in `[Console]::OutputEncoding` inside a PowerShell session:
* That is, they must *encode* their output based on said code page, e.g. `437` on US-English systems, and if the text to output contains characters that cannot be represented in that code page - which (for non-CJK locales) is a _single_-byte encoding limited to _256_ characters in total - you'll get error messages like the one you saw.
* To avoid this limitation, modern CLIs increasingly encode their output using UTF-8 instead, either by default (e.g., Node.js), or on an _opt-in_ basis (e.g., Python).
Notably, Python exhibits nonstandard behavior even by default, by encoding redirected output based on the _ANSI_ code page rather than the _OEM_ code page (both of which are determined by the system's active legacy _system locale_, aka _language for non-Unicode programs_).
---
In the context of PowerShell, an external program's (stdout) output is considered _redirected_ (*not* targeting the console/terminal) in one of the following cases:
* capturing external-program output in a variable (`$text = wget ...`, as in your case), or using it as part an of _expression_ (e.g., `"foo" + (wget ...)`)
* _relaying_ external-program output _via the pipeline_ (e.g., `wget ... | ...`)
* in _Windows PowerShell_ and [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md) _up to v7.3.x_: also with `>`, the [redirection operator](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Redirection); in *v7.4+*, using `>` directly on an external-program call now _passes the raw bytes through_ to the target file.
That is, in all those cases _decoding_ the external program-output comes into play, into _.NET strings_, based on the encoding stored in `[Console]::OutputEncoding`.
In the case at hand, this stage wasn't even reached, because Python itself wasn't able to _encode_ its output.
---
The **solution** in your case is therefore two-pronged, as suggested by [zett42](https://stackoverflow.com/users/7571258/zett42):
* Make sure that `html2text` outputs *UTF-8*-encoded text.
* `html2text` is a Python-based script/executable, so (temporarily) set `$env:PYTHONUTF8=1` before invoking it.
* Make sure that PowerShell interprets the output as UTF-8:
* To that end, (temporarily) set `[Console]::OutputEncoding` to `[System.Text.UTF8Encoding]::new()`
To put it all together:
```
$text =
& {
$prevEnv = $env:PYTHONUTF8
$env:PYTHONUTF8 = 1
$prevEnc = [Console]::OutputEncoding
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
try {
wget.exe -O - https://www.voidtools.com/forum/viewtopic.php?p=36618#p36618 |
html2text
} finally {
$env:PYTHONUTF8 = $prevEnv
[Console]::OutputEncoding = $prevEnc
}
}
```
|
I have the following code in a file testKtor.main.kts:
@file:DependsOn("com.aallam.openai:openai-client-jvm:3.7.0")
@file:DependsOn("io.ktor:ktor-client-cio-jvm:2.3.9")
import com.aallam.openai.client.OpenAI
val openAiClient = OpenAI(token = "your-api-token")
When running this with `kotlin testKtor.main.kts` I get this exception:
> java.lang.AbstractMethodError: Receiver class io.ktor.client.engine.cio.CIOEngine does not define or inherit an implementation of the resolved method 'abstract kotlinx.coroutines.CoroutineDispatcher getDispatcher()' of interface io.ktor.client.engine.HttpClientEngine.
at io.ktor.client.engine.cio.CIOEngine.<init>(CIOEngine.kt:29)
at io.ktor.client.engine.cio.CIO.create(CIOCommon.kt:35)
at io.ktor.client.HttpClientKt.HttpClient(HttpClient.kt:42)
at io.ktor.client.HttpClientJvmKt.HttpClient(HttpClientJvm.kt:21)
at com.aallam.openai.client.internal.HttpClientKt.createHttpClient(HttpClient.kt:89)
at com.aallam.openai.client.OpenAIKt.OpenAI(OpenAI.kt:60)
at com.aallam.openai.client.OpenAIKt.OpenAI(OpenAI.kt:40)
at com.aallam.openai.client.OpenAIKt.OpenAI$default(OpenAI.kt:30)
at TestKtor_main.<init>(TestKtor.main.kts:6)
I checked, the `CIOEngine` in `ktor-client-cio-jvm` depends on `ktor-client-core-jvm` where the dispatcher is implemented in the `HttpClientEngineBase`. It should exist. |
Why doesn't CIOEngine have a dispatcher in kotlin script? |
|kotlin|kotlin-coroutines|ktor|kotlin-script| |
The solution is to reorder the dependencies. This works:
@file:DependsOn("io.ktor:ktor-client-cio-jvm:2.3.9")
@file:DependsOn("com.aallam.openai:openai-client-jvm:3.7.0")
import com.aallam.openai.client.OpenAI
val openAiClient = OpenAI(token = "your-api-token")
As to why, I can give an educated guess:
The `openai-client-jvm` library depends on the multiplatform version of `ktor-client-core` via the multiplatform `commonMain` sourceset (see [build.gradle.kts][1]). I assume the kotlin script cannot handle this multiplatform dependency correctly. However through the `ktor-client-cio-jvm` dependency we somehow get the correct version of `ktor-client-core` (maybe because its a `project` dependency, see [built.gradle.kts][2]).
Now depending on the order of our operations, the openai library can either find the ktor core correctly or it gets the `non-jvm` version and it fails.
[1]: https://github.com/aallam/openai-kotlin/blob/main/openai-client/build.gradle.kts
[2]: https://github.com/ktorio/ktor/blob/main/ktor-client/ktor-client-cio/build.gradle.kts |
{"Voters":[{"Id":3745413,"DisplayName":"Ron Maupin"},{"Id":354577,"DisplayName":"Chris"},{"Id":4850040,"DisplayName":"Toby Speight"}],"SiteSpecificCloseReasonIds":[18]} |
I am trying to extract some links and text in a .json file from a web-page.
I have parsed the HTML tbody > tr > td, and each td contains `<a href="TextWithUrlBehind">Something</a>`
But this `TextWithUrlBehind` in Inspect Element is clickable, it has a link attached to it.
It is not a well-known `<a href=https//...>`
So, my extraction of href is `str: TextWithUrlBehind`, then `text(also str):Something` in the .json file
The code looks like this:
```
rows = test_results_table.find_all("tr")
# Iterate over each anchor tag
for row in rows:
first_cell = row.find("td")
if first_cell:
anchor_tag = first_cell.find("a", href=True)
self._debug_print("Anchor tag content:", anchor_tag)
if anchor_tag:
href = anchor_tag["href"]
text = anchor_tag.get_text(strip=True)
links.append({"href": href, "text": text})
self._debug_print("Content extracted:", {"href": href, "text": text})
else:
self._debug_print("No anchor tag found in cell:", first_cell)
else:
self._debug_print("No table cell found in row:", row)
```
I do not understand how that link is attached in HTML, and I don't know how beautifulsoup built-in functions can help me to get that link. |
|reactjs|webpack|webpack-dev-server|webpack-5| |
null |
You need to send the message to the `HWND` that `CreateWindow()` creates. You can get that from the return value of `CreateWindow()`, or from `GetDlgItem()` after `CreateWindow()` is finished.
The `LPARAM` needs to be a pointer to the 1st character of a null-terminated C-style string, eg:
```
char myline[size];
//fill myline as needed...
HWND hwndLB = CreateWindowA(WC_LISTBOXA, ... reinterpret_cast<HMENU>(LST_LISTBOX), ...);
//HWND hwndLB = GetDlgItem(hwnd, LST_LISTBOX);
SendMessage(hwndLB, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(myline)/*&myline[0]*/);
```
Alternatively:
```
std::string myline;
//fill myline as needed...
HWND hwndLB = ...;
SendMessage(hwndLB, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(myline.c_str()));
``` |
I have an application (nestjs) working into docker container into vm in google cloud, sending and receiving http requests to/from server of other company in other city/state (they use azure cloud).
But that other company created a vpn site to site, and now we need to make this container send and receive the http requests passing by that vpn site to site.
How can i setup and make just my container to connect like that, and not all my server host.
Create a vpn client into container?
I really need help about that. (tutorial, step by step, etc)
Thank you for attention.
I've tryied some tutorials about create a vpn, but i dont know if it is what i need, or a need only to be a client of the vpn of that other company.
|
m hosting a c# api locally on my machine , while trying to connect to it from my flutter app i kept getting a timeout . This is not my first time trying to connect to a local api so i know that i have to use my private ip address instead of localhost . Tried to shutdown my firewall but when shutting my public network firewall i started to get a connection refused exception(No idea why).The api is working since i tested it with postman.Any help is appreciated and thank u.
This is my screen code:
```
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:geolocator/geolocator.dart';
import 'package:image_picker/image_picker.dart';
import 'package:orange_app/models/pointage_model.dart';
import 'package:orange_app/services/pointage_api.dart';
import 'package:orange_app/ui/views/vente_affiche.dart';
import 'package:orange_app/ui/views/vente_add.dart';
import 'package:orange_app/view_models/pointage_view_model.dart';
class AddPointage extends StatefulWidget {
const AddPointage({Key? key});
@override
State<AddPointage> createState() => _AddVenteState();
}
class _AddVenteState extends State<AddPointage> {
late final GlobalKey<FormState> _formKey ;
late final TextEditingController _nom;
late final TextEditingController _prenom;
late final TextEditingController _idUserTerrain;
late double? latitude ;
late DateTime Date_pointage;
late double? longitude;
File? faceImage;
Position? position;
@override
void initState() {
super.initState();
_formKey= GlobalKey<FormState>();
_nom=TextEditingController();
_prenom=TextEditingController();
_idUserTerrain=TextEditingController();
Date_pointage=DateTime.now();
}
@override
void dispose(){
_nom.dispose();
_prenom.dispose();
_idUserTerrain.dispose();
super.dispose();
}
@override
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('New Pointage'),
),
body: Center(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (value) {
if (value == null || value.isEmpty ) {
return 'Please enter some text';
}
if (RegExp(r'\d').hasMatch(value)) {
return 'name should not contain numeric characters';
}
return null;
},
controller: _nom
,
decoration: const InputDecoration(
labelText: 'Name',
hintText: 'Enter Your Name',
),
),
TextFormField(
validator: (value) {
if (value == null || value.isEmpty ) {
return 'Please enter some text';
}
if (RegExp(r'\d').hasMatch(value)) {
return 'last name should not contain numeric characters';
}
return null;
},
controller: _prenom,
decoration: const InputDecoration(
labelText: 'Last Name',
hintText: 'Enter Your Last Name',
),
),
TextFormField(
validator: (value) {
if (value == null || value.isEmpty ) {
return 'Please enter some text';
}
if (RegExp(r'[a-zA-Z]').hasMatch(value)) {
return 'id should not contain alphabetic characters';
}return null;},
controller: _idUserTerrain,
decoration: const InputDecoration(
labelText: 'idUserTerrain',
hintText: 'Enter idUserTerrain',
),
),
ElevatedButton(
child: Text('Save'),
onPressed: () async {
if(_formKey.currentState!.validate())
{
PointageViewModel.determinePosition().then((value) {
setState(() {
position = value;
});
});
if (position != null) {
var model=PointageModel(nom: _nom.text.trim(), prenom: _prenom.text.trim(), idUserTerrain: int.parse(_idUserTerrain.text.trim()), longitude: position!.longitude, latitude: position!.latitude, datePointage: DateTime.now());
bool res=await PointageViewModel.createResponse(model);
if(res)
{Navigator.push(
context,
MaterialPageRoute(builder: (context) => AddVente()),
);}
else{
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Error'),
content: Text("An error has occured"),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("OK"),
),
],
);
},
);
}
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Error'),
content: Text("Unable to get current position."),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("OK"),
),
],
);
},
);
}
}
},
),
],
)),
// Boutons pour choisir les images
MaterialButton(
child: Text('Choose Face Image'),
onPressed: () async {
XFile? xFile = await ImagePicker()
.pickImage(source: ImageSource.gallery);
if (xFile != null) {
setState(() {
faceImage = File(xFile.path);
});
}
},
),
],
),
),
),
floatingActionButton: FloatingActionButton(
child: Text('Pointer'),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => AddVente()));
},
),
);
}
}
```
And this is method where m calling the api:
```
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:orange_app/models/pointage_model.dart';
import 'package:orange_app/models/vente_model.dart';
import '../global/config/api_connection.dart';
class PointageApi {
static Future<http.Response> createPointage(PointageModel model) async {
var url =Uri.http(Api.apiUrl,Api.baseUrl+Api.addPointage);
var request = http.MultipartRequest('POST', url);
// ... (autres parties du code sont inchangées)
request.fields['nom'] = model.nom;
request.fields['prénom'] = model.prenom;
request.fields['IdUserTerrain'] = model.idUserTerrain.toString();
request.fields['longitude'] = model.longitude.toString();
request.fields['latitude'] = model.latitude.toString();
request.fields['date_Pointage'] = model.datePointage.toIso8601String();
// Ajout des images
if (model.faceImage!= null) {
var faceImageBytes = await model.faceImage!.readAsBytes();
request.files.add(http.MultipartFile.fromBytes(
'FaceImage',
faceImageBytes,
filename: 'faceImage'
));
}
// Vérifier si aucune image n'est enregistrée
if (model.faceImage == null) {
print('Image not uploaded');
}
print(request.fields);
var response = await http.Response.fromStream(await request.send());
return response;
}
}
```
And finally this is the error(or part of it):
E/flutter ( 9791): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: ClientException with SocketException: Connection timed out (OS Error: Connection timed out, errno = 110), address = 192.168.100.59, port = 45756, uri=http://192.168.100.59:5187/api/Vente/AddPointage
E/flutter ( 9791): #0 IOClient.send (package:http/src/io_client.dart:154:7)
E/flutter ( 9791): <asynchronous suspension>
E/flutter ( 9791): #1 BaseRequest.send (package:http/src/base_request.dart:133:22)
E/flutter ( 9791): <asynchronous suspension>
E/flutter ( 9791): #2 PointageApi.createPointage (package:orange_app/services/pointage_api.dart:38:51)
E/flutter ( 9791): <asynchronous suspension>
E/flutter ( 9791): #3 PointageViewModel.createResponse (package:orange_app/view_models/pointage_view_model.dart:9:25)
E/flutter ( 9791): <asynchronous suspension>
E/flutter ( 9791): #4 _AddVenteState.build.<anonymous closure> (package:orange_app/ui/views/pointage.dart:129:36)
E/flutter ( 9791): <asynchronous suspension>
E/flutter ( 9791):
|
Flutter connection to a local api |
|.net|flutter|rest|timeout| |
**This is not possible.**
Because the font is not applied to the text and is applied to the visible output for you. Therefore, the font will never be a part of your text and you will not be able to copy or share it as text.
**The solution for your case is to provide an image output** to the user and copy, share or save the generated image of the text with the font applied.
Of course, the **explanations provided are for file fonts** with specific formats. Otherwise, there are some limited characters that can be used to write the desired text with a certain style, which is not available in all languages and is not a suitable approach to use. The best approach is what was said, that is, using the method of creating an image for the user |
from https://www.warp.dev/blog/how-to-open-warp-vscode
VS Code > Settings > Preferences
Type "terminal" into the search bar
Where it says "Terminal > External: Osx Exec", replace whatever is there with "warp.app"
Now when you press Command + Shift + C, a new session of Warp should pop up.
|
I've got a component which does this:
```jsx
<CodeBlock language="css" code={`p { color: hsl(1deg, 100%, 50%};`} />
```
Inside the component I run Prism.js for code highlighting. This is all good. The problem I have is when the indentation of the general code leads to a situation like this:
```jsx
<Box>
<CodeBlock code={`p {
color: hsl(0deg, 100%, 50%;
}`} language="css" />
</Box>
```
and lots of extra whitespace gets added.
I want to be able to process and format the strings for whitespace. I can trim the edges of the string but I need to sort indentation. I have looked at i[ndent.js][1] but that doesn't remove whitespace from the beginning.
Does anyone know how I can solve this?
EDIT (on request):
Current Output:
```css
p {
color: hsl(0deg, 100%, 50%;
}
```
Required Output:
```css
p {
color: hsl(0deg, 100%, 50%;
}
```
[1]: https://zebzhao.github.io/indent.js/ |
The type of B is displayed as A when `type B = A` is used. Why is it displayed as `any` when `type B = A | A` is used instead? |
|typescript|types| |
Your second working command is running commands in a Bourne shell (`/bin/sh`); that's what the `-exec sh -c '...'` is for in your `find` command.
On the other hand, you're trying to run the first command directly in the `fish` shell. That's not going to work. You could explicitly run it using `/bin/sh`, just like in your `find` command:
```
sh -c 'for i in *.cue; do chdman createcd -i "$i" -o "${i%.*}.chd"; done'
``` |
Not exactly to your question, but I have similar issue, just share here, hope it help.
My project is blazor server app with VS2022, .Net8, it works fine in Dev and Prod Env. After some code refactor, I rename the project name from 'ProjectName' to 'ProjectNameNew'. It still works fine in Dev environment.
However, after I publish it to Prod env, the page displayed with "An unhandled error has occurred. Reload ", the page loaded without any style/formatting.
Chrome's Network shows all file is downloaded, the 'ProjectNameNew.style.css' is also there.
After troubleshooting, find that the 'link tag' in the css file is different between Dev and Prod.
.page[b-sx9inz7k4q]
Then find there are two *.style.css file in the 'ProjectNameNew\obj\Debug\net8.0\scopedcss\bundle'
ProjectName.style.css
ProjectNameNew.style.css
Manually delete folder **bin**, and **obj**, rebuild the project, and publish it again to Prod env, all works fine. |
I'm trying to solve a problem in CS50W Project 1 'wiki'.
I'm working on the specification - 'Entry Page' where if I add `/wiki/title` to url it should fetch the entry page.
These are my files:
wiki/urls.py
```
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("encyclopedia.urls"))
]
```
encyclopedia/urls.py
```
from django.urls import path
from . import views
# List of urls
urlpatterns = [
path("", views.index, name="index"),
path("<str:title>", views.entry, name="page"),
]
```
encyclopedia/views.py
```
def entry(request, title):
"""
A function that retrieves the content of an entry based on the title provided.
If the entry is not found, it renders a 404 error page.
"""
content = util.get_entry(title)
if content == None:
return render(request, "encyclopedia/404.html")
else:
html_content = markdown2.markdown(content)
return render(request, "encyclopedia/entry.html", {
"title": title, "content": html_content
})
```
entry.html file:
```
{% extends "encyclopedia/layout.html" %}
{% block title %}
{{ title | safe }}
{% endblock %}
{% block body %}
{{ content | safe }}
<!--Link to edit page-->
<div>
<a href="{% url 'edit' title %}" class="btn btn-primary mt-5">
Edit Page
</a>
</div>
{% endblock %}
```
This is the error I'm getting when I add 'css' to the url:
```
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/css/
Using the URLconf defined in wiki.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
<str:title> [name='page']
search/ [name='search']
newpage/ [name='newpage']
edit/<str:title> [name='edit']
random/ [name='random']
The current path, css/, didn’t match any of these.
```
With any other entries (eg - django/html etc.) added I'm just getting "encyclopedia/404.html".
But when the url input exactly matches the name of entry file (eg- 'CSS - CSS', 'Git - Git') it gives me the correct entry page and any other combination of upper & lower case letters raising the errors above.
I tried different paths in the urls.py. Also tried different variations of the code in `def entry(#, #)` to get the contents of entries. Appreciate the help!
|
null |
I have server code and index.js code conected to index.html file. everything seemed to be working, but i cant get the next task done. Taks is: If a new user created, and he;s redirected to casino.html and after this when he will wisit home page, hape page should check if he has session cookie set, and if yes, he should be automaticly redirected to casino.html. But it dont seem to work
server.js:
```
const express = require('express')
const uuid = require('uuid').v4
const mysql = require('mysql2')
const app = express()
const PagePassword = '1234'
const pool = mysql.createConnection({
host: "localhost",
port:'3306',
user: 'root',
password:'1234567890',
database:'mydb'
})
app.use(express.json())
app.use(express.static('client'))
const sessions ={}
app.post('/', (req,res) =>{
const sesionCheck = req.headers.cookie?.split('=')[1]
const usersession = sessions[sesionCheck]
if(usersession){
document.location.href = 'http://localhost:3000/casino.html'
}else{
console.log(req.headers)
const loginCode = `select * from users where nickname="${req.body.nickname}"`
const PostPasswd = req.body.PostPasswd
pool.query(loginCode, (err,resoult) =>{
if(!resoult.length && PostPasswd==PagePassword){
//console.log('New user created')
const code = `INSERT into Users (nickname,points,is_croupier)\nVALUES("${req.body.nickname}",1000, 0);`
pool.query(code)
//set cookie and session for new user
pool.query(loginCode, (err,resoult)=>{
const userID = resoult[resoult.length-1].user_id
const _nickname = resoult[resoult.length-1].nickname
const sessionId = uuid()
sessions[sessionId] = {_nickname, userID}
res.set('Set-Cookie', `session=${sessionId}`)
res.json({message: "UserIsCreated"})
console.log('added cookie to' + sessionId)
console.log(sessions)
})
}
if(resoult.length){
if(resoult[resoult.length-1].nickname == req.body.nickname && PostPasswd==PagePassword){
//ocupated nickname
res.json({message: "nicknameIsOccupated"})
}
}
if(PostPasswd!=PagePassword){
//invalid password
console.log('Invalid password')
}
})
}
})
app.listen(3000, ()=>{
console.log('server is running at port 3000')
})
```
index.js script:
```
const NicknameText = document.getElementById('nickname');
const PasswdText = document.getElementById('passwd');
const LoginButton = document.getElementById('loginBtn');
const ServerURL = 'http://localhost:3000';
LoginButton.onclick = async function Login(e) {
e.preventDefault();
const response = await fetch(ServerURL, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
nickname: NicknameText.value,
PostPasswd: PasswdText.value
}),
credentials: 'include'
});
const data = await response.json();
if (response.ok) {
if (data.message === "nicknameIsOccupated") {
console.log('This nickname is in use!');
NicknameText.value = ''
PasswdText.value = ''
NicknameText.placeholder = "This nickname is in use!"
const icon = document.createElement('i')
icon.className = 'fa-solid fa-circle-exclamation'// Assuming you're using Font Awesome
const container = document.createElement('div')
container.appendChild(icon)
NicknameText.appendChild(container)
// Append the icon and error message to the login button
}
if(data.message === "UserIsCreated"){
document.location.href = 'http://localhost:3000/casino.html';
}
} else {
console.error('Error:', data.message);
}
};
```
What is the problem? Please i need help
I just need help with code |
Express session is not seened in server code |
|javascript|node.js|express|cookies| |
null |
so i am new at coding and im trying to create a Clicker game. To sum it up its supposed to be like Cookie Clicker. Click something to get a point and with those points buy upgrades. But i ran into a little Problem, i want to create Infinite Upgrades. So that i can buy a Click upgrader a infinite amount of times. But I dont know how i can code that.
I havent yet tried anything BUT i have researched. I read allot about Loops but i dont think it would fit because The upgrade part of my Code needs to go up in numbers with the Price of points and the amount of upgrades. Also i would need to somehow Fittingly change the Button Click of the "Cookie" ( cant really explain it well but i basically need to change the code of the thing i click as well ) For now i just did a Max level.
Here is my code
```
using System.Linq.Expressions;
using System.Printing;
using System.Text;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace wieso
{
public partial class MainWindow : Window
{
long Score = 0;
long Upgrade1 = 1;
public MainWindow()
{
InitializeComponent();
ClickAnzahl.Content = Score.ToString();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ClickAnzahlTEXT.Content = "du hast so viele Clicks :";
ClickAnzahl.Content = Score.ToString();
if (Upgrade1 == 1)
{
Score = Score + 1;
ClickAnzahl.Content = Score.ToString();
}
if (Upgrade1 == 2)
{
Score = Score + 2;
ClickAnzahl.Content = Score.ToString();
}
if (Upgrade1 == 3)
{
Score = Score + 3;
ClickAnzahl.Content = Score.ToString();
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (Upgrade1 == 1 && Score >= 10)
{
Score -= 10;
Upgrade1++;
ClickAnzahl.Content = Score.ToString();
knopfding.Content = "50 CLICKS FÜR EIN CLICK UPGRADE!";
}
if (Upgrade1 == 2 && Score >= 50)
{
Score -= 50;
Upgrade1++;
ClickAnzahl.Content = Score.ToString();
knopfding.Content = "Max Level!";
}
}
}
}
``` |
Use ::ng-deep along with :host or you can add your css in style.scss so that you dont need to use ::ng-deep.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
:host{
::ng-deep {
mat-menu {
.mat-mdc-menu-panel {
.mat-mdc-menu-content {
button {
min-height: 24px;
}
}
}
}
}
}
<!-- end snippet -->
|
Guided by https://github.com/microsoft/vscode-python/issues/14639 I suggest to do the following steps:
1. **CTRL + P**
2. Search for **>Preferences: Open User Settings (JSON)** <br> - *(settings.json)* <br>
3. Add `"python.experiments.optInto": ["pythonDiscoveryModule"]`
4. Save the file
5. **View > Comand Palette** and running **Developer: Reload Window** |
To get some code executed just once in this function, you need to tag the order like:
```php
add_action( 'woocommerce_order_status_changed', 'bacs_payment_complete', 10, 4 );
function bacs_payment_complete( $order_id, $old_status, $new_status, $order ) {
// 1. For Bank wire and cheque payments
if ( $order->get_payment_method() === 'bacs'
&& in_array( $new_status, wc_get_is_paid_statuses() )
&& ! $order->get_meta('confirmed_paid') )
{
$order->update_meta_data('confirmed_paid', '1'); // Tag the order
$order->save(); // Save to database
// Here your code to be executed only once
}
}
```
Code goes in functions.php file of your active child theme (or active theme). It should work. |
If you want to use a `switch` statement for ranges, generally you need to map the ranges to specific values - they could be discrete integers, but in Java it makes sense to use `enum`s, because the `enum` definition can have a method that does the mapping.
`enum`s can be public, but they can also be private, within a class, if you don't need to use them anywhere else.
For example:
```
public class Something {
private static enum RangeType {
LOW(0, 10),
MID(10, 20),
HIGH(20, 30);
private final int lowRange;
private final int highRange;
RangeType(int lowRange, int highRange) {
this.lowRange = lowRange;
this.highRange = highRange;
}
public RangeType getRange(int val) {
for (RangeType rt : RangeType.values()) {
if (rt.lowRange <= val && val > rt.highRange) {
return rt;
}
}
return null;
}
}
public int doSomething(int s) {
int newS;
RangeType sRange = RangeType.getRange(s);
switch (sRange) {
case LOW:
newS = 15;
break;
case MID:
newS = 3;
break;
case HIGH:
newS = 9;
break;
default:
newS = 0;
}
return newS;
}
}
```
Using an enum might be overkill, but it does illustrate how the mapping can be done. |
Svelte reactivity affected by initial variable value |
I've started working with Svelte and I stumbled upon some unexpected behavior. This is the snippet of my app source
let currentPage = 1;
$: if (currentPage || $selectedOption) {
fetchPage(currentPage, $selectedOption);
}
async function fetchPage(page: number, option: string) {
//...
}
onMount(() => {
fetchPage(currentPage, $selectedOption);
});
When I load the page for the first time `fetchPage()` function is called twice. However, if I'll make this change `let currentPage = 0;` it is properly called only once. The problem is that I need to have `currentPage` value initially set to 1.
I've tried also this change:
let currentChange = 0;
// ... rest the same
onMount(() => {
fetchPage(currentPage, $selectedOption);
currentPage = 1;
});
But this didn't help as well. Similarly any bool flags set in `onMount()` and then checked in if statement didn't help.
Any suggestion what else can I do? |
Error fetching the entry page through Django url path |
|html|django-views|web-applications|django-urls| |
null |
|c#|unity-game-engine| |
Trying to work using the fleet ide that was created by Jetbrains
Followed the tuturial on the jetbrains webiste: https://www.jetbrains.com/help/fleet/getting-started-with-java-in-fleet.html
I am following the one for JAVA and I going for the Gradle wrapper.
Was able to get everything working in intellij
But as shown in the screen shots provided when I go to run it in Fleet I got the error message:
"is not recognized as an internal or external command,
operable program or batch file."
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/6elp9.png
[2]: https://i.stack.imgur.com/QhuYr.png |
Jetbrains Intellij Works but Fleet does not |
|gradle|intellij-idea|jetbrains-fleet|jetbrains-hub| |
I came up with a solution myself.
```
SELECT DISTINCT * FROM (
SELECT group_concat(v2_id ORDER BY v2_sort_me ASC) FROM (
SELECT v1.id AS v1_id, v2.id AS v2_id, v1.sort_me AS v1_sort_me, v2.sort_me AS v2_sort_me FROM
t v1 JOIN t v2 ON abs(v1.value - v2.value) < 20
)
GROUP BY v1_id HAVING COUNT(*) > 1
ORDER BY v1_sort_me ASC
)
``` |
As mentioned [here](https://github.com/jupyterlab/jupyterlab/issues/2044#issuecomment-1015377299), you can reuse existing kernel by using `--KernelProvisionerFactory.default_provisioner_name=pyxll-provisioner`.
For example:
```bash
STARTUP_CODE="a = 42"
export PYXLL_IPYTHON_CONNECTION_FILE="$(mktemp -d)/connection-file.json"
(printf "%s\n" "$STARTUP_CODE" && sleep infinity) |
jupyter console --kernel=python3 -f="$PYXLL_IPYTHON_CONNECTION_FILE" &
jupyter notebook --KernelProvisionerFactory.default_provisioner_name=pyxll-provisioner --log-level=ERROR
```
```
0.00s - Debugger warning: It seems that frozen modules are being used, which may
0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off
0.00s - to python to disable frozen modules.
0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.
0.00s - Debugger warning: It seems that frozen modules are being used, which may
0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off
0.00s - to python to disable frozen modules.
0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.
[I 2024-03-31 03:19:56.892 LabApp] JupyterLab extension loaded from /home/nixos/demo/.venv/lib/python3.11/site-packages/jupyterlab
[I 2024-03-31 03:19:56.893 LabApp] JupyterLab application directory is /home/nixos/peftai/.venv/share/jupyter/lab
[I 2024-03-31 03:19:56.893 LabApp] Extension Manager is 'pypi'.
Warning: Input is not a terminal (fd=0).
Jupyter console 6.6.3
Python 3.11.8 (main, Feb 6 2024, 21:21:21) [GCC 13.2.0]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.16.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: In [1]: a = 42
In [2]: ^[[23;1R[C 2024-03-31 03:19:59.664 ServerApp]
To access the server, open this file in a browser:
file:///home/nixos/.local/share/jupyter/runtime/jpserver-93926-open.html
Or copy and paste one of these URLs:
http://localhost:8888/tree?token=da6ee2fac54afc8591bb9c2de3039036fb15bd5150002e29
http://127.0.0.1:8888/tree?token=da6ee2fac54afc8591bb9c2de3039036fb15bd5150002e29
WARNING: your terminal doesn't support cursor position requests (CPR).
In [2]: 0.00s - Debugger warning: It seems that frozen modules are being used, which may
0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off
0.00s - to python to disable frozen modules.
0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.
```
You can see `jupyter console` executes `a = 42` and holds on the kernel, then all `jupyter notebook` kernels will reuse the existing kernel, where `a` is initialized to `42` out-of-box.
[![Jupyter Notebook][1]][1]
[1]: https://i.stack.imgur.com/6486D.png |
[`git-subtree`](https://github.com/git/git/blob/master/contrib/subtree/git-subtree.txt) is a script designed for exactly this use case of merging multiple repositories into one while preserving history (and/or splitting history of subtrees, though that seems to be irrelevant to this question). It is distributed as part of the git tree [since release 1.7.11](https://github.com/git/git/commit/634392b26275fe5436c0ea131bc89b46476aa4ae).
To merge a repository `<repo>` at revision `<rev>` as subdirectory `<prefix>`, use `git subtree add` as follows:
git subtree add -P <prefix> <repo> <rev>
git-subtree implements the [subtree merge strategy](https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging#_subtree_merge) in a more user friendly manner.
For your case, inside repository YYY, you would run:
git subtree add -P ZZZ /path/to/XXX.git master
The **downside** is that in the merged history the files are unprefixed (not in a subdirectory). As a result `git log ZZZ/a` will show you all the changes (if any) except those in the merged history. You can do:
git log --follow -- a
but that won't show the changes other then in the merged history.
In other words, if you don't change `ZZZ`'s files in repository `XXX`, then you need to specify `--follow` and an unprefixed path. If you change them in both repositories, then you have 2 commands, none of which shows all the changes.
More on it [here](https://gist.github.com/x-yuri/8ad01701db51ec2891ca431b78c58c72#file-4-2-sh). |
{"Voters":[{"Id":3689450,"DisplayName":"VLAZ"},{"Id":5468463,"DisplayName":"Vega"},{"Id":522444,"DisplayName":"Hovercraft Full Of Eels"}],"SiteSpecificCloseReasonIds":[13]} |
Please advise how to control rows order in flextable.
For example, in the table [The Epidemiologist R Handbook](https://epirhandbook.com/en/index.html) the order of rows arranged in the ascending way, and Other and Missing rows in the midle of table. But I want to have these rows in the end. How to do this?
https://epirhandbook.com/en/tables-for-presentation.html
[enter image description here](https://i.stack.imgur.com/9vt9o.png)
I expected that rows order in the table will be looks like this:
Central Hospital
Military Hospital
Port Hospital
St. Mark's Maternity Hospital (SMMH)
Other
Missing
Total
|
Flextable R - change order of rows |
|r|row|flextable| |
null |
I have the following input
```
<input type="number" [ngModel]="inputValue" (ngModelChange)="handleChange($event)"/>
```
And I am trying to force the input to stay less or equal to 100.
using the method handleChange
```
export class AppComponent {
inputValue: number = 0;
handleChange($event: any) {
if ($event > 100) {
this.inputValue = 100;
}
}
}
```
And it only works the first time I enter the first input that is higher than 100, but after that it doesn't.
My understanding of it is that the DOM doesn't update when there are no value updates.
I can solve this problem using other methods like @ViewChild for example, **but I am more interested in knowing how this works and how angular handles this specific use case**.
Thanks! |
I'm trying to simulate it, but besides en/decoding, it will also designedly ignore part of the content, and I'm not sure is there more features I don't know.
Btw, maybe there is some diffrence when achieving it between Chrome, Edge and other modern explorers?
I think I've know the common en/decoding details in it. I prefer a complete document which I didn't find. |
What will the explorer do when I use the fuction "Copy Link To text"? |
|google-chrome| |
null |
I have installed evolution x custom rom via adb sideload.Now there is an update coming from evolution x team and i want to update it.But can i dirty flash it via adb sidelaod
I am getting issue in installing custom recovery. |
Having issue with dirty flash |
|pixel|rom| |
null |
You could have the `-exec` run each line via `bash -c` instead of `echo`ing it to a file to be run later. That would also enable (require, in fact) adjusting your quoting, ultimately allowing a simpler and clearer command. For example:
```
find ./build/html -name '*.html' \
-exec bash -c '../emojize_pngorsvg.py "{}" > "{}.emojized" && mv "{}.emojized" "{}"' \;
```
I took the liberty of some additional simplification, too. Specifically, it is unnecessary to remove the original file before `mv`ing the new one to the original name. Also, the `\(` and `\)` in the original command served no useful purpose, so I dropped them.
Also, I generally pipe `find`'s output into `xargs` instead of using an `-exec` action. You could consider that, but it probably does not provide enough advantage in this case to justify the conversion. |
{"OriginalQuestionIds":[41179199],"Voters":[{"Id":1159478,"DisplayName":"Servy","BindingReason":{"GoldTagBadge":".net"}}]} |
For `react-router-dom` version 5.3 I used `useHistory()`.
Sample code
```JavaScript
import React from 'react';
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const redirectToOverview = () => {
// Use the history.push method to navigate to /app/overview
history.push('/app/overview');
};
return (
<div>
{/* When this button is clicked, redirectToOverview will be called */}
<button onClick={redirectToOverview}>Go to Overview</button>
</div>
);
}
export default MyComponent;
``` |
### **How Can I Fix this, italic to Normal Style! ***[enter image description here](https://i.stack.imgur.com/qlGtZ.png)
I want to make it normal style without italic version. how can I achieve this, please solve me this. this italic version makes me so anger. now I want to make it simple and without italic version. |
How Can I Fix Sublime Text CSS Style italic to Normal? |
|html|css|sublimetext|sublime-text-plugin| |
null |
Cart ui not loading data after reload although data are in local storage
cart.js
```
import React, { useState } from "react";import { RxCross1 } from "react-icons/rx";import { IoBagHandleOutline } from "react-icons/io5";import { HiOutlineMinus, HiPlus } from "react-icons/hi";import { Link } from "react-router-dom";import styles from "../../../styles/style";import { useDispatch, useSelector } from "react-redux";import { addToCart, removeFromCart } from "../../../redux/actions/cart";import { toast } from "react-toastify";// import EmptyCart from "../../../assets/images/emptyCart.png";import EmptyCart from "../../../assets/images/empty-cart.jpg";
const Cart = ({ setOpenCart }) => { const { cart } = useSelector((state) => state.cart); const dispatch = useDispatch(); // console.log(cart);
const removeFromCartHandler = (data) => { dispatch(removeFromCart(data)); };
const totalPrice = cart.reduce( (acc, item) => acc + item.qty * item.discountPrice, 0 );
const quantityChangeHandler = (data) => { dispatch(addToCart(data)); }; return ( <div className="fixed top-0 w-full left-0 h-screen z-10 bg-[#0000004b]"> <div className="fixed top-0 right-0 min-h-full w-[25%] shadow-sm bg-white flex flex-col justify-between"> {cart && cart.length === 0 ? ( <div className="w-full h-screen flex items-center justify-center"> <div className={`flex w-full justify-end fixed pt-5 pr-5 top-3 right-3`} > <RxCross1 size={25} className="cursor-pointer" onClick={() => setOpenCart(false)} /> </div> <div className="text-center items-center justify-center"> <img src={EmptyCart} alt="" className="w-full h-min p-2 mb-2 object-cover" /> <h5 className="font-semibold">Your cart is empty</h5> </div> </div> ) : ( <> <div> <div className="flex w-full justify-end pt-5 pr-5"> <RxCross1 size={25} className="cursor-pointer" onClick={() => setOpenCart(false)} /> </div> {/* Items length */} <div className={`${styles.normalFlex} p-4`}> <IoBagHandleOutline size={25} /> <h5 className="pl-2 font-[500] text-[20px]"> {cart && cart.length} items </h5> </div> {/* cart single items */} <br /> <div className="w-full border-t"> {cart && cart.map((i, index) => ( <CartSingle key={index} data={i} quantityChangeHandler={quantityChangeHandler} removeFromCartHandler={removeFromCartHandler} /> ))} </div> </div> </> )}
<div className="px-5 mb-3"> {/* Check Out Button */} <Link to={`/checkout`}> <div className="h-[45px] flex items-center justify-center w-[100%] bg-[#e44343] rounded-[5px]"> <h1 className="text-[#fff] text-[15px] font-[600]"> Checkout Now (USD ${totalPrice}) </h1> </div> </Link> </div> </div> </div> );};
const CartSingle = ({ data, quantityChangeHandler, removeFromCartHandler }) => { const [value, setValue] = useState(data.qty); const totalPrice = data.discountPrice * value;
const increment = (data) => { if (data.stock < value) { toast.error(`Product Stock limited`); } else { setValue(value + 1); const updatecartData = { ...data, qty: value + 1 }; quantityChangeHandler(updatecartData); } }; const decrement = (data) => { setValue(value === 1 ? 1 : value - 1); const updatecartData = { ...data, qty: value === 1 ? 1 : value - 1 }; quantityChangeHandler(updatecartData); }; return ( <div className="border-b p-4"> <div className="w-full flex items-center"> <div> <div className={`bg-[#e44343] border border-[#e4434373] rounded-full w-[25px] h-[25px] ${styles.normalFlex} justify-center cursor-pointer`} onClick={() => increment(data)} > <HiPlus size={18} color="#fff" /> </div> <span className="pl-[10px]">{data.qty}</span> <div className="bg-[#a7abb14f] rounded-full h-[25px] flex items-center justify-center cursor-pointer" onClick={() => decrement(data)} > <HiOutlineMinus size={16} color="#7d879c" /> </div> </div> <img src={data.images[0].url} alt="" className="w-[100px] h-min mr-2 rounded-[5px] object-cover ml-2" /> <div className="pl-[5px]"> <h1>{data.name}</h1> <h4 className="font-[400] text-[15px] text-[#00000082]"> ${data.discountPrice}*{value} </h4> <h4 className="font-[600] text-[17px] pt-[3px] text-[#d02222] font-Roboto"> US ${totalPrice} </h4> </div> <RxCross1 className="cursor-pointer" onClick={() => removeFromCartHandler(data)} /> </div> </div> );};
export default Cart;
```
To display cartItems after reloding a web page. |
With "Android Studio 2023.2.1", now in 2024-04, it is like this:
5.1 ( Burger Menu ) > Build > Rebuild Project
”( Burger Menu ) > Build > Select Build Variant…”.
“Build Variants:”.
“Module” = ”:app”
“Active Build Variant”.
“debug ( default )”.
“release”.
”( Burger Menu ) > Build > Rebuild Project”.
“AndroidStudioProjects\{project name}\app\build\outputs\apk\debug\app-debug.apk”.
“AndroidStudioProjects\{project name}\app\build\outputs\apk\release\app-release-unsigned.apk”.
You may either create a “debug” or a “release” item.
One directory with the item is created. Other items in the directory are deleted.
If the other directory exist, it is deleted.
When building a “release” build, the “debug” directory is deleted.
When building a “debug” build, the “release” directory is deleted.
So you can't generate “bundle” files by this.
So you may have just either a “debug” or a “release” item at the same time :-).
5.2 ( Burger Menu ) > Build > Build Bundle(s) / APK(s)
”( Burger Menu ) > Build > Select Build Variant…”.
“Build Variants:”.
“Module” = ”:app”
“Active Build Variant”.
“debug ( default )”.
“release”.
”( Burger Menu ) > Build > Build Bundle(s) / APK(s)”.
“Build APK(s)”:
“AndroidStudioProjects\{project name}\app\build\outputs\apk\debug\app-debug.apk”.
“AndroidStudioProjects\{project name}\app\build\outputs\apk\release\app-release-unsigned.apk”.
“Build Bundle(s)”.
“AndroidStudioProjects\{project name}\app\build\outputs\bundle\debug\app-debug.aab”.
“AndroidStudioProjects\{project name}\app\build\outputs\bundle\release\app-release.aab”.
You may either create a “debug” or a “release” item.
One directory with the item is created. Other items in the directory are deleted.
If the other directory exist, it is not deleted.
So you may have “apk” and “bundle” directories and so “apk” and “bundle” files at the same time :-).
5.3 ( Burger Menu ) > Build > Generate Signed Bundle / APK...
”( Burger Menu ) > Build > Generate Signed Bundle / APK…”.
“Build APK(s)”.
“AndroidStudioProjects\{project name}\app\debug\app-debug.apk”.
“AndroidStudioProjects\{project name}\app\release\app-release.apk”.
“Build Bundle(s)”
“AndroidStudioProjects\{project name}\app\debug\app-debug.aab”.
“AndroidStudioProjects\{project name}\app\release\app-release.aab”.
You may either create “debug” or “release” items, or “debug” and “release” items at the same time.
One directory with the item is created. Other items in the directory are deleted.
If one item is generated, and if the other directories exist, they are not deleted.
So you may have “debug” and “release” directories directories at the same time :-). But you can have either “apk” and “bundle” files at the same time :-(.
|
{"Voters":[{"Id":9952196,"DisplayName":"Shawn"},{"Id":9214357,"DisplayName":"Zephyr"},{"Id":4850040,"DisplayName":"Toby Speight"}],"SiteSpecificCloseReasonIds":[18]} |
```
import React from "react";
export default function TestComponent(){
const [booValue, setBoolValue] = React.useState(false)
React.useEffect(() => {
setBoolValue(!booValue);
},[])
React.useEffect(() => {
console.log('booValue is', booValue)
},[booValue])
return (
<></>
)
}
```
What to do not to print twice. **Its not in StrictMode**
```
boolValue is false
boolValue is true
```
tried default value as undefined, i assume that `useEffect` triggers on setting default values. tried with null values too. |
{"OriginalQuestionIds":[574594],"Voters":[{"Id":10871900,"DisplayName":"dan1st might be happy again"},{"Id":642706,"DisplayName":"Basil Bourque","BindingReason":{"GoldTagBadge":"java"}}]} |
Found out that the key mapping for basic movement is initialized when the character is spawned to the world. The reason that movement does not work let alone moving the camera is, that the input mapping references the player controller and at the point of spawning the pawn, the controller assigned is not the controller controlling the pawn in the future.
The solution is to turn the input mapping into an event and call the event after possessing the pawn using Client RPC.
[Input Mapping in ThridPersonCharacter][1]
[1]: https://i.stack.imgur.com/3UIvT.png |
I'm pretty new to SQL and I have 12 tables with the same schema containing the same types of data from 12 months, and I need to merge them all into one big table. How can I do this in BigQuery using SQL?
I have tried creating a temp table, which is all well and good, but I want to be able to come back to it later. |
|sql|google-cloud-platform|google-bigquery|merge| |
null |
from https://www.warp.dev/blog/how-to-open-warp-vscode
1. VS Code > Settings > Preferences
2. Type "terminal" into the search bar
3. Where it says "Terminal > External: Osx Exec", replace whatever is there with "warp.app"
4. Now when you press Command + Shift + C, a new session of Warp should pop up.
|
I am new to typescript and I am using next auth to build a project I faced this and I do not know why this is happening I checked the next auth files and wrote this question this is not a typescript question since I tried it in a normal ts file and it was working as expected. I am just curious and want an answer to this
**I have this config that is working but it should not**
import nextAuth from "next-auth/next";
import { AuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
export const authOptions: AuthOptions = {
providers: [
CredentialsProvider({
credentials: {
email: {},
password: {},
},
async authorize(credentials) {
const user = { id: "hello", name: "jay", password: "dave" };
if (!user || !user.password) return null;
const passwordsMatch = user.password === credentials?.password;
if (passwordsMatch) return user;
return null;
},
}),
],
};
export default nextAuth(authOptions);
this is how credentials config interface is defined
export interface CredentialsConfig<
C extends Record<string, CredentialInput> = Record<string, CredentialInput>
> extends CommonProviderOptions {
type: "credentials"
credentials: C
authorize: (
credentials: Record<keyof C, string> | undefined,
req: Pick<RequestInternal, "body" | "query" | "headers" | "method">
) => Awaitable<User | null>
}
as you can see it returns awaitable user and user is defined like this
export interface DefaultUser {
id: string
name?: string | null
email?: string | null
image?: string | null
}
/**
* The shape of the returned object in the OAuth providers' `profile` callback,
* available in the `jwt` and `session` callbacks,
* or the second parameter of the `session` callback, when using a database.
*
* [`signIn` callback](https://next-auth.js.org/configuration/callbacks#sign-in-callback) |
* [`session` callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) |
* [`jwt` callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) |
* [`profile` OAuth provider callback](https://next-auth.js.org/configuration/providers#using-a-custom-provider)
*/
export interface User extends DefaultUser {}
awaitable is like this
export type Awaitable<T> = T | PromiseLike<T>;
as you can see password is not part of User in the interface then why is it working
|
From .NET 4.5 it can be handled as follows,
void DoDynamicCall()
{
MethodInfo method = /*referencing MyClass method void MyStaticFunction(int x)*/;
try
{
method.Invoke(null, new object[] { 5 });
}
catch (TargetInvocationException e)
{
//Capture an exception and re-throw it without changing the stack-trace
ExceptionDispatchInfo.Capture(e.InnerException ?? e).Throw();
throw;
}
} |
I dont quite understand why have we used .clone() method when we have a second for loop to restore the letterCount.And when i'm runnig this code without .clone() method its giving me the wrong answer? So what exactly is the need
public int solution(String[] words, int[] letterCount, int[] score, int ind) {
if (ind == words.length)
return 0;
int sno = solution(words, letterCount.clone(), score, ind + 1); // Skip word
String word = words[ind];
int sword = 0;
boolean flag = true;
for (char ch : word.toCharArray()) {
int letterIndex = ch - 'a';
if (letterCount[letterIndex] == 0) {
flag = false;
break;
}
letterCount[letterIndex]--;
sword += score[letterIndex];
}
int syes = 0;
if (flag)
syes = sword + solution(words, letterCount, score, ind + 1); // Use word
// Restore letterCount
for (char ch : word.toCharArray()) {
letterCount[ch - 'a']++;
}
return Math.max(sno, syes);
}
} |
Leetcode 1255-recursion and backtracking |
|java|recursion|dynamic-programming|clone|backtracking| |
null |
According the instruction in Next.js docs [here](https://nextjs.org/docs/messages/app-static-to-dynamic-error), you can use `export const dynamic = 'force-dynamic';` like in the bellow example:
```js
export const dynamic = 'force-dynamic'; // <- add this to force dynamic render
export const getUsers = async (request) => {
const url = new URL(request.url);
...
```
In my code, i used it like this:
```js
export const dynamic = 'force-dynamic';
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
...
```
|
Diving deep into azure development and can't find any logical solution for load testing of AppService that is using OpenAI services.
I suppose there should be some "load testing mode" for Azure Open AI. Maybe separate testing model that will behave like a regular OpenAI model but will not cost a lot of money as a real one does. But I can't find one.
There is always an option to mock calls to OpenAI and simulate response with some delay but I can't believe Microsoft doesn't have smart solution. |
Azure openai load testing mode |