instruction stringlengths 0 30k ⌀ |
|---|
|python|matrix|diagonal| |
I have a very simple to-do app with a form and a list of to-dos, built in Fiber and HTMX. When the user adds a new to-do via the form, I want HTMX to refresh the list of todos. I know I can use `hx-swap-oob`, but then I'm returning the new To-Do as part of my form partial, and that doesn't feel correct.
According to the [HTMX Docs](https://htmx.org/examples/update-other-content/#events), I can set an `HX-Trigger` response header.
So, in Fiber, this is what the code for my `POST /todos` handler looks like:
```go
func (h *TodoHandler) Create(c *fiber.Ctx) error {
// do stuff to create the todo and persist it...
c.Context().Response.Header.Set("HX-Trigger", "newTodo")
return adaptor.HTTPHandler(templ.Handler(partial.TodoForm(&td)))(c)
}
```
This seems to work, but the header is being set to `Hx-Trigger`, not `HX-Trigger`. How can I force Fiber (or the underlying fasthttp) to respect the casing for the header name?
[![Picture showing the header name as Hx-Trigger][1]][1]
[1]: https://i.stack.imgur.com/9WiDo.png |
Go Fiber and HTMX - HX-Trigger header is changed to Hx-Trigger, which is not what HTMX is listening for |
|go|htmx|go-fiber| |
I'm currently working on a topic model in R for the purpose of extracting topics from groups of tasks. I've been using an LDA with the topicmodels package, and while this runs, it's not exactly what I'm looking for in terms of topic coherence. I've tried separating these tasks to one document each, and while this has yielded slightly better results, I would like to explore options that could produce even better results. I recently read a paper on the effectiveness of a GSDMM on extracting topics from short-form text documents, and I want to pursue this type of topic model in R.
I am fairly new to topic modeling in R, and after some research into GSDMM, I haven't been able to find a lot of literature on doing one in R.
I am just curious if this is possible in R, and if so, what would that look like? I know that this topic modeling technique is more complex to do compared to an LDA, but I would just like some advice on where to look for info.
Like I had mentioned, I've run an LDA and it produces results, but I would like my topics to be less related to each other. Breaking down these tasks and lowering the alpha value did yield better results. |
Is it possible (or necessary) to run a GSDMM topic model in R? |
|lda|topic-modeling|topicmodels| |
null |
I have a main website example.com and another website subsidary.com.
The subsidary.com website is to be phased out and redirects put in place.
`subsidary.com` will have its A record repointed to `example.com` and a domain added in cPanel for `example.com`
Most of the entries in htaccess are straightforward, of the form
Redirect 301 /old-page-1 https://example.com/new-page-1
Redirect 301 /old-page-2 https://example.com/new-page-2
Redirect 301 /old-page-3 https://example.com/new-page-1
...
where old-page-1, 2 and 3 **do not** exist as URLs on the new site
So far, so good. My problem is that I need to direct the home page of the old site to a specific page on the new site.
Obviously I can't do
Redirect 301 / https://example.com/new-landing-page-subsidary-com
How do I target the old URL so that someone requesting `https://subsidary.com` is correctly redirected to `https://example.com/new-landing-page-subsidary-com`
|
301 Redirect to assimilate one website into another |
|redirect|http-status-code-301| |
I have collection with below documents:
_id : "123"
name : "rahul"
age : 40
experience: "10"
_id : "124"
name : "manish"
age : 42
experience: "12"
I want to find the sum of all the ages and also experience:
I am using below query:
db.emp_data.aggregate({
group:
{
_id: null,
totalCap: {
$sum: "$age",
},
},
})
But , i am getting empty records. What condition should i put in the _id field?
|
How do i find the sum of a field in Mongo with specific conditions? |
|jquery|mongodb|collections|field|compass| |
Compression was supported by TLS v1.2 and earlier but is prohibited in TLS v1.3 and higher, since compression creates known bit patterns which greatly ease hacking attempts. As such, you should assume that no compression will be done by HTTPS/TLS and if you want compression, must enable it on the HTTP level. |
You can do this with a mapped conditional type. First, let's describe the basic shape of your `settings` param:
```
type GetSettingsParamObject = Record<
string,
| { setting: StringSetting }
| { setting: StringSettingWithParam; param: string }
| { setting: ArrayOfStringsSetting }
>;
```
We'll use that as the `extends` clause of a generic parameter on `getSetting`:
```
function getSetting<ParamType extends GetSettingsParamObject>(
settings: ParamType
): GetSettingsResult<ParamType> {
// ...
}
```
So now we need to create the `GetSettingsResult` mapped type that maps those keys to their equivalent return types:
```
type GetSettingsResult<ParamType extends GetSettingsParamObject> = {
[Key in keyof ParamType]: ParamType[Key]["setting"] extends StringSetting
? string
: ParamType[Key]["setting"] extends StringSettingWithParam
? string
: string[];
};
```
[Playground link][1]
[1]: https://www.typescriptlang.org/play?#code/C4TwDgpgBAysBOBLAdgcxhYwWqgXigCIB7AV2DHIAUBDYAC0KgB8iAzRAGwgDkaBbCIQDcAKFCRYCHBiw4A6oga14A-EQj8aXAIIATPfAgBnY01aF6xQQBFERgMbBi8ECPHhoO+KpAB5NjgkNGNZbDR1QhRKYFoGMzEPSQBxTDCcYxUBPwAjACsIJ3UAJUKXPQAeUSgaqGNpNAAaatrWAG86zHDUAC4pYPQunCgAXxaa9s65ND6gmSG0RWUaVX5hKDAVgT76gdHxligO4wXeqG9fALmQ9IixgD5EiWhU4FvUY1LjUk5gCqz+AAVTxQCAAD2AEGQemMUFe70yW34uQKTnu6jaBwA2gBpCAgKAoKAAa3xxDYUABwMgAF0+lTPLj8TSsYQTtNUIQaaCIVCYf15hyDrUoAB+OoNVDC2r0pHUiBMkAstmnLk8yHQ2HXQYcpb0AHSmri3Y4Q1QHaSrE0sQjRJsUjIJyIYjIKCoNKnf5ykHgjX8+GnRGrFGFYD3AAUB3Z3WMstW8tEAEo+gGOZ8TD8-gzIOjMSKHC7jMRuAA6TjEVDh6MZRNiEVGYCkeCu5A-ThQGiwmjIEA20SiAvIepQIzfX7qd1vU7hvO1Gh9Y6nPokcgxOKMUbNEU5BdTbrLzTaTj6QwmMyNDZI5ekE7wHRMEZb2oOXfVmZEaLUOj0Myb0QjWsB0LYsIDLCtw1HTMSxoQCAHpYJFRCkJqAA9UUgKHECwMrSDfhLHI4IQ5DiKgNCMKLUtyxwjM8IcQiSOIsigA |
I have images like this [![Orig OCR image][1]][1]
When trying to use C# TesseractOCR to read them, I sometimes get result 38845283-05 which is incorrect because the '3' at the beginning is something that should not be there.
This is page.ThresholdedImage image directly from Tesseract result:
[![thresholded image][2]][2]
Even if I pass this image to Tesseract I get the same wrong 38845283-05 result.
Or in this: [![date image][3]][3] I get 13.11.238 even though I have ROI region set quite near the characters.
Seems like 3 or 8 are being recognized twice.
I have tried different EngineModes, different PageSegModes but I have not found reliable settings yet.
Do you have some advice? ( Except training :) )
Thank you.
Even on tesseract.projectnaptha.com the result is wrong:
[![enter image description here][4]][4]
[1]: https://i.stack.imgur.com/WOsO1.png
[2]: https://i.stack.imgur.com/0hjqQ.png
[3]: https://i.stack.imgur.com/hTTcW.png
[4]: https://i.stack.imgur.com/yxSYa.png |
Using NOT LIKE and OR statement together producing FALSE output |
There's possible solutions:
1- Is to close the keyboard before popping the screen, using `FocusManager.instance.primaryFocus?.unfocus();`
2- Is to set the resizeToAvoidBottomInset property in the first screen to `false`. |
Error is occur due to .next folder is not present in your that is related to your build folder
You need to start **npm run build** than start the server again it's getting works |
I’m new to programing in C and have run into a problem trying to add a value to an array.
When trying to ad the value the following error is thrown: “subscripted value is neither array nor pointer nor vector”.
If someone could help me out, I would be thankful
Here is my code:
The array is declared in the main function as followed:
```
int main(void) {
entity_e *entity = spawnEntity(1, 2, 140, 30, 1, 1, 5, 2, 1, 1);
int xyGrid[10][5];
while(1) {
updateEntity(entity, xyGrid, -1, 1);
}
}
```
The update Entity function calls on the array, and tries to pass a value to it:
```
void updateEntity(entity_e *entity, int *xyGrid, int32_t kx, int32_t ky) {
for(int i=0; i<5; i ++) {
gotoxy(entity[i].x_position, entity[i].y_position);
printf("%s", " ");
xyGrid[entity[i].x_position][entity[i].y_position] = 0; #Error accrues here.
}
}
```
The values for (entity[i].x_position) and (entity[i].x_position) are generated in the spawnEntity function:
```
entity_e* spawnEntity(int8_t indexMin, int8_t indexMax, int8_t xPosition, int8_t yPosition]) {
static entity_e spawn[3];
for(int i=indexMin; i<indexMax; i++) {
spawn[i].x_position = xPosition;
spawn[i].y_position = yPosition;
}
return spawn;
}
```
Thank you for your time. |
|java|spring|apache-kafka|microservices|reactive| |
I'm trying to handle a text file containing a list of numbers (generated from a python script) into a LUA script.
the text file contain this (I formatted it in the python script to match the list syntax of LUA) :
{"0.0", "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0", "834.3", "1667.6", "2500.9", "3334.2", "4167.5", "5000.8", "5834.1", "6667.4", "7500.7", "8334.0", "9167.3", "10000.6", "10833.9", "11667.2", "12500.5", "13333.8", "14167.1", "15000.4", "15833.7", "16667.0", "17500.3", "18333.6", "19166.9", "20000.2", "20833.5", "21666.8", "22500.1", "23333.4", "24166.7", "25000.0", "22244444.44", "44463888.89", "66683333.33", "88902777.78", "111122222.22", "133341666.67", "155561111.11", "177780555.56", "200000000.0", }
However when I try to read it in LUA, first I use this command (where "params.style_weight_list" is a link to the text file previously generated) :
print("SW LIST = ",params.style_weight_list)
which gives me this result :
SW LIST = {"0.0", "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0", "834.3", "1667.6", "2500.9", "3334.2", "4167.5", "5000.8", "5834.1", "6667.4", "7500.7", "8334.0", "9167.3", "10000.6", "10833.9", "11667.2", "12500.5", "13333.8", "14167.1", "15000.4", "15833.7", "16667.0", "17500.3", "18333.6", "19166.9", "20000.2", "20833.5", "21666.8", "22500.1", "23333.4", "24166.7", "25000.0", "22244444.44", "44463888.89", "66683333.33", "88902777.78", "111122222.22", "133341666.67", "155561111.11", "177780555.56", "200000000.0", }
yet everything seems good (there is several blank spaces before the first bracket, don't know why though)
but when I try to access a specific item from the list this way (frameIdx is an int) :
local neu_sw = params.style_weight_list[frameIdx]
it return a nil value, so I think I got to convert the imported list from a string to a proper usable list in LUA but don't know how? Anybody has an idea? |
This problem comes when there is no input value passing in routerchain, If you can provide logs from langsmith we can detect problem more easily.
Or you can try this: https://towardsdatascience.com/a-gentle-intro-to-chaining-llms-agents-and-utils-via-langchain-16cd385fca81
which contains same use case.
Currently, i am seeing there are lots of problem in RouterChain, and it's evolving in daily basis. Support of routerchaining is more promising in Nodejs rather than python |
This happened to me. I had a Vim extension enabled in vscode. Disable it if you have one installed. You can go to your extensions and type vim. You should be able to see the one you installed and disable it. |
I create an array of size 50 for example without any value, then I insert let's say 3 values in it at random indexes and then I want to fill the rest of the array by interpolating between those values.
First I create my array:
n = 50
a = [None]*n
which give me an "empty array" of 50 slots:
[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]
then I replace manually several "None" randomly chosen with values:
a.pop(0)
a.insert(0,0)
a.pop(10)
a.insert(10,50)
a.pop(49)
a.insert(49,25000)
which give this:
[0, None, None, None, None, None, None, None, None, None, 50, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 25000]
How can I fill the rest of the array, meaning replacing the "Nones" by actual values calculated by linear interpolation between the values I manually added in my array? |
```
m = [[[math.inf] * 10] for i in range(10)]
for i in range(len(m)):
for j in range(len(m)):
if(i == j):
m[i][i] = 0
```
[![][1]][1]
[1]: https://i.stack.imgur.com/YypkA.png
I try to insert zero And I used the debugger to watch the process go. Instead of changing it to
```
[[[0,inf,inf,inf,inf,inf,inf,inf,inf,inf],[......],[.......]]]
```
It changes it to
```
[[0], [[inf,inf,inf,inf....],[inf,inf,....]]
```
Which then causes an index out of bound error because it just reduced a 10x10 matrix to the top row being zero,
as opposed to `inf,inf,inf,inf,inf,inf,inf,inf,inf,inf`.
Where my goal is to set a 10x10 matrix's diagonal to all zeros.
I tried to use:
```
m = [[[math.inf] * 10] for i in range(10)]
``` |
Setting diagonal of a matrix to zero |
Hey all I am wondering how I can have a generic call to one of my classes so that I can minimize my code.
Currently I have a at of if else code that determines which class should be loaded up.
As an example in my MainActivity:
if (btnName.equals("up"))
if (globalRoom.equals("ABC")) {
btnNumber = 0;
ABC.sendTheCmd("?action=volume_up", globalTV, all_TvType, btnNumber, false);
}
else if (globalRoom.equals("NBC")) {
btnNumber = 1;
NBC.sendTheCmd("?action=volume_up", globalTV, all_TvType, btnNumber, false);
}
else if (globalRoom.equals("CBS")) {
btnNumber = 2;
CBS.sendTheCmd("?action=volume_up", globalTV, all_TvType, btnNumber, false);
}
else if (globalRoom.equals("REK")) {
btnNumber = 3;
REK.sendTheCmd("?action=volume_up", globalTV, all_TvType, btnNumber, false);
}
else if (globalRoom.equals("DSR")) {
btnNumber = 4;
DSR.sendTheCmd("?action=volume_up", globalTV, all_TvType, btnNumber, false);
}
else if (globalRoom.equals("LR2")) {
btnNumber = 0;
LR2.sendTheCmd("?action=volume_up", globalTV, all_TvType, btnNumber, false);
}
} else if (btnName.equals("down"))
if (globalRoom.equals("ABC")) {
btnNumber = 0;
ABC.sendTheCmd("?action=volume_down", globalTV, all_TvType, btnNumber, false);
}
else if (globalRoom.equals("NBC")) {
btnNumber = 1;
NBC.sendTheCmd("?action=volume_down", globalTV, all_TvType, btnNumber, false);
}
else if (globalRoom.equals("CBS")) {
btnNumber = 2;
CBS.sendTheCmd("?action=volume_down", globalTV, all_TvType, btnNumber, false);
}
else if (globalRoom.equals("REK")) {
btnNumber = 3;
REK.sendTheCmd("?action=volume_down", globalTV, all_TvType, btnNumber, false);
}
else if (globalRoom.equals("DSR")) {
btnNumber = 4;
DSR.sendTheCmd("?action=volume_down", globalTV, all_TvType, btnNumber, false);
}
else if (globalRoom.equals("LR2")) {
btnNumber = 0;
LR2.sendTheCmd("?action=volume_down", globalTV, all_TvType, btnNumber, false);
}
} etc etc....
In each of my classes ABC.java class:
public class ABC {
public static void sendTheCmd(String theCmd, String TV, List<ThemedButton> all_TvType, btnNumber, Boolean keyboard) {
try {
...
} catch (Exception e) {
Log.d("", e.getMessage());
}
return null;
}
}
NBC.java class:
public class NBC {
public static void sendTheCmd(String theCmd, String TV, List<ThemedButton> all_TvType, btnNumber, Boolean keyboard) {
try {
...
} catch (Exception e) {
Log.d("", e.getMessage());
}
return null;
}
}
So instead of having all those if/else I would like to make a variable that holds any of those classes (ABC, NBC, CBS, etc...) so that I can do something like this instead:
GlobalClass GC;
if (globalRoom.equals("ABC")) { btnNumber = 0; GC = new ABC(); }
else if (globalRoom.equals("NBC")) { btnNumber = 1; GC = new NBC(); }
else if (globalRoom.equals("CBS")) { btnNumber = 2; GC = new CBS(); }
else if (globalRoom.equals("REK")) { btnNumber = 3; GC = new REK(); }
else if (globalRoom.equals("DSR")) { btnNumber = 4; GC = new DSR(); }
else if (globalRoom.equals("LR2")) { btnNumber = 0; GC = new LR2(); }
if (btnName.equals("up")) {
GC.sendTheCmd("?action=volume_up", globalTV, all_TvType, btnNumber, false);
} else if (btnName.equals("down")) {
GC.sendTheCmd("?action=volume_down", globalTV, all_TvType, btnNumber, false);
} else if (btnName.equals("Keyboard")) {
GC.sendTheCmd("text?", globalTV, all_TvType, btnNumber, false);
} else if (btnName.equals("Other")) {
//Not sure what to make this icon
}
I was thinking I could do something like this:
List<String, Class<?>> GC;
Then populate it like this:
GC.put("ABC", new ABC());
GC.put("NBC", new NBC());
GC.put("CBS", new CBS());
GC.put("REK", new REK());
GC.put("DSR", new DSR());
GC.put("LR2", new LR2());
But that does not seem to work as I was expecting it to.
Is there any way of doing this? |
Creating global Class holder |
|java|android| |
I have had to overcome this same kind of issue with a leaflet map being called via JSInterop. What I ended up doing was making the map div itself a component, with a bool parameter of "display: @isVisible ? block : none"
I put that component into my actual MainLayout.razor, which was my central layout for the multiple tabs I had.
Then I used a LocationChangingHandler via injected NavigationManager to detect when the user navigated to the "Map" page, setting that parameter true. |
I rewrote and simplified your code. Since I'm assuming you might want to choose different colors, I wrote a method specifically to choose a color based on the `colorName` parameter.
def select_color(colorName):
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, f"//div[./div[text()='{colorName}']]"))).click()
Then the main script looks like
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
url = 'https://www.digikala.com/product/dkp-4645665'
driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)
colorName = "آبی کاربنی"
select_color(colorName)
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='add-to-cart']"))).click()
# do other stuff
This selects the provided color and adds the item to the cart. |
It seems like this issue is related to authentication with the KubeAPI server. To troubleshoot and resolve this problem follow these steps:
**Check Kubernetes API Server Configuration:**
Ensure that your Python environment has access to the Kubernetes configuration file (~/.kube/config by default). This file contains the credentials and configuration details required to access the Kubernetes cluster.
**Verify Correct Context:**
Check if the Kubernetes configuration file specifies the correct context with the necessary permissions to list pods in the argocd namespace.
You can do this by running:
kubectl config current-context
**Test API Server Reachability:**
Verify that the Kubernetes API server is reachable from your Python environment using:
curl http://localhost:8080/api
Replace `localhost:8080` with the actual API server address if different, you can check your api server port by running `cat /etc/kubernetes/manifests/kube-apiserver.yaml`
**Add Authentication:**
If authentication is required by your Kubernetes API server and is not configured in your Python environment, set up authentication. This can involve using service account tokens, kubeconfig files with credentials, or other authentication methods based on your Kubernetes cluster setup.
**Debugging Output:**
Include more verbose output in your Python script to capture any error messages or details that might help diagnose the authentication issue.
Example:
import subprocess
try:
result = subprocess.run(["kubectl", "get", "pods", "-n", "argocd"], capture_output=True, text=True, check=True)
print("Output:", result.stdout)
except subprocess.CalledProcessError as e:
print("Error:", e)
print("Error Output:", e.stderr) |
|asp.net-core-webapi|.net-6.0|azure-keyvault|docker-desktop|azure-identity| |
As per React documentation, [you cannot call hooks conditionally][1].
[Here][2] is explained in depth why.
When the need to call a hook conditionally arises, you could opt for two soutions :
1. Either you call `useDataForm` and then you use `contactForm` only if `dataValid` is `true`
```jsx
const contactForm = useDataForm(onSubmit, modelToForm(dataValid));
if (dataValid) {
// do what you need to do with dataValid
}
// or
return <Child data={dataValid ? contactForm : otherData} />
```
2. Either you move the hook in a separate component and render said component only if `dataValid` is true
3. Either, depending on the hook, you can pass the arguments conditionally. e.g. in your exemple:
```jsx
const contactForm = useDataForm(onSubmit, dataValid ? modelToForm(dataValid) : fallbackArg);
```
## Edit:
The canary version of React introduces `use`, a new hook that will likely become a standard feature in the React 19 version. This hook supersedes the rule that hooks cannot be called conditionally or within loops. You may find a way to use this hook to solve your conundrum with the custom hook.
However, it's important to note that the other rules of hooks remain valid. Specifically, hooks must still be called at the top level of components or other hooks.
[1]: https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
[2]: https://reactjs.org/docs/hooks-rules.html#explanation |
To direct to the point, you can easily use xpath. The exact and simple way to do this using the below code. Kindly try and provide feedback. Thank you.
JavascriptExecutor js = (JavascriptExecutor) driver;
//To click an element
WebElement element=driver.findElement(By.xpath(Xpath));
js.executeScript(("arguments[0].click();", element);
//To gettext
String theTextIWant = (String) js.executeScript("return arguments[0].value;",driver.findElement(By.xpath("//input[@id='display-name']")));
Further readings -
https://medium.com/@smeesheady/webdriver-javascriptexecutor-interact-with-elements-and-open-and-handle-multiple-tabs-and-get-url-dcfda49bfa0f |
Here is an example of how to insert an image and resize to fit a range of cells.
**Code.gs**
function insertImage() {
try {
let spread = SpreadsheetApp.getActiveSpreadsheet();
let sheet = spread.getSheetByName("Sheet25");
let file = DriveApp.getFileById("1F..........................PF");
let range = sheet.getRange("A2:B4");
let size = getRangeSize(range);
console.log(JSON.stringify(size));
let image = sheet.insertImage(file.getBlob(),size.column,size.row);
image.setWidth(size.width);
image.setHeight(size.height);
}
catch(err) {
console.log("Error in test: "+err)
}
}
function getRangeSize(range) {
try {
let sheet = range.getSheet();
let rows = range.getHeight();
let columns = range.getWidth();
let row = range.getRow();
let column = range.getColumn();
let image = { row: row, column: column };
let width = 0;
let height = 0;
for( let i=1; i<=rows; i++ ) {
height = height+sheet.getRowHeight(row++);
}
for( let i=1; i<=columns; i++ ) {
width = width+sheet.getColumnWidth(column++);
}
image.width = width;
image.height = height;
return image;
}
catch(err) {
console.log("Error in getRangeSize: "+err);
}
}
Reference
- [Range.getSheet()][1]
- [Range.getHeight()][2]
- [Range.getWidth()][3]
- [Sheet.getRowHeight()][4]
- [Sheet.getColumnWidth()][5]
- [Sheet.insertImage()][6]
- [OverGridImage.setWidth()][7]
- [OverGridImage.setHeight()][8]
[1]: https://developers.google.com/apps-script/reference/spreadsheet/range#getSheet()
[2]: https://developers.google.com/apps-script/reference/spreadsheet/range#getheight
[3]: https://developers.google.com/apps-script/reference/spreadsheet/range#getwidth
[4]: https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrowheightrowposition
[5]: https://developers.google.com/apps-script/reference/spreadsheet/sheet#getcolumnwidthcolumnposition
[6]: https://developers.google.com/apps-script/reference/spreadsheet/sheet#insertimageblobsource,-column,-row
[7]: https://developers.google.com/apps-script/reference/spreadsheet/over-grid-image#setWidth(Integer)
[8]: https://developers.google.com/apps-script/reference/spreadsheet/over-grid-image#setheightheight |
The official [example](https://datatables.net/examples/ajax/custom_data_flat.html) explains that flat data sources should use `dataSrc: ''` in the option, and your option would look like this:
$("#tblNotes").DataTable({
"ajax" : {
"url": "/projects/ajaxGetProjectNotes/",
"type" : "post",
"dataType" : "json",
"data" : {"idProject" : "b92792db-9ea6-49bf-b4dc-1cdf3f441148"},
"dataSrc": '', // Add this one!
},
"columns" :
[
{"data" : "dComment", "width" : "130px", "orderable" : true},
{"data" : "cComment", "width" : "270px", "orderable" : false}
]
}); |
I am having problems with autocomplete of imported styles in JSX files.
Whenever i import styles from another files i dont get autocompletion.
Like i have a style in JS file:
```
searchWrapper: {
flex: 1,
backgroundColor: COLORS.white,
marginRight: SIZES.small,
justifyContent: "center",
alignItems: "center",
borderRadius: SIZES.medium,
height: "100%",
},
```
and i am importing it to JSX file.
Yet i dont get autocompletion.
```
<View styles={styles.searchContainer}>
<View styles={styles.}> //no autocompletion here
</View>
</View>
```
I am importing this file like so:
```
import styles from './welcome.style';
```
Code executes properly, but no autocompletion.
Also everything enabled:
Emmet file:
```
{
"python.defaultInterpreterPath": "C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python312\\python.exe",
"python.languageServer": "Pylance",
"workbench.iconTheme": "material-icon-theme",
"editor.largeFileOptimizations": false,
"editor.unicodeHighlight.ambiguousCharacters": false,
"redhat.telemetry.enabled": true,
"workbench.startupEditor": "none",
"workbench.colorTheme": "Visual Studio Dark",
"typescript.suggest.completeFunctionCalls": true,
"javascript.suggest.completeFunctionCalls": true,
"emmet.preferences": {
},
"emmet.includeLanguages": {
"javascript": "javascriptreact",
},
"emmet.syntaxProfiles": {
"javascript": "jsx"
},
"emmet.triggerExpansionOnTab": true,
"files.associations": {
"*.jsx": "javascriptreact"
}
}
```
|
VSC Autocomplete imported styles for JSX files |
|javascript|node.js|autocomplete| |
null |
{"OriginalQuestionIds":[123758],"Voters":[{"Id":12002570,"DisplayName":"user12002570","BindingReason":{"GoldTagBadge":"c++"}}]} |
In the Bellman equation for MRP, I cannot understand why:
expectation[ G_(t+1) | s_t = s] = expectation[ expectation[ G_(t+1) | s_(t+1)] | s_t = s].
How should I understand this?
[bellman equatin for MRP](https://i.stack.imgur.com/V6fW3.png)
Equations of the process of transformation. |
Bellman equation for MRP? |
null |
{"Voters":[{"Id":4369919,"DisplayName":"N69S"},{"Id":1255289,"DisplayName":"miken32"},{"Id":14732669,"DisplayName":"ray"}],"SiteSpecificCloseReasonIds":[13]} |
I installed OpenVINO dependencies and converted the model to OpenVINO format. I have OpenCL device available:
```
$ clinfo -l
Platform #0: Intel(R) OpenCL HD Graphics
`-- Device #0: Intel(R) Graphics [0xa7a0]
```
Trying to run `yolo predict` on a GPU, e.g.
```
yolo predict model=openvino_model source='samples/*.jpg' device=gpu
yolo predict model=openvino_model source='samples/*.jpg' device=0
```
always results in `Invalid CUDA device requested`. It runs fine on the CPU, though.
What parameter should I use for yolo to find and use OpenCL device #0? |
`sudo pip install` is most likely installing globally into a Python interpreter that is different than the one that you have selected in VS Code. Please [select the Python interpreter you want to use][1] and then install explicitly using that interpreter (if you're not using a virtual environment then use something like `/path/to/python -m pip install SimpleITK`, although I **strongly** recommend [using a virtual environment][2] and to not install packages globally).
[1]: https://code.visualstudio.com/docs/python/environments#_working-with-python-interpreters
[2]: https://code.visualstudio.com/docs/python/python-tutorial#_create-a-virtual-environment |
In your `ProductModel` schema the `category` property has a `name` property given to it. That suggests you want `category` to be an Object with a `name` property. I pressume that was not your intention. You need to remove that so that `category` is just a property with a value of type `ObjectId`.
````js
const ProductModel = new Schema({
//...
category: {
name: String, //< delete this
type: Schema.Types.ObjectId,
ref: 'Category',
},
})
````
To get the `product._id` into the `productCategory.products` array you need to manually push it to the array like so:
````js
const productCategory = await CategoryModel.find({ name: category })
console.log(productCategory)
// Creating product
const doc = new ProductModel({
productName,
price,
preview,
color,
specs,
category: productCategory._id,
})
// Save product
const product = await doc.save()
// Now save product._id into productCategory.products array
productCategory.products.push(product._id);
await productCategory.save();
// Returning a response from the server to the client
return res.json(product)
```` |
First of all, response.json() does not return a JavaScript object, it returns a Promise which resolves to a JavaScript object. Second, I can't recall how response.json() works but I have a feeling it 'runs' its input as regular JavaScript, which means if the MIME type returned by the server isn't application/javascript then it might not recognise it as runnable code. (Perhaps!)
First, try dumping/inspecting the data you get back from the server to double check it is indeed plain JSON. Then use JSON.parse() instead of response.json() to turn it from a string into an object. If the MIME type is indeed the problem, then JSON.parse() will work so long as you feed it a string, regardless of how the network headers described that string. |
I want to show text within an SVG which is wholly defined in js. The SVG picture shows as expected, but the text does not.
I have tried the actual SVG definition in an online SVG viewer and it has the same result: picture is good, but no text showing.
I create the following string in js and then use it as the content in an AdvancedMarkerElementmarker in Google Maps.
```
SVGstring = '<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-3 -49 52 52" > <style>svg { margin-top: 3px margin-bottom: 3px margin-right: 3px margin-left: 3px}</style> <path stroke="black" stroke-width="3" d="m 0,0 l 0,-25 l 23,0 l 7,-20 l 7,20 l 3,0 l 0,25 z" fill="#9494ff" /><text x="20" y="35" font = "20px sans-serif" fill="black" >999</text></svg>'
```
The google maps marker then has its content set by:
```
pinSvg = document.createElement('pinSvg');
pinSvg.innerHTML = SVGstring;
gMarkersA[mkrIndex].content = pinSvg;
```
|
subscripted value is neither array nor pointer nor vector (C) |
|arrays|c| |
null |
I am building a simple drag gesture animation in a **Rectangle()** that, in the end of the gesture, stick the shape in the closest item of a group.
Check the example in the image bellow.
I was able to achieve a decent result with the following approach:
- Manually computing the x absolute position of the black rectangles:
@State private var xPos : [Int] = [40,110,180,250,320]
- Placing the rectangles in the screen with a absolute position property:
Rectangle()
.position(x: CGFloat(xPos[i]), y: 0)
- Finally, in the blue Rectangle, add the gesture property, with a fancy func on .onEnded to find the closest element, and apply the x position accordingly.
Rectangle()
.fill(.blue)
.position(location)
.gesture(
DragGesture()
.onChanged { gesture in
location.x = gesture.location.x
}
.onEnded { value in
withAnimation(.spring()) {
var goal = Int(value.location.x)
var closest = xPos[0]
var index = 0
for item in xPos {
var distanceToActual = abs(closest - goal)
if (xPos.count - 1 > index) { // prevent out of the bound
var distanceToNext = abs(xPos[index + 1] - goal)
if(distanceToNext < distanceToActual) {
closest = xPos[index + 1]
}
}
index += 1
}
location.x = CGFloat(closest)
}
}
My question is, is there a more elegant way of doing it? It's very annoying to manually calc the position of the Black rectangles... Is there any way of doing this with the Black Rectangles placed in a HStack instead of manually position then?
[![A iphone screen if some Rectangles][1]][1]
[1]: https://i.stack.imgur.com/tkEYY.gif
|
How to build a DragGesture with a "sticky" behavior in SwifUI? |
|swift|swiftui|gesture|hstack|draggesture| |
```
from pysmt.shortcuts import *
from pysmt.typing import *
hello = [Symbol(s, INT) for s in "hello"]
pysmt = [Symbol(s, REAL) for s in "pysmt"]
domains_1 = And([And(GE(l, Int(1)),
LT(l, Int(10))) for l in hello])
domains_2 = And([And(GE(l, Real(1)),
LT(l, Real(10))) for l in pysmt])
sum_hello = Plus(hello) # n-ary operators can take lists
sum_pysmt = Plus(pysmt) # as arguments
problem = And(Equals(sum_hello, sum_pysmt),
Equals(sum_hello, Int(25)))
formula = And(domains_1, domains_2, problem)
print("Serialization of the formula:")
print(formula)
model = get_model(formula, solver_name="z3")
if model:
print(model)
else:
print("No solution found")
```
This code will display: PysmtTypeError: The formula `((h + e + l + l + o) = (p + y + s + m + t))` is not well-formed. |
{"OriginalQuestionIds":[2735783],"Voters":[{"Id":11182,"DisplayName":"Lex Li","BindingReason":{"GoldTagBadge":"c#"}}]} |
I found that this package solves the problem: [pure_dart_ui][1]. Replace this import
import 'dart:ui';
to
import 'package:pure_dart_ui/pure_dart_ui.dart';
[1]: https://pub.dev/packages/pure_dart_ui |
I follow https://www.infragistics.com/products/ignite-ui-react/react/components/general-getting-started
```
npx create-react-app MyAppName --typescript
npm install --save igniteui-react
npm install --save igniteui-react-charts igniteui-react-core
npm install --save igniteui-react-excel igniteui-react-core
npm install --save igniteui-react-gauges igniteui-react-core
npm install --save igniteui-react-grids igniteui-react-core
npm install --save igniteui-react-maps igniteui-react-core
npm install --save igniteui-react-spreadsheet igniteui-react-core
```
but result
[![enter image description here][1]][1]
Why I use parameter typescript, but still generate javascript project?
[1]: https://i.stack.imgur.com/lFMi5.png |
Why I use parameter typescript, but still generate javascript project? |
|javascript|reactjs|typescript|create-react-app|infragistics| |
In React, using something like updating on `document.body.scrollHeight` worked for me:
```jsx
const [viewHeight, setViewHeight] = useState<
string | number
>("100vh")
useEffect(() => {
setViewHeight(document.body.scrollHeight)
}, [document.body.scrollHeight])
...
return <div style={{ height: viewHeight }}>...</div>
``` |
{"Voters":[{"Id":839601,"DisplayName":"gnat"},{"Id":213269,"DisplayName":"Jonas"},{"Id":14732669,"DisplayName":"ray"}]} |
We're creating an app that uses custom icons that we made in Figma, some of which are faces, waving hands, etc. As of now, we're just using a default yellow color, but I think it would be a nice touch if we could just use the same settings as what the user has for their device. Does Flutter have a way of accessing and viewing those settings?
So far, I've looked around stackoverflow and GitHub issues, but I couldn't find anything at all. |
In Flutter, is there a way to determine the user's skin color settings for their emojies? |
|flutter|dart|colors|flutter-dependencies| |
null |
I have an application in Laravel 11 that is configured as follows in the `app.php` file:
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
apiPrefix: 'api/v0',
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
In `api.php` file, I have the following route:
Route::get('/updateAllMovies', [\App\Http\Controllers\APIController::class, 'updateAllMovies']);
Inside my `APIController`, I have this code:
public function updateAllMovies(APIRequest $request){
$validated = $request->validated();
if ($request->fails()) {
return response()->json(['errors' => $request->errors()], 422);
}
return response()->json(['success' => true], 200);
}
And finally inside my `APIRequest` I have:
class APIRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'access_token' => 'required|exists:tokens_access,token'
];
}
public function messages(){
return [
'access_token.required' => 'O token de acesso é obrigatório na requisição.',
'access_token.exists' => 'O token de acesso informado é inválido.'
];
}
}
When I try to make a request to the `/updateAllMovies` route via postman (Sending the `access_token` or not.), I am redirected to the main route that exists in the `web.php` file.
Route::get('/', function () {
return 'Welcome to my Cinema API ';
});
I would like to understand why this is happening, why don't I continue on the `api.php` route and don't receive any error messages? |
inline SVG text (js) |
|javascript|svg| |
null |
I'm struggling to edit a Jtabel with a picture on it.
So basically, I can edit the table ONLY if I edit the picture on it.
I can't edit anything if I am not editing the column on the picture on it:
trying to debug but the listener isn't doing the query on the server.
here's the code
```
public class VisualizzaprodottiPanel extends JPanel {
// Attribut
private JTable jtable;
private ListaProdottiTableModel tableModel;
private Set<Integer> righeModificate = new HashSet<>(); // Set per tenere traccia delle righe modificate
// Costruttore
public VisualizzaprodottiPanel() {
setLayout(new BorderLayout());
// Creazione del modello della tabella e inizializzazione dei dati
IArticoloDAO articoloDAO = ArticoloDAO.getInstance();
List<Prodotto> prodotti = articoloDAO.findAll();
tableModel = new ListaProdottiTableModel(prodotti, articoloDAO);
// Creazione della tabella con il modello
JTable tabellaProdotti = new JTable(tableModel);
tabellaProdotti.setRowHeight(100); // Altezza della riga
tabellaProdotti.setShowGrid(false); // Nasconde le linee di griglia
tabellaProdotti.setIntercellSpacing(new Dimension(0, 0)); // Nessuno spazio tra le celle
JButton modifica = new JButton("Modifica");
Map<Integer, String> imagePathMap = new HashMap<>();
modifica.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DbOperationExecutor executor = new DbOperationExecutor(); //conn database
for (int row : righeModificate) {
Prodotto p = new Prodotto();
p.setId(prodotti.get(row).getId()); //gestire dopo la roba degli id
p.setNome(tabellaProdotti.getValueAt(row,0).toString());
p.setTipoProdotto(IArticolo.TIPO_PRODOTTO.valueOf(tabellaProdotti.getValueAt(row,1).toString()));
p.setDisponibilita(Integer.valueOf(tabellaProdotti.getValueAt(row,2).toString()));
p.setPrezzo(Float.valueOf(tabellaProdotti.getValueAt(row,3).toString()));
p.setFoto(imagePathMap.get(row));
p.setDescrizione(tabellaProdotti.getValueAt(row,5).toString());
articoloDAO.updateProdotto(p);
}
// Pulisci il set delle righe modificate dopo l'aggiornamento nel database
righeModificate.clear();
}
});
tabellaProdotti.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
int column = tabellaProdotti.columnAtPoint(evt.getPoint());
if (column == 4) { // Controlla se il click è sulla colonna delle immagini
int row = tabellaProdotti.rowAtPoint(evt.getPoint());
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(VisualizzaprodottiPanel.this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
String imagePath = selectedFile.getAbsolutePath();
imagePath = imagePath.replace("\\", "\\\\");
// Aggiorna il percorso dell'immagine nel modello della tabella
tableModel.setValueAt(imagePath, row, column);
// Aggiungi la riga modificate al set
righeModificate.add(row);
imagePathMap.put(row, imagePath);
}
}
}
});
JScrollPane scrollPane = new JScrollPane(tabellaProdotti);
add(scrollPane, BorderLayout.CENTER);
add(modifica, BorderLayout.SOUTH);
}
}
```
The Table Model that im working with it( i dont think the problem is there)
```
public class ListaProdottiTableModel extends AbstractTableModel {
private List<Prodotto> prodotti = new ArrayList<>();
private IArticoloDAO articoloDAO;
public ListaProdottiTableModel(List<Prodotto> prodotti, IArticoloDAO articoloDAO) {
this.prodotti = prodotti;
this.articoloDAO = articoloDAO;
}
@Override
public int getRowCount() {
return prodotti.size();
}
@Override
public int getColumnCount() {
return 6;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Prodotto prodotto = prodotti.get(rowIndex);
switch (columnIndex) {
case 0: return prodotto.getNome();
case 1: return prodotto.getTipoProdotto();
case 2: return prodotto.getDisponibilita();
case 3: return prodotto.getPrezzo();
case 4:
String imagePath = prodotto.getFoto();
if (imagePath != null && !imagePath.isEmpty()) {
ImageIcon imageIcon = new ImageIcon(imagePath);
Image image = imageIcon.getImage();
Image scaledImage = image.getScaledInstance(100, 100, Image.SCALE_SMOOTH);
return new ImageIcon(scaledImage);
}else {
return null;
}
case 5: return prodotto.getDescrizione();
default:return null;
}
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Prodotto prodotto = prodotti.get(rowIndex);
switch (columnIndex) {
case 0: prodotto.setNome((String) aValue); break;
case 1: // Converte la stringa in enum
try {
IArticolo.TIPO_PRODOTTO tipoProdotto = IArticolo.TIPO_PRODOTTO.valueOf((String) aValue);
prodotto.setTipoProdotto(tipoProdotto);
} catch (IllegalArgumentException e) {
// Gestisce il caso in cui la stringa non corrisponda a nessun valore dell'enum
// Potresti mostrare un messaggio di errore o gestire il caso in un altro modo appropriato
System.out.println("Valore non valido per il tipo di prodotto.");
}
break;
case 2: try {
int disponibilita = Integer.parseInt((String) aValue);
prodotto.setDisponibilita(disponibilita);
} catch (NumberFormatException e) {
System.out.println("Errore durante la conversione della disponibilità in intero.");
}
break;
case 3: prodotto.setPrezzo((float) aValue); break;
case 4: prodotto.setFoto((String) aValue); break;
case 5: prodotto.setDescrizione((String) aValue); break;
}
// Aggiorna il prodotto nel database
//articoloDAO.updateProdotto(prodotto);
// Aggiorna la tabella
fireTableRowsUpdated(rowIndex, rowIndex);
}
@Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == 4) {
return ImageIcon.class; // Immagine
} else {
return super.getColumnClass(columnIndex);
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
}
```
Maybe the problem is on the mouseLister but i cant solve the problem. |
null |
I want to show text within an SVG which is wholly defined in js. The SVG picture shows as expected, but the text does not.
I have tried the actual SVG definition in an online SVG viewer and it has the same result: picture is good, but no text showing.
I create the following string in js and then use it as the content in an AdvancedMarkerElementmarker in Google Maps.
```
SVGstring = '<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-3 -49 52 52" > <style>svg { margin-top: 3px margin-bottom: 3px margin-right: 3px margin-left: 3px}</style> <path stroke="black" stroke-width="3" d="m 0,0 l 0,-25 l 23,0 l 7,-20 l 7,20 l 3,0 l 0,25 z" fill="#9494ff" /><text x="20" y="35" font = "20px sans-serif" fill="black" >999</text></svg>'
```
The google maps marker then has its content set by:
```
pinSvg = document.createElement('pinSvg');
pinSvg.innerHTML = SVGstring;
marker.content = pinSvg;
```
|
The problem is not (as Greg and lorem ipsum have suggested) that your API key is not secured, as that value is only accessible to folks who have administrative access to your project.
The problem is that your `generateText` Cloud Function performs a pretty blanket API call to OpenAI and doesn't do anything to verify that the API call is authorized. Essentially: anyone who knows the endpoint of `generateText` (which they can determine from your public app), can call that endpoint with whatever prompt they want to send to OpenAI, and make that call on your API key.
One way to protect against this sort of abuse is with App Check, which sends a special app attestation token with requests coming from your genuine code on an unhacked device, and then validates that token on the server. See the documentation on [enabling enforcement of App Check on callable Cloud Functions](https://firebase.google.com/docs/app-check/cloud-functions#enforcement). |
null |
null |
I am creating a app that will read data from firebase and display it on a map. The app keeps crashing because there are hell lot of records to retrieve from the database. I need a way with which I get only the latest node data and not the entire data snapshot.
MainActivity.java:
```
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback{
FirebaseDatabase db;
DatabaseReference dbReference;
TextView speed_disp;
public List<LatLng> polygon;
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
private GoogleMap googleMap;
private double latitude=19.10815888216128;
private double longitude=72.83706388922495;
public void setCord(String lat,String lon){
this.latitude=Double.parseDouble(lat);
this.longitude=Double.parseDouble(lon);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
polygon = new PolyList<>(10);
setContentView(R.layout.activity_main);
db = FirebaseDatabase.getInstance();
speed_disp=findViewById(R.id.speed);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1000);
// }
try{
dbReference = db.getReference("Data");
dbReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot datasnapshot) {
Log.d("Lat",datasnapshot.getValue().toString());
for (DataSnapshot snapshot: datasnapshot.getChildren()) {
String latitude = snapshot.child("lat").getValue(String.class);
String longitude = snapshot.child("lon").getValue(String.class);
String speed = snapshot.child("speed").getValue(String.class);
speed_disp.setText(speed);
setCord(latitude,longitude);
googleMap.clear();
double lat = getLatitude();
double lon = getLongitude();
LatLng current=new LatLng(lat,lon);
// Add marker position to polygon list
polygon.add(current);
// Draw polyline
if (polygon.size() >= 2) {
PolylineOptions polylineOptions = new PolylineOptions()
.addAll(polygon)
.width(5)
.color(Color.RED);
googleMap.addPolyline(polylineOptions);
}
googleMap.addMarker(new MarkerOptions().position(current).title("Current Location"));
// Move camera to marker
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(current,20 ));
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(MainActivity.this,"Read error!!!",Toast.LENGTH_SHORT).show();
}
});
}catch (Error e) {
Toast.makeText(MainActivity.this, "Read module error", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap=googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// LatLng current=new LatLng(19.10815888216128,72.83706388922495);
// this.googleMap.addMarker(new MarkerOptions().position(current).title("Dub maro pls!!"));
// this.googleMap.moveCamera(CameraUpdateFactory.newLatLng(current));
}
}
```
Firebase:

I want to read only the newest node from the real-time database. Also, I would appreciate if you guys could improve my code. |
null |
null |
You can do it by creating a function that changes the `fontSize` and add it on the `LocalStorage` every time a person clicks on it.
After that you can use the `window.onload()` to always check, when the page loads, if there is any `fontSize` on the `LocalStorage` and set it if there is.
Example:
**HTML**
<section class="sec">
<div class="content">
<div class="buttons">
<span class="btn" onclick="changeFontSize('1em')">A</span>
<span class="btn" onclick="changeFontSize('1.25em')">A</span>
<span class="btn" onclick="changeFontSize('1.75em')">A</span>
</div>
<div class="text" id="text">
<h3>i'm an h3</h3>
<p>i'm a paragraph</p>
</div>
</div>
</section>
**JavaScript**
let buttons = document.querySelector('.buttons');
let btn = buttons.querySelectorAll('.btn');
window.onload = function() {
let fontSize = localStorage.getItem('fontSize');
if (fontSize) {
document.getElementById('text').style.fontSize = fontSize;
}
}
function changeFontSize(size) {
localStorage.setItem('fontSize', size);
document.getElementById('text').style.fontSize = size;
}
for(let i = 0; i < btn.length; i++){
btn[i].addEventListener('click', function(){
let current = document.getElementsByClassName('clicked');
current[0].className = current[0].className.replace(" clicked", "");
this.className += " clicked";
})
} |
I created an Azure function and enabled the managed identity option. It creates a new Enterprise application with a unique guid. I would like to add this managed identity as an owner of a specific AAD group. In the browser it works when I enter the managed identity guid, but when I try it by PowerShell code I get the error below:
Add-PnPMicrosoft365GroupMember -Identity $aadGroupId -Users $guidOfMyManagedIdentityServicePrincipal
Not Found (404): Resource 'guidOfMyManagedIdentityServicePrincipal' does not exist or one of its queried reference-property objects are not present
|
null |
I try to launch multiple experiments, but I want to keep the code script in cache so that any change will not affect experiments waiting to be executed.
The bash script I use is:
```
for SIZE in 1 2 4 8 16; do
python main.py $SIZE
done
```
The problem with my current script is that once I make changes to the code file `main.py`, the experiments waiting to be executed will use the modified `main.py`. For example, If `python main.py 1` is currently executed, any change to `main.py` will affect `main.py 2`, `main.py 4`... Is there a way to put `main.py` in cache so that any change to `main.py` will not affect `python main.py $SIZE`? |
Launch jobs in cache in a loop in bash script |
|bash|for-loop|caching| |
null |
{"Voters":[{"Id":1116230,"DisplayName":"Nico Haase"},{"Id":794749,"DisplayName":"gre_gor"},{"Id":1007220,"DisplayName":"aynber"}],"SiteSpecificCloseReasonIds":[18]} |
I am using Parros OS [tag:parrotOS]. Recently I update my apt packages by this comment: `sudo apt update` and it shows some packages telling me that, These packages it not needed anymore. I uninstalled this packages manually. Then I got this:
```
$sudo apt full-upgrade
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Calculating upgrade... Done
The following packages have been kept back:
hashcat
0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
```
I tried `sudo apt install hashcat` but it shows:
```
└──╼ $sudo apt install hashcat
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
hashcat : Depends: libminizip1t64 but it is not installable
E: Unable to correct problems, you have held broken packages.
```
I tried to fix the broken package: `sudo apt-get -f install` but it shows:
```
sudo apt-get -f install
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
```
|
hashcat : Depends: libminizip1t64 but it is not installable E: Unable to correct problems, you have held broken packages |
|linux|package|apt|parrot-os|hashcat| |
Create a middleware.ts (or .js) in the root of your project. (https://nextjs.org/docs/app/building-your-application/routing/middleware)
import { NextResponse } from 'next/server';
export function middleware(request: Request) {
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-url', request.url);
return NextResponse.next({
request: {
headers: requestHeaders
}
});
}
then use headers in your layout or page
const requestUrl = headers().get('x-url') |
I am have an issue with google colab pro. I subscribed to this plan to use the generative code assistant however I cannot access this feature. I am located in Germany at the moment if this info could be helpful.
Thank you in advance.
I tried to find colab customer service but there was none as they mentioned that I should post my issue either in github or stackoverflow. |
google colab pro issue, cannot access generative code ai assistant |
|google-colaboratory| |
null |