instruction stringlengths 0 30k ⌀ |
|---|
Slow pagespeed render delay |
|performance|pagespeed| |
null |
```
const date = ref(new Date(2024, 1, 19))
<v-date-picker v-model="date" :rows="2" :step="1" class="bg-surface" locale="tr" />
```
[enter image description here](https://i.stack.imgur.com/0Er7c.png)
I am using vue nuxtjs vuetify. I want to show more than one selected date in date picker. I tried the Multiple feature but it didn't work. Can you help? |
There is currently no way to access the Track Changes feature with the Office JavaScript APIs. But it is a good idea, so please raise it at [M365 Dev Platform Ideas](https://techcommunity.microsoft.com/t5/microsoft-365-developer-platform/idb-p/Microsoft365DeveloperPlatform). First search to see if someone has already made this suggestion.
|
had the same issue just recently. my problem was that my view classes were inhereting from `dajngo.views.generic.<view name>` instead of `rest_framework.generics.<view name>` and yasg was ignoring them since they were not REST endpoints. |
"I'm puzzled why post.title and post.body aren't updating as expected. I attempted to manage separate state variables for title and body, but the issue persisted."
**CreatePost.jsx**
```
export default function CreatePost() {
const [post, setPost] = useState({ title: "", body: "" });
function addNewPost(e) {
e.preventDefault();
const newPost = {
...post,
id: Date.now(),
};
console.log(newPost);
}
return (
<form>
<MyInput
placeholder="Enter title"
onChange={(e) => setPost({ ...post, title: e.target.value })}
value={post.title}
type="text"
/>
<MyInput
placeholder="Enter description"
value={post.body}
type="text"
onChange={(e) =>
setPost({
...post,
body: e.target.value,
})
}
/>
<MyButton onClick={addNewPost}>Create post</MyButton>
</form>
);
}
I rewatched my code hundrend times and I don't know why it doesn't work |
According to [the manual][1], when defining
```java
http.oauth2Login(oauth2 -> {
oauth2.loginPage("/login/oauth2");
});
```
> You need to provide a `@Controller` with a `@RequestMapping("/login/oauth2") ` that is capable of rendering the custom login page.
You could write something like that in a servlet:
```java
@Controller
public class LoginController {
private final Pattern bizIpsPattern;
public LoginController (@Value("biz-ips-pattern") String pattern) {
this.bizIpsPattern = Pattern.compile(pattern);
}
@GetMapping("/login/oauth2")
public RedirectView getAuthorizationCodeInitiationUrl(HttpServletRequest request) {
// Instead of throwing, you could as well decide to redirect to "com" IDP
final var header = Optional.ofNullable(request.getHeader("X-Forwarded-For")).orElseThrow(() -> new MissingForwardedForException());
final var matcher = bizIpsPattern.matcher(header);
return matcher.matches() ? new RedirectView("/oauth2/authorization/idpbiz") : new RedirectView("/oauth2/authorization/idpcom");
}
@ResponseStatus(HttpStatus.UNAUTHORIZED)
static final class MissingForwardedForException extends RuntimeException {
private static final long serialVersionUID = 8215954933514492489L;
MissingForwardedForException() {
super("X-Forwarded-For header is missing");
}
}
}
```
In a reactive application, the controller method would use `ServerWebExchange` instead of `HttpServletRequest`:
```java
@GetMapping("/login/oauth2")
public Mono<RedirectView> getAuthorizationCodeInitiationUrl(ServerWebExchange exchange) {
final var header = exchange.getRequest().getHeaders().getOrEmpty("X-Forwarded-For");
if (header.size() < 1) {
throw new MissingForwardedForException();
}
final var matcher = bizIpsPattern.matcher(header.get(0));
return Mono.just(matcher.matches() ? new RedirectView("/oauth2/authorization/idpbiz") : new RedirectView("/oauth2/authorization/idpcom"));
}
```
the `SecurityWebFilterChain` would be configured slightly differently too:
```java
http.exceptionHandling(exceptionHandling -> {
exceptionHandling.authenticationEntryPoint(new RedirectServerAuthenticationEntryPoint("/login/oauth2"));
});
```
[1]: https://docs.spring.io/spring-security/reference/servlet/oauth2/login/advanced.html#oauth2login-advanced-login-page |
|react-native|notifications|react-native-permissions| |
If you use CDN, you have to load components individually (see [docs](https://primevue.org/cdn/#component)), so for datatable and column, you need to add:
```html
<script src="https://unpkg.com/primevue/datatable/datatable.min.js"></script>
<script src="https://unpkg.com/primevue/column/column.min.js"></script>
```
Here it is in a snippet:
<!-- begin snippet: js hide: true console: false babel: false -->
<!-- language: lang-js -->
const { createApp, ref } = Vue
const App = {
setup() {
const products = ref([])
return {
products
}
},
components: {
"p-column": primevue.column,
"p-datatable": primevue.datatable
}
}
const app = createApp(App)
.use(primevue.config.default)
.mount("#app")
<!-- language: lang-html -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/primevue/core/core.min.js"></script>
<script src="https://unpkg.com/primevue/datatable/datatable.min.js"></script>
<script src="https://unpkg.com/primevue/column/column.min.js"></script>
<div id="app">
<p-datatable :value="products">
<p-column field="code" header="Code"></p-column>
<p-column field="name" header="Name"></p-column>
<p-column field="category" header="Category"></p-column>
<p-column field="quantity" header="Quantity"></p-column>
</p-datatable>
</div>
<script src="app.js"></script>
<!-- end snippet -->
|
If you can install Libreoffice in your environment. You can use it to convert Excel files to CSV in Python and use read_csv instead of read_excel.
The sample code is below:
def convert_excel_to_csv(input_file):
exe_path = 'C:/Program Files/LibreOffice/program/soffice.exe'
command = [
exe_path,
'--headless',
'--convert-to', 'csv',
'--outdir', os.path.dirname(__file__),
input_file
]
subprocess.run(command, check=True)
|
### **How Can I Fix this, italic to Normal Style! ***[see this image for better understanding] (https://i.stack.imgur.com/qlGtZ.png)
I want to make it normal style without italic version. how can I achieve this, please solve me this. this italic version makes me so anger. now I want to make it simple and without italic version. |
How should I formulate a function that passes the agent from Exit to Enter?

|
How can i do this nav-bar Call to Action Button with border:3px in Divi theme ?
or Question: how can i split Nav menu item with border: 3px in Divi theme?
[image](https://i.stack.imgur.com/U17ZD.png)
#divitheme #divi #problem #AyanSujon
#wordpress
i want to create a "Call to Action Buttom" in nav-menu with border: 3px in Divi theme wordpress.
split "NEED ANY SOLUTION" Button will be Right of the Header and others menu items will be CENTER and Header Logo will be Left.
thats it. |
How can i do this nav-bar Call to Action Button with border:3px in Divi theme? |
null |
Try uninstalling Visual Studio, then reinstalling it. And make sure you choose to download the .net 6 runtime from the 'individual components tab'. And also .net desktop dev for wpf. |
## Short Answer
In practice, the measured histogram discrepancy with a 4:2:2 jpg is ~1%, therefore one would expect about 16,609,443 colors—this is mainly due to factors other than YCbCr, such as the DCT compression.
# Longer Answer
The above value based on compressing using 4:2:2, and 100% quality. DCT artifacts are certainly part of the discrepancies. The measurement was using a histogram of the pure RGB image and compared to the 4:2:2 jpg, using DIFFERENCE transfer mode.
Some of the loss is due to the DCT algorithm, and some due to the spatial subsampling. That considered, the total colors would be no less than 16,579,244 to 16,642,998, but the difference is at worst effectively dithered. I.e. we are splitting hairs here.
Using Bruce Lindbloom's ["every possible color" image][1], an uncompressed RGB array of all possible colors, exported to a jpg at **100% quality** out of GIMP at **4:2:2**.
Then importing as a layer and setting it to difference transfer mode, to find any differences between the pure RGB and the 4:2:2 jpg.
For the following examples, I cropped to a small area of the full image.
## 100% Quality, 4:2:2
### The original:
[![RGB16MillionCLIPorig][2]][2]
#### The 4:2:2 jpeg laid on top, using difference mode:
[![RGB16MillionCLIP422DIFF][3]][3]
#### A histogram of that result (16bpc was used):
[![enter image description here][4]][4]
#### Expanding that 1% range to full range, to show the nature of the differences:
[![RGB16MillionCLIP422DIFFexpanded][5]][5]
## Discussion
In playing with this, including using 4:4:4 and 4:2:0 variants, it appears clear the main cause of the variations is the DCT compression, not so much the YCbCr. Perhaps it's useful to point out: we are never viewing YCbCr, we are always viewing RGB, thus the YCbCr is only the intermediate encoding for storage.
For every color stored in YCbCr it must be converted to a color in RGB. The only question then regards "round trips" in and out. I.e. for any given RGB color, mapped to a given YCbCr color, come back out to the exact same RGB color?
Here this is the difference with a jpeg that was exported five times consecutively:
[![RGB16Million422pass5DIFF][9]][9]
And expanded to show the bottom 1%:
[![RGB16Million422pass5DIFFexpanded][10]][10]
The vertical bars are due to the 4:2:2 subsampling. But otherwise, the discrepancy is essentially the same. This is consistent with the fact that after the first pass through DCT at 100% quality, subsequent passes at 100% quality have minimal effect.
## 50% Quality, 4:2:2
#### For reference, here is the difference using a 4:2:2 at 50% quality:
[![RGB16MillionCLIP422QUAL50DIFF][6]][6]
#### In this case the histogram of the difference indicates up to 25% discrepancy:
[![enter image description here][7]][7]
#### And expanded for detail:
[![RGB16MillionCLIP422QUAL50DIFFexpanded][8]][8]
## Conclusion
**We are always viewing RGB**. There is no reason to think that the round trip RGB->YCbCr->RGB results in lost colors per se, assuming an appropriate reverse transform.
However, the addition of DCT compression and chroma subsampling certainly does add errors, the degree of which are largely dependent on the quality settings.
[1]: http://www.brucelindbloom.com/index.html?RGB16Million.html
[2]: https://i.stack.imgur.com/4SCcg.png
[3]: https://i.stack.imgur.com/GmpzX.png
[4]: https://i.stack.imgur.com/9SbK3.png
[5]: https://i.stack.imgur.com/nDrIz.png
[6]: https://i.stack.imgur.com/QB2Gm.png
[7]: https://i.stack.imgur.com/j7BKK.png
[8]: https://i.stack.imgur.com/xWl3u.png
[9]: https://i.stack.imgur.com/k8i0U.png
[10]: https://i.stack.imgur.com/LyhKd.png |
Player input not working properly in unity |
|input| |
null |
I would like to use uuid as primary key in an intermediate table. I know you can add the following to a model:
```use Illuminate\Database\Eloquent\Concerns\HasUuids;```
and
```use HasUuids;```
But as I don't have/need a model for my intermediate table I'm not sure if it's possible to create the uuids automatically in a similar way? Do I have to generate the uuid manually whenever I create an entry in my intermediate table?
The migration file looks something like this:
```
public function up(): void {
Schema::create('post_user', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->timestamps();
$table->string('title');
$table->string('body');
}
}
```
|
Using uuid as primary key in intermediate table? |
|laravel|eloquent| |
Simple question. Are you sure you need to have those fields omitted or passed through at the dto level? How about?
```typescript
@Injectable()
export class UserService {
constructor(
@Inject(REQUEST) private request: Record<string, unknown>,
private readonly userRepository: RepositoryForUser,
) {}
async updateUser(dto: UpdateUserDto) {
let updatable = await this.userRepository.findOneOrThrow(dto.id);
if (!!dto.someImportantField && dto.someImportantField !== updatable.someImportantField) {
this.allowOnly(Role.Admin);
updatable.someImportantField = dto.someImportantField;
}
}
private allowOnly(...roles: Role[]) {
// check from request if matches any role, if not:
throw new UnauthorizedException();
}
}
```
Dto layer is, more or less, a data-transfer object layer. It's good to put there basic validation logic, like is the country code really country code, or check if all data that need to be provided are provided, because it's just easy to do. But there's no need to struggle especially when the goal is to put there some "heavier", business logic, that's rather on services, domain services, cqrs handlers, etc.
Another argument that it's not always best to overload DTO is a simple case:
```
user can't update e-mail address
unless they are admins
or they are updating their own e-mail
but only if they hadn't updated their e-mails for at least one month before
```
You can write that in dtos, but then somebody will come up and tell: "hey, I want to know who's shady, and I want the logs stored in-app of every e-mail change attempt".
---
Speaking of accessing `Request` by class-validator - see https://github.com/typestack/class-validator?tab=readme-ov-file#custom-validation-classes. You can always create a class. And if you can that, you can make it injectable too. And then - you know :) |
I have a parser written on puppeteer, where i download a file, so how to use this downloaded file in js code?
```const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
headless: false,
defaultViewport: false,
args: ['--start-maximized']
});
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 });
await page.goto('');
await page.type('#username', '');
await page.type('#password', '');
await page.click('#loginbtn');
await page.click('.aalink.stretched-link');
setTimeout(async () => {
await browser.close();
3000);
})();
```
Please help me |
I am trying to access google calendar api, I have the OAuth 2.0 set up, I am trying to use a raspberry pico W to access the api |
|python|google-calendar-api|micropython|raspberry-pi-pico| |
null |
I connected my website to Analytics 4 via GTM. However, I have a request: I want GA4 not to count the traffic coming to a link I specify within my site. Is something like this possible?
For example, let's say I set website.com/link_url. It won't count traffic to it.
But it will continue to calculate all traffic to the website.com domain normally, except for the URL address I chose.
Thank you...
I tried on GTM but it didn't work |
Hope, This will help, you can try once.
Step 1: Created a Animate segment Controller view
struct AnimatedSegmentedControl: View {
let items: [String]
@Binding var selectedItemIndex: Int
var body: some View {
GeometryReader { geometry in
HStack(spacing: 0) {
ForEach(items.indices) { index in
Button(action: {
withAnimation {
self.selectedItemIndex = index
}
}) {
VStack{
Text(items[index])
.font(.headline)
.padding()
.foregroundColor(index == selectedItemIndex ? Color(hex: "0F4D80", alpha: 1.0) : Color(hex: "35353A", alpha: 1.0))
ZStack {
Capsule()
.fill(Color.clear)
.frame(height: 2)
if index == selectedItemIndex {
Capsule()
.fill(Color(hex: "0F4D80", alpha: 1.0))
.frame(height: 2)
}
else {
Capsule()
.fill(Color.gray.opacity(0.4))
.frame(height: 2)
}
}
}
}
.frame(width: geometry.size.width / CGFloat(items.count))
.background(Color.clear)
}
Rectangle()
.frame(width: geometry.size.width / CGFloat(items.count), height: 2)
.foregroundColor(.blue)
.offset(x: CGFloat(selectedItemIndex) * (geometry.size.width / CGFloat(items.count)))
}
// .animation(.easeInOut)
}
.frame(height: 50)
}}
Step 2: call from main view to segment view
struct TestView: View {
@State private var selectedItemIndex = 0
let items = ["History", "Favorites"]
var body: some View {
VStack {
AnimatedSegmentedControl(items: items, selectedItemIndex: $selectedItemIndex)
Spacer()
if selectedItemIndex == 1 {
Text("History items containt details display here..")
}
else {
Text("Favorite items containt Details display here..")
}
Spacer()
}
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}}
Below code will change from hexa to color.
extension Color {
init(hex: String, alpha: Double = 1.0) {
var formattedHex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
if formattedHex.hasPrefix("#") {
formattedHex.remove(at: formattedHex.startIndex)
}
let scanner = Scanner(string: formattedHex)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
self.init(
.sRGB,
red: Double((hexNumber & 0xFF0000) >> 16) / 255.0,
green: Double((hexNumber & 0x00FF00) >> 8) / 255.0,
blue: Double(hexNumber & 0x0000FF) / 255.0,
opacity: alpha
)
return
}
// Fallback color (black) if invalid hex string
self.init(.sRGB, red: 0, green: 0, blue: 0, opacity: 1.0)
}}
**You can see the screenshot below**
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/Gnyb6.png |
Today, I thought I'd implement a simple new visual into the little web-based space game I've been working on. I'd already implemented some nice looking twinkly stars in the background behind the ship, but I decided I wanted those stars to move downwards to make the ship seem like it was moving through space. The faster the ship was going, the faster the stars would move, and vice versa. This, coupled with some slight deviations in the speed of each star, would add a sense of depth and 3D space.
Well, it's the end of the day, and after 6 hours of tinkering with it, I just can't get it to fully work. With a lot of recoding and GitHub Copilot help, I've managed to get the basics working: the stars spawn properly, they move down the screen properly, and they even change their speed based on the speed of the ship. Unfortunately, however, each time their speed updates, they jump. Even when the speed itself stays exactly the same, they jump. This creates quite the jarring effect each time the speed increases or decreases, rather than the nice speed-up effect I was going for.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function startDivertGame() {
updateAllMeters();
regenerateShield();
initializeCoreTemperature();
setInterval(calculateEnemyDistance, 100);
gameOver = false;
document.documentElement.style.setProperty('--scale-factor', enginePower.toString());
document.documentElement.style.setProperty('--shield-health', shieldHealth.toString());
document.documentElement.style.setProperty('--shield-power', shieldPower.toString());
starSpawnInterval = setInterval(() => {
if (starCounter < 150) {
createStar(enginePower + 0.1);
starCounter++;
} else {
clearInterval(starSpawnInterval);
}
}, 50);
}
function createStar(speed) {
const star = document.createElement('div');
star.className = 'stars';
const xPos = Math.random() * window.innerWidth;
const yPos = -10;
star.style.left = `${xPos}px`;
star.style.top = `${yPos}px`;
const size = Math.random() + 1;
star.style.width = size + 'px';
star.style.height = size + 'px';
const twinklingDelay = Math.random() * 2;
const randomFactor = Math.random() * 2 + 0.5;
const newDuration = Math.max(1, 10 / (speed * randomFactor + 1));
star.style.animation = `moveDown ${newDuration}s 0s linear infinite, twinkle 2s ${twinklingDelay}s infinite alternate`;
star.style.animationPlayState = 'running';
star.addEventListener('animationiteration', () => {
if (star.getBoundingClientRect().top > window.innerHeight) {
star.remove();
const index = stars.indexOf(star);
if (index !== -1) {
stars.splice(index, 1);
}
}
});
document.body.appendChild(star);
stars.push(star);
}
function updateStarSpeed(enginePower) {
stars.forEach(star => {
star.style.animationPlayState = 'paused';
const currentDuration = parseFloat(getComputedStyle(star).animationDuration);
const currentTime = Date.now();
const elapsedTime = (currentTime - (star.animationStartTime || currentTime)) % currentDuration;
const progress = elapsedTime / currentDuration;
const randomFactor = Math.random() * 2 + 0.5;
const newDuration = Math.max(1, 10 / (enginePower * randomFactor + 1));
const adjustedElapsedTime = progress * newDuration;
const twinklingDelay = Math.random() * 2;
star.style.animationDuration = `${newDuration}s, 2s`;
star.style.animationDelay = `${adjustedElapsedTime}ms, ${twinklingDelay}s`;
star.style.animationPlayState = 'running';
star.animationStartTime = currentTime - adjustedElapsedTime;
});
}
<!-- end snippet -->
There's my code currently for spawning and updating the stars. updateStarSpeed is called anytime enginePower changes.
CSS:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
body::before {
content: "";
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
background-color: #000; /* Set your desired background color */
overflow: hidden;
}
@keyframes moveDown {
0% {
transform: translateY(-100vh); /* Start from the top of the viewport */
}
100% {
transform: translateY(100vh); /* Move down to the bottom of the viewport */
}
}
.stars {
position: absolute;
width: 1px;
height: 1px;
background-color: #fff; /* Set your desired star color */
animation: moveDown 10s linear infinite, twinkle 4s infinite alternate; /* Adjust duration values as needed */
animation-fill-mode: forwards; /* Add this line */
animation-play-state: running;
}
@keyframes twinkle {
0% {
opacity: 1;
}
50% {
opacity: 0.5;
}
100% {
opacity: 1;
}
}
<!-- end snippet -->
My GitHub page for it is https://github.com/lcbmann/lcbmann.github.io, go to divert.js and divertgame.html.
I cannot for the life of me fix this. Turns out that dynamically modifying the speed of an animation just doesn't really work. I attempted deleting stars and creating new stars of different speeds at the same position after each update, but this didn't work either.
I feel like there must be a simpler and easier way to make this effect happen, but I just cannot figure it out. It seems so simple. Make a bunch of stars, have them go down the screen at a speed determined by a variable. How hard is that?
|
Cutting multimedia files based on start and end time using ffmpeg |
|ffmpeg| |
null |
I tried to cut the video using the start and end time of the video by using the following command:
ffmpeg -ss 00:00:03 -t 00:00:08 -i movie.mp4 -acodec copy -vcodec copy -async 1 cut.mp4
By using the above command I want to cut the video from `00:00:03` to `00:00:08`. But it is not cutting the video between those times instead of that it is cutting the video with first 11 seconds. Can anyone help me how resolve this?
**Edit 1:**
I have tried to cut by using the following command which is suggested by [mark4o][1].
ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4
But it was shown the following error:
>***the encoder 'aac' is experimental but experimental codecs are not enabled***
So I added the `-strict -2` into the command i.e.,
ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 -strict -2 cut.mp4
Now it is working fine.
[1]: https://stackoverflow.com/users/112212/mark4o |
I am trying to resolve the avoid large layout shifts in PagespeedInsights
The solution is to set with and height of the below div element.
```<div id="HomeNewsEventsWrapper" class="section fixedheight1 introduction table">```
```
@media (min-width:0px) and (max-width:580px) {
#HomeNewsEventsWrapper{
}
}
```
However, It will also affect the media queries(If the viewport is greater than 580px in real life)
Also, how can I set with and height for every viewport?
I also tries setting height and width to auto but it does not work.
|
How to set specific width and height of a div element when media queries are present in css file? |
|html|css|media-queries|seo|pagespeed| |
Copy activity advanced editor and collection reference is only supported for the Array of Objects.

Your array is a simple array without any objects. So, copy activity won't support this kind of array.
However, you can try below workaround in this case. But this involves complex and time taking operations like loops and SQL scripts, and this only works when the JSON rows are less than 5000. **Dataflow is the better option than this**.
First give your API to a web activity and get the required JSON from it. Give the `product_ids` array from the web activity output to a For-Each activity and check the Sequential checkbox.
Here, I am using lookup to get the JSON and given `product_ids` array from lookup output.

Create an array variable in the variables section of the pipeline.
Inside for-each activity, take an append variable activity to the created array variable and give the below expression.
```
@json(concat(split(string(activity('Lookup1').output.value[0]),'"product_ids":')[0],'"product_id":',item(),'}'))
```

After for-loop, it will generate the JSON array like below.
```
[
{
"order_id": 1,
"date": "20170122",
"product_id": 123
},
{
"order_id": 1,
"date": "20170122",
"product_id": 124
},
{
"order_id": 1,
"date": "20170122",
"product_id": 125
}
]
```
Next, take a copy activity and at source, use SQL dataset with below script in the query option.
```
DECLARE @json NVARCHAR(max) = N'@{variables('myjson')}';
SELECT * FROM
OPENJSON (@json)
WITH (
order_id int '$.order_id' ,
date varchar(32) '$.date',
product_id int '$.product_id'
);
```
In the copy activity sink, give your target SQL table and debug the pipeline. It will give you expected result like below.
 |
I found the answer partly through this question, and one I asked which was asking exactly the same thing, but for me, it was:
C:\Users\VssAdministrator\Downloads |
This isn't an answer but I wanted to report that this issue is still occurring as of FF 124.0.1. Chrome (123.0.6312.59) works as expected. You would think Mozilla would have resolved this by now. |
I need a help to use or build a regular expression to mask alphanumeric with *.
I tried it with this expression, but it doesn't work correctly when it has zeros in the middle of the string:
```
(?<=[^0].{3})\w+(?=\w{4})
```
Live samples:
https://www.regexplanet.com/share/index.html?share=yyyyf47wp3r
|Input |Output |
|--------------------|--------------------|
|0001113033AA55608981|0001113*********8981|
|23456237472347823923|2345************3923|
|00000000090000000000|0000000009000***0000|
|09008000800060050000|09008***********0000|
|AAAABBBBCCCCDDDDEEEE|AAAA************EEEE|
|0000BBBBCCCCDDDDEEEE|0000BBBB********EEEE|
The rules are:
1. The first 4 that are not zeros, and the last 4 digits must be displayed.
1. Leading zeros are ignored, but not removed or replaced. |
Java Regular Expression for Masked Alphanumeric Codes |
|java|regex|pcre|replaceall| |
null |
I got it working in the end. I was missing the `coverlet.msbuild` NuGet package in my project. It turns out both `coverlet.collector` (which I had installed) and `coverlet.msbuild` are required.
The reference to the `project.runsettings` file was correct. Its content needed to be slightly updated:
```xml
<?xml version="1.0" encoding="utf-8" ?>
<RunSettings>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="XPlat code coverage">
<Configuration>
<Format>cobertura</Format>
<Exclude>[microsoft.azure.webjobs.*]*</Exclude>
</Configuration>
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
</RunSettings>
```
And also, I needed to adjust my Azure pipelines yaml file to contain:
```yml
# Perform .Net 6 Test
- task: DotNetCoreCLI@2
displayName: Test
inputs:
command: test
projects: 'src/$(Build.Repository.Name).sln'
publishTestResults: true
arguments: '--configuration $(build_configuration) /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura'
condition: and(succeeded(), eq(variables['Build.Reason'], 'PullRequest'))
# Publish code coverage results
- task: PublishCodeCoverageResults@1
displayName: 'Publish code coverage results'
inputs:
codeCoverageTool: 'Cobertura'
summaryFileLocation: '**/*coverage.cobertura.xml'
condition: and(succeededOrFailed(), eq(variables['Build.Reason'], 'PullRequest'))
```
In your use case, it's likely your conditions will be different.
This was enough to get it working and generating a code coverage report. Hope this helps someone in the future! |
I would avoid messing with the focus default styles. You could use outline instead?
.in:focus {
outline: 1px solid #002f86;
}
|
You should not need a variable to do this.
I can't test this at the moment but I think this should work.
=SUM(
IIF(
Month(Fields!ReportDate.Value) = (Parameters!Month.Value + 2 MOD 12) -1,
1,
0
)
)
All I've done here is calc the previous month number directly in the expression. |
count the number of field values prior to the current id then group by and aggregate
eg
select rn,
max(case when name = 'Finished' then value else null end) 'Finished',
max(case when name = 'faculty' then value else null end) 'faculty',
max(case when name = 'Characteristic' then value else null end) 'Characteristic',
max(case when name = 'Photo' then value else null end) 'Photo'
from
(
select f.name,fv.value,(select count(*) from field_values fv1 where fv1.field_id = fv.field_id and fv1.id < fv.id) rn
from field_values fv
join fields f on f.id = fv.field_id
) s
group by rn |
I'm working with a new JavaFX project. I have legacy Swing control panels. When I try to do `new SwingNode`, I get an exception:
Caused by: java.lang.IllegalAccessError: superclass access check
failed: class com.sun.javafx.embed.swing.SwingNodeHelper (in unnamed
module @0x35dc99d5) cannot access class
com.sun.javafx.scene.NodeHelper (in module javafx.graphics) because
module javafx.graphics does not export com.sun.javafx.scene to
unnamed module @0x35dc99d5
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1027)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:150)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:862)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:760)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:681)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:639)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526)
at javafx.embed.swing.SwingNode.<clinit>(SwingNode.java:135)
at test.app.MJFXtest.start(MJFXtest.java:11)
This is on JavaFX v21. I tried 19, but still the same.
_______________
package test.app;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.embed.swing.SwingNode;
public class MJFXtest extends Application {
@Override
public void start(Stage primaryStage) {
SwingNode sn = new SwingNode();
}
public static void main(String[] args) {
launch(args);
}
}
_________________
I expect this not to throw an exception on the new SwingNode(); line, but to create a new SwingNode.
I saw this Q/A about the same problem, but I have javafx-swing included in my pom file.
([https://stackoverflow.com/questions/55874607/the-class-swingnode-in-openjfx-causes-problems](https://stackoverflow.com))
This is the javafx section from pom.xml and it looks like all the relevant libraries are there.
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>21</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-swing -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-swing</artifactId>
<version>21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-web -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-web</artifactId>
<version>21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx</artifactId>
<version>21</version>
<type>pom</type>
</dependency>
Any assistance would be appreciated. Thank you. |
|wordpress|menubar|divi|divi-theme|wp-nav-menu-item| |
null |
|c++|sqlite| |
I am trying to iterate over an array of objects which I then need to process another array of items that I need to query the database for and process the data to push into an array while updating a value in the array.
The below code does what I want in the sense of the order, the lookups, data processing etc however it does not allow me to return the updated `seriesData` to the API endpoint caller.
```
// Setup process
let seriesData = [];
const seriesDataTemplate = {
x: "",
y: 0,
goals: [
{
name: "",
value: 0,
strokeHeight: 5,
strokeColor: "#775DD0",
}
]
};
// Some code not included that populates seriesData with seriesDataTemplate as the base for the object with x, y, goals.name and goals.value updated
// Area with the problem
itemIds.forEach(async itemId => {
subArr.forEach(async sI => {
const category = sI.category.toUpperCase().replace(/ /g, "_");
const t = await getT(sI, category);
sI.t = t;
const total = t.reduce((acc, ta) => {
return acc + ta.amount;
}, 0);
await updateSeriesData(sI, total);
});
});
// Supporter function
async function updateSeriesData(sI, total) {
let foundIndex = seriesData.findIndex(obj => obj.x === sI.category);
seriesData[foundIndex].y = total;
}
```
This all runs inside an express.js route that is async and right after the end of this code I return `seriesData` to the user which only contains the template code
|
Returning default data not updated data |
|javascript|node.js|express|foreach| |
null |
The pgAgent Service will not start on Windows 10 with a AzureAD login.
I ran EnterpriseDB’s PostgreSQL Stack Installer as an Administrator to install the pgAgent. During multiple installation attempts, at the "pgAgent service account" setup step, I tried the following values for the "Operating system username": `my_username`, `azuread\my_username`, `my_username@corpname.com`, and `azuread\my_username@corpname.com`.
The only one that did not give an error telling me it could not create the file `%APPDATA%\Roaming\postgresql\pgpass.conf` when installing was when I used `my_username` as the "Operating system username."
However, this created a completely different user named `my_username.computername` and put the `pgpass.conf` file in that users `%APPDATA%\Roaming\postgresql\` directory. This is of no use to me. I have admin privileges on my computer and can force my way into that new user profile and the only thing in there is the `%APPDATA%\Roaming\postgresql\pgpass.conf` file.
Back in my actual user profile, I cannot start the pgAgent Service.
After installing with `my_username` as the "Operating system username", the pgAgent "Log On As" setting is automatically changed to `.\my_username`.
When trying to start the Service with "Log On As" set to `.\my_username`, I get the following message:
[![enter image description here][1]][1]
When installed with or "Log On As" set to any of the other `domain\username` options, I get the following error:
[![enter image description here][2]][2]
When running `net start pgAgent-pg16` from an elevated Powershell terminal, I get:
The PostgreSQL Scheduling Agent - pgagent-pg16 service is starting...................
The PostgreSQL Scheduling Agent - pgagent-pg16 service could not be started.
The service did not report an error.
More help is available by typing NET HELPMSG 3534.
----
How can I get the pgAgent Service installed and started on a Windows 10 OS with an AzureAD login?
----
Note: I have seen all of the following SO posts and other instructions and none of them help at all.
* https://stackoverflow.com/questions/58798858/unable-to-install-pgagent-with-application-stack-builder
* https://stackoverflow.com/questions/77122194/pgagent-install-on-windows-error-required-systempassword-for-userpostgres
* https://stackoverflow.com/questions/66584292/how-can-i-install-pgagent-for-postgresql-9-5-on-windows
* https://stackoverflow.com/questions/17567168/how-to-install-pgagent-service-on-windows
* https://stackoverflow.com/questions/11762671/could-not-start-pgagent-due-to-log-on-failure?rq=2
* https://dba.stackexchange.com/questions/248538/pgagent-service-for-postgresql-does-not-run
* https://www.pgadmin.org/docs/pgadmin4/latest/pgagent_install.html#service-installation-on-windows
* https://www.postgresql.org/docs/current/libpq-pgpass.html
----
Additionally, when installed, running either `./pgAgent REMOVE pgAgent` or `./pgAgent REMOVE pgAgent-pg16` returns `ERROR: Failed to uninstall source`, and the following does nothing at all.
./pgAgent INSTALL pgAgent -u my_Win10_username -p my_Win10_password hostaddr=127.0.0.1 dbaname=postgres user=postgres password=***
[1]: https://i.stack.imgur.com/ZFwP4.png
[2]: https://i.stack.imgur.com/W1hOc.png |
Move navigation container out of view |
I have an existing go webserver that has a route that accepts form elements (one of which is a file) and uploads the resulting file (after resizing and renaming) into the images folder that the webserver serves up. I am changing the application to use lambda (go) and a static website on s3. Other things like storing the information on MongoDB (aws hosted), I understand completely.
I know that I need to add the PutObject permissions on the website bucket. Again in s3 I have an images folder... Does anyone have an example similar? All the code on the AWS github repo has the file going to the bucket (not a folder in the bucket like images).
Again I need to resize the image (write to /tmp in lambda?), and upload to the folder in the s3 bucket.
Any examples or ideas regarding this would be much appreciated. Thanks in advance. |
Golang lambda upload image into s3 static website |
|image|go|amazon-s3|aws-lambda| |
**SOLUTION:**
> Need to additionally the libs in your pom.xml if that is acceptatble for you: The [docusign 4.5.0][1] using [jerseay-version 3.0.9][2] but the following dependencies not retrieved with docusign. The Spring Boot 3.2 had dependencies jersey libraries 3.1.5 built in.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>3.0.9</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>3.0.9</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>3.0.9</version>
</dependency>
[1]: https://github.com/docusign/docusign-esign-java-client/blob/4.5.0-v2.1-23.3.01.02/pom.xml
[2]: https://github.com/docusign/docusign-esign-java-client/blob/4.5.0-v2.1-23.3.01.02/pom.xml#L398 |
Without `docker-compose.yml` (as most VPS CPanels (open-source PaaS like Dokku, Caprover, Easypanel) don't support `docker-compose.yml`) so I had to find an alternate solution using `--env-file` option in a `Makefile`:
```make
.PHONY: build-staging
build-staging: ## Build the staging docker image.
docker build -f docker/staging/Dockerfile -t easypanel-nextjs:0.0.1 .
.PHONY: start-staging
start-staging: ## Start the staging docker container.
docker run --detach --env-file .env.staging --publish 3000:3000 --restart unless-stopped easypanel-nextjs:0.0.1
.PHONY: stop-staging
stop-staging: ## Stop the staging docker container.
docker stop $$(docker ps -a -q --filter ancestor=easypanel-nextjs:0.0.1)
```
Now, I just do this in the terminal:
```bash
$ make build-staging
$ make start-staging
$ make stop-staging
```
Obviously, the syntax becomes much cleaner with `docker compose` but most VPS CPanels don't support it so this is as good as it gets.
My repo that uses this method -> https://github.com/deadcoder0904/easypanel-nextjs-sqlite |
The thing you should know is that the size of a pointer is independent of its data type and it is based on the computer architecture; for example, on a 64-bit machine this code snippet always returns 8 which means whatever the type of pointer is it always takes 8 bytes;
int main()
{
int *p;
float *p1;
double *p2;
char *p3;
printf("%d",sizeof(p));
printf("%d",sizeof(p1));
printf("%d",sizeof(p2));
printf("%d",sizeof(p3));
return 0;
} |
I have done chunking of the data prior to this and intend to do embeddings and store in pinecone. I have reffered youtube on this as well and found this code and its not working.
```
docsearch = pc.from_documents([t.page_content for t in text_chunks], embeddings, index_name= 'mcahtbot')
```
I get this error.
```
AttributeError: 'Pinecone' object has no attribute 'from_documents'
```
Reffered to pinecone, youtube and searched other platforms for answers to similar problem
|
I am unable to perform the vector embeddings with the help of pinecone and python |
{"Voters":[{"Id":807126,"DisplayName":"Doug Stevenson"},{"Id":10802527,"DisplayName":"K J"},{"Id":13376511,"DisplayName":"Michael M."}],"SiteSpecificCloseReasonIds":[13]} |
I am trying to have the album images for each of the top tracks shown next to their song but no matter what I do they are showing up as little green boxes.
[
Photo of Whats Happening](https://i.stack.imgur.com/MFFak.png)
Here is the relevant code:
```
public void onGetUserProfileClicked() {
if (mAccessToken == null) {
Toast.makeText(this, "You need to get an access token first!", Toast.LENGTH_SHORT).show();
return;
}
// Create a request to get the user profile
final Request request = new Request.Builder()
.url("https://api.spotify.com/v1/me")
.addHeader("Authorization", "Bearer " + mAccessToken)
.build();
cancelCall();
mCall = mOkHttpClient.newCall(request);
mCall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("HTTP", "Failed to fetch data: " + e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonResponse = response.body().string();
Log.d(TAG, "JSON Response: " + jsonResponse);
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray itemsArray = jsonObject.getJSONArray("items");
StringBuilder formattedData = new StringBuilder();
// Add header for top tracks
formattedData.append("<h2>Your top tracks!</h2>");
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject trackObject = itemsArray.getJSONObject(i);
JSONObject albumObject = trackObject.getJSONObject("album");
JSONArray imagesArray = albumObject.getJSONArray("images");
String imageUrl = "";
if (imagesArray.length() > 0) {
JSONObject imageObject = imagesArray.getJSONObject(0);
imageUrl = imageObject.getString("url");
Log.d(TAG, "Image URL for track " + i + ": " + imageUrl);
}
String artistName = "";
JSONArray artistsArray = trackObject.getJSONArray("artists");
if (artistsArray.length() > 0) {
JSONObject artistObject = artistsArray.getJSONObject(0);
artistName = artistObject.getString("name");
}
String trackName = trackObject.getString("name");
// Load image using Glide
ImageView imageView = new ImageView(MainActivity.this);
Glide.with(MainActivity.this)
.load(imageUrl)
.into(imageView);
// Create HTML content for each song box
formattedData.append("<div style=\"display:flex; align-items:center;\">")
.append("<div style=\"width: 200px; height: 200px; margin-right: 10px;\">")
.append(imageView)
.append("</div>")
.append("<div style=\"border: 1px solid #ccc; padding: 10px; margin-bottom: 10px;\">")
.append("<p>").append(trackName).append(" - ").append(artistName).append("</p>")
.append("</div>")
.append("</div>");
}
// Display the formatted data with HTML formatting
runOnUiThread(() -> {
profileTextView.setText(Html.fromHtml(formattedData.toString(), Html.FROM_HTML_MODE_COMPACT));
profileTextView.setMovementMethod(LinkMovementMethod.getInstance());
});
} catch (IOException | JSONException e) {
Log.e(TAG, "Error processing response: " + e.getMessage());
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Failed to process response",
Toast.LENGTH_SHORT).show());
}
}
});
}
```
When I logged the image urls in my logcat to see if theyre valid, they were as when I clicked on them they showed up fine on the internet and I made sure my androidmanifest.xml allowed internet usage. |
Album Images Not Showing Up When Called From Spotify API Android Studio |
|android|spotify| |
null |
I am trying to implement a higher order component in TypeScript so that I can pass my ErrorBoundary as a parameter to the higher order component and then the higher order component returns the current location of the user so that I can use it in my ErrorBoundary component.
ErrorBoundary:
```
import React from "react";
interface ErrorBoundaryProps {
fallback: React.ReactNode;
children: React.ReactNode;
location: {
pathname: string;
};
}
class ErrorBoundary extends React.Component<ErrorBoundaryProps> {
state = { hasError: false };
static getDerivedStateFromError(error: Error) {
return { hasError: true };
}
componentDidUpdate(previousProps: ErrorBoundaryProps) {
if (previousProps.location.pathname !== this.props.location.pathname) {
this.setState({ hasError: false });
}
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
export default ErrorBoundary;
```
WithRouter (higher order component):
```
import { useLocation } from "react-router-dom";
function WithRouter(OriginalComponent: React.ComponentType) {
const NewComponent = (props: any) => {
const location = useLocation();
return <OriginalComponent {...props} location={location} />;
};
return NewComponent;
}
```
Apparently the TypeScript compiler is not happy and I'm not sure how to fix it. Sorry I am very new to this!
I've just tried to experiment with different implementations but nothing seems to be working.
If this helps, this is what works in JavaScript:
```
import { useLocation } from "react-router-dom";
function WithRouter(OriginalComponent) {
const NewComponent = (props) => {
const location = useLocation();
return <OriginalComponent location={location} {...props} />;
};
return NewComponent;
}
```
But I'm just struggling to convert it to TypeScript. |
The top rated answer does not work with the new Reflection implementation of [JEP416](https://openjdk.org/jeps/416) in e.g. Java 21 that uses MethodHandles and ignores the flags value on the Field abstraction object.
One solution is to use Unsafe, however with [this JEP](https://openjdk.org/jeps/8323072) Unsafe and the important `long objectFieldOffset(Field f)` and
`long staticFieldOffset(Field f)` methods are getting deprecated for removal so for example this will not work in the future:
```java
final Unsafe unsafe = //..get Unsafe (...and add subsequent --add-opens statements for this to work)
final Field ourField = Example.class.getDeclaredField("changeThis");
final Object staticFieldBase = unsafe.staticFieldBase(ourField);
final long staticFieldOffset = unsafe.staticFieldOffset(ourField);
unsafe.putObject(staticFieldBase, staticFieldOffset, "it works");
```
I do not recommend this but it is possible in Java 21 with the new reflection implementation when making heavy use of the internal API if really needed.
# Java 21+ solution without `Unsafe`
The gist of it is to use a `MethodHandle` that can write to a static final field by getting it from the internal [`getDirectFieldCommon(...)`](https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/invoke/MethodHandles.java) method of the Lookup by providing it with a `ReferenceKind` that is manipulated via Reflection to remove the Final flag from it.
```java
MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(MyClassWithStaticFinalField.class, MethodHandles.lookup());
Method getDirectFieldCommonMethod = lookup.getClass().getDeclaredMethod("getDirectFieldCommon", byte.class, Class.class, memberNameClass, boolean.class);
getDirectFieldCommonMethod.setAccessible(true);
//Invoke last method to obtain the method handle
MethodHandle finalFieldHandle = (MethodHandle) getDirectFieldCommonMethod.invoke(lookup, manipulatedReferenceKind, myStaticFinalField.getDeclaringClass(), memberNameInstanceForField, false);
finalFieldHandle.invoke("new Value for static final field");
```
See my answer [here](https://stackoverflow.com/a/77705202/23144795) for a full working example on how to leverage the internal API to set a final field in Java 21 without Unsafe.
|
For a given `MaxDegreeOfParallelism` and fixed amount of objects that need to be processed (i.e. have certain code executed on them) it would seem `Parallel.ForEach` and an `ActionBlock` would be equally useful.
What considerations would need to be taken into account when choosing one over the other? |
I use eslint and tslint to help me avoid silly mistakes.
However, today, I made a mistake when declaring an event listener to catch uncaught promise rejections:
window.addEventListener('unhandledRejection', debugError)
The correct type is `unhandledrejection`, not `unhandledRejection`. I wasted a lot of time debugging this before I realized I had made a typo. Given the prevelance of camelCase in JS, I fear I will make the same mistake again.
Is there some way to lint this against known event types? I don't use any custom events in my app. |
Is there a way to lint event listener types in JS/TS? |
|javascript|eslint|tslint|typescript-eslint| |
io.cucumber.core.exception.CucumberException: Could not find object factory org.example.CustomObjectFactory.
Cucumber uses SPI to discover object factory implementations.
Has the class been registered with SPI and is it available on
the classpath?
at io.cucumber.core.runtime.ObjectFactoryServiceLoader.loadSelectedObjectFactory(ObjectFactoryServiceLoader.java:93)
at io.cucumber.core.runtime.ObjectFactoryServiceLoader.loadObjectFactory(ObjectFactoryServiceLoader.java:46)
at java.base/java.lang.ThreadLocal$SuppliedThreadLocal.initialValue(ThreadLocal.java:305)
at java.base/java.lang.ThreadLocal.setInitialValue(ThreadLocal.java:195)
at java.base/java.lang.ThreadLocal.get(ThreadLocal.java:172)
at io.cucumber.core.runtime.ThreadLocalObjectFactorySupplier.get(ThreadLocalObjectFactorySupplier.java:18)
at io.cucumber.core.runtime.BackendServiceLoader.loadBackends(BackendServiceLoader.java:48)
at io.cucumber.core.runtime.BackendServiceLoader.get(BackendServiceLoader.java:37)
at io.cucumber.core.runtime.BackendServiceLoader.get(BackendServiceLoader.java:33)
at io.cucumber.core.runtime.ThreadLocalRunnerSupplier.createRunner(ThreadLocalRunnerSupplier.java:46)
at java.base/java.lang.ThreadLocal$SuppliedThreadLocal.initialValue(ThreadLocal.java:305)
at java.base/java.lang.ThreadLocal.setInitialValue(ThreadLocal.java:195)
at java.base/java.lang.ThreadLocal.get(ThreadLocal.java:172)
at io.cucumber.core.runtime.ThreadLocalRunnerSupplier.get(ThreadLocalRunnerSupplier.java:40)
at io.cucumber.core.runtime.RethrowingThrowableCollector.executeAndThrow(RethrowingThrowableCollector.java:35)
at io.cucumber.core.runtime.CucumberExecutionContext.getRunner(CucumberExecutionContext.java:140)
at io.cucumber.core.runtime.CucumberExecutionContext.runBeforeAllHooks(CucumberExecutionContext.java:92)
at io.cucumber.testng.TestNGCucumberRunner.<init>(TestNGCucumberRunner.java:124)
at io.cucumber.testng.AbstractTestNGCucumberTests.setUpClass(AbstractTestNGCucumberTests.java:27)
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.testng.internal.invokers.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:139)
at org.testng.internal.invokers.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:69)
at org.testng.internal.invokers.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:393)
at org.testng.internal.invokers.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:326)
at org.testng.internal.invokers.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:180)
at org.testng.internal.invokers.TestMethodWorker.run(TestMethodWorker.java:122)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.testng.TestRunner.privateRun(TestRunner.java:819)
at org.testng.TestRunner.run(TestRunner.java:619)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:443)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:437)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:397)
at org.testng.SuiteRunner.run(SuiteRunner.java:336)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:95)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1228)
at org.testng.TestNG.runSuites(TestNG.java:1134)
at org.testng.TestNG.run(TestNG.java:1101)
at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:65)
at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:105)
Ideally, It should work with Latest version of Cucumber but it's throwing above error but the same code is working cucumber 3.x.x version without any changes.
Let me know any changes happend in the cucumber latest version |
Facing issue while running Testcases from runner class in the Cucumber with ObjectFactory with Latest Version of Cucumber |
|cucumber|cucumber-jvm|cucumber-java| |
null |
I just set up firebase in my angular project. I have a problem while trying to use a firestore function.
I have this service:
```
import { Injectable } from '@angular/core';
import { Firestore } from '@angular/fire/firestore';
import {
doc,
getDoc,
} from 'firebase/firestore';
@Injectable({
providedIn: 'root',
})
export class FirestoreService {
constructor(public firestore: Firestore) {}
async getCollection() {
const docRef = doc(this.firestore, 'teams', 'pippo');
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log('Document data:', docSnap.data());
} else {
// docSnap.data() will be undefined in this case
console.log('No such document!');
}
}
}
```
If I try to run this function from the code, let's say, from a button event, everything works fine, but if I put this code inside my app.component.ts ngOnInit(), the page recharge on my browser never stops recharging, and if I stop the refresh and try to start it manually I get this error:
> Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.
I don't understand this error. But if I try to put the code of getCollection directly inside of my ngOnInit function, everything works fine again |
null |
When I run my next js project it gives me this feedback:
next\swc-win32-x64-msvc\next-swc.win32-x64-msvc.node is not a valid Win32 application.
\\?\C:\Users\ABDUL-MOOMIN IS-HAQ\Desktop\Desktop\lms_app\node_modules\@next\swc-win32-x64-msvc\next-swc.win32-x64-msvc.node
⨯ Failed to load SWC binary for win32/x64, see more info here: https://nextjs.org/docs/messages/failed-loading-swc
|
Try using Scala 2 syntax (still working in Scala 3 so far)
fastparse.parse("1234", implicit p => parseAll(MyParser.int(p)))
https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA
Possible Scala 3 syntaxes are a little awkward:
fastparse.parse("1234", p => {given P[_] = p; parseAll(MyParser.int(p))})
https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA/11
fastparse.parse("1234", p => {given P[_] = p; parseAll(MyParser.int)})
https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA/21
fastparse.parse("1234", { case p @ given P[_] => parseAll(MyParser.int(p))})
https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA/13
fastparse.parse("1234", { case given P[_] => parseAll(MyParser.int)})
https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA/20
fastparse.parse("1234", p => parseAll(MyParser.int(using p))(using p))
https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA/16
It would be nice if `fastparse.parse("1234", p ?=> parseAll(MyParser.int(p)))` worked, but this would require support on fastparse side.
---
https://stackoverflow.com/questions/72034665/correct-scala-3-syntax-for-providing-a-given-from-a-higher-order-function-argume
https://github.com/scala/scala3/discussions/12007 |
The following code (at [Playground here](https://www.typescriptlang.org/play?#code/MYGwhgzhAEDKCuAHApgJwMLigKAN7ekOgDN4A7YACjFQHMAuaSgW2UYBcALASwgEpoAXgB80AG4B7bgBMB+Iguipk7eKjLQatAkQC+2fdlCQYAETTcxyaZhPRkAD3bIy0mAhQYsEPDsJiabjAAIxBkIWguXgA6UgpKSgERaFxdPgBuA2wjCTIIdmgJYIArRg80WygIsmQAd2hzVEtrSohE9KA)) gives an error `Type 'DerivedClass' is not assignable to type 'SuperClass'` at the variable `obj`. How is this possible, when `DerivedClass extends SuperClass`? Does this contradict Liskov substitution principle?
```typescript
class SuperClass
{
func(arg: (me: this) => void) {
return arg
}
}
class DerivedClass extends SuperClass
{
variable = this.func(() => {});
}
const obj: SuperClass = new DerivedClass();
```
In an attempt to further isolate the 'problem', the [following code](https://www.typescriptlang.org/play?#code/IYIwzgLgTsDGEAJYBthjAgygVwA4FMoBhVdAKAG8yEaFcoB7CfefAEwVEhngQDdgUAJahk+AFwIAFAFsJCCAAshYAJQIAvAD5+DIWwDcZAL5kyKNBgAihIX3YlLCfAA9mAOzYYcBYqTCU1LT0TCzMHALCovia0nKSSirq2ggUxkam5gzukAgMIABWkj6Ejuix7vgA7gg2wvZsZWBSqgZAA) errors for some reason, unless `protected` is removed in both classes:
```
abstract class SuperClass
{
protected abstract variable: (me: this) => void;
}
class DerivedClass extends SuperClass
{
protected variable = (me: this) => {};
}
const obj: SuperClass = new DerivedClass();
```
There are many definitions of the Liskov substitution principle, but commonly it is assumed that objects of a derived type can behave like/pretend to be a super type. I would expect an error inside the definition of `DerivedClass` if something is wrong with the inheritance, not on the last line of code. |
Ok. I have fixed this issue by using `useEffect` and `ReactDOM.render` method:
**Code:**
import React, {useEffect} from "react";
import ReactDOM from "react-dom";
import CustomTooltip from "./CustomTooltip";
const BBCodeComponent = ({content}) => {
useEffect(() => {
const tooltipWrappers = document.querySelectorAll(".tooltip-wrapper");
tooltipWrappers.forEach((wrapper) => {
const title = wrapper.getAttribute("data-title");
const src = wrapper.getAttribute("data-src");
if (title && src) {
const tooltipComponent = (
<CustomTooltip msg={title}><img src={src} alt={title} /></CustomTooltip>
);
ReactDOM.render(tooltipComponent, wrapper);
}
});
}, [content]);
const parseBBCode = (text) => {
return text
.replace(/\[img=(.*?)\](.*?)\[\/img\]/g, (match, title, src) => {
return `<div class=\"tooltip-wrapper\" data-title=\"${title}\" data-src=\"${src}\"><img src=\"${src}\" alt=\"${title}\"></div>`;
})
.replace(/\[quote\](.*?)\[\/quote\]/g, "<blockquote>$1</blockquote>");
};
return <div dangerouslySetInnerHTML={{__html: parseBBCode(content)}} />;
};
export default BBCodeComponent;
I get all `.tooltip-wrapper` items by using `document.querySelectorAll` method. Then I use `forEach` loop to get `title` and `src` attributes. Finally, I create tooltip component and render it. It works well. The issue is resolved. |
I often got solution from chatgpt after writing many prompts it actually comes to the point back.
What is 'chatGBT' ? why you all are talking about 'chatGBT' its a discussion of chatgpt ? |
null |
When C++ creates `std::ofstream` it instantly and implicitly creates the underlying file.
I am totally fine with this behaviour unless I have a code which only during its run can see if any data at all will be produced.
So, I want to avoid creating empty files when no data sent to them (kind of transactional integrity: no data, no changes on file system).
I see two approaches I don't like much:
1. See if something was sent to the stream (`tellg()`) and remove the file if the stream was empty. I don't like to create and delete files (sometimes there are many of them) and `remove` operation itself puts too much responsibility.
2. Create `std::stringstream`, collect output there and create `std::ofstream` and copy content only in case the stringstream is not empty. Much better, but still requires temporary memory allocation which could be big.
Is there a better solution for this? Am I missing some idea?
In form of code:
```C++
#include <fstream>
int main()
{
std::ofstream ofs("file.txt");
// Some code that might or might not output to ofs
// Some other code that might or might not output to ofs
// Some more code that might or might not output to ofs
// It would be nice if file is not created if no data sent to ofs
}
```
So, the code could contain many places where the output will be performed. |
Why is my border not working as I would like? |
I'm trying to scrape from Linkedin hrefs to better filter the results. However, for some reason the code will only return results 1-7 only. Results 8 or more will not return, even if explicitly stated. I have included sleep timers to help the website complete the load, but still only 1-7. Is there a bug, a security measure or something wrong with the code?
```
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from icecream import ic
PATH = "C:\Program Files (x86)\chromedriver.exe"
service = Service(executable_path=PATH)
driver = webdriver.Chrome(service=service)
user = "*********"
pswd = "***********"
driver.get("https://www.linkedin.com/jobs")
driver.implicitly_wait(10)
userLogin = driver.find_element('id', "session_key")
pswdLogin = driver.find_element('id', "session_password")
userLogin.send_keys(user)
pswdLogin.send_keys(pswd)
pswdLogin.send_keys(Keys.RETURN)
driver.implicitly_wait(600)
searchKey = driver.find_element(By.XPATH, '//input[contains(@id, "jobs-search-box-keyword-id-ember")]')
searchLocation = driver.find_element(By.XPATH, '//input[contains(@id, "jobs-search-box-location-id-ember")]')
searchKey.send_keys("python developer")
searchLocation.send_keys("27560")
time.sleep(0.25)
searchLocation.send_keys(Keys.RETURN)
WebDriverWait(driver, 3)
time.sleep(2)
jobs = []
time.sleep(2)
for i in range(1, 16):
ic(i)
the_url = driver.find_element(by=By.XPATH,
value='/html/body/div[5]/div[3]/div[4]/div/div/main/div/div[2]/div[1]/div/ul/li[' + str(
i) + ']/div/div/div[1]/div[2]/div[1]/a')
print(the_url.get_attribute('href'))
``` |
I'm trying to create a code for **perfectly optimal chess endgame**.
This code for chess endgame is my currently best [one](https://pastebin.com/zkcbgANy)
import chess
def simplify_fen_string(fen):
parts = fen.split(' ')
simplified_fen = ' '.join(parts[:4]) # Zachováváme pouze informace o pozici
return simplified_fen
def evaluate_position(board):
#print(f"Position: {board.fen()}")
if board.is_checkmate():
### print(f"Position: {board.fen()}, return -1000")
return -1000 # Mat protihráči
elif board.is_stalemate() or board.is_insufficient_material() or board.can_claim_draw():
### print(f"Position: {board.fen()}, return 0")
return 0 # Remíza
else:
#print(f"Position: {board.fen()}, return None")
return None # Hra pokračuje
def create_AR_entry(result, children, last_move):
return {"result": result, "children": children, "last_move": last_move, "best_child": None}
def update_best_case(best_case):
if best_case == 0:
return best_case
if best_case > 0:
return best_case - 1
else:
return best_case + 1
def update_AR_for_mate_in_k(board, AR, simplified_initial_fen, max_k=1000):
evaluated_list = []
#print(f"")
for k in range(1, max_k + 1):
print(f"K = {k}")
changed = False
for _t in range(2): # Zajistíme, že pro každé k proběhne aktualizace dvakrát
print(f"_t = {_t}")
for fen in list(AR.keys()):
#print(f"Fen = {fen}, looking for {simplified_initial_fen}, same = {fen == simplified_initial_fen}")
board.set_fen(fen)
if AR[fen]['result'] is not None:
if fen == simplified_initial_fen:
print(f"Finally we found a mate! {AR[fen]['result']}")
return
continue # Pokud již máme hodnocení, přeskočíme
# Získáme výchozí hodnoty pro nejlepší a nejhorší scénář
best_case = float("-inf")
#worst_case = float("inf")
nones_present = False
best_child = None
for move in board.legal_moves:
#print(f"Move = {move}")
board.push(move)
next_fen = simplify_fen_string(board.fen())
#AR[fen]['children'].append(next_fen)
if next_fen not in AR:
AR[next_fen] = create_AR_entry(evaluate_position(board), None, move)
evaluated_list.append(next_fen)
if ((len(evaluated_list)) % 100000 == 0):
print(f"Evaluated: {len(evaluated_list)}")
board.pop()
#for child in AR[fen]['children']:
next_eval = AR[next_fen]['result']
if next_eval is not None:
if (-next_eval > best_case):
best_case = max(best_case, -next_eval)
best_child = next_fen
#worst_case = min(worst_case, -next_eval)
else:
nones_present = True
if nones_present:
if best_case > 0:
AR[fen]['result'] = update_best_case(best_case)
AR[fen]['best_child'] = best_child
changed = True
else:
# Aktualizace hodnocení podle nejlepšího a nejhoršího scénáře
#if worst_case == -1000:
# Pokud všechny tahy vedou k matu, hráč na tahu může být matován v k tazích
# AR[fen] = -1000 + k
# changed = True
#elif best_case <= 0:
# Pokud nejlepší scénář není lepší než remíza, znamená to remízu nebo prohru
# AR[fen] = max(best_case, 0) # Zabráníme nastavení hodnoty méně než 0, pokud je remíza možná
# changed = True
#elif best_case == 1000:
# Pokud existuje alespoň jeden tah, který vede k matu protihráče, hráč na tahu může vynutit mat v k tazích
# AR[fen] = 1000 - k
# changed = True
AR[fen]['result'] = update_best_case(best_case)
AR[fen]['best_child'] = best_child
changed = True
### print(f"Position = {fen}, results = {best_case} {nones_present} => {AR[fen]['result']}")
if (fen == "8/8/3R4/8/8/5K2/8/4k3 b - -" or fen == "8/8/3R4/8/8/5K2/8/5k2 w - -"):
print("^^^^^^^^")
# remove here
#break
#if not changed:
#break # Pokud nedošlo k žádné změně, ukončíme smyčku
#if not changed:
#break # Ukončíme hlavní smyčku, pokud nedošlo ke změně v poslední iteraci
def print_draw_positions(AR):
"""
Vytiskne všechny remízové pozice (hodnota 0) zaznamenané v slovníku AR.
"""
print("Remízové pozice:")
for fen, value in AR.items():
if True or (value > 990 and value < 1000):
print(f"FEN>: {fen}, Hodnota: {value}","\n",chess.Board(fen),"<\n")
def find_path_to_end(AR, fen):
if AR[fen]['result'] is None:
print(f"Unfortunately, there is no path that is known to be the best")
fen_i = fen
print(chess.Board(fen_i),"\n<")
path = fen
while AR[fen_i]['best_child'] is not None:
fen_i = AR[fen_i]['best_child']
print(chess.Board(fen_i),"\n<")
path = path + ", " + fen_i
print(f"Path is: {path}")
def main():
initial_fen = "1k6/5P2/2K5/8/8/8/8/8 w - - 0 1"
initial_fen_original = "8/8/8/8/3Q4/5K2/8/4k3 w - - 0 1"
initial_fen_mate_in_one_aka_one_ply = "3r1k2/5r1p/5Q1K/2p3p1/1p4P1/8/8/8 w - - 2 56"
initial_fen_mate_in_two_aka_three_plies = "r5k1/2r3p1/pb6/1p2P1N1/3PbB1P/3pP3/PP1K1P2/3R2R1 b - - 4 28"
initial_fen_mated_in_two_plies = "r5k1/2r3p1/p7/bp2P1N1/3PbB1P/3pP3/PP1K1P2/3R2R1 w - - 5 29"
mate_in_two_aka_three_plies_simple = "8/8/8/8/3R4/5K2/8/4k3 w - - 0 1"
mated_in_one_aka_two_plies_simple = "8/8/3R4/8/8/5K2/8/4k3 b - - 1 1"
mate_in_one_aka_one_ply_simple = "8/8/3R4/8/8/5K2/8/5k2 w - - 2 2"
initial_fen = mate_in_two_aka_three_plies_simple
initial_fen = "1k6/5P2/2K5/8/8/8/8/8 w - - 0 1"
initial_fen = "1k6/8/2K5/8/8/8/8/8 w - - 0 1"
initial_fen = "8/8/8/8/8/7N/1k5K/6B1 w - - 0 1"
initial_fen = "7K/8/k1P5/7p/8/8/8/8 w - - 0 1"
simplified_fen = simplify_fen_string(initial_fen)
board = chess.Board(initial_fen)
AR = {simplified_fen: {"result": None, "last_move": None, "children": None, "best_child": None}} # Inicializace AR s počáteční pozicí
update_AR_for_mate_in_k(board, AR, simplified_fen, max_k=58) # Aktualizace AR
#print_draw_positions(AR)
print(f"AR for initial fen is = {AR[simplified_fen]}")
find_path_to_end(AR, simplified_fen)
main()
However,for initial fen = "8/8/8/4k3/2K4R/8/8/8 w - - 0 1" it doesn't give the optimal result like this one: https://lichess.org/analysis/8/8/8/4k3/2K4R/8/8/8_w_-_-_0_1?color=white
Rather, it gives 27 [like this](https://pastebin.com/hZ6AaBZe) while lichess.com link above gives 1000-977==23. Finding the bug will be highly appreciated. |
chess endgame engine in Python doesn't work perfectly |
|python-3.x|chess|python-chess| |
If the variable being checked is not an argument to the method, then it would be bad. The ArgumentNullException.ThrowIfNull throws an [ArgumentNullException][1] which explicitly means that caller of the function did something wrong.
If the checks are for the state of the object then you are probably after an [InvalidOperationException][2]. You might also want to consider the [ObjectNotFoundException][3], or create an exception type of your own.
[1]: https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception?view=net-7.0
[2]: https://learn.microsoft.com/en-us/dotnet/api/system.invalidoperationexception?view=net-8.0
[3]: https://learn.microsoft.com/en-us/dotnet/api/system.data.objectnotfoundexception?view=netframework-4.8.1 |
I don't understand why the results display 'cat' first, followed by 'dog', and then 'bird'. I expect to see 'bird' first, followed by 'dog', and finally 'cat'.
```
async function asyncOperation1() {
return new Promise(resolve => {
let x = 0;
for (let i = 0; i < 10000000; i++) {
x += 1;
}
console.log(`cat`, x);
resolve(x)
});
}
async function asyncOperation2() {
return new Promise(resolve => {
let x = 0;
for (let i = 0; i < 1000; i++) {
x += 1;
}
console.log(`dog`, x);
resolve(x)
});
}
async function concurrentExecution() {
try {
asyncOperation1();
asyncOperation2();
console.log("bird");
} catch (error) {
console.error("An error occurred:", error);
}
}
concurrentExecution();
```
I am using Node.js version 18.19.0. I attempted to run the code, but the result did not meet my expectations, as I mentioned earlier. |