instruction stringlengths 0 30k ⌀ |
|---|
If a popup/tab is opened from Javascript using `window.open` where
- The popup/tab is on a different domain from the opener
- The page in the popup/tab has the HTTP header `Cross-Origin-Opener-Policy: same-origin-allow-popups` set
Then does the opener have access to the popup via the return value of `window.open`? From https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy it says
> **same-origin-allow-popups**
>
> Retains references to newly opened windows or tabs that either don't set COOP or that opt out of isolation by setting a COOP of unsafe-none.
But this seems to describe the behaviour of the site calling `window.open` with this value of `Cross-Origin-Opener-Policy`. I'm wondering about how things behave if some (possibly adversarial) site uses `window.open` to open a site, and that site uses "Cross-Origin-Opener-Policy: same-origin-allow-popups". |
Popup loaded with "Cross-Origin-Opener-Policy: same-origin-allow-popups" in it (not its opener) |
|javascript|google-chrome|security|http-headers|cross-origin-opener-policy| |
I have two following models created in my SwiftData project in Xcode
@Model
class Notebook {
var id: String = ""
var name: String = ""
var desc: String?
var notes: [Note]?
init(id: String, name: String, desc: String? = nil) {
self.id = id
self.name = name
self.desc = desc
}
}
and
@Model
class Note {
var id: String = ""
var created: Date = Date()
var updated: Date?
var text: String = ""
var notebook: Notebook
init(id: String, created: Date, updated: Date? = nil, text: String, notebook: Notebook) {
self.id = id
self.created = created
self.updated = updated
self.text = text
self.notebook = notebook
}
}
Project is compiled and works fine if CloudKit capability is unchecked but when I allow it and assign container on iCloud then it fails with error
> Fatal error: Could not create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer)
I tried to make notebook property in Note model optional but it didn't help.
Code for ModelContainer creation
var sharedModelContainer: ModelContainer = {
let schema = Schema([Notebook.self, Note.self])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
I'll be grateful for advice.
Thanks. |
How can I retrieve the remote Git address of a repository?
I tried `git remote`, but that just lists the branches.
|
How can I retrieve the remote Git address of a repository? |
This ...
> ```
> int xyGrid[10][5];
> ```
... in `main` declares `xyGrid` as an array of 10 arrays of 5 `int`s. In most contexts, such an array value is automatically converted upon evaluation to a pointer to the first array element. In this case, the first array element has type "array of 5 `int`", so the resulting pointer is a pointer to an array (of 5 `int`). That can be spelled `int (*)[5]`, and it is not at all the same thing as `int *`.
When you call ...
> updateEntity(entity, xyGrid, -1, 1);
... you are passing an `int (*)[5]` argument where the function expects to receive an `int *`. This produces undefined behavior, and if your compiler is not warning you about that then you should either turn up the warning level until it does, or get a better compiler. (And if the compiler *is* warning, then why are you not paying attention to that?)
The error you ask about is related to that mismatch, but does not arise directly from it. The problem is that in function `updateEntity()`, the compiler interprets parameter `xyGrid` according to the type declared for it *in that function*, which is `int *`. From that perspective, consider the erroneous expression:
> xyGrid[entity[i].x_position][entity[i].y_position]
The indexing operator associates from right to left, so that's equivalent to
(xyGrid[entity[i].x_position])[entity[i].y_position]
Now, what's the type of sub-expression `xyGrid[entity[i].x_position]`? `xyGrid` is an `int *` and `entity[i].x_position` is presumably an integer, so that's a valid expression whose type is `xyGrid`'s pointed-to type, `int`.
So now we have
(some integer value)[entity[i].y_position]
Both operands of *that* indexing expression are integers, which is not valid. **This is the nature of the error.**
The most direct solution would be to correct the signature of `updateEntity()` to match both its implementation and its usage:
```
void updateEntity(entity_e *entity, int (*xyGrid)[5], int32_t kx, int32_t ky) {
```
You could also spell that
```
void updateEntity(entity_e *entity, int xyGrid[][5], int32_t kx, int32_t ky) {
```
or even
```
void updateEntity(entity_e *entity, int xyGrid[10][5], int32_t kx, int32_t ky) {
```
. All of those mean exactly the same thing in that particular context. |
I'm making a psychological quiz шт REACT. There is text. In a text editor. The text consists of 100 questions and 340 answers. How to make a React program that took at least 2 questions, preferably 10 questions at once, and inserted brackets and other characters so that this data could be taken from an array file? I put a plus sign next to the correct answer.
# As I understand it, regular expressions and array are needed...
Example-
1. Which of the following concepts corresponds to “Psyche” among the ancient Greeks:
Nervous system
+Soul
Psyche
Superego
Consciousness
2. Which of the Greek philosophers admits that the mind depends on the nature of the fire in the soul:
Galen
Socrates
+ Heraclitus
Pythagoras
Data in Data.js-
Example
{
question: ' 1. Which of the following concepts corresponds to “Psyche” among the ancient Greeks: ',
incorrectAnswers: [
"Nervous system",
"psyche",
"Суперэго",
"Consciousness",
],
correctAnswer: "Soul",
},
{
question:
"2. Which of the Greek philosophers admits that the mind depends on the nature of the fire in the soul: ",
incorrectAnswers: [
"Galen",
"Socrates",
"Pythagoras“,
],
correctAnswer: "Heraclitus",
},
[enter image description here](https://i.stack.imgur.com/jkMhe.png)
[enter image description here](https://i.stack.imgur.com/j98ak.png)
Hello! I'm making a psychological quiz шт REACT. There is text. In a text editor. The text consists of 100 questions and 340 answers. How to make a React program that took at least 2 questions, preferably 10 questions at once, and inserted brackets and other characters so that this data could be taken from an array file? I put a plus sign next to the correct answer.
# As I understand it, regular expressions and array are needed...
Example-
1. Which of the following concepts corresponds to “Psyche” among the ancient Greeks:
Nervous system
+Soul
Psyche
Superego
Consciousness
2. Which of the Greek philosophers admits that the mind depends on the nature of the fire in the soul:
Galen
Socrates
+ Heraclitus
Pythagoras
Data in Data.js-
Example
{
question: ' 1. Which of the following concepts corresponds to “Psyche” among the ancient Greeks: ',
incorrectAnswers: [
"Nervous system",
"psyche",
"Суперэго",
"Consciousness",
],
correctAnswer: "Soul",
},
{
question:
"2. Which of the Greek philosophers admits that the mind depends on the nature of the fire in the soul: ",
incorrectAnswers: [
"Galen",
"Socrates",
"Pythagoras“,
],
correctAnswer: "Heraclitus",
},
[enter image description here](https://i.stack.imgur.com/jkMhe.png)
[enter image description here](https://i.stack.imgur.com/j98ak.png)
I'm completely confused. How can you select the correct text with questions and answers from one array of text and place the correct answer separately? |
It’s not possible to take text and translate it into a convenient format. I'm completely confused |
|reactjs| |
null |
For my model evaluation, I am using cosine similarity with below code:
```
cosine_similarity = (np.dot(np.array(v1), np.array(v2))) / (norm(np.array(v1)) * norm(np.array(v2)))
```
But getting below error, any help here
```
<scipy.stats._distn_infrastructure.rv_continuous_frozen object at 0x000001E703C665A0>
<scipy.stats._distn_infrastructure.rv_continuous_frozen object at 0x000001E701D1EEA0>
Traceback (most recent call last):
File "c:\Users\91888\OneDrive\Desktop\SkillMatch\Doc2Vec_Test_Resume.py", line 102, in <module>
print((norm(np.array(v1)) * norm(np.array(v2))))
~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for *: 'rv_continuous_frozen' and 'rv_continuous_frozen'
```
For my model evaluation, I am using cosine similarity |
amplify gen2 sandbox with existing stack |
|amazon-web-services|aws-amplify| |
For this I would simply:
* Concatenate everything to a single line:
<span />
$OneLine = -Join (Get-Content .\VerticalFile.txt)
* Than split the rows based on the commas that are followed ([LookAhead](https://www.regular-expressions.info/lookaround.html)) by a date string:
<span />
$Csv = $OneLine -Split ',(?=\d\d ... \d\d\d\d)', [Environment]::NewLine
* Optionally, if you need the fields quoted:
<span />
$Csv | ConvertFrom-Csv | ConvertTo-Csv
|
My website preloader is not showing properly first the website appears for a few mili seconds then preloader then the website.
I am using Elementor WordPress, I have added the preloader code in my theme file editor here is the code snippet
"add_action('wp_footer', 'Allprocoding_Preloader');
function Allprocoding_Preloader() {
if (!is_admin() && $GLOBALS["pagenow"] !== "wp-login.php") {
$delay = 1; // seconds
$desktop_loader = 'https://spoky.co/wp-content/uploads/2024/02/Group-1171275193-1.gif';
$mobile_loader = 'https://spoky.co/wp-content/uploads/2024/02/mobile-.gif';
$overlayColor = '#ffffff';
?>
<script>
document.addEventListener("DOMContentLoaded", function () {
var preloader = document.createElement('div');
preloader.style.position = 'fixed';
preloader.style.top = '0';
preloader.style.bottom = '0';
preloader.style.left = '0';
preloader.style.right = '0';
preloader.style.backgroundColor = '<?php echo esc_js($overlayColor); ?>';
preloader.style.zIndex = '100000';
preloader.style.display = 'flex';
preloader.style.alignItems = 'center';
preloader.style.justifyContent = 'space-around';
var loaderImg = document.createElement('img');
loaderImg.src = '<?php echo esc_url($desktop_loader); ?>';
loaderImg.alt = '';
loaderImg.style.height = '30vw';
preloader.appendChild(loaderImg);
document.body.appendChild(preloader);
document.body.style.overflow = "hidden";
var mediaQuery = window.matchMedia("only screen and (max-width: 760px)");
function handleMediaChange(event) {
if (event.matches) {
loaderImg.src = '<?php echo esc_url($mobile_loader); ?>';
loaderImg.style.height = '20vw';
} else {
loaderImg.src = '<?php echo esc_url($desktop_loader); ?>';
loaderImg.style.height = '15vw';
}
}
mediaQuery.addListener(handleMediaChange);
handleMediaChange(mediaQuery);
window.addEventListener("load", function () {
// Remove the preloader after the delay
setTimeout(function () {
preloader.remove();
document.body.style.overflow = "visible";
}, <?php echo esc_js($delay * 1000); ?>);
});
});
</script>
<?php
}
}
"
what to do to make the prelaoder appears perfectly fine
I have tried adding code to inline css and and preload css and JavaScript files but there is no change in the scenario. What are other possible ways to figure out this issue? |
In JavaScript (including ES6), there isn't a concept of upcasting or downcasting like in statically-typed languages such as Java or C++. However, you can achieve a similar effect by treating objects of a subclass as if they were objects of their superclass. This is because JavaScript objects are based on prototypes, and you can always access properties and methods of the superclass from an instance of a subclass.
Here's an example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
console.log(`${this.name} barks.`);
}
fetch() {
console.log(`${this.name} fetches.`);
}
}
// Creating an instance of the subclass
const myDog = new Dog('Buddy', 'Golden Retriever');
// Upcasting to the superclass
const myAnimal = myDog; // No explicit casting needed, just assign the subclass instance to a superclass reference
// Accessing superclass methods and properties
myAnimal.speak(); // Outputs: Buddy barks.
console.log(myAnimal.name); // Outputs: Buddy
// You cannot access subclass-specific properties or methods
// myAnimal.fetch(); // This would throw an error since fetch is not a method of the superclass
<!-- end snippet -->
In this example, Dog is a subclass of Animal. When you assign an instance of Dog to a variable of type Animal, you're effectively treating it as an Animal. However, you won't be able to access subclass-specific methods or properties using the superclass reference.
|
**<h2>In my nextjs project,this solved me:</h2>**
1. deleting the .next folder
2. deleting package.json
3. npm run build again |
I have a textarea where users can paste text from the clipboard.
The text pasted `clipboarddata.getData('text')` gets modified.
However, I need a switch that if pressing <kbd>CTRL</kbd> <kbd>SHIFT</kbd> <kbd>V</kbd> instead of <kbd>CTRL</kbd> <kbd>V</kbd> the pasted text does not get modified.
I tried to catch the shift key with keydown/keyup:
```
$('textarea').on('keyup', function(e)
{
shiftkey_down = e.shiftKey;
});
```
and then try to read the boolean variable in the paste event handler:
```
$('textarea').on('paste', function(e)
{
if (shiftkey_down)
{
// ...
}
});
```
but the `paste` event comes after keydown and keyup. So I cannot read what key has been pressed. And `shiftkey_down` is always `false` inside the paste handler.
What would be the right way to handle this?
The only idea I got is to save the last key combination pressed inside the keydown event and then check the **last** one pressed inside the paste handler. But maybe there is a better way? |
Get keys pressed with Clipboard event in Javascript? |
|javascript|events|clipboard| |
I'm trying to build navbar component in react with tailwindCss.
I've added `space-y-2` to get spacing on y axis, for all `li` elements.
But the first li element (Home) is not getting spacing as expected.
It looks like
[![enter image description here][1]][1]
Why Home is behaving differently ?
Can anybody pls help
[Here is Code][2]
[1]: https://i.stack.imgur.com/Tg37H.png
[2]: https://play.tailwindcss.com/8c9qGiLCXp |
The answer, in case anyone else comes across this, is that the default Blazor template comes without interactivity enabled which leaves a lot of developers baffled (me included). Basic stuff such as button click event handler no longer works and there is no warning or exception.
This means that you must select a type of interactivity in the pages, such as InteractiveServer or InteractiveWebAssembly or InteractiveAuto in case of inherited parent interactivity, otherwise no Blazor event will work.
E.g.:
@rendermode InteractiveServer |
In my angular app there can be 2 type of layout(e.g. List and Detail).
I have to get the layoutConfig based on activated route. For this I'm using a route resolver.
My plan is ResolveFn will return a signal not an observable.
My *LayoutService* has an additional requirement, if its a List, it will get list data from layoutConfig's serviceUrl.
Below is my existing code which pass url as parameter and return an observable:
```
export const LayoutResolver: ResolveFn<LayoutConfig> = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
) => {
const _layoutService = inject(LayoutService);
_layoutService.setCurrentActivatedRoute(state.url);
return _layoutService.layoutConfig$;
};
```
```
export class LayoutService {
#httpClient = inject(ApiHttpService);
readonly #url_layout: string = 'listConfig';
constructor() {
effect(() => {
console.log('currentActivatedRoute', this.CurrentActivatedRouteSig());
});
}
CurrentActivatedRouteSig = signal<string | undefined>(undefined);
setCurrentActivatedRoute(url: string) {
this.CurrentActivatedRouteSig.set(url);
}
currentActivatedRoute$ = toObservable(this.CurrentActivatedRouteSig);
layoutConfig$ = this.currentActivatedRoute$
.pipe(
filter(Boolean),
switchMap(x => this.#httpClient.GETT<LayoutConfig>(`${this.#url_layout}`)
.pipe(
map(x => x.data)
))
);
LayoutConfigSig = toSignal(this.layoutConfig$, { initialValue: undefined });
private gridData$ = toObservable(this.LayoutConfigSig)
.pipe(
tap(x => console.log('gridData$ =>', x)),
filter(Boolean),
switchMap(x => this.#httpClient.GETT<any>(x.serviceUrl)
.pipe(
tap(x => console.log('serviceUrl$ =>', x.data)),
map(x => x.data)
))
)
GridDataSig = toSignal(this.gridData$, { initialValue: [] });
}
``` |
Currently have this and it automatically connecting the plot if they are continues marks.
```
plot(stopLossPrice, color=color.rgb(255, 153, 0), title="Mark", linewidth=2, style=plot.style_steplinebr, offset=0)
if (not na(stopLossPrice))
label.new(bar_index, stopLossPrice, text="SL - 2%", style=label.style_label_up, color=color.new(#00f708, 100), textcolor=color.rgb(255, 153, 0), size=size.small)
```
[](https://i.stack.imgur.com/pZ9hV.png)
I tried this, but its thickness is not enough and its width is too short.
```
plotchar(series=buyPrice, char="——", color=color.rgb(0, 255, 0), title="Mark", offset=0, location=location.absolute)
```
Is there a way or other alternatives to separate continues plot mark for each candlesticks like this image:
[](https://i.stack.imgur.com/J6Zt9.png)
|
My website appears for few mili seconds then preloader then website |
|javascript|php|css|wordpress-theming|preloader| |
null |
When running the game in the editor when I press the keys sequence N,O,T,E,S it's opening a small window. then when I type inside the window some text and also type /exit or /close it will close the window.
but then when I try to type the sequence of keys N,O,T,E,S again it's not opening the window again only after sometimes I press the keys sequence.
when typing the notes sequence first time it's working also in lower case. and if I make the sequence NOTES and then not clicking on the window to get its focus and then type NOTES again it will toggle and open/close the window without a problem.
the problem I described happens after I click the window to get its focus and after typing some text inside then closing it with the command /close or /exist then when typing notes again it's not working immediately.
using UnityEngine;
public class GameNotes : MonoBehaviour
{
private bool showNotes = false;
private string notesContent = "";
private static string filePath = "GameNotes.txt";
private int keySequenceIndex = 0;
private KeyCode[] keySequence = new KeyCode[] { KeyCode.N, KeyCode.O, KeyCode.T, KeyCode.E, KeyCode.S };
private void Update()
{
if (Input.GetKeyDown(keySequence[keySequenceIndex]))
{
keySequenceIndex++;
if (keySequenceIndex >= keySequence.Length)
{
showNotes = !showNotes;
keySequenceIndex = 0;
if (showNotes) LoadNotes();
}
}
else if (Input.anyKeyDown)
{
keySequenceIndex = 0;
}
}
private void OnGUI()
{
if (showNotes)
{
GUI.BeginGroup(new Rect(Screen.width / 2 - 150, Screen.height / 2 - 100, 300, 200));
GUI.Box(new Rect(0, 0, 300, 200), "Notes");
string prevContent = notesContent;
notesContent = GUI.TextArea(new Rect(10, 20, 280, 170), notesContent);
GUI.EndGroup();
// Detect special commands
ProcessCommands();
// Save notes if there's any change and no command was detected
if (prevContent != notesContent && showNotes)
{
SaveNotes();
}
}
}
private void ProcessCommands()
{
if (notesContent.Contains("/close") || notesContent.Contains("/exit"))
{
showNotes = false;
// Remove the command text from the notes
notesContent = notesContent.Replace("/close", "").Replace("/exit", "").Trim();
SaveNotes();
}
}
private void SaveNotes()
{
System.IO.File.WriteAllText(filePath, notesContent);
}
private void LoadNotes()
{
if (System.IO.File.Exists(filePath))
{
notesContent = System.IO.File.ReadAllText(filePath);
}
}
} |
Why sometimes the sequence keys is working and sometimes not responding? |
Tailwindcss not aligning element <li> as expected with utility space-y-3 |
[error show when I run my code in android studio I want to run my app in emulator[this is showing when I want to select device](https://i.stack.imgur.com/ltR9j.png)](https://i.stack.imgur.com/FhssX.png)
I want to run my code in verchular device
error - (Installation did not succeed.
The application could not be installed: INSTALL_FAILED_OLDER_SDK
List of apks:
[0] 'C:\Users\hp\Downloads\notes\app\build\intermediates\apk\debug\app-debug.apk'
The application's minSdkVersion is newer than the device API level.
Retry
Failed to launch an application on all devices)
|
when I try to run my app in emulator showing error |
Try doing:
pip install -U datasets
>This error stems from a breaking change in fsspec. It has been fixed in the latest datasets release (2.14.6). Updating the installation with pip install -U datasets should fix the issue.
git link : https://github.com/huggingface/datasets/issues/6352
************
if you are using `fsspec` then do:
pip install fsspec==2023.9.2
There is a problem with `fsspec==2023.10.0`
git link : https://github.com/huggingface/datasets/issues/6330
****
***
**Edit**: Looks like it broken again in `2.17` and `2.18` downgrading to `2.16` should work. |

for the given example html page:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<div class="ia-secondary-content">
<div class="plugin_pagetree conf-macro output-inline" data-hasbody="false" data-macro-name="pagetree">
<div class="plugin_pagetree_children_list plugin_pagetree_children_list_noleftspace">
<div class="plugin_pagetree_children" id="children1326817570-0">
<ul class="plugin_pagetree_children_list" id="child_ul1326817570-0">
<li>
<div class="plugin_pagetree_childtoggle_container">
<a aria-expanded="false" aria-label="Expand item Topic 1" class="plugin_pagetree_childtoggle aui-icon aui-icon-small aui-iconfont-chevron-right" data-page-id="1630374642" data-tree-id="0" data-type="toggle" href="" id="plusminus1630374642-0"></a>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span" id="childrenspan1630374642-0"> <a href="#">Topic 1</a></span>
</div>
<div class="plugin_pagetree_children_container" id="children1630374642-0"></div>
</li>
<li>
<div class="plugin_pagetree_childtoggle_container">
<a aria-expanded="false" aria-label="Expand item Topic 2" class="plugin_pagetree_childtoggle aui-icon aui-icon-small aui-iconfont-chevron-right" data-page-id="1565544568" data-tree-id="0" data-type="toggle" href="" id="plusminus1565544568-0"></a>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span" id="childrenspan1565544568-0"> <a href="#">Topic 2</a></span>
</div>
<div class="plugin_pagetree_children_container" id="children1565544568-0"></div>
</li>
<li>
<div class="plugin_pagetree_childtoggle_container">
<a aria-expanded="true" aria-label="Expand item Topic 3" class="plugin_pagetree_childtoggle aui-icon aui-icon-small aui-iconfont-chevron-down" data-children-loaded="true" data-expanded="true" data-page-id="3733362288" data-tree-id="0" data-type="toggle"
href="" id="plusminus3733362288-0"></a>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span" id="childrenspan3733362288-0"> <a href="#">Topic 3</a></span>
</div>
<div class="plugin_pagetree_children_container" id="children3733362288-0">
<ul class="plugin_pagetree_children_list" id="child_ul3733362288-0">
<li>
<div class="plugin_pagetree_childtoggle_container">
<span class="no-children icon"></span>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span"> <a href="#">Subtopic 1</a></span>
</div>
<div class="plugin_pagetree_children_container"></div>
</li>
<li>
<div class="plugin_pagetree_childtoggle_container">
<span class="no-children icon"></span>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span"> <a href="#">Subtopic 2</a></span>
</div>
<div class="plugin_pagetree_children_container"></div>
</li>
</ul>
</div>
</li>
<li>
<div class="plugin_pagetree_childtoggle_container">
<a aria-expanded="false" aria-label="Expand item Topic 4" class="plugin_pagetree_childtoggle aui-icon aui-icon-small aui-iconfont-chevron-right" data-page-id="2238798992" data-tree-id="0" data-type="toggle" href="" id="plusminus2238798992-0"></a>
</div>
<div class="plugin_pagetree_children_content">
<span class="plugin_pagetree_children_span" id="childrenspan2238798992-0"> <a href="#">Topic 4</a></span>
</div>
<div class="plugin_pagetree_children_container" id="children2238798992-0"></div>
</li>
</ul>
</div>
</div>
<fieldset class="hidden">
</fieldset>
</div>
</div>
<!-- end snippet -->
I need to extract the innermost nested links from this sort of a page tree. Given the title within which, I need to get all the links, how can I find all the innermost nested links. I want to write a python script for the same which dynamically extracts the innermost nested links of the various html pages provided. Take note that the nesting levels may not be the same.
thus for the example I should get:
```
<a href="#">Subtopic 1</a>
<a href="#">Subtopic 2</a>
```
I tried extracting all the links in the same nesting structure but it didn't work
# Step 1: Find the div with the given title
title = "Topic 3"
target_div = soup.find('span', class_='plugin_pagetree_children_span', text=title)
# Step 2: Extract the next div with class "plugin_pagetree_children_container"
if target_div:
container_div = target_div.find_next_sibling('div', class_='plugin_pagetree_children_container')
# Step 3: Extract all links within the container and print them
if container_div:
links = container_div.find_all('a')
for link in links:
print(link['href'])
|
OP here. I've reached an offline solution for now. It became very clear how to get the timestamps I wanted once I installed JSONvue on my browser and saw the structure of the JSON data. Excuse any inefficiencies as the timestamp data was quite nested.
It's also obvious that retrieving the JSON by putting .json at the end the url did not give me the data of every single main comment in the post as it is probably dynamically loaded by Javascript as someone pointed out. I have experimented with requesting HTML as well as json from the URL itself, but it will fail half of the time and return with a data structure that is incompatible with my current code. In either case however, the data still seems to be a fraction of what exists. I will further explore this exercise with how I can get the data of all comments
Here is the code:
#from bs4 import BeautifulSoup
#import requests
import json
import csv
import datetime
data = open('Reddit.json')
html_json = json.load(data)
file = open("scraped_timestamps.csv", "w")
writer = csv.writer(file)
writer.writerow(["TIMESTAMPS"])
#print(html.status_code)
parent = html_json[1]['data']['children']
timestamps = []
for i in parent:
if 'created_utc' in i['data']:
timestamps.append(datetime.datetime.fromtimestamp(i['data]['created_utc']))
else:
break
sorted_timestamps = sorted(timestamps)
for x in sorted_timestamps:
writer.writerow([x])
file.close()
#html_json[0] contains the post itself without the comment section
#html_json[1] contains the entire comment section
#I had to check for the existence of the timestamp data, otherwise the query throws
#an error passing the list as html_json[1] also contains the footer without such timestamp data |
|pine-script|pine-script-v5|tradingview-api|pine-script-v4| |
{"Voters":[{"Id":2518285,"DisplayName":"Brett Donald"},{"Id":1427878,"DisplayName":"CBroe"},{"Id":6463558,"DisplayName":"Lin Du"}],"SiteSpecificCloseReasonIds":[13]} |
{"Voters":[{"Id":2446254,"DisplayName":"Cody Geisler"},{"Id":14732669,"DisplayName":"ray"},{"Id":5053002,"DisplayName":"Jaromanda X"}],"SiteSpecificCloseReasonIds":[11]} |
1. grab that div element using the the id or class
2. then in js file render the result in that element
refer:- https://www.geeksforgeeks.org/dom-document-object-model/ |
Your functions don't match is why: missing `- 1` on the orange and red lines. `linewidth` will control the line width.
ggplot() + xlim(0, 50) +
geom_function(fun = function(x) exp(I0 - b * x), colour = "blue", linewidth = 0.1) +
geom_function(fun = function(x) exp(d * x) - 1, colour = "orange", linewidth = 1.5) +
geom_function(fun = function(x) exp(I1 - b * x), color = "green") +
geom_function(fun = function(x) exp(d1 * x) - 1, color = "red")
[![enter image description here][1]][1]
or with `+ ggthemes::theme_base()`
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/kk0K2.png
[2]: https://i.stack.imgur.com/VoDtj.png |
|shell| |
|python|python-requests| |
I have setup a declarative Jenkins-Pipeline which runs fine so far. During a post-action I would like to publish issues found by warnings-ng-plugin. This had worked till 4 weeks ago or so. Suddenly the publish doesn't work anymore.
This is my post-action
post {
always {
script {
echo "ISSUES_DOXYGEN: ${ISSUES_DOXYGEN}"
echo "ISSUES_PCLINT: ${ISSUES_PCLINT}"
echo "ISSUES_AXIVION: ${ISSUES_AXIVION}"
echo "env.Workspace: ${env.WORKSPACE}"
if (env.BRANCH_NAME == 'main') {
// provided by warnings-ng-plugin
publishIssues (
issues: [
ISSUES_DOXYGEN,
ISSUES_PCLINT,
ISSUES_AXIVION
]
)
} else {
// provided by warnings-ng-plugin
publishIssues (
issues: [
ISSUES_PCLINT
]
)
}
}
}
}
Whenever I run the pipeline everything works but the post-action now always fails. All steps shown in the WebUI are green, only the overall status is red ...
This is the exception I got:
```
ISSUES_DOXYGEN: io.jenkins.plugins.analysis.core.steps.AnnotatedReport@781b8ff7
ISSUES_PCLINT: io.jenkins.plugins.analysis.core.steps.AnnotatedReport@260d6b49
ISSUES_AXIVION: io.jenkins.plugins.analysis.core.steps.AnnotatedReport@6c4499e0
env.Workspace: null
Error when executing always post condition:
Also: org.jenkinsci.plugins.workflow.actions.ErrorAction$ErrorId: 82ec7aae-3f00-4eae-bfe5- 35eb2b1a9906
java.io.IOException: No workspace available for
io.jenkins.plugins.analysis.core.steps.PublishIssuesStep$Execution@52fe54f0
at
io.jenkins.plugins.analysis.core.steps.AnalysisExecution.getWorkspace(AnalysisExecution.java:99)
at io.jenkins.plugins.analysis.core.steps.PublishIssuesStep$Execution.run(PublishIssuesStep.java:415)
at io.jenkins.plugins.analysis.core.steps.PublishIssuesStep$Execution.run(PublishIssuesStep.java:372)
at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
```
As you can see, the Variable env.WORKSPACE is indeed null. But all the variables used in the publishIssue command are there.
How can I fix this?
Plugin-Version is 11.2.2
Jenkins-Version is 2.440.1
Any idea?
Thanks in advance
-----
According to the suggestion of @Noam I added the following
```
post {
agent {
node {
label AGENT
}
}
always {
script {
echo "ISSUES_DOXYGEN: ${ISSUES_DOXYGEN}"
echo "ISSUES_PCLINT: ${ISSUES_PCLINT}"
echo "ISSUES_AXIVION: ${ISSUES_AXIVION}"
echo "env.Workspace: ${env.WORKSPACE}"
if (env.BRANCH_NAME == 'main') {
// provided by warnings-ng-plugin
publishIssues (
issues: [
ISSUES_DOXYGEN,
ISSUES_PCLINT,
ISSUES_AXIVION
]
)
} else {
// provided by warnings-ng-plugin
publishIssues (
issues: [
ISSUES_PCLINT
]
)
}
}
}
}
```
still no success, workspace is still null. Also "label" is missing ...
Variable AGENT is used in other steps too with success.
Can someone answer with an example that works, please? It seems that I am missing the clue what to add where...
-----
Found a solutions that works now.
I need to change the global **agent** directive from **none** to **'any'**.
```
pipeline {
agent 'any'
...
}
```
After that the publishIssue step works again.
|
In my angular app there can be 2 type of layout(e.g. List and Detail).
I have to get the layoutConfig based on activated route. For this I'm using a route resolver.
My plan is ResolveFn will return a signal not an observable.
My *LayoutService* has an additional requirement, if its a List, it will get list data from layoutConfig's serviceUrl.
Below is my existing code which pass url as parameter and return an observable:
```
export const LayoutResolver: ResolveFn<LayoutConfig> = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
) => {
const _layoutService = inject(LayoutService);
_layoutService.setCurrentActivatedRoute(state.url);
return _layoutService.layoutConfig$;
};
```
```
export class LayoutService {
#httpClient = inject(ApiHttpService);
readonly #url_layout: string = 'listConfig';
constructor() {
effect(() => {
console.log('currentActivatedRoute', this.CurrentActivatedRouteSig());
});
}
CurrentActivatedRouteSig = signal<string | undefined>(undefined);
setCurrentActivatedRoute(url: string) {
this.CurrentActivatedRouteSig.set(url);
}
currentActivatedRoute$ = toObservable(this.CurrentActivatedRouteSig);
layoutConfig$ = this.currentActivatedRoute$
.pipe(
filter(Boolean),
switchMap(x => this.#httpClient.GETT<LayoutConfig>(`${this.#url_layout}`)
.pipe(
map(x => x.data)
))
);
LayoutConfigSig = toSignal(this.layoutConfig$, { initialValue: undefined });
private gridData$ = toObservable(this.LayoutConfigSig)
.pipe(
tap(x => console.log('gridData$ =>', x)),
filter(Boolean),
switchMap(x => this.#httpClient.GETT<any>(x.serviceUrl)
.pipe(
tap(x => console.log('serviceUrl$ =>', x.data)),
map(x => x.data)
))
)
GridDataSig = toSignal(this.gridData$, { initialValue: [] });
}
```
I'm expecting *LayoutConfigSig* and *GridDataSig(if List)* in my component as Signal. |
|c#|unity-game-engine| |
Localization languages are defined in the `AdministrationServiceDomainModule` (under **services/administration** folders). So, you can configure the localization languages there.
Alternatively, you can configure the localization languages in your final application. For example, if you selected the MVC UI, you can configure the localization in the `MyProjectNameWebModule` (under **apps/web** folders), or for Blazor `MyProjectNameBlazorModule` (under **apps/blazor** folders):
```csharp
Configure<AbpLocalizationOptions>(options =>
{
options.Languages.Clear();
options.Languages.Add(new LanguageInfo("en", "en", "English"));
options.Languages.Add(new LanguageInfo("de", "de", "Deutsch"));
});
``` |
It is recommended to use [Title bar customization][1] to get the effect you want. Add the image in the custom title bar.
### MainPage.xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="48"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid x:Name="AppTitleBar" Background="Transparent">
<Image Source="Assets/header.png"
Grid.Column="1"
HorizontalAlignment="Left"
Width="200" Height="50"
Margin="8,0,0,0"/>
</Grid>
<muxc:NavigationView Grid.Row="1" IsBackButtonVisible="Collapsed">
<muxc:NavigationView.MenuItems>
<muxc:NavigationViewItem Content="A"/>
<muxc:NavigationViewItem Content="B"/>
<muxc:NavigationViewItem Content="C"/>
</muxc:NavigationView.MenuItems>
<Frame x:Name="ContentFrame"/>
</muxc:NavigationView>
</Grid>
----------
### MainPage.xaml.cs
public MainPage()
{
this.InitializeComponent();
var coreTitleBar = CoreApplication.GetCurrentView().TitleBar;
coreTitleBar.ExtendViewIntoTitleBar = true;
// Set XAML element as a drag region.
Window.Current.SetTitleBar(AppTitleBar);
}
[1]: https://learn.microsoft.com/en-us/windows/uwp/ui-input/title-bar
|
|php|symfony|doctrine| |
null |
I want to add a moving circle on MKMapView it will remain in the centre of the map and start moving when the user moves the map and zoom in and zoom out when the user zooms in/out the map I am able to achieve this by using the centre coordinate of the map but when I move the app it is flickering as I am removing and adding the MKCircle overlay when the coordinate changes
Here is the code
**Adding pan gesture and circle overlay here**
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
mapView.isUserInteractionEnabled = true
mapView.showsUserLocation = true
mapView.showsCompass = false
let panGesture = UIPanGestureRecognizer(target: context.coordinator, action: #selector(context.coordinator.addPinBasedOnGesture(_:)))
panGesture.delegate = context.coordinator
mapView.addGestureRecognizer(panGesture)
return mapView
}
**Adding and removing method which updated the moving circle coordinate to**
func updateMovingCircle(regionToUpdate: MKCoordinateRegion, view: MKMapView) {
DispatchQueue.main.async {
addMovingCircle(to: view, movingLocation: CLLocationCoordinate2D(latitude: regionToUpdate.center.latitude, longitude: regionToUpdate.center.longitude), radius: radius)
}
}
**func to add and remove circle**
func addMovingCircle(to view: MKMapView, movingLocation: CLLocationCoordinate2D, radius: Int) {
for overlay in overlays where overlay.title == "1" {
view.removeOverlay(overlay)
}
let radius: Double = Double(radius) * 1.5
let movingCircle = MKCircle(center: movingLocation, radius: radius * 1000)
movingCircle.title = "1"
view.addOverlay(movingCircle)
}
**gesture recognizer delegate method on coordinator**
@objc func addPinBasedOnGesture(_ gestureRecognizer: UIGestureRecognizer) {
if let mapView = gestureRecognizer.view as? MKMapView {
mapViewController.updateMovingCircle(regionToUpdate: mapView.region, view: mapView)
}
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
**Overlay renderer**
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let circleOverlay = overlay as? MKCircle {
let circleRenderer = MKCircleRenderer(overlay: circleOverlay)
circleRenderer.strokeColor = UIColor(Color.SG.purple)
circleRenderer.lineWidth = 2
circleRenderer.lineDashPattern = [2, 5]
return circleRenderer
}
return MKOverlayRenderer()
}
This code is working but the experience is not smooth and circle is flickering |
Accelerated PyTorch for Macbook with AMD GPUS |
I am trying to run flet code on ubuntu 22.04 and keep getting the following error message
(flet:6177): Gdk-CRITICAL **: 11:08:50.080: gdk_window_get_state: assertion 'GDK_IS_WINDOW (window)' failed
What could be wrong? I have updated my system so its not about updates.
I have tried to run flet code on ubuntu 22.04 and I keep getting the following error message.
(flet:6177): Gdk-CRITICAL **: 11:08:50.080: gdk_window_get_state: assertion 'GDK_IS_WINDOW (window)' failed
what could be wrong? my system is up to date.
|
GDK Assertion IS_Window failed |
|flet| |
null |
|python|machine-learning|xgboost|shap| |
I have a question about understanding the behavior of clearRect() in JavaFX, using JavaFX 18.0.2 & OpenJDK 17.0.9+9:
In the following example, clearRect() doest not clear the given 10x10px area as expected.Output is:
**Try with Clear:**
Color:0xffffffff : 100
Color:0x0000ffff : 22379
Color:0x4040ffff : 1
Color:0x8080ffff : 20
**Try with fill**
Color:0xffffffff : 100
Color:0x0000ffff : 22400
I would expect `clearRect` having the same output as with `fillRect()`. But instead, with `clearRect()` some other colors appear.
EDIT
-
I disabled `hidpi` with `-Dprism.allowhidpi=false`. 0x4040ffff and 0x8080ffff seem to came from antialising. Now, with `hidpi=false`, the cleared `rect` is not 10x10px but 11x11:
**Try with Clear**
Color:0xffffffff : 121
Color:0x0000ffff : 22379
**Try with Fill**
Color:0xffffffff > 100
Color:0x0000ffff > 22400
Does anyone know whats happening?
```
import java.util.HashMap;
import java.util.Map;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.PixelReader;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ClearRectTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Canvas canvas = new Canvas(150, 150);
Group root = new Group();
root.getChildren().add(canvas);
primaryStage.setScene(new Scene(root));
primaryStage.show();
GraphicsContext gc = canvas.getGraphicsContext2D();
System.out.println("\nTry with Clear\n-");
gc.setFill(Color.BLUE);
gc.fillRect(0, 0, 150, 150);
gc.clearRect(30, 30, 10, 10);
{
Map<Color, Integer> colorMap = countColors(canvas);
for (Color c : colorMap.keySet()) {
System.out.println("Color:" + c + " : " + colorMap.get(c));
}
}
System.out.println("\n\nTry with fill\n-");
gc.setFill(Color.BLUE);
gc.fillRect(0, 0, 150, 150);
gc.setFill(Color.WHITE);
gc.fillRect(30, 30, 10, 10);
{
Map<Color, Integer> colorMap = countColors(canvas);
for (Color c : colorMap.keySet()) {
System.out.println("Color:" + c + " : " + colorMap.get(c));
}
}
}
public static Map<Color, Integer> countColors(Canvas canvas) {
WritableImage fxImage = canvas.snapshot(null, null);
Map<Color, Integer> map = new HashMap<>();
PixelReader pixelReader = fxImage.getPixelReader();
for (int y = 0; y < fxImage.getHeight(); ++y){
for (int x = 0; x < fxImage.getWidth(); ++x) {
Color c = pixelReader.getColor(x, y);
Integer i = map.get(c);
map.put(c, i == null ? 1 : i + 1);
}
}
return map;
}
public static void main(String[] args) {
launch(args);
}
}
``` |
Here is the official document about uninstalling the JDK.
https://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html#uninstall |
Upon checking, I found that there was no issue with the Flutter application; the problem was with the cache policy of the website I was trying to access. |
I am attempting to perform Device Authorization Flow on a CLI in Go. I have followed the steps in https://auth0.com/blog/securing-a-python-cli-application-with-auth0/ to set up my application in Auth0. After successfully requesting a device code, I attempt to get a request token.
```
// Gets a request token.
func (loginJob *LoginJob) GetRequestToken(deviceCodeData loginResponse.LResponse) error {
//Setup an http request to retreive a request token.
url := loginJob.Domain + "/oauth/token"
method := "POST"
payload := strings.NewReader("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=" +
deviceCodeData.DeviceCode + "&client_id=" + loginJob.ClientID)
client := &http.Client{}
req, reqErr := http.NewRequest(method, url, payload)
if reqErr != nil {
fmt.Println(reqErr)
return reqErr
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
authenticate := false
for !authenticate {
authenticate = PollRequestTokenStatus(req, client)
time.Sleep(time.Duration(deviceCodeData.Interval) * time.Second)
}
return nil
}
func PollRequestTokenStatus(req *http.Request, client *http.Client) bool {
res, resErr := client.Do(req)
if resErr != nil {
log.Panic(resErr)
return true
}
defer res.Body.Close()
body, ReadAllErr := io.ReadAll(res.Body)
if ReadAllErr != nil {
fmt.Println(ReadAllErr)
return true
}
fmt.Println("res.Body: ")
fmt.Println(string(body))
if res.StatusCode == 200 {
fmt.Println("Authenticated!")
fmt.Println("- Id Token: ")
return true
} else if res.StatusCode == 400 {
fmt.Println("res.StatusCode: ")
fmt.Print(res.StatusCode)
return false
} else {
fmt.Println("res.StatusCode: ")
fmt.Print(res.StatusCode)
}
return false
}
```
The idea is that I poll Auth0 for a request token at specific intervals. The first time I poll, I get a 403 Forbidden:
```
{"error":"authorization_pending","error_description":"User has yet to authorize device code."}
```
However, on subsequent polls, I get 400 Bad Request:
```
<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>cloudflare</center>
</body>
</html>
```
I am unsure why this is happening. I have tried manually polling Auth0 with Postman, and I have always managed to avoid error 400 using Postman.
[![Manually polling Auth0 with Postman][1]][1]
How do I fix this problem?
[1]: https://i.stack.imgur.com/tlAz0.png |
Auth0 return status code 400 after on subsequent polls for request token |
|go|httprequest|auth0| |
I'm trying to add items to a linked list, however if an node's data repeats instead of returning the new node it should return the original node with the same data.
I have a test file along with the methods I'm testing. the trouble comes from my addOnce() method returning the node parsed through instead of the first occurrence. trying to avoid
"Error: The initial item was not returned for " + result" line of code
here's the test block of code, no editing required
```
import java.util.Iterator;
public class OrderedListTest {
static private class Courses implements Comparable<Courses>{
String rubric;
int number;
int occurance;
public Courses(String rub, int num, int occ) {
rubric = rub;
number = num;
occurance = occ;
}
public int compareTo(Courses other) {
if (rubric.compareTo(other.rubric) < 0)
return -1;
else if (rubric.compareTo(other.rubric) > 0)
return 1;
else
return number - other.number;
}
public String toString() {
return rubric + " " + number;
}
}
public static void main(String[] args) {
Courses listOfCourses[] = {
new Courses("COSC", 2436, 1),
new Courses("ITSE", 2409, 1),
new Courses("COSC", 1436, 1),
new Courses("ITSY", 1300, 1),
new Courses("ITSY", 1300, 2),
new Courses("COSC", 1436, 2),
new Courses("COSC", 2436, 2),
new Courses("ITSE", 2417, 1),
new Courses("ITNW", 2309, 1),
new Courses("CPMT", 1403, 1),
new Courses("CPMT", 1403, 2)};
OrderedAddOnce<Courses> orderedList = new OrderedAddOnce<Courses>();
Courses result;
for (int i = 0; i < listOfCourses.length; i++){
result = orderedList.addOnce(listOfCourses[i]);
if (result == null)
System.out.println("Error: findOrAdd returned null for " +
listOfCourses[i]);
else {
if (result.occurance != 1)
System.out.println("Error: The initial item was not returned for " + result);
if (result.compareTo(listOfCourses[i]) != 0)
System.out.println("Error: " + listOfCourses[i] + " was passed to findOrAdd but " + result + " was returned");
}
}
Iterator<Courses> classIter = orderedList.iterator();
while(classIter.hasNext()) {
System.out.println(classIter.next());
}
// There should be 7 courses listed in order
}
}
```
Here's the code in need of debugging, specifically in the addOnce() method
```
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
*
* @author User
*/
// Interface for COSC 2436 Labs 3 and 4
/**
* @param <E> The class of the items in the ordered list
*/
interface AddOnce <E extends Comparable<? super E>> {
/**
* This method searches the list for a previously added
* object, if an object is found that is equal (according to the
* compareTo method) to the current object, the object that was
* already in the list is returned, if not the new object is
* added, in order, to the list.
*
* @param an object to search for and add if not already present
*
* @return either item or an equal object that is already on the
* list
*/
public E addOnce(E item);
}
//generic linked list
public class OrderedAddOnce<E extends Comparable<? super E>> implements Iterable<E>, AddOnce<E> {
private Node<E> firstNode;
public OrderedAddOnce() {
this.firstNode = null;
}
@Override
public E addOnce(E item) {
Node<E> current;
if (firstNode == null || item.compareTo(firstNode.data) <= 0) {
Node<E> newNode = new Node<>(item);
newNode.next = firstNode;
firstNode = newNode;
return firstNode.data;
}
current = firstNode;
while (current.next != null && item.compareTo(current.next.data) > 0) {
current = current.next;
}
Node<E> newNode = new Node<>(item);
newNode.next = current.next;
current.next = newNode;
return newNode.data;
}
@Override
public Iterator iterator() {
return new AddOnceIterator();
}
private class AddOnceIterator implements Iterator{
private Node<E> currentNode = firstNode;
@Override
public boolean hasNext() {
return currentNode != null;
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
E data = currentNode.data;
currentNode = currentNode.next;
return data;
}
}
private class Node<E> {
public E data;
public Node<E> next;
public Node(E intialData){
this.data = intialData;
this.next = null;
}
}
}
```
I've tried swapping the return statement values from newNode.data, current.data, item. but it returns the same error messages regardless
Error: The initial item was not returned for ITSY 1300
Error: The initial item was not returned for COSC 1436
Error: The initial item was not returned for COSC 2436
Error: The initial item was not returned for CPMT 1403
COSC 1436
COSC 1436
COSC 2436
COSC 2436
CPMT 1403
CPMT 1403
ITNW 2309
ITSE 2409
ITSE 2417
ITSY 1300
ITSY 1300
I'm expecting the list without duplicates |
What line of code do I change to avoid duplication in a linked list? |
|java|generics|linked-list|duplicates|nodes| |
null |
{"Voters":[{"Id":-1,"DisplayName":"Community"}]} |
After upgrading to openjdk 17, test cases are failing with error<br>
**Exception in thread "closer-shutdown-hook" java.lang.NoClassDefFoundError: org/apache/maven/plugin/surefire/booterclient/output/InPluginProcessDumpSingleton
at org.apache.maven.plugin.surefire.booterclient.ForkStarter$CloseableCloser.run(ForkStarter.java:209)
at java.base/java.lang.Thread.run(Thread.java:833)**
Full trace
```
**Caused by: org.apache.maven.surefire.booter.SurefireBooterForkException: The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
Command was /bin/sh -c cd /builds/some-module && /opt/jdk-17.0.7+7/bin/java '-javaagent:/root/.m2/repository/org/jacoco/org.jacoco.agent/0.8.8/org.jacoco.agent-0.8.8-runtime.jar=destfile=/builds/path/target/jacoco.exec,append=true -Duser.language=en -Dfile.encoding=UTF-8 -XX:+UseG1GC -XX:+UseStringDeduplication -XX:+ParallelRefProcEnabled -XX:MaxHeapSize=2g -Xmx2g --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.util.function=ALL-UNNAMED --add-opens=java.base/java.util.stream=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.xml/com.sun.org.apache.xerces.internal.impl=ALL-UNNAMED --add-opens=java.xml/com.sun.org.apache.xerces.internal.xni=ALL-UNNAMED --add-opens=java.xml/com.sun.org.apache.xerces.internal.xni.parser=ALL-UNNAMED --add-opens=java.xml/com.sun.org.apache.xerces.internal.util=ALL-UNNAMED --add-opens=java.base/java.nio.file=ALL-UNNAMED --add-opens=java.base/java.time=ALL-UNNAMED --add-opens=java.base/jdk.internal.reflect=ALL-UNNAMED --add-opens=java.base/java.util.regex=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED org.apache.maven.surefire.booter.ForkedBooter /builds/path/target/surefire 2024-03-14T15-01-53_612-jvmRun2 surefire7317203603829991286tmp surefire_113447887520135489243tmp
Error occurred in starting fork, check output in log
Process Exit Code: 137
Crashed tests:
org.TestClass
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork (ForkStarter.java:748)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.access$700 (ForkStarter.java:121)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter$1.call (ForkStarter.java:393)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter$1.call (ForkStarter.java:370)
at java.util.concurrent.FutureTask.run (FutureTask.java:264)
at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1136)
at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:635)
at java.lang.Thread.run (Thread.java:833)
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
Exception in thread "closer-shutdown-hook" java.lang.NoClassDefFoundError: org/apache/maven/plugin/surefire/booterclient/output/InPluginProcessDumpSingleton
at org.apache.maven.plugin.surefire.booterclient.ForkStarter$CloseableCloser.run(ForkStarter.java:209)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.ClassNotFoundException: org.apache.maven.plugin.surefire.booterclient.output.InPluginProcessDumpSingleton
at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
... 2 more**
```
```
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<append>true</append>
<!-- surefire (unit tests runner) arguments -->
<propertyName>surefireJacocoArgs</propertyName>
<includes>
<include>org.somepackage.*</include>
</includes>
</configuration>
</execution>
<!-- attached to Maven test phase -->
<execution>
<id>jacoco-report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<!-- report output dir -->
<outputDirectory>target/jacoco-reports</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
<forkCount>2</forkCount>
<reuseForks>true</reuseForks>
<failIfNoTests>false</failIfNoTests>
<trimStackTrace>false</trimStackTrace>
<redirectTestOutputToFile>true</redirectTestOutputToFile>
<excludes>
<exclude>**/*File.java</exclude>
</excludes>
<runOrder>alphabetical</runOrder>
<rerunFailingTestsCount>5</rerunFailingTestsCount>
<argLine>
${surefireJacocoArgs} ${argline-add-open}
</argLine>
</configuration>
</plugin>
</plugins>
</build>
```
Previously i was on openjdk 11, same used to work. suspecting issue is with maven surefire plugin incompatible with java 17. i even upgraded surefire to latest version still faced same issue
**Update 1**
After removing `useSystemClassLoader` flag, now i see another error <br> Process exit code --> 137 issue related to memory
```
ExecutionException The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
Command was /bin/sh -c cd /builds/modules/module1 && /opt/jdk-17.0.7+7/bin/java '-javaagent:/root/.m2/repository/org/jacoco/org.jacoco.agent/0.8.8/org.jacoco.agent-0.8.8-runtime.jar=destfile=/builds/modules/module1/target/jacoco.exec,append=true -Duser.language=en -Dfile.encoding=UTF-8 -Xmx5g --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util.function=ALL-UNNAMED --add-opens java.base/java.util.stream=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED --add-opens java.xml/com.sun.org.apache.xerces.internal.impl=ALL-UNNAMED --add-opens java.xml/com.sun.org.apache.xerces.internal.xni=ALL-UNNAMED --add-opens java.xml/com.sun.org.apache.xerces.internal.xni.parser=ALL-UNNAMED --add-opens java.xml/com.sun.org.apache.xerces.internal.util=ALL-UNNAMED --add-opens java.base/java.nio.file=ALL-UNNAMED --add-opens java.base/java.time=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/jdk.internal.reflect=ALL-UNNAMED --add-opens java.base/java.util.regex=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED org.apache.maven.surefire.booter.ForkedBooter /builds/modules/module1/target/surefire 2024-03-14T10-28-32_626-jvmRun4 surefire8889132164816018609tmp surefire_1182817604224050150tmp
Error occurred in starting fork, check output in log
Process Exit Code: 137
Crashed tests:
SomeTestClass
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.awaitResultsDone(ForkStarter.java:532)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.runSuitesForkOnceMultiple(ForkStarter.java:405)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:321)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:266)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1314)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:1159)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:932)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:193)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)
Caused by: org.apache.maven.surefire.booter.SurefireBooterForkException: The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
``` |
Thread 46: "UIGraphicsBeginPDFContextToFile() failed to allocate CGPDFContext: bounds={{inf, inf}, {0, 0}}, path=/Users/kishanvirani/Library/Developer/CoreSimulator/Devices/B1AA298A-2DDE-46BA-9091-9D9A45F9240C/data/Containers/Data/Application/0FC5CFB0-916F-4646-9342-5A463F84F10A/Library/Caches/EasyPdfViewer/F9807771-01F9-4F15-AD56-72ABAF22414C-0.png, documentInfo=(null). Use UIGraphicsPDFRenderer to avoid this assert."
I got this error when load pdf on IOS device |
libc++abi: terminating due to uncaught exception of type NSException when load PDF on IOS Device |
|ios|flutter| |
null |
I'm making a psychological quiz шт REACT. There is text. In a text editor. The text consists of 100 questions and 340 answers. How to make a React program that took at least 2 questions, preferably 10 questions at once, and inserted brackets and other characters so that this data could be taken from an array file? I put a plus sign next to the correct answer.
# As I understand it, regular expressions and array are needed...
Example-
1. Which of the following concepts corresponds to “Psyche” among the ancient Greeks:
Nervous system
+Soul
Psyche
Superego
Consciousness
2. Which of the Greek philosophers admits that the mind depends on the nature of the fire in the soul:
Galen
Socrates
+ Heraclitus
Pythagoras
Data in Data.js-
Example
```
{
question: ' 1. Which of the following concepts corresponds to “Psyche” among the ancient Greeks: ',
incorrectAnswers: [
"Nervous system",
"psyche",
"Суперэго",
"Consciousness",
],
correctAnswer: "Soul",
},
{
question:
"2. Which of the Greek philosophers admits that the mind depends on the nature of the fire in the soul: ",
incorrectAnswers: [
"Galen",
"Socrates",
"Pythagoras“,
],
correctAnswer: "Heraclitus",
},
```
[enter image description here](https://i.stack.imgur.com/jkMhe.png)
[enter image description here](https://i.stack.imgur.com/j98ak.png)
I'm completely confused. How can you select the correct text with questions and answers from one array of text and place the correct answer separately? |
The redirect URI in the initial auth link should not be pointing to redirect_uri=https://mysecurity.keycloak.com/realms/myrealm/account, instead it should point back to your application.
This redirect_URI needs to match the redirect URL defined inside KeyCloak EXACTLY.
The URL should not be your welcome page, it should point to where KeyCloak should post the authorization code and other information. So your client can then retrieve the tokens from KeyCloak. what this url is, all depends on what libraries you are using.
If you use ASP.NET Core, it is typically /signin-oidc
|
Seems like nativewind has two separate documentations. One for v2 (default) and one for v4.
With v2 I was encountering this error. But with v4, the setup works
V4 link: https://www.nativewind.dev/v4/overview
Here is my complete setup.
package.json
```{
"name": "habitapp",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo run:android",
"ios": "expo run:ios",
"web": "expo start --web"
},
"dependencies": {
"@babel/plugin-proposal-export-namespace-from": "^7.18.9",
"expo": "~50.0.6",
"expo-status-bar": "~1.11.1",
"nativewind": "^4.0.1",
"react": "18.2.0",
"react-native": "0.73.4",
"react-native-reanimated": "~3.6.2"
},
"devDependencies": {
"@babel/core": "^7.24.0",
"tailwindcss": "^3.4.1"
},
"private": true
}
```
tailwind.config.js
```
/** @type {import('tailwindcss').Config} */
module.exports = {
// NOTE: Update this to include the paths to all of your component files.
content: ["./App.{js,jsx,ts,tsx}", "./screens/**/*.{js,jsx,ts,tsx}"],
presets: [require("nativewind/preset")],
theme: {
extend: {},
},
plugins: [],
}
```
metro.config.js
```
const { getDefaultConfig } = require("expo/metro-config")
const { withNativeWind } = require("nativewind/metro")
const config = getDefaultConfig(__dirname)
module.exports = withNativeWind(config, { input: "./global.css" })
```
babel.config.js
```
module.exports = function (api) {
api.cache(true)
return {
presets: [
["babel-preset-expo", { jsxImportSource: "nativewind" }],
"nativewind/babel",
],
plugins: [
"react-native-reanimated/plugin",
"@babel/plugin-proposal-export-namespace-from",
],
}
}
```
Hope this helps! |
Add this Code to your script
<script>
function logicalAND($opA, $opB) {
if($opA) {
if($opB) {
return true;
}
}
return false;
}
if (logicalAND(script.readyState, script.onload) !== null){
...
</script> |
If you're after building an `Explanation` object (not `Explainer` like you stated in your question), then you can do the following:
import xgboost as xgb
import shap
from sklearn.model_selection import train_test_split
X, y = shap.datasets.california()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
d_train = xgb.DMatrix(X_train, y_train)
d_test = xgb.DMatrix(X_test, y_test)
params = {"objective": "reg:squarederror", "tree_method": "hist", "device":"cuda"}
model = xgb.train(params, d_train, 100)
shap_values = model.predict(d_test, pred_contribs=True)
exp = shap.Explanation(shap_values[:,:-1], data = X_test, feature_names=X.columns)
shap.summary_plot(exp)
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/0iYax.png |
First set up some test files and create `features`. Now read the files into `DFs` and create a `years` vector that gives the corresponding year for each entry in `DFs` splitting `DFs` by `years` giving `spl`. Then for each component of the split perform the merge.
# set up test files
for(year in c(2015, 2019, 2022))
for(let in letters[1:3])
write.csv(BOD + year + match(let, letters), paste0("BOD-", year, let, ".csv"),
row.names = FALSE, quote = FALSE)
features <- dir()
# we now have features and the test files so process them
DFs <- Map(read.csv, features)
years <- gsub("\\D", "", features)
spl <- split(DFs, years)
L <- lapply(spl, \(x) Reduce(function(x, y) merge(x, y, by="Time", all=TRUE), x))
str(L) # show structure of result
giving:
List of 3
$ 2015:'data.frame': 9 obs. of 4 variables:
..$ Time : int [1:9] 2017 2018 2019 2020 2021 2022 2023 2024 2025
..$ demand.x: num [1:9] 2024 2026 2035 2032 2032 ...
..$ demand.y: num [1:9] NA 2025 2027 2036 2033 ...
..$ demand : num [1:9] NA NA 2026 2028 2037 ...
$ 2019:'data.frame': 9 obs. of 4 variables:
..$ Time : int [1:9] 2021 2022 2023 2024 2025 2026 2027 2028 2029
..$ demand.x: num [1:9] 2028 2030 2039 2036 2036 ...
..$ demand.y: num [1:9] NA 2029 2031 2040 2037 ...
..$ demand : num [1:9] NA NA 2030 2032 2041 ...
$ 2022:'data.frame': 9 obs. of 4 variables:
..$ Time : int [1:9] 2024 2025 2026 2027 2028 2029 2030 2031 2032
..$ demand.x: num [1:9] 2031 2033 2042 2039 2039 ...
..$ demand.y: num [1:9] NA 2032 2034 2043 2040 ...
..$ demand : num [1:9] NA NA 2033 2035 2044 .
|
My method of generating a random string with full range of ascii.
use rand::Rng;
fn main() {
let value: String = (0..100).map(|_| char::from(rand::thread_rng().gen_range(32..127))).collect();
println!("{}", value);
}
Example output:
**n/5;X D0}xbc8sEGY^cHSW3BiV-Ws "pojGKo93pbu0iZ#iT^f(L?S8j{-e^tbz^htQ"?{C'I+}ny|/[Qy.(>wGFzC%W,9*9j%Y_** |
Using any sed:
$ sed 's/\\/\\\\/' file
Hello\\nmate
$ sed 's/\(.*\)\\\(.*\)/{"output":"\1\\\\\2"}/' file
{"output":"Hello\\nmate"}
The above was run on this input file:
$ cat file
Hello\nmate
If your input instead looked like this:
$ cat file
Hello
mate
and you want to replace all LineFeeds except the last one (assuming it's a valid POSIX text file) with `\\n` then you could do the following using any awk:
$ awk '{rec=rec sep $0; sep="\\\\n"} END{printf "{\"output\":\"%s\"}\n", rec}' file
{"output":"Hello\\nmate"}
|
Adding moving circle overly on MKMapView on iOS 16 and above |
|ios|swiftui|mkmapview|overlay|mkcircle| |
I have several larger files (400-800MiB) in which I need to convert Hex values to others.
I can do this in some Hex editor, but I would like to do it automatically, in a Bash script.
I know how to check with xxd whether a given value is in a file:
FILE='file.vpk'
SEARCH_STRING='MaxRagdollCount'
OLD_HEX_VALUE="$( echo -n "$SEARCH_STRING" | xxd -p )"
HEX_VALUE=($( xxd -p "$FILE" | grep -E -o "${OLD_HEX_VALUE}222022[0-9]{,2}22" ))
echo "$HEX_VALUE"
but I can't figure out how to edit it.
I need to replace the value of
> MaxRagdollCount" "any_number"
(4d6178526167646f6c6c436f756e742220223222)
with
> MaxRagdollCount" "9"
(4d6178526167646f6c6c436f756e742220223922).
|
Edit the file and replace the Hex value with Bash script |
|linux|bash|hex| |
Change your code from:
@{
await Component.InvokeAsync("Edit", new { config = new List<EditConfiguration>() });
}
To:
@await Component.InvokeAsync("Edit",new { config = new List<EditConfiguration>() })
|
I have a vectorised def:
def selection_update_weights(df):
# Define the selections for 'Win'
selections_win = ["W & O 2.5 (both untested)", "Win (untested) & O 2.5", "Win & O 2.5 (untested)", "W & O 2.5",
"W & O 1.5 (both untested)", "Win (untested) & O 1.5", "Win & O 1.5 (untested)", "W & O 1.5",
"W & U 4.5 (both untested)", "Win (untested) & U 4.5", "Win & U 4.5 (untested)", "W & U 4.5",
"W (untested)", "W"]
# Create a boolean mask for the condition for 'Win'
mask_win = (df['selection_match'] == "no match") & \
(df['selection'].isin(selections_win)) & \
(df['result_match'] == "no match") & \
(df['result'] != 'draw')
# Apply the condition and update the 'Win' column
df.loc[mask_win, 'Win'] = df.loc[mask_win, 'predicted_score_difference'] + 0.02
# Define the selections for 'DNB'
selections_DNB = ["DNB or O 2.5 (both untested)", "DNB (untested) or O 2.5", "DNB or O 2.5 (untested)",
"DNB or O 2.5", "DNB or O 1.5 (both untested)", "DNB (untested) or O 1.5",
"DNB or O 1.5 (untested)", "DNB or O 1.5", "DNB (untested)", "DNB"]
# Create a boolean mask for the condition for 'DNB'
mask_DNB = ((df['selection_match'] == 'no match') & \
(df['selection'].isin(selections_DNB)) & \
(df['result_match'] == 'no match') & \
(df['result'] != 'draw'))
# Apply the condition and update the 'DNB' column
df.loc[mask_DNB, 'DNB'] = df.loc[mask_DNB, 'predicted_score_difference'] + 0.02
# Define the selections for O 1.5'
selections_O_1_5 = ["W & O 1.5 (both untested)", "Win (untested) & O 1.5", "Win & O 1.5 (untested)",
"W & O 1.5", "DNB or O 1.5 (both untested)", "DNB (untested) or O 1.5",
"DNB or O 1.5 (untested)", "DNB or O 1.5", "O 1.5 (untested)", "O 1.5"]
# Create a boolean mask for the condition for 'O 1.5'
mask_O_1_5 = ((df['selection_match'] == 'no match') & \
(df['selection'].isin(selections_O_1_5)) & \
(df['total_score'] < 2))
# Apply the condition and update the 'O 1.5' column
df.loc[mask_O_1_5, 'O_1_5'] = df.loc[mask_O_1_5, 'predicted_total_score'] + 0.02
# Define the selections for O 2.5'
selections_O_2_5 = ["W & O 2.5 (both untested)", "Win (untested) & O 2.5", "Win & O 2.5 (untested)",
"W & O 2.5", "DNB or O 2.5 (both untested)", "DNB (untested) or O 2.5",
"DNB or O 2.5 (untested)", "DNB or O 2.5", "O 2.5 (untested)", "O 2.5"]
# Create a boolean mask for the condition for 'O 2.5'
mask_O_2_5 = ((df['selection_match'] == 'no match') & \
(df['selection'].isin(selections_O_2_5)) & \
(df['total_score'] < 3))
# Apply the condition and update the 'O 2.5' column
df.loc[mask_O_2_5, 'O_2_5'] = df.loc[mask_O_2_5, 'predicted_total_score'] + 0.02
# Define the selections for U 4.5'
selections_U_4_5 = ["W & U 4.5 (both untested)", "Win (untested) & U 4.5", "Win & U 4.5 (untested)",
"W & U 4.5", "U 4.5 (untested)", "U 4.5"]
# Create a boolean mask for the condition for 'O 2.5'
mask_U_4_5 = ((df['selection_match'] == 'no match') & \
(df['selection'].isin(selections_U_4_5)) & \
(df['total_score'] > 4))
# Apply the condition and update the 'O 2.5' column
df.loc[mask_U_4_5, 'U_4_5'] = df.loc[mask_U_4_5, 'predicted_total_score'] - 0.02
return df
and I apply it by:
df = selection_update_weights(df)
While I have a very large dataframe, This snippet **is where the weights dont get updated**. Weights are updated partially. And I am not sure why.
df.head():
home_score away_score total_score score_difference predicted_total_score predicted_score_difference result predicted_result result_match Win DNB O_1_5 O_2_5 U_4_5 selection selection_match
44 3 3 6 0 8.748172 8.135116 draw home no match 1.1 0.7 2.0 3.000000 4.0 W & O 2.5 (both untested) no match
50 1 0 1 1 8.605350 7.932909 home home match 1.1 0.7 2.0 8.625350 4.0 W & O 1.5 (both untested) no match
57 1 1 2 0 7.510030 7.750101 draw home no match 1.1 0.7 2.0 7.530030 4.0 W & O 1.5 (both untested) no match
62 0 1 1 1 8.895045 7.710740 away away match 1.1 0.7 2.0 8.915045 4.0 W & O 1.5 (both untested) no match
85 1 0 1 1 8.099853 7.444815 home home match 1.1 0.7 2.0 8.119853 4.0 W & O 1.5 (both untested) no match
so when i am applying it:
df = selection_update_weights(df)
I should ideally get
home_score away_score total_score score_difference predicted_total_score predicted_score_difference result predicted_result result_match Win DNB O_1_5 O_2_5 U_4_5 selection selection_match
3 3 6 0 8.748172 8.135116 draw home no match 8.155116 0.7 2.0 3 4.0 W & O 2.5 (both untested) no match
1 0 1 1 8.605350 7.932909 home home match 1.100000 0.7 8.625350 8.625350 4.0 W & O 1.5 (both untested) no match
1 1 2 0 7.510030 7.750101 draw home no match 7.770101 0.7 2.0 7.530030 4.0 W & O 1.5 (both untested) no match
0 1 1 1 8.895045 7.710740 away away match 1.100000 0.7 8.915045 8.915045 4.0 W & O 1.5 (both untested) no match
1 0 1 1 8.099853 7.444815 home home match 1.100000 0.7 8.119853 8.119853 4.0 W & O 1.5 (both untested) no match
However thats not happening and the original dataframe is unaffected.
|
> ...and the problem seems doesn't reach to solution
This is exactly the problem that is also mentioned on [Wikipedia](https://en.wikipedia.org/wiki/Knight%27s_tour):
> A brute-force search for a knight's tour is impractical on all but the smallest boards. For example, there are approximately 4×10<sup>51</sup> possible move sequences on an 8×8 board, and it is well beyond the capacity of modern computers (or networks of computers) to perform operations on such a large set.
The order of moves in the implementation you quote from GfG, is a *lucky* order. With the order that you have tested with, the amount of backtracking is enormous. One can imagine that taking the right moves in the very beginning of the path is crucial. If one of the early moves is wrong, there will be a tremendous amount of backtracking taking place in the deeper nodes of the recursion tree.
There is a heuristic that greatly reduces the number of moves to consider, most of the time only 1: this is [Warnsdorff's rule](https://en.wikipedia.org/wiki/Knight%27s_tour#Warnsdorff's_rule):
> The knight is moved so that it always proceeds to the square from which the knight will have the fewest onward moves. When calculating the number of onward moves for each candidate square, we do not count moves that revisit any square already visited. It is possible to have two or more choices for which the number of onward moves is equal; there are various methods for breaking such ties,...
In the case of an 8×8 board there is no practical need for breaking ties: the backtracking will resolve wrong choices. But as now the search tree is very narrow, this does not lead to a lot of backtracking, even if we're unlucky.
Here is an implementation in a runnable JavaScript snippet. It intentionally shuffles the list of moves randomly, and prints "backtracking" whenever it needs to backtrack, so that you can experiment on different runs. This will show that this always finds the solution with hardly any backtracking on average:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
class Solver {
constructor(size) {
this.size = size;
this.grid = Array.from({length: size}, () => Array(size).fill(-1));
}
toString() {
return this.grid.map(row =>
row.map(i => (i + "").padStart(2, "0")).join(" ")
).join("\n");
}
liberty(x, y) {
// Count the number of legal moves
return [...this.getMoveList(x, y)].length;
}
*getMoveList(x, y) {
// Get list of legal moves, in random order
let moves = [[1, 2], [1, -2], [-1, -2], [-1, 2],
[2, -1], [2, 1], [-2, -1], [-2, 1]];
// Shuffle moves randomly
for (var i = moves.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
[moves[i], moves[j]] = [moves[j], moves[i]]; // Swap
}
// Yield the valid positions that can be reached
for (let [moveX, moveY] of moves) {
if (this.grid[x + moveX]?.[y + moveY] == -1) {
yield [x + moveX, y + moveY];
}
}
}
getBestMoveList(x, y) {
// Get list of move(s) that have the least possible follow-up moves
let minLiberty = 100000;
const bestMoves = [];
// Consider every legal move:
for (let [nextX, nextY] of this.getMoveList(x, y)) {
let liberty = this.liberty(nextX, nextY);
if (liberty < minLiberty) {
minLiberty = liberty;
bestMoves.length = 0; // Empty the array
}
if (liberty == minLiberty) bestMoves.push([nextX, nextY]);
}
if (Math.random() >= 0.5) bestMoves.reverse();
return bestMoves;
}
solve(x, y, moveCount=0) {
this.grid[x][y] = moveCount++;
if (moveCount == this.size * this.size) return true;
// Try all of the BEST next moves from the current coordinate x, y
for (let [nextX, nextY] of this.getBestMoveList(x, y)) {
if (this.solve(nextX, nextY, moveCount)) return true;
}
console.log("backtrack");
this.grid[x][y] = -1;
return false;
}
}
// Driver code
const solver = new Solver(8);
let success = solver.solve(0, 0);
console.log(success ? solver.toString() : "Solution does not exist");
<!-- end snippet -->
|
On the Docker Engine earlier than version 23.0, the legacy Docker Engine builder processes all stages of a Dockerfile leading up to the selected **`--target`**. It will build a stage even if the selected target doesn't depend on that stage.
However, since Docker Engine 23.0, **BuildKit** is the default builder for users. BuildKit only builds the stages that the target stage depends on.
For your case, with BuildKit enabled (**DOCKER_BUILDKIT=1**):
- The target stage (**`final`**) depends on '**`base`**' (`FROM base AS final`) and '**`publish`**' (`COPY --from=publish /app/publish .`) stages.
- The '**`publish`**' depends on '**`build`**' stage (`FROM build AS publish`). So, the target stage also is determined to depend on '**`build`**' stage.
- The '**`test`**' stage is not depended on by the target stage, and the other stages depended on by the target stage also does not depend on the '**`test`**' stage.
So, finally, only the '**`base`**', '**`build`**', '**`publish`**' and '**`final`**' stages are executed when building the Dockerfile.
---
To disable BuildKit, you can use one of the following methods:
1. Set the pipeline variable below. It will map/override the environment variable with the new value "**DOCKER_BUILDKIT=0**".
```yaml
variables:
DOCKER_BUILDKIT: 0
```
2. Directly add "**DOCKER_BUILDKIT=0**" before the "**`docker build`**" command. It will build Dockerfile with BuildKit disabled.
```sh
DOCKER_BUILDKIT=0 docker build xxx
```
---
Related documentations:
- [**BuildKit**][1]
- [**Multi-stage builds**][2]
---
[1]: https://docs.docker.com/build/buildkit/
[2]: https://docs.docker.com/build/building/multi-stage/#differences-between-legacy-builder-and-buildkit |
How I solved my issue?
I don't know the actual reason for this error and its solution but I deleted mongodb database folders `C:\data\db` and restarted my PC.
**Note:** This is not a recommended solution for production env. |
I am writing a package to be shared by various projects. I have import statements in my package such as:
```from my_package.module.script import foo```
However if I place this package in my project under any name other than `my_project` then the code will break. Is there a way around this **without** relying on relative imports since relative imports get really messy to write? |
Absolute import in package of unknown name |
|python|import|package| |
I am trying to run java microservices on an Macbook Pro with M1 Arm processor.
The Internet is awash with instructions on this. Most of them declare victory at getting Minikube to run. I haven't found any that carry this all the way to having even a Hello World service deployed all the way from source code.
My current toolset is Podman with Minikube using Containerd. I'm not unwaveringly committed to this setup although it does seem the most desirable to me, and I'd like to get it working because I foolishly believe this is the last hurdle.
I have made it this far:
Created Podman VM with generous allocations of cpu, memory, etc
Modified registries.conf
unqualified-search-registries = ["docker.io"]
registries = ['localhost:41597']
Installed Minikube and start with --driver=podman --container-runtime-containerd
Minikube addons: storage-provisioner, ingress-dns, dashboard, registry-creds, logviewer, metallb, default-storageclass, metrics-server, ingress, registry
Told minikube to use docker registry: minikube -p minikube docker-env
Then I can build an image using podman build and it shows up in the podman image repository
But when I try to install it with helm I see this error in the Pod Events:
> failed to resolve reference "localhost:41597/auth-server:latest"
Poking at podman with postman I get an http 200 for localhost:41597/v2 so that endpoint is good. I am of course less certain about what "localhost" means inside kubernetes, but for right now I'm hoping for the best.
The problem is that auth-server is not valid (404). Even though the image is clearly there:
REPOSITORY TAG IMAGE ID CREATED SIZE
localhost/auth-server latest 69b8f90684e2 16 hours ago 391 MB
Any advice on my apparent registry problem - or links to a better solution greatly appreciated! |
Minikube cannot access Podman Registry |
|minikube|podman|apple-silicon| |
For some reason I had next as a dev-dependency, once i moved it to a dependency, it fixed it for me. |
Add these two permission in the androidmanifest file:
```xml
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO"/>
``` |
Add this code snippet to your script
<script>
function logicalAND($opA, $opB) {
if($opA) {
if($opB) {
return true;
}
}
return false;
}
if (logicalAND(script.readyState, script.onload) !== null){
...
</script> |