instruction
stringlengths
0
30k
I want to test my react project array ```ts // this method is in the utils.ts export const platform = ( navigator.userAgentData?.platform || navigator.platform ).toLowerCase() export const keyboardPlayerShortcutsData = [ { name: 'play/pause', shortcut: platform.startsWith('mac') ? `⌘ + p` : 'Ctrl + p', } ] ``` ```ts it('should generate correct keyboard player shortcuts data (mac)', () => { // need to mock "import { platfrom } from './utils'" expect(keyboardPlayerShortcutsData).toEqual([ { name: 'play/pause', shortcut: '⌘ + p', }, ]) const shortcutElement = screen.getByText('⌘ + p') expect(shortcutElement).toBeInTheDocument() }) it('should generate correct keyboard player shortcuts data (win)', () => { // need to mock "import { platfrom } from './utils'" expect(keyboardPlayerShortcutsData).toEqual([ { name: 'play/pause', shortcut: 'ctrl + p', }, ]) const shortcutElement = screen.getByText('ctrl + p') expect(shortcutElement).toBeInTheDocument() }) ``` I use `vi.mock('./utils', () => ({ platform: 'mac' }))` in each test, but `vi.mock` will hoist to the top, so the test will fail. I also tried, but it also not work ```ts import { platform } from './utils' describe('EditKeyboardShortcutSheet', () => { vi.mock('./utils', () => ({ platform: 'MacIntel'.toLowerCase(), })) afterEach(() => { vi.clearAllMocks() }) it('should generate correct keyboard player shortcuts data (mac)', () => { expect(keyboardPlayerShortcutsData).toEqual([ { name: 'play/pause', shortcut: '⌘ + p', }, ]) }) it('should generate correct keyboard player shortcuts data (win)', () => { // ref: https://github.com/vitest-dev/vitest/discussions/4328 // got an ts error: Property 'mockReturnValue' does not exist on type 'string'. vi.mocked(platform).mockReturnValue('Windows') expect(keyboardPlayerShortcutsData).toEqual([ { name: 'play/pause', shortcut: 'ctrl + p', }, ]) }) }) ```
I'm trying to send a delete http request but it does not work. Delete request should be send when clicking a button. Please help. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const ondeletehandle = async() => { const response = await fetch('/api/notebook/' + notebooks._id, { method: 'DELETE' }) const json = await response.json() if (response.ok) { dispatch({ type: 'DELETE_NOTEBOOK', payload: json }) console.log(notebooks) } if (!response.ok) { console.log("error") } } i tried looking up for delete header but that didn't work
How to send http delete request in ReactJS when clicking a button?
null
I am trying to understand an issue that arose following the news regarding the new format of the Champions League. As some of you may know, the new format consists of `n=36` teams, divided into `p=4` pots. Each team will face `o=2` teams from each pot, resulting in a total of `p*o=8` matches, with one match played away and one at home for each pot. Update --- This is my attempt as now. For low values of N_TEAMS the script works in a reasonable time, for larger it can stuck. It surely need some optimization, what can I optimize? PS:the biggest issue is the limitation on the number of matches to be played home vs away (if that control is removed, everything is really fast!) ``` <?php const N_TEAMS = 36; const N_POTS = 4; const M_PER_POT = 2; function main() { $teams = array_map(fn($i) => "team_{$i}", range(1, N_TEAMS)); foreach($teams as $team) { $teams_pots[$team] = findPotOfTeam($team, $teams, N_POTS); } foreach(getPossiblePots(N_TEAMS) as $pot) { echo "Can be divided in {$pot} pots - with these number of matches per pot" . json_encode(getPossibleMatchesNumberPerPot(N_TEAMS, $pot)) . "\n"; } if(!in_array(N_POTS, getPossiblePots(N_TEAMS))) { throw new Error('POTS NUMBER IS WRONG'); } if(!in_array(M_PER_POT, getPossibleMatchesNumberPerPot(N_TEAMS, N_POTS))) { throw new Error('MATCHES PER POT WRONG!'); } $schedule = generateSchedule($teams, getFixture($teams, $teams_pots), $teams_pots); // Calendar foreach ($schedule as $day => $matches) { echo "\nDay " . ($day + 1) . ":\n"; foreach ($matches as $match) { echo implode(" vs ", $match) . "\n"; } } $flat = array_merge(...$schedule); foreach($teams as $team) { $matches_home = count(array_filter($flat, fn($t) => $t[0] == $team)); $matches_away = count(array_filter($flat, fn($t) => $t[1] == $team)); echo "\n{$team} plays " . $matches_home + $matches_away . " matches: {$matches_home} H - {$matches_away} A\n" ; for($i = 0;$i < N_POTS;$i++) { $home_pots = count(homeTeamMatchesVSPot($team, $flat, $i, $teams_pots)); $away_pots = count(awayTeamMatchesVSPot($team, $flat, $i, $teams_pots)); echo "POT {$i}: H " . $home_pots . " A:" . $away_pots . "\n"; } } } function getPossiblePots(int $nTeams): array { return array_filter(range(1, $nTeams), fn($e) => ($nTeams % $e == 0 && $e != $nTeams)); } function getPossibleMatchesNumberPerPot(int $nTeams, int $pots): array { return array_values(array_filter(range(1, $nTeams / $pots - 1), fn($e) => (($nTeams / $pots % 2 == 0) || ($e % 2 == 0)))); } function findPotOfTeam($team, array $teams, int $nPots): int { $pots_length = ceil(N_TEAMS / $nPots); $pos = array_search($team, $teams); return ceil(($pos + 1) / $pots_length) - 1; } function getFixture(array $teams, array $teams_pots) { $chunked_teams = array_chunk($teams, N_TEAMS / N_POTS); /* Opponents array initialization */ foreach($teams as $team) { $teams_opponents[$team] = []; } foreach($teams as $team) { /* Skip team if opponents filled */ if(count($teams_opponents[$team]) == N_POTS * M_PER_POT) { continue; } /* Check each pot for $team*/ for($pot = 0;$pot < N_POTS;$pot++) { $opp_of_teams_in_pot = opponentsOfTeamOfPot($teams_opponents[$team], $pot, $teams_pots); /* If team has M_PER_POT opponents in POT, skip */ if(count($opp_of_teams_in_pot) == M_PER_POT) { continue; } /* If team has more than M_PER_POT opponents in POT, restart */ if(count($opp_of_teams_in_pot) > M_PER_POT) { return getFixture($teams, $teams_pots); } /* Team here has less opponents in POT than M_PER_POT, so we will find, among the teams in pot, the possible opponents. */ $remaining_opponents = array_filter( $chunked_teams[$pot], fn($val) => ( $val != $team && !in_array($val, $teams_opponents[$team]) // all teams that are not already paired && (count($teams_opponents[$val]) < (N_POTS * M_PER_POT)) // all teams that have space left for team && (count(opponentsOfTeamOfPot($teams_opponents[$val], $teams_pots[$team], $teams_pots)) < M_PER_POT)// all teams that have space left for team in pot ), ); /* If there are no opponents left, restart */ if(count($remaining_opponents) == 0) { return getFixture($teams, $teams_pots); } /* We can pick, from this pot, an amount of random opponents that is the minimum between the num of opponents left and the opponents left in pot */ $opponents = array_rand(array_flip($remaining_opponents), min(count($remaining_opponents), M_PER_POT - count($opp_of_teams_in_pot))); /* If one element is picked we turn it into array */ if(!is_array($opponents)) { $opponents = [$opponents]; } /* We add each opponent to the list of opponents of $team, and to each $opponent we add $team as opponent */ foreach($opponents as $o) { $teams_opponents[$team][] = $o; $teams_opponents[$o][] = $team; } } } /* Double check */ foreach($teams as $team) { if(count($teams_opponents[$team]) != N_POTS * M_PER_POT) { return getFixture($teams, $teams_pots); } } return $teams_opponents; } function opponentsOfTeamOfPot(array $team_opponents, int $currentPot, array $teams_pots) { return array_values(array_filter($team_opponents, fn($t) => $teams_pots[$t] == $currentPot)); } function matchesOfTeam($team, array $plays): array { return array_values(array_filter($plays, fn($play) => in_array($team, $play))); } function matchesOfTeamAgainstPot($team, array $plays, int $pot, array $teams_pots): array { return array_values(array_filter(matchesOfTeam($team, $plays), fn($play) => ($teams_pots[$play[0] == $team ? $play[1] : $play[0]] == $pot))); } function homeTeamMatchesVSPot($team, array $plays, int $pot, array $teams_pots): array { return array_values(array_filter(matchesOfTeamAgainstPot($team, $plays, $pot, $teams_pots), fn($play) => $play[0] == $team)); } function awayTeamMatchesVSPot($team, array $plays, int $pot, array $teams_pots): array { return array_values(array_filter(matchesOfTeamAgainstPot($team, $plays, $pot, $teams_pots), fn($play) => $play[1] == $team)); } function getNumberOfMatchesPerTeam($team, $plays) { return count(array_values(array_filter($plays, fn($play) => in_array($team, $play)))); } function getNumberOfMatchesPerTeamHome($team, $plays) { return count(array_values(array_filter($plays, fn($play) => $play[0] == $team))); } function getNumberOfMatchesPerTeamAway($team, $plays) { return count(array_values(array_filter($plays, fn($play) => $play[1] == $team))); } function generateDay(array $teams, array &$teams_opponents, array $teams_pots, $matches_for_team_home, $matches_for_team_away, $matches_for_team_home_pot, $matches_for_team_away_pot, array $last_home) { $day = []; $remainingTeams = array_filter($teams, fn($team) => ($matches_for_team_home[$team] + $matches_for_team_away[$team]) != N_POTS * M_PER_POT); /* We order the remaining teams first on the total matches, then on the home matches and then on the away matches. Always ASC */ usort($remainingTeams, function($a, $b) use ($matches_for_team_home, $matches_for_team_away, $last_home) { $matchesTotalComparison = ($matches_for_team_home[$a] + $matches_for_team_away[$a]) - ($matches_for_team_home[$b] + $matches_for_team_away[$b]); if ($matchesTotalComparison != 0) { return $matchesTotalComparison; } $last_home_order = $last_home[$a] - $last_home[$b]; if($last_home_order != 0) { return $last_home[$a] - $last_home[$b]; } $matchesHomeComparison = $matches_for_team_home[$a] - $matches_for_team_home[$b]; $matchesAwayComparison = $matches_for_team_away[$a] - $matches_for_team_away[$b]; if ($matchesHomeComparison != 0) { return $matchesHomeComparison; } if($matchesAwayComparison != 0) { return $matchesAwayComparison; } /* Seems to fix some infinite loop in some cases... you figure it why... */ return rand(-1, 1); }); while(count($remainingTeams) > 0) { // Let's pick the first team $team1 = array_shift($remainingTeams); $team2 = null; /* We order opponents with the same method of before */ usort($teams_opponents[$team1], function($a, $b) use ($matches_for_team_home, $matches_for_team_away, $last_home) { $matchesTotalComparison = ($matches_for_team_home[$a] + $matches_for_team_away[$a]) - ($matches_for_team_home[$b] + $matches_for_team_away[$b]); if ($matchesTotalComparison != 0) { return $matchesTotalComparison; } $last_home_order = $last_home[$b] - $last_home[$a]; if($last_home_order != 0) { return $last_home[$b] - $last_home[$a]; } $matchesAwayComparison = $matches_for_team_away[$a] - $matches_for_team_away[$b]; $matchesHomeComparison = $matches_for_team_home[$a] - $matches_for_team_home[$b]; if ($matchesAwayComparison != 0) { return $matchesAwayComparison; } if($matchesHomeComparison != 0) { return $matchesHomeComparison; } return rand(-1, 1); }); $couple = []; foreach($teams_opponents[$team1] as $potOpp) { /* Is the possible opponent yet to be coupled in the day?*/ if(!in_array($potOpp, $remainingTeams)) { continue; } $team2 = $potOpp; /* Now we check which team should play home and which away */ $t1_H_VS_P_T2 = $matches_for_team_home_pot[$team1][$teams_pots[$team2]]; $t2_H_VS_P_T1 = $matches_for_team_home_pot[$team2][$teams_pots[$team1]]; $t1_A_VS_P_T2 = $matches_for_team_away_pot[$team1][$teams_pots[$team2]]; $t2_A_VS_P_T1 = $matches_for_team_away_pot[$team2][$teams_pots[$team1]]; $t1_stop_H_PT2 = $t1_H_VS_P_T2 >= ceil(M_PER_POT / 2); $t2_stop_H_PT1 = $t2_H_VS_P_T1 >= ceil(M_PER_POT / 2); $t1_stop_A_PT2 = $t1_A_VS_P_T2 >= ceil(M_PER_POT / 2); $t2_stop_A_PT1 = $t2_A_VS_P_T1 >= ceil(M_PER_POT / 2); if($t2_stop_H_PT1 && $t2_stop_A_PT1) { $team2 = null; break; } $couple = [$team1, $team2]; if($t1_stop_H_PT2 || $t2_stop_A_PT1) { /* If team1 has already enough matches against the pot of team 2 as HOME OR If team2 has already enough matches against the pot of team 1 as AWAY Team 2 will play home and Team 1 will play away */ $couple = [$team2, $team1]; if($t2_stop_H_PT1 || $t1_stop_A_PT2) { /* If team 2 has already enough matches against the pot of team 1 as HOME OR If team 1 has already enough matches against the pot of team 2 as AWAY we have to break as the schedule is not right */ $team2 = null; break; } } break; } if ($team2) { /* We add the match to the day and remove team_1 from the opponents of team_2 and vice-versa. */ $day[] = $couple; $teams_opponents[$team1] = array_diff($teams_opponents[$team1], [$team2]); $teams_opponents[$team2] = array_diff($teams_opponents[$team2], [$team1]); $remainingTeams = array_diff($remainingTeams, [$team1, $team2]); } } return $day; } function generateSchedule($teams, $teams_opponents, $teams_pots, &$iteration = 0) { $schedule = []; $completedMatches = []; $initial_team_opp = $teams_opponents; $total_matches = array_reduce($teams_opponents, fn($carry, $opp) => $carry + count($opp), 0) / 2; if($iteration > 5) { $iteration = 0; return generateSchedule($teams, getFixture($teams, $teams_pots), $teams_pots, $iteration); } echo "\nTotal matches: " . $total_matches . "\n"; foreach($teams as $team) { $matches_for_team_home_pot[$team] = array_map(fn() => 0, range(0, N_POTS - 1)); $matches_for_team_away_pot[$team] = array_map(fn() => 0, range(0, N_POTS - 1)); $matches_for_team_home[$team] = 0; $matches_for_team_away[$team] = 0; $last_home[$team] = true; } /* Loop to run until the number of completed matches is not equal to the total needed */ while (count($completedMatches) < $total_matches) { $day = generateDay($teams, $initial_team_opp, $teams_pots, $matches_for_team_home, $matches_for_team_away, $matches_for_team_home_pot, $matches_for_team_away_pot, $last_home); if (empty($day)) { break; } $schedule[] = $day; $completedMatches = array_merge($completedMatches, $day); foreach($teams as $team) { $matches_for_team_home_pot[$team] = array_map(fn($pot) => count(homeTeamMatchesVSPot($team, $completedMatches, $pot, $teams_pots)), range(0, N_POTS - 1)); $matches_for_team_away_pot[$team] = array_map(fn($pot) => count(awayTeamMatchesVSPot($team, $completedMatches, $pot, $teams_pots)), range(0, N_POTS - 1)); $matches_for_team_home[$team] = getNumberOfMatchesPerTeamHome($team, $completedMatches); $matches_for_team_away[$team] = getNumberOfMatchesPerTeamAway($team, $completedMatches); $last_home[$team] = array_search($team, array_merge(...$day)) % 2 == 0; } } if(count($completedMatches) != $total_matches) { $iteration++; return generateSchedule($teams, $teams_opponents, $teams_pots, iteration:$iteration); } foreach($teams as $team) { if(abs($matches_for_team_home[$team] - $matches_for_team_away[$team]) > 1) { $iteration++; return generateSchedule( $teams, $teams_opponents, $teams_pots, iteration:$iteration, ); } } return $schedule; } main(); ``` For limited number of total matches it works, but for the champions league structure it gives infinite loop error. How can I make it faster/correct?
I have an error during build up of WAR file. Can anyone help to fix this error ? FAILURE: Build failed with an exception. * What went wrong: A problem occurred configuring root project 'mpm'. > Could not resolve all files for configuration ':classpath'. > Could not resolve io.jmix.gradle:jmix-gradle-plugin:2.2.1.1. Required by: project : > io.jmix:io.jmix.gradle.plugin:2.2.1.1 > No matching variant of io.jmix.gradle:jmix-gradle-plugin:2.2.1.1 was found. The consumer was configured to find a library for use during runtime, compatible with Java 11, packaged as a jar, and its dependencies declared externally, as well as attribute 'org.gradle.plugin.api-version' with value '8.6' but: - Variant 'apiElements' capability io.jmix.gradle:jmix-gradle-plugin:2.2.1.1 declares a library, packaged as a jar, and its dependencies declared externally: - Incompatible because this component declares a component for use during compile-time, compatible with Java 17 and the consumer needed a component for use during runtime, compatible with Java 11 - Other compatible attribute: - Doesn't say anything about org.gradle.plugin.api-version (required '8.6') - Variant 'javadocElements' capability io.jmix.gradle:jmix-gradle-plugin:2.2.1.1 declares a component for use during runtime, and its dependencies declared externally: - Incompatible because this component declares documentation and the consumer needed a library - Other compatible attributes: - Doesn't say anything about its target Java version (required compatibility with Java 11) - Doesn't say anything about its elements (required them packaged as a jar) - Doesn't say anything about org.gradle.plugin.api-version (required '8.6') - Variant 'runtimeElements' capability io.jmix.gradle:jmix-gradle-plugin:2.2.1.1 declares a library for use during runtime, packaged as a jar, and its dependencies declared externally: - Incompatible because this component declares a component, compatible with Java 17 and the consumer needed a component, compatible with Java 11 - Other compatible attribute: - Doesn't say anything about org.gradle.plugin.api-version (required '8.6') - Variant 'sourcesElements' capability io.jmix.gradle:jmix-gradle-plugin:2.2.1.1 declares a component for use during runtime, and its dependencies declared externally: - Incompatible because this component declares documentation and the consumer needed a library - Other compatible attributes: - Doesn't say anything about its target Java version (required compatibility with Java 11) - Doesn't say anything about its elements (required them packaged as a jar) - Doesn't say anything about org.gradle.plugin.api-version (required '8.6') * Try: > Review the variant matching algorithm at https://docs.gradle.org/8.6/userguide/variant_attributes.html#sec:abm_algorithm. > No matching variant errors are explained in more detail at https://docs.gradle.org/8.6/userguide/variant_model.html#sub:variant-no-match. > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. > Get more help at https://help.gradle.org. BUILD FAILED in 1s
The error: > org.springframework.mail.MailSendException: Mail server connection failed. Failed messages: jakarta.mail.MessagingException: Could not convert socket to TLS;\n nested exception is:\n\tjava.net.SocketTimeoutException: Read timed out; message exception details (1) are:\r\nFailed message 1:\r\njakarta.mail.MessagingException: Could not convert socket to TLS;\n nested exception I have no antivirus on my pc and try some things I've here on stack overflow but the program isn't working yet. I will show some snippets of my code: ```yaml aplications.yml: spring: mail: host: email-smtp.us-east-1.amazonaws.com port: 587 username: ses-smtp-user.20240330-201531 password: properties: mail: smtp: auth: true starttls: enable: true connectiontimeout: 5000 timeout: 300 writetimeout: 5000 ssl: protocols: TLSv1.2 server: port: 8081 -Djavax: net: debug=all: ``` My service class: ```java @Service public class EmailService { @Autowired private JavaMailSender emailSender; public void sendEmail(Email email) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true); mimeMessageHelper.setFrom(email.getFrom()); mimeMessageHelper.setTo(email.getTo()); mimeMessageHelper.setSubject(email.getSubject()); mimeMessageHelper.setText(email.getText()); Properties props = new Properties(); props.put("mail.smtp.ssl.protocols", "TLSv1.2"); emailSender.send(message); } } ``` Can someone please help me? I tried to start the program with debug ```yaml -Djavax: net: debug=all: ``` But it doesn't work. Tried to add props in the service class but didn't work. Also I commented the `java.security` line ``` jdk.tls.disabledAlgorithms=SSLv3, TLSv1, TLSv1.1, DTLSv1.0, RC4, DES, \ MD5withRSA, DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, ``` Still doesn't work
|c#|client|
Creating a Google Login-In Extension for a personal project so I've set up funtionality that allows me to log in to the extension with my Google account and it works. I'm using an initial HTML file called "popup.html" to hold the logic of Google's Authentication by calling "popup.js" as the backend script, displaying a "Waiting for Log-in" message, and then setting that <div> attribute to display the contents of another HTML file called "authorized.html" after succesful sign-in by setting its contents as the innerHTML property of "popup.html". The issue is that "authorization.html" own script "authorized.js" will not print anything to either my console nor will it even throw an error on the console despite the other contents of "authorized.html" succefully being displayed. Only the relevant parts of my code are below but I'd like to know why I'm having this issue and how to circumvent it. Thank you popup.html: ``` <!DOCTYPE html> <html> <head> <title>Google OAuth Sign-In</title> <script src="popup.js"></script> </head> <body> <div id="Sign-In TempUI" class="content-body">Waiting for Google Sign-In</div > </body> </html> ``` popup.html: ``` console.log('popup.js loaded'); document.addEventListener('DOMContentLoaded', function () { const NewGUI = document.getElementById('Sign-In TempUI'); chrome.identity.getAuthToken({ interactive: true }, function (token) { if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError.message); return; } console.log('Token acquired:', token); loadAuthorizedUI(token); }); function loadAuthorizedUI(token) { console.log('Debug:', token); fetch('authorized.html') .then(response => response.text()) .then(html => { console.log('HTML content:', html); NewGUI.innerHTML = html; }) .catch(error => console.error('Error fetching or processing HTML:', error)); } }); ``` authorized.html: ``` <!-- Page Displayed after recieving token from OAuthetication. Should display GUI for Email handling --> <!DOCTYPE html> <html> <head> <title>Authorized UI</title> </head> <body> <h1>Welcome! You are now authorized.</h1> <ul id="emailList"> </ul> <script src="authorized.js"></script> <div>Hit end</div> </body> </html> ``` authorized.js: ``` //throw new Error('This is a test error from authorized.js'); console.log('authorized.js loaded'); ``` I'm using Chrome DevTool to debug, while also including popup debugger so before I was starting another document.addEventListener('DOMContentLoaded', function ()) and then trying to replace the contents of emailList after trying to get its element by Id, but it wont even open authorized.js. Console.log doesnt print anything and the exception doesnt actually display anything on the console. However when I move the authorized.js script to popup.html, it'll suddenly display albiet errors. My biggest confusion is that "<h1>Welcome! You are now authorized.<h1>" and "<div>Hit end</div>" will display on my GUI but the script wont even print, as if its skipping it
Mass Resource deletion in REST
|api|rest|
[enter image description here][1]Suppose A is a symmetric matrix whose SVD is A= USV^T, and let B = U\sqrt{S}V^T, then B^2 should be equal to A. But when I implemented it using tensorflow, B^2 and A does not match. Highly appreciated if you could give some advice! [1]: https://i.stack.imgur.com/ODigC.png
As the title says, I use next-sanity for my Next.js blog. I recently wanted to update all npm packages. Now I can´t run `npm run build` as the one of the dependncies itself throws a type error as follows: ```console ./node_modules/@sanity/types/lib/dts/src/index.d.ts:756:3 Type error: Type parameter declaration expected. 754 | */ 755 | export declare function defineArrayMember< > 756 | const TType extends string | IntrinsicTypeName, // IntrinsicTypeName here improves autocompletion in _some_ IDEs (not VS Code atm) | ^ 757 | const TName extends string, 758 | TSelect extends Record<string, string> | undefined, 759 | TPrepareValue extends Record<keyof TSelect, any> | undefined, ``` I tried manually adding older versions of the package in question but I could not find a suitable solution so far. Deleting node_modules or package.json and then running `npm i`again also did nothing to change the outcome. Has anyone also had the same problem? I had this problem after I ran `npm update`, then I fixed the issues due to some changes mentioned in the docs. But the main issue is, that previously normally functioning features are not working despite no change inside the docs suggesting I did something wrong. I use `next 14.1.0`, `next-sanity 8.5.0` and `sanity 3.36.2`
I am getting an error in `R` in Windows 10 about finding a directory while trying to install a package from GitHub*. Trying to troubleshoot this error led me to a few observations. For example, both Windows Explorer and my browser can find `C:/PROGRA~1`, but only my browser can find `C:/PROGRA~1/R`, where `R` is installed. The specific Windows Explorer error is: Windows can't find 'C:/PROGRA~1/R'. Check the spelling and try again. Yet, Windows Explorer can find `C:/Program Files/R` no problem. And the error above is the same with `C:/PROGRA~1/Adobe`, `C:/PROGRA~1/Google`, or any other. Even more interesting, Windows Explorer can't even find the raw program files path as long as we add a simple slash at the end! So `C:/PROGRA~1/` will output a similar error. So can anyone explain to me why Windows Explorer is not able to find `C:/PROGRA~1/R` or `C:/PROGRA~1/`? Is this normal/expected? If I solve this, I can probably resolve my `R` error too. Thanks. *Here is the full original error in `R`: Error: Failed to install 'package' from GitHub: create process 'C:/PROGRA~1/R/R-40~1.3/bin/x64/Rcmd.exe' (system error 267, The directory name is invalid. ) @win/processx.c:1040 (processx_exec) Edit: My investigation revealed that it might be related to the direction of slashes... So for instance, `C:/PROGRA~1\R` (or even `C:/PROGRA~1\`) works in Windows Explorer, but only as long as the second slash is a backslash... Can this be of any help in resolving this issue? Doesn't seem like `R` wants to put that second slash as backslash... Edit 2: My answer below was deleted so here it is again: > The issue was with the processx package and the development version has since received a fix (in version v3.5.3). Please see the following discussion for more info: https://github.com/r-lib/processx/issues/313
What is causing the store latency in this program?
|c|cpu-architecture|micro-optimization|micro-architecture|
{"Voters":[{"Id":22180364,"DisplayName":"Jan"},{"Id":1940850,"DisplayName":"karel"},{"Id":6461462,"DisplayName":"M--"}],"SiteSpecificCloseReasonIds":[13]}
You can just use the native web import: 1. Go to Data > From web 2. paste "https://www.screener.in/api/company/13611040/peers/" 3. Click on "Table0" 4. Click on "load"
scanf in x64 NASM results in segfault
In your original post at first picture i can see a lot of stencils which are opened in separated windows as Read-Only [RO]… It is not ShapeSheet windows!!! I have not documents with same issue and I create one with code Option Base 1 Sub Prepare() Dim pth(3) As String, curpath As String, i As Integer pth(1) = "C:\My Shapes\19_inch_Rack_flexible_RU.vss" pth(2) = "C:\My Shapes\Favorites.vssx" pth(3) = "C:\My Shapes\GOST_R_21.1101-2013.vss" For i = LBound(pth) To UBound(pth) curpath = pth(i) Documents.OpenEx curpath, visOpenRO ' open stencil in new window as read-only Next ActiveDocument.DocumentSheet.OpenSheetWindow ' add Document ShapeSheet window End Sub ![Demo](https://i.stack.imgur.com/5Ajeq.png) At my side next code close all windows if type of window is not **Drawing window**. Please read more about [VisWinTypes enumeration (Visio)](https://learn.microsoft.com/en-us/office/vba/api/visio.viswintypes)! Next code can close all non-drawing windows Sub Test() Dim va As Application, vw As Window Set va = Application For Each vw In va.Windows Debug.Print vw.Caption, vw.Type, vw.SubType If Not vw.Type = visDrawing Then vw.Close ' visDrawing = 1 Python dont know Visio internal constants Next ActiveDocument.ContainsWorkspaceEx = False ' prevent save document workspace (a lot of RO-opened stencils) ActiveDocument.Save End Sub `ActiveDocument.ContainsWorkspaceEx = False` this line prevent save workspace (all RO stencils). Please check this article [Document.ContainsWorkspaceEx property (Visio)](https://learn.microsoft.com/en-us/office/vba/api/visio.document.containsworkspaceex). ~~Right now I have not Python environment, I try find it later…~~ I try this code with Jupyter Notebook, it works at my side… import win32com.client app = win32com.client.Dispatch('Visio.Application') app.Visible = True for i in range(app.windows.count,1,-1): vw = app.windows(i) if vw.Type!=1: vw.close app.ActiveDocument.ContainsWorkspaceEx = False app.ActiveDocument.Save
So I am basically very new to Assembly in general. I was trying to write this simple code where I need to sort numbers in an ascending order from source data and rewrite it into destination data. and whenever I run it, it shows: executables selected for download on to the following processors doesn't exist... here is the code, maybe something wrong with it: ``` .global _start _start: ldr r0, =Input_data // load the input data into r0 ldr r1, =Output_data // load the output data into r1 mov r2, #32 // word is 32 first_loop: ldr r3, =Input_data // load the input data into r3 ldr r4, [r3], #4 // load the 1st elem of input data into r4 mov r5, r0 // move to the second loop second_loop: ldr r6, [r1] // load the value of output data into r6 cmp r4, r6 // compare the current element eith the value in output data ble skip_swap // if the current element is less than or equal, continue // swap the elements: str r6, [r1] str r4, [r1, #4] skip_swap: // move to the next elem in output data add r1, r1, #4 // decrement by one remaining elements (r2 was 32) subs r2, r2, #1 // check if we have reached the end of input_data cmp r3, r0 // if not, continue to the second loop bne second_loop // if the first loop counter is not zero, continue to the first loop subs r2, r2, #1 bne first_loop // exit mov r7, #0x1 svc 0 // software interrupt .data .align 4 Input_data: .word 2, 0, -7, -1, 3, 8, -4, 10 .word -9, -16, 15, 13, 1, 4, -3, 14 .word -8, -10, -15, 6, -13, -5, 9, 12 .word -11, -14, -6, 11, 5, 7, -2, -12 // should list the sorted integers of all 32 input data // like if saying: .space 32 Output_data: .word 0, 0, 0, 0, 0, 0, 0, 0 .word 0, 0, 0, 0, 0, 0, 0, 0 .word 0, 0, 0, 0, 0, 0, 0, 0 .word 0, 0, 0, 0, 0, 0, 0, 0 ``` well, basically registers were all blank in Vitis IDE, even though I think it is supposed to be working..
How vitest mock different variable value?
|reactjs|typescript|vitest|
null
#Step 02 CREATE TABLE company_customer ( cust_ID INT, address_num VARCHAR (6), street VARCHAR(20), city VARCHAR(20), cust_contact_num VARCHAR(12) UNIQUE NOT NULL, cust_alt_contact VARCHAR(12), cust_email VARCHAR(20) UNIQUE NOT NULL, company_name VARCHAR(20) NOT NULL, company_reg_num VARCHAR(25) UNIQUE NOT NULL, CONSTRAINT ccus_pk PRIMARY KEY (cust_ID) ); #Step 03 CREATE TABLE individual_customer ( cust_ID INT , address_num VARCHAR (6), street VARCHAR(20), city VARCHAR(20), cust_contact_num VARCHAR(12) UNIQUE NOT NULL, cust_alt_contact VARCHAR(12), cust_email VARCHAR(20)UNIQUE NOT NULL, cust_nic VARCHAR(13)UNIQUE NOT NULL, c_fname VARCHAR(15)NOT NULL, c_lname VARCHAR(15)NOT NULL, CONSTRAINT icus_pk PRIMARY KEY (cust_ID) ); #Step 04 CREATE TABLE project ( project_ID INTEGER NOT NULL, cust_ID INTEGER, site_ad_num VARCHAR (6)NOT NULL, site_street VARCHAR(20) NOT NULL, site_city VARCHAR(20) NOT NULL, project_type VARCHAR(15) NOT NULL, proj_start_date DATE NOT NULL, estimated_completion_date DATE NOT NULL, actual_completion_date DATE, current_progress VARCHAR(15)NOT NULL, specific_requirements VARCHAR (40), CONSTRAINT prog_ID_pk PRIMARY KEY (project_ID), CONSTRAINT proj_icusID_fk FOREIGN KEY (cust_ID) REFERENCES individual_customer(cust_ID), CONSTRAINT proj_ccusID_fk FOREIGN KEY (cust_ID) REFERENCES company_customer(cust_ID) ); INSERT INTO project (project_ID,cust_ID,site_ad_num, site_street,site_city ,project_type, proj_start_date, estimated_completion_date,actual_completion_date, current_progress, specific_requirements) VALUES (301, 100, '123', 'Beach Road', 'Galle', 'CONSTRUCTION', '2020-04-06', '2020-05-17', null, 'On hold', 'Need additional labour.'), (302,700,'99/7','Dehiwala Road', 'Maharagama','CONSTRUCTION','2020-08-09','2021-10-11',null,'On hold', 'Payment issue.'), (303, 305, '456', 'Hillside Avenue', 'Galle', 'RENOVATION', '2021-01-01', '2021-12-12', null, 'Ongoing', null), (304,205, '67J', 'Temple Road', 'Kottawa', 'CONSTRUCTION', '2021-02-03','2021-08-10', NULL, 'Ongoing', null), (305, 205, '789', 'Beachfront Road', 'Negombo', 'RENOVATION', '2022-01-02', '2023-09-10', NULL, 'Ongoing',null), (306,505,'67A','Bangalawatta Road', 'Kandy','CONSTRUCTION','2022-01-23','2023-09-26', '2023-08-29','Complete', null), (307, 500,'21A', 'Coastal Road', 'Batticaloa', 'RENOVATION', '2023-01-02', '2023-09-05', '2023-10-12', 'Complete', null), (308,705, '123B', 'Lake View Street', 'Colombo', 'CONSTRUCTION', '2023-01-01', '2023-12-30','2023-12-15', 'Complete', null), (309, 105, '987/23', 'Hilltop Drive', 'Kottawa','RENOVATION', '2023-09-02', '2024-12-12', NULL, 'Ongoing', null), (310,400, '45', 'Dabahen Road','Kandy', 'CONSTRUCTION', '2024-01-01','2024-03-30','2024-03-29', 'Complete', null), (311, 500, '345B', 'Hill Road', 'Colombo', 'RENOVATION', '2024-01-03', '2025-01-02', null, 'On hold', 'Awaiting governent approval.'), (312,600,'24/56','Samagi Road', 'Homagama','CONSTRUCTION','2024-03-03','2025-01-20',null,'Ongoing',null), (313,600,'123A','Sinha Road','Dehiwala','RENOVATION','2024-01-30','2025-05-09',null, 'Ongoing',null), (314,500,'34C','Barnse Road', 'Colombo','RENOVATION','2024-01-01','2024-03-20','2024-03-19', 'Complete',null), (315,205,'209','Kingsley Road','Colombo','RENOVATION','2024-01-20','2024-04-01','2024-04-02','Complete',null); if I disable the foriegn key check it runs,I want it to be run without unticking the box
We have couple of applications which are desktop(PC) , Mobile applications, so planned to create unique test automation framework in java we have created a framework to support both desktop and mobile platforms using below tech stack Selenium webdriver, appium, java client, testNG, allure , java 17 but i am facing issues while running tests in parallel , only one tests run on desktop browser the other tests open in mobile but it sits in idle state without running tests baseTests.java Boolean isMobile= (Boolean) deviceInfo.get("isMobile"); Boolean isHeadLess = (Boolean) deviceInfo.get("isHeadless"); if (Objects.isNull(DriverManager.getDriver())) { if (isMobile) { serverManager.startServer(); deviceName = deviceInfo.getString("devicename"); String avd = deviceInfo.getString("avd"); String udid = deviceInfo.getString("udid"); String platformVersion = deviceInfo.getString("platformVersion"); Boolean isEmulator = (Boolean) deviceInfo.get("isEmulator"); URL url = new ServerManager().getServer().getUrl(); RemoteWebDriver driver=DriverFactory.initializeMobileDriver(MobilePlatformName.valueOf(platformType.toUpperCase()), deviceName, udid, isEmulator, isHeadLess,browserName, url); } else { RemoteWebDriver driver=DriverFactory.initializeWebDriver(WebBrowserName.valueOf(browserName.toUpperCase()), isHeadLess); } } here i am using 'RemoteWebDriver' to refer both selenium webdriver and appium driver DriverManager.java private static final ThreadLocal<RemoteWebDriver> threadLocalDriver = new ThreadLocal<>(); public static synchronized RemoteWebDriver getDriver() { return threadLocalDriver.get(); } public static synchronized void setAppiumDriver(RemoteWebDriver driver) { if (Objects.nonNull(driver)) { threadLocalDriver.set(driver); } } public static synchronized void unload() { threadLocalDriver.remove(); } Testsclass.java public class SearchTest extends BaseTest{ public test(){ driver= DriverManager.getDriver(); if (PlatformUtils.isMobile(driver)) { googleSearch() Else{ googleSearch() } } } If I use if (PlatformUtils.isMobile(driver)) { googleSearch() Else{ googleSearch() } This way tests run on both the platforms but If I use simply googleSearch() Then both desktop and mobile browser will open but only one test run on desktop but mobile tests just stay idle without moving Is it right the way using of remotewedriver to refer both selenium web drover and appium driver ? If I use above way so that I can use common driver and common code to tests ,instead of using different appium driver and selenium driver separately Can someone help me to get the correct approach to handle both mobile and desktop(pc) ?
[Per my top comment], building with `-Wall -O0 -g -fsanitize=address`, a few issues ... 1. With `-Wall`, arguments `col` and `row` are `char` and compiler complains about that (converted to `int`) 1. `row` and `col` are unitialized (in `main`) but the _values_ are never used by `computerMove` or `UserMove` (set to zero to eliminate warning). They do _not_ need to be arguments. 1. After fixing the warnings (which one should _always_ do), the address sanitizer is detecting a fault. ---------- With a board size of `8` and computer with `B`, in `computerMove`, the sanitizer complains about the `if`: ``` for (int i = 0; i < counter; i++) { for (int j = 0; j < n; j++) { dbgprt("i=%d j=%d tracker=%d\n",i,j,tracker); if ((movesrow[duplicates[i]] < movesrow[duplicates[i + j]]) && movescol[duplicates[i]] < movescol[duplicates[i + j]]) { rowtemp = movesrow[duplicates[i]]; coltemp = movescol[duplicates[i]]; } else { rowtemp = movesrow[duplicates[i + j]]; coltemp = movescol[duplicates[i + j]]; } } } ``` The debug `printf` I added shows: ``` i=0 j=0 tracker=4 i=0 j=1 tracker=4 i=0 j=2 tracker=4 i=0 j=3 tracker=4 i=0 j=4 tracker=4 ``` The array `duplicates` is of dimension `tracker` (which is 4), so `i + j` is becoming too large and overflows `duplicates`. This is UB (undefined behavior). ---------- Here is the refactored code. It is annotated: ``` #include <stdio.h> #include <stdlib.h> #if 0 #include "lab8part1.h" #else #include <stdbool.h> #endif #if DEBUG #define dbgprt(_fmt...) \ printf(_fmt) #else #define dbgprt(_fmt...) do { } while (0) #endif void printBoard(char board[][26], int n); bool positionInBounds(int n, int row, int col); bool checkLegalInDirection(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol); bool validMove(char board[][26], int n, int row, int col, char colour); #if 0 bool computerMove(char board[][26], int n, char colour, char row, char col); bool UserMove(char board[][26], int n, char colour, char row, char col); #else bool computerMove(char board[][26], int n, char colour, int row, int col); bool UserMove(char board[][26], int n, char colour, int row, int col); #endif int checkBestMoves(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol); bool checkifmove(char board[][26], int n, char color); int main(void) { #if 0 char board[26][26], color, row, col; #else char board[26][26], color; int row, col; #endif printf("Enter the board dimension: "); int n; scanf(" %d", &n); int start = n / 2; for (int m = 0; m < n; m++) { for (int j = 0; j < n; j++) { if ((m == start - 1 && j == start - 1) || (m == start && j == start)) { board[m][j] = 'W'; } else if ((m == start - 1 && j == start) || (m == start && j == start - 1)) { board[m][j] = 'B'; } else { board[m][j] = 'U'; } } } printf("Computer plays (B/W): "); scanf(" %c", &color); char color1; if (color == 'B') { color1 = 'W'; } else { color1 = 'B'; } printBoard(board, n); printf("\n"); char turn = 'B'; bool validmove = true; // NOTE/BUG: these are unitialized, but the neither computerMove nor UserMove // use them. they do _not_ need to be arguments #if 1 row = 0; col = 0; #endif while ((checkifmove(board, n, color) == true) || (checkifmove(board, n, color1) == true)) { validmove = true; if (turn == color) { validmove = computerMove(board, n, color, row, col); } else { UserMove(board, n, color1, row, col); } if (validmove == false) { break; } if (turn == 'W') { turn = 'B'; } else { turn = 'W'; } } int whitwin = 0; int blacwin = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'W') { whitwin += 1; } else { blacwin += 1; } } } if (whitwin > blacwin) { printf("W player wins."); } else if (whitwin < blacwin) { printf("B player wins."); } else { printf("Draw."); } return 0; } #if 0 bool computerMove(char board[][26], int n, char colour, char row, char col) #else bool computerMove(char board[][26], int n, char colour, int row, int col) #endif { int movesrow[100] = { 0 }; int movescol[100] = { 0 }; int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'U') { if (checkLegalInDirection(board, n, i, j, colour, -1, -1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, -1, 0)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, -1, 1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 0, -1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 0, 1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, -1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, 0)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, 1)) { movesrow[count] = i; movescol[count] = j; } } } count += 1; } int bestMoves[600] = { 0 }; int tracker = 0; int tot = 0; for (int i = 0; i < count; i++) { if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, -1); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 0); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 1); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, -1); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, 1); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, -1); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 0); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 1); if (tot != 0) { bestMoves[tracker] = tot; } } } // if computer runs out of moves if (bestMoves[0] == 0) { printf("%c player has no valid move.", colour); return false; } int counter = 0; int bigNum = bestMoves[0]; int duplicates[tracker]; for (int i = 1; i < tracker; i++) { if (bestMoves[i] > bigNum) { bigNum = bestMoves[i]; duplicates[0] = i; counter = 1; } else if (bestMoves[i] == bigNum) { duplicates[counter] = i; counter++; } } int rowtemp = 0, coltemp = 0; for (int i = 0; i < counter; i++) { for (int j = 0; j < n; j++) { dbgprt("i=%d j=%d tracker=%d\n",i,j,tracker); // NOTE/BUG: i + j will exceed tracker -- this is UB if ((movesrow[duplicates[i]] < movesrow[duplicates[i + j]]) && movescol[duplicates[i]] < movescol[duplicates[i + j]]) { rowtemp = movesrow[duplicates[i]]; coltemp = movescol[duplicates[i]]; } else { rowtemp = movesrow[duplicates[i + j]]; coltemp = movescol[duplicates[i + j]]; } } } row = rowtemp; col = coltemp; if (validMove(board, n, (row), (col), colour)) { board[row][col] = colour; printf("\nComputer places %c at %c%c\n", colour, (row + 'a'), (col + 'a')); printBoard(board, n); return true; } else { return false; } } #if 0 bool UserMove(char board[][26], int n, char colour, char row, char col) #else bool UserMove(char board[][26], int n, char colour, int row, int col) #endif { int movesrow[100] = { 0 }; int movescol[100] = { 0 }; int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'U') { if (checkLegalInDirection(board, n, i, j, colour, -1, -1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, -1, 0)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, -1, 1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 0, -1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 0, 1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, -1)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, 0)) { movesrow[count] = i; movescol[count] = j; } if (checkLegalInDirection(board, n, i, j, colour, 1, 1)) { movesrow[count] = i; movescol[count] = j; } } } count += 1; } int bestMoves[100] = { 0 }; int tracker = 0; int tot = 0; for (int i = 0; i < count; i++) { if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, -1); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 0); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, -1, 1); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, -1); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 0, 1); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, -1); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 0); if (tot != 0) { bestMoves[tracker] = tot; } } if (tot != 0) { tracker += 1; } tot = 0; for (int j = 0; j < count; j++) { tot += checkBestMoves(board, n, movesrow[i], movescol[i], colour, 1, 1); if (tot != 0) { bestMoves[tracker] = tot; } } } // if player runs out of moves if (bestMoves[0] == 0) { printf("%c player has no valid move.", colour); return false; } printf("\nEnter a move for colour %c (RowCol): ", colour); #if 0 scanf(" %c%c", &row, &col); #else char c_row, c_col; scanf(" %c%c", &c_row, &c_col); row = c_row; col = c_col; #endif if (validMove(board, n, (row - 'a'), (col - 'a'), colour)) { board[row - 'a'][col - 'a'] = colour; printBoard(board, n); } return true; } bool validMove(char board[][26], int n, int row, int col, char colour) { int score = 0; if (checkLegalInDirection(board, n, row, col, colour, -1, -1)) { score++; int i = 1; while (board[row + (i * -1)][col + (i * -1)] != colour) { board[row + (i * -1)][col + (i * -1)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, -1, 0)) { score++; int i = 1; while (board[row + (i * -1)][col + (i * 0)] != colour) { board[row + (i * -1)][col + (i * 0)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, -1, 1)) { score++; int i = 1; while (board[row + (i * -1)][col + (i * 1)] != colour) { board[row + (i * -1)][col + (i * 1)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, 0, -1)) { score++; int i = 1; while (board[row + (i * 0)][col + (i * -1)] != colour) { board[row + (i * 0)][col + (i * -1)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, 0, 1)) { score++; int i = 1; while (board[row + (i * 0)][col + (i * 1)] != colour) { board[row + (i * 0)][col + (i * 1)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, 1, -1)) { score++; int i = 1; while (board[row + (i * 1)][col + (i * -1)] != colour) { board[row + (i * 1)][col + (i * -1)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, 1, 0)) { score++; int i = 1; while (board[row + (i * 1)][col + (i * 0)] != colour) { board[row + (i * 1)][col + (i * 0)] = colour; i++; } } if (checkLegalInDirection(board, n, row, col, colour, 1, 1)) { score++; int i = 1; while (board[row + (i * 1)][col + (i * 1)] != colour) { board[row + (i * 1)][col + (i * 1)] = colour; i++; } } if (score > 0) { return true; } else { return false; } } void printBoard(char board[][26], int n) { printf(" "); for (int i = 0; i < n; i++) { printf("%c", 'a' + i); } for (int m = 0; m < n; m++) { printf("\n%c ", 'a' + m); for (int j = 0; j < n; j++) { printf("%c", board[m][j]); } } } bool positionInBounds(int n, int row, int col) { if (row >= 0 && row < n && col >= 0 && col < n) { return true; } else { return false; } } bool checkLegalInDirection(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol) { if (positionInBounds(n, row, col) == false) { return false; } if (board[row][col] != 'U') { return false; } row += deltaRow; col += deltaCol; if (positionInBounds(n, row, col) == false) { return false; } if (board[row][col] == colour || board[row][col] == 'U') { return false; } while ((positionInBounds(n, row, col)) == true) { if (board[row][col] == colour) { return true; } if (board[row][col] == 'U') { return false; } row += deltaRow; col += deltaCol; } return false; } int checkBestMoves(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol) { int tiles = 0; if (positionInBounds(n, row, col) == false) { return false; } if (board[row][col] != 'U') { return false; } row += deltaRow; col += deltaCol; if (positionInBounds(n, row, col) == false) { return false; } if (board[row][col] == colour || board[row][col] == 'U') { return false; } while ((positionInBounds(n, row, col)) == true) { if (board[row][col] == colour) { return tiles; } if (board[row][col] == 'U') { return false; } tiles += 1; row += deltaRow; col += deltaCol; } return false; } bool checkifmove(char board[][26], int n, char color) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'U') { if (checkLegalInDirection(board, n, i, j, color, -1, -1) || checkLegalInDirection(board, n, i, j, color, -1, 0) || checkLegalInDirection(board, n, i, j, color, -1, 1) || checkLegalInDirection(board, n, i, j, color, 0, -1) || checkLegalInDirection(board, n, i, j, color, 0, 1) || checkLegalInDirection(board, n, i, j, color, 1, -1) || checkLegalInDirection(board, n, i, j, color, 1, 0) || checkLegalInDirection(board, n, i, j, color, 1, 1)) { return true; } } } } return false; } ``` ---------- In the code above, I've used `cpp` conditionals to denote old vs. new code: ``` #if 0 // old code #else // new code #endif #if 1 // new code #endif ``` Note: this can be cleaned up by running the file through `unifdef -k`
I'm programming a simple 'game' that is just a block that can jump around. I placed a wall, but now the character phases through when moving to the right, but the collision works when going to the right. The collision in question: ``` function willImpactMovingRight(a, b){ var docA = document.getElementById(a); var docB = document.getElementById(b[0]); for(var i=0;i<b.length;i++){ docB = document.getElementById(b[i]); if((docA.offsetTop>docB.offsetTop&&docA.offsetTop<docB.offsetTop+docB.offsetHeight)||(docA.offsetTop+docA.offsetHeight>docB.offsetTop&&docA.offsetTop+docA.offsetHeight<docB.offsetTop+docB.offsetHeight)){//vertical check, not broken if(docA.offsetLeft>docB.offsetWidth+docB.offsetLeft-runSpeed){//also fine //below this is the problem if(docA.offsetLeft+docA.offsetWidth+runSpeed<=docB.offsetLeft){ CUBE.textContent = "WIMR"; return docB.offsetLeft-docA.offsetWidth; } //all syntax is fine but the if statement never returns as true. } } } return false; } ``` it looks like a lot, but the only problem is the last if statement. Even when the condition is true, it still returns false. Any idea why? P.S. **I CANNOT USE THE CONSOLE, I AM ON A MANAGED COMPUTER** I'm also locked out of my github account and have a link to a code.org page (just copy the code) https://studio.code.org/projects/applab/iFUpHIl-Vq3nQ4PYxY8Y1tMkIIgh9tAl95RexkDQUh8
Character phases through wall one way, but not the other
|javascript|html|css|
null
I am rendering different sections in my dashboard using a nested Route. The problem is when I navigate between sections (using react-router-dom `Link`) it unmounts the section so when I go back it has to re-load and re-render the section. Here is how i'm setting the routes ``` <Routes> {(!user.loaded && userWasLoaded) || (user.loaded && user?.user) ? ( <Route path='/' element={<DashboardPage />}> <Route index element={<Feed />} /> <Route path='/configuration' element={<Listeners />} /> <Route path='/team' element={<Team />} /> {user?.user?.isAdmin && ( <Route path='/admin' element={<Admin />} /> )} </Route> ) : ( <Route path='/' element={<LoginPage />} /> )} <Route path='/login' element={<LoginPage />} /> <Route path='/pricing' element={<Pricing />} /> <Route path='/privacy' element={<PrivacyPolicyPage />} /> <Route path='*' element={<Navigate to='/' />} /> </Routes> ``` and here is how i'm getting data in my pages: ``` const Team = () => { const [plan, setPlan] = React.useState(null); useEffect(() => { API.getMyPlan().then((data) => setPlan(data)); }, []); ``` I am expecting react and react-router-dom to NOT unmount each section whenever I navigate between pages.
react-router-dom unmounting outlet on page switch
|reactjs|react-router-dom|
Optimizing Memory-Bound Loop with Indirect Prefetching
|optimization|vectorization|intel|compiler-optimization|prefetch|
null
|java|spring-boot|spring-data-jpa|
{"OriginalQuestionIds":[218384],"Voters":[{"Id":286934,"DisplayName":"Progman"},{"Id":10632369,"DisplayName":"tomerpacific"},{"Id":9214357,"DisplayName":"Zephyr"}]}
I believe in this case you should not use the entry API anyway - even without considering this issue. This is because the entry API, in order to be able to insert the key if missing, needs an owned key. For you that means that you cannot lookup with `&str`, you must call `to_string()` on it - and that means an allocation, which is a bigger cost than a second lookup, and assuming (as I understand) that most of the times the pattern is already registered, the cost of the allocation will dwarf the cost of the double lookup. So the best solution for you is to use a simple structure: ```rust fn register_pattern(&mut self, pattern: &str) { if !self.regex_registry.contains(pattern) { let asc = self.parse_locale_pattern(pattern.to_string(), ParseLocale::Ascii); let jap = self.parse_locale_pattern(pattern.to_string(), ParseLocale::Japanese); let parse_localized_regex = ...expression involving asc, jap...; self.regex_registry.insert(pattern.to_string(), ParseLocalized::new(asc, jap)); } } ```
`getTimezoneOffset()` returns wrong timezone. I'm in Kyiv and my local time is 10:07. **Kyiv time confirmed**: ``` > new Date().toLocaleString('en-GB', {timeZone: 'Europe/Kyiv' }); // '31/03/2024, 10:07:28' ``` Yesterday Kyiv was on winter time GMT+3, but today winter time is off and Kyiv is on GMT+2. **2 hour difference confirmed**: ``` > new Date().toLocaleString('en-GB', {timeZone: 'Europe/London' }); // '31/03/2024, 08:07:07' ``` So, getTimezoneOffset() suppose to return -120, right? No. ``` > new Date().getTimezoneOffset() // -180 ``` I switched local TZ on my PC to Paris and got `-120` though Paris is GMT+1 and `-60` was expected. So it seems `getTimezoneOffset()` is one hour off for all the TZs. I can see that people struggled with `getTimezoneOffset()` before and some workarounds are out there, but the question stands: Why `getTimezoneOffset()` returns wrong result at the first place?
Why new Date.getTimezoneOffset() returns wrong result?
|javascript|
{"Voters":[{"Id":238704,"DisplayName":"President James K. Polk"},{"Id":1840146,"DisplayName":"Toerktumlare"},{"Id":5277820,"DisplayName":"dur"}],"SiteSpecificCloseReasonIds":[13]}
bash: parse command line arguments *and* write useful *usage* message without additional code
I´m new to stackoverflow and i´ve just been into software testing and this whole world for about a year but I am currently developing myself as a QA in a startup and i´ve been automating my test plan using Selenium with Python and Pytest. Currently I have 359 tests that run perfectly on my computer when using the GUI but now my team has established a virtual machine to run them twice a day for what they have to run in headless mode and most of them fail. When I run them headless on my computer they also fail, I don´t know why because it should work identically as far as i´m concerned. I´ll be super gratefull if you guys can help me in making the necessary changes to make the automated suite run well in headless mode as well. Thanks! I just run them headless expecting them to pass as always but that didn´t go as I expected. This is a bit of the code i´m using: ```python class Test_CON_02_Coupons(unittest.TestCase): def setUp(self): chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--no-sandbox") self.driver = webdriver.Chrome(options=chrome_options) self.driver.implicitly_wait(60) self.driver.maximize_window() self.vars = {} self.driver.get(CON_SELFSERVICE_URL) ```
I have a spec flow automation framework. I am using Visual Studio Editor. in that, any definition in the definition file shows references zero. I want to display the reference number with the definition. suggest to me the solution to display the references with definitions. [as in the image the reference shows zero even if it referred at a number of places in the project](https://i.stack.imgur.com/y8BjB.png)](https://i.stack.imgur.com/y8BjB.png) I did research and installed some extensions of Spec-flow but it did not work. also, I follow the spec flow documentation
Specflow defination not showing references
|.net|automation|integration-testing|bdd|specflow|
null
I run GRPC and REST on different ports and different goroutines: func main() { cfg := config.MustLoad() log := setupLogger(cfg.Env) grpcApplication := app.NewGrpc(log, cfg.GRPC.Port, cfg.StoragePath, cfg.TokenTTL) restApplication := app.NewRest(log, cfg.GRPC.Port, cfg.StoragePath, cfg.TokenTTL) go func() { grpcApplication.GRPCServer.MustRun() }() go func() { restApplication.RestServer.MustRun() }() // Graceful shutdown stop := make(chan os.Signal, 1) signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT) <-stop grpcApplication.GRPCServer.Stop() log.Info("Gracefully stopped") }
Is there any way to tell Notepad please remove the following [DOCUMENT](https://i.stack.imgur.com/Ukr0X.jpg) Remove all the empty characters after the last , sign. I know I can tell please replace , with empty but the problem is I have many , that hast to stay in the file. I just need notepad to remove EVERYTHING including that last , sign after the last , sign in the document. For example 14.56364,46.02230,1,80,1**,216,Golovec** I need that to be 14.56364,46.02230,1,80 With no empty spaces after that or that last , sign. The problem is sometimes some lines have more than one empty characters after the last , sign. This does not help **.{1}$** The problem is the Python script I have and is very sensitive to any kind of extra signs of characters after the last , sign. Thank you I tried all the .{1}$ replace empty spaces...works but needs to be repeated since some lines have more than one empty charatcter.
Notepad++ Remove Empty Spaces or characters after the specific LAST character
|character|notepad++|line|
null
|javascript|angular|firebase|firebase-realtime-database|
null
{"Voters":[{"Id":1431750,"DisplayName":"aneroid"},{"Id":21972629,"DisplayName":"jQueeny"},{"Id":14732669,"DisplayName":"ray"}]}
The code below uses a **background callback** (dash) to retrieve a value. Every 3 seconds, `update_event(event, shared_value)` sets an `event` and define a `value`. In parallel, `listening_process(set_progress)` waits for the `event`. This seems to work nicely and the waiting time is low (say a few seconds). When the waiting time is below 1 second (say 500ms), `listening_process(set_progress)` is missing values. Is there a way for the **background callback** to refresh faster ? It looks like the server updates with a delay of a few hundred of ms, independently of the rate at which I set the `event`. I could have used a `dcc.interval` but wanted to prevent polling. [![enter image description here][1]][1] ``` import time from uuid import uuid4 import diskcache import dash_bootstrap_components as dbc from dash import Dash, html, DiskcacheManager, Input, Output from multiprocessing import Event, Value, Process from datetime import datetime import random # Background callbacks require a cache manager + a unique identifier launch_uid = uuid4() cache = diskcache.Cache("./cache") background_callback_manager = DiskcacheManager( cache, cache_by=[lambda: launch_uid], expire=60, ) # Creating an event event = Event() # Creating a shared value shared_value = Value('i', 0) # 'i' denotes an integer type # Updating the event # This will run in a different process using multiprocessing def update_event(event, shared_value): while True: event.set() with shared_value.get_lock(): # ensure safe access to shared value shared_value.value = random.randint(1, 100) # generate a random integer between 1 and 100 print("Updating event...", datetime.now().time(), "Shared value:", shared_value.value) time.sleep(3) app = Dash(__name__, background_callback_manager=background_callback_manager) app.layout = html.Div([ html.Button('Run Process', id='run-button'), dbc.Row(children=[ dbc.Col( children=[ # Component sets up the string with % progress html.P(None, id="progress-component") ] ), ] ), html.Div(id='output') ]) # Listening for the event and generating a random process def listening_process(set_progress): while True: event.wait() event.clear() print("Receiving event...", datetime.now().time()) with shared_value.get_lock(): # ensure safe access to shared value value = shared_value.value # read the shared value set_progress(value) @app.callback( [ Output('run-button', 'style', {'display': 'none'}), Output("progress-component", "children"), ], Input('run-button', 'n_clicks'), prevent_initial_call=True, background=True, running=[ (Output("run-button", "disabled"), True, False)], progress=[ Output("progress-component", "children"), ], ) def run_process(set_progress, n_clicks): if n_clicks is None: return False, None elif n_clicks > 0: p = Process(target=update_event, args=(event,shared_value)) p.start() listening_process(set_progress) return True, None if __name__ == '__main__': app.run(debug=True, port=8050) ``` [1]: https://i.stack.imgur.com/mHARa.gif
I have created a custom SAML application in the Google Admin panel for my workspace account to allow users to login via SSO to an application using their Google Workspace credentials. Currently only users of my organisation can login to this application. I want to make it so that users of an external organisation can also login to this application using their Google Workspace credentials using SSO. How do I do this? Tried: I have created a Google Group and all users who should have access to this application (both internal and external organisation users) and turned on access to this Google Group in the access settings of the custom SAML app. Expected: Both internal and external users should be able to login to the application. Result: Only internal users are able to login to the application using their credentials.
{"OriginalQuestionIds":[77941885],"Voters":[{"Id":11182,"DisplayName":"Lex Li","BindingReason":{"GoldTagBadge":"iis"}}]}
{"OriginalQuestionIds":[64341589],"Voters":[{"Id":5577765,"DisplayName":"Rabbid76","BindingReason":{"GoldTagBadge":"pygame"}}]}
{"OriginalQuestionIds":[10825926],"Voters":[{"Id":476,"DisplayName":"deceze","BindingReason":{"GoldTagBadge":"python"}}]}
No module named 'keras.layers.core
``` mpg['grade'] = np.where(mpg['total'] >= 30, 'A', np.where(mpg['total'] >= 20, 'B', 'C')) ``` code 1) ``` count_grade = mpg['grade'].value_counts() count_grade.plot.bar(rot=0) plt.show() ``` code 2) ``` count_grade = mpg['grade'].value_counts().sort_index() # method chaining count_grade.plot.bar(rot=0) plt.show() ``` reference) count_grade -> 'A' : 10, 'B' : 118, 'C' : 106 **(in VSCode)** The execution result is different with and without the code 1). When I only run code 2) without code 1), A is more than 120 instead of 10 (in graph) [enter image description here](https://i.stack.imgur.com/JRHEp.png) However, when the two codes are executed together, the result is normally output as a result of only 'A', 'B', and 'C' being sorted. [enter image description here](https://i.stack.imgur.com/sxG6B.png) **(in Colab)** ``` mpg['grade'] = np.where(mpg['total'] >= 30, 'A', np.where(mpg['total'] >=20, 'B', 'C')) count_grade = mpg['grade'].value_counts().sort_index() print(count_grade) count_grade.plot.bar(rot=0) ``` When I put this code in one block and run it, the results are output strangely. [enter image description here](https://i.stack.imgur.com/KLC1Z.png) However, running the last line separately solves the problem [enter image description here](https://i.stack.imgur.com/IMFDI.png) I'd like to know what the problem is. please help me expecting : ![enter image description here](https://i.stack.imgur.com/7u58B.png) but my result : ![enter image description here](https://i.stack.imgur.com/V2bK7.png)
I need to print the bounding box coordinates of a walking person in a video. Using YOLOv5 I detect the persons in the video. Each person is tracked. I need to print each person's bounding box coordinate with the frame number. Using Python how to do this. The following is the code to detect and track persons in a video using YOLOv5. ``` #display bounding boxes coordinates import cv2 from ultralytics import YOLO # Load the YOLOv8 model model = YOLO('yolov8n.pt') # Open the video file cap = cv2.VideoCapture("Shoplifting001_x264_15.mp4") #get total frames frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) print(f"Frames count: {frame_count}") # Initialize the frame id frame_id = 0 # Loop through the video frames while cap.isOpened(): # Read a frame from the video success, frame = cap.read() if success: # Run YOLOv8 tracking on the frame, persisting tracks between frames results = model.track(frame, persist=True,classes=[0]) # Visualize the results on the frame annotated_frame = results[0].plot() # Print the bounding box coordinates of each person in the frame print(f"Frame id: {frame_id}") for result in results: for r in result.boxes.data.tolist(): if len(r) == 7: x1, y1, x2, y2, person_id, score, class_id = r print(r) else: print(r) # Display the annotated frame cv2.imshow("YOLOv5 Tracking", annotated_frame) # Increment the frame id frame_id += 1 # Break the loop if 'q' is pressed if cv2.waitKey(1) & 0xFF == ord("q"): break else: # Break the loop if the end of the video is reached break # Release the video capture object and close the display window cap.release() cv2.destroyAllWindows() ``` The following code is working and display the coordinates of tracked persons. But the problem is in some videos it is not working properly 0: 384x640 6 persons, 1292.9ms Speed: 370.7ms preprocess, 1292.9ms inference, 20.8ms postprocess per image at shape (1, 3, 384, 640) Frame id: 0 [849.5707397460938, 103.34817504882812, 996.0990600585938, 371.2213439941406, 1.0, 0.9133888483047485, 0.0] [106.60043334960938, 74.8958740234375, 286.6423645019531, 562.144287109375, 2.0, 0.8527513742446899, 0.0] [221.3446044921875, 60.8421630859375, 354.4775390625, 513.18017578125, 3.0, 0.7955091595649719, 0.0] [472.7821044921875, 92.33056640625, 725.2569580078125, 632.264404296875, 4.0, 0.7659056782722473, 0.0] [722.457763671875, 222.010986328125, 885.9102783203125, 496.00372314453125, 5.0, 0.7482866644859314, 0.0] [371.93310546875, 46.2138671875, 599.2041625976562, 437.1387939453125, 6.0, 0.7454277873039246, 0.0] This output is correct. But for another video there are only three people in the video but at the beginning of the video at 1st frame identify as 6 person. 0: 480x640 6 persons, 810.5ms Speed: 8.0ms preprocess, 810.5ms inference, 8.9ms postprocess per image at shape (1, 3, 480, 640) Frame id: 0 [0.0, 10.708396911621094, 37.77726745605469, 123.68929290771484, 0.36418795585632324, 0.0] [183.0453338623047, 82.82539367675781, 231.1952667236328, 151.8341522216797, 0.2975049912929535, 0.0] [154.15158081054688, 74.86528778076172, 231.10934448242188, 186.2017822265625, 0.23649221658706665, 0.0] [145.61187744140625, 69.76246643066406, 194.42532348632812, 150.91973876953125, 0.16918501257896423, 0.0] [177.25042724609375, 82.43289947509766, 266.5430908203125, 182.33889770507812, 0.131477952003479, 0.0] [145.285400390625, 69.32669067382812, 214.907470703125, 184.0771026611328, 0.12087596207857132, 0.0] Also, the output does not show the person ID here. Only display coordinates, confidence score, and class id. What is the reason for that?
I need a part to be incerted to the character's body everytime they respawn Here's the script I made: ``` local Backpack = game:GetService("ReplicatedStorage"):Waitforchild("Backpack") local Player = game:GetService("Players").localplayer Player.Character.Respawned:Connect(function(Character) local clone = Backpack:clone(Character.Torso) end ```
null
### Summary There is a difference between `any` in type parameter and `any` in regular function parameter. Your case is the former one for generics. So you need to instantiate `T`(decide `T`'s concrete type) first when assigning it to the concrete variables Ref. https://stackoverflow.com/questions/71628061/difference-between-any-interface-as-constraint-vs-type-of-argument ### In detail It's because in `GetAllProducts`, type `T` is not decided yet. So it is impossible to assign `[]models.Products` to `T`. ```golang func (db *DbConnection[T]) GetAllProducts() { var re []models.Products re, _ = db.GetAll() } ``` But you can assign `models.Products` to `T` if `T` is decided as `models.Products`, like this. ```golang db := DbConnection[models.Products]{} var re []models.Products re, _ = db.GetAll() ``` I reproduce your problem in the simplified version(https://go.dev/play/p/GHkDThFLOKG). You can find the same error `GetAllProducts()` but in the main code, it works.
You may try- =HSTACK( TOROW(FILTER($A$2:$A$7;BYROW($B$2:$M$7;LAMBDA(rw;INDEX(OR(rw=H13)))));3); TOROW(FILTER($B$1:$M$1;BYCOL($B$2:$M$7;LAMBDA(col;INDEX(OR(col=H13)))));3) ) [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/FfW29.png
The following code will add 3000 to 4000 documents of various sizes to a Firebird Blob field before running out of memory. I believe I have freed the streams I create, but I may not be doing it correctly. Streams are a new tool in my toolbox. Can anyone spot what I'm doing wrong? ``` procedure TfrmMigration.Button1Click(Sender: TObject); var DocFile: string; Blob: TStream; fs: TFileStream; begin with DM.qImageList do begin close; SQL.Text := ImgListSQL; open; First; while not eof do begin { Ignore if previously done.} if (FieldByName('Document_Files').IsNull) then begin DocFile := Trim(gsDocumentPath + '\' + FieldByName('ImageName').asString); if FileExists(DocFile) then begin edit; Blob := CreateBlobStream(FieldByName('Document_Files'), bmWrite); try Blob.Seek(0, soFromBeginning); fs := TFileStream.Create(DocFile, fmOpenRead or fmShareDenyWrite); try Blob.CopyFrom(fs, fs.Size); finally fs.free; end; finally Blob.free; end; post; end; end; next; end; end; end; ```
Out of memory while adding documents to a Firebird BLOB field with Delphi
|delphi|blob|streaming|firebird|
> while(true); Your code probably can't detect the GPS for some reason, so it go into this infinite `while(true)` loop. For ESP8266, the watchdog timer running in the background need to be "feed" regularly, this infinite loop choke the "dog" to death, change the line to the follow would allow the watchdog to "breath". ```cpp while(true) { delay(1); } ``` This will solve the reboot problem, you still need to deal with why the GPS is not working, so check the connection and test it outdoor with clear view of open sky.
I'm deploying a zip package as an Azure function with the use of Terraform. The relevant code fragments below: resource "azurerm_storage_account" "mtr_storage" { name = "mtrstorage${random_string.random_storage_account_suffix.result}" resource_group_name = azurerm_resource_group.mtr_rg.name location = azurerm_resource_group.mtr_rg.location account_kind = "BlobStorage" account_tier = "Standard" account_replication_type = "LRS" network_rules { default_action = "Deny" ip_rules = ["127.0.0.1", "my.id.addr.here"] virtual_network_subnet_ids = [azurerm_subnet.mtr_subnet.id] bypass = ["AzureServices", "Metrics"] } tags = { environment = "local" } } resource "azurerm_storage_blob" "mtr_hello_function_blob" { name = "MTR.ListBlobsFunction.publish.zip" storage_account_name = azurerm_storage_account.mtr_storage.name storage_container_name = azurerm_storage_container.mtr_hello_function_container.name type = "Block" source = "./example_code/MTR.ListBlobsFunction/MTR.ListBlobsFunction.publish.zip" } resource "azurerm_service_plan" "mtr_hello_function_svc_plan" { name = "mtr-hello-function-svc-plan" location = azurerm_resource_group.mtr_rg.location resource_group_name = azurerm_resource_group.mtr_rg.name os_type = "Linux" sku_name = "B1" tags = { environment = "local" } } data "azurerm_storage_account_blob_container_sas" "storage_account_blob_container_sas_for_hello" { connection_string = azurerm_storage_account.mtr_storage.primary_connection_string container_name = azurerm_storage_container.mtr_hello_function_container.name start = timeadd(timestamp(), "-5m") expiry = timeadd(timestamp(), "5m") permissions { read = true add = false create = false write = false delete = false list = false } } resource "azurerm_linux_function_app" "mtr_hello_function" { name = "mtr-hello-function" location = azurerm_resource_group.mtr_rg.location resource_group_name = azurerm_resource_group.mtr_rg.name service_plan_id = azurerm_service_plan.mtr_hello_function_svc_plan.id storage_account_name = azurerm_storage_account.mtr_storage.name storage_account_access_key = azurerm_storage_account.mtr_storage.primary_access_key app_settings = { "FUNCTIONS_WORKER_RUNTIME" = "dotnet" "WEBSITE_RUN_FROM_PACKAGE" = "https://${azurerm_storage_account.mtr_storage.name}.blob.core.windows.net/${azurerm_storage_container.mtr_hello_function_container.name}/${azurerm_storage_blob.mtr_hello_function_blob.name}${data.azurerm_storage_account_blob_container_sas.storage_account_blob_container_sas_for_hello.sas}" "AzureWebJobsStorage" = azurerm_storage_account.mtr_storage.primary_connection_string "AzureWebJobsDisableHomepage" = "true" } site_config { always_on = true application_insights_connection_string = azurerm_application_insights.mtr_ai.connection_string application_stack { dotnet_version = "8.0" use_dotnet_isolated_runtime = true } cors { allowed_origins = ["*"] } } tags = { environment = "local" } } The zip file is uploaded to the storage account, is downloadable and has the correct structure (or so I think). Function App is created as well, however when I scroll down to see the functions, it tells me there was an error loading functions: `Encountered an error (ServiceUnavailable) from host runtime.` It's probably some configuration error, but I just can't see it. Also I went to the advanced tools tab and in wwwroot there's only one file named `run_from_package_failure.log`. Its contents are: RunFromPackage> Failed to download package from https://mtrstorageqbr56n79h4.blob.core.windows.net/hello-function-releases/MTR.ListBlobsFunction.publish.zip?sv=2018-11-09&sr=c&st=2024-03-31T12:09:08Z&se=2024-03-31T12:19:08Z&sp=r&spr=https&sig=c6dhOCRPL%2BEQujbuq0589D2MXFN5eXfBmhow1QWSfHU%3D. Return code: 1 - (this URL is malformed, I swapped some characters ;) ). However when I go to the url the log contains, the zip file gets downloaded successfully...
important: I don't have a deep understanding of malloc so try to put things as simple as possible Greetings, I want to create a dynamic array of strings (using malloc) and then print those strings out (for starters). That's what I have ``` int main(){ char **namesofcolumns = malloc(4 * sizeof(char*)); for(int i = 0; i < 4; i++){ namesofcolumns[i] = malloc(20 * sizeof(char)); } int count = 1; for(int i = 0; i < 4; i++){ printf("Enter %d column name\n", count); scanf("%s", namesofcolumns[i]); count++; } ``` I probably have errors here already. How do I print entered strings out?
I need to create a malloc array of strings and print those strings out
|c|malloc|c-strings|
null
Trying to create a dialog class which will contain a QTableView widget, all is good, information gets inserted, but i cannot understand why pycharm show the error: "Unresolved attribute reference 'setModel' for class 'Dialog'" all class code here: ``` from PyQt5.QtGui import QStandardItemModel, QStandardItem from PyQt5.QtWidgets import QDialog, QTableView from PyQt5.uic import loadUi class Dialog(QDialog): def __init__(self): super(Dialog, self).__init__() loadUi("dialog.ui", self) self.table = self.findChild(QTableView, "tableView") def fill_table(self, data): column_names = ["full_name", "mail", "age", "phone_number"] model = QStandardItemModel(1, 4) model.setHorizontalHeaderLabels(column_names) for col_idx in range(4): item = QStandardItem(data[col_idx]) model.setItem(0, col_idx, item) self.table.setModel(model) ``` explain me what's going on and suggest solutions to the problem.
Unresolved attribute reference 'setModel' for class 'Dialog'
|python|pycharm|pyqt5|
null
i found a way, using: - integer pixel coordinates which is much more intuitive and convenient at least for what i'm doing here - and considering the "pixel size" i wanted to paste my code but the crazy blocking rules pretending my code is not "formatted" correctly prohibits it! ctrl-k does not work ... so i wonder how people can post anything here anymore? #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> #include <cctype> float pixelSize = 10.0; GLint worldWidth = 800; GLint worldHeight = 600; //float epsilonX = 1.16*pixelSize/worldWidth; //float epsilonY = 1.16*pixelSize/worldHeight; // Starting position of the pixel //float currX = 0.2f; //float currY = 0.5f; int currX = 25; int currY = 50; //float stepSize = 1.0f / worldWidth; int stepSize = 1; //float speed = 2.0f; bool isCollision = false; // OpenGL functions void setupOrthographicProjection(int screenWidth, int screenHeight) { // Set up an orthographic projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, screenWidth, 0.0, screenHeight, -1.0, 1.0); // Switch back to the model view matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } ///////////////////////////////////////////////// void updateWorld(char keyPressed){ int p = ((int) pixelSize)/2; switch (keyPressed) { case 'W': //up currY += stepSize; break; case 'A': //left currX -= stepSize; break; case 'S': //down currY -= stepSize; break; case 'D': //right currX += stepSize; break; } printf("currX=%d, currY=%d \n", currX, currY); /* //using openGL 'normalized' coords i.e. between -1 and 1 if (currX >= (1.0-epsilonX) || currX <= (-1.0+epsilonX) || currY >= (1.0-epsilonY) || currY <= (-1.0+epsilonY)){ printf("You hit the walls !!!!"); isCollision = true; } */ if (currX <= p || currX >= (worldWidth-p) || currY <= p || currY >= (worldHeight-p)){ printf("You hit the walls !!!!"); isCollision = true; } } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { char key_str = '0'; if (action == GLFW_PRESS || action == GLFW_REPEAT) { switch (key) { case GLFW_KEY_W: key_str = 'W'; break; case GLFW_KEY_A: key_str = 'A'; break; case GLFW_KEY_S: key_str = 'S'; break; case GLFW_KEY_D: key_str = 'D'; break; case GLFW_KEY_Q: printf("Bye ..."); glfwSetWindowShouldClose(window, GL_TRUE); break; default: printf("unknown key pressed \n"); break; } updateWorld(key_str); } } int main(void) { GLFWwindow* window; // Initialize the library if (!glfwInit()) return -1; //remove win frame //glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); // Create a windowed mode window and its OpenGL context window = glfwCreateWindow(worldWidth, worldHeight, "Move Pixel with Keyboard", NULL, NULL); if (!window) { glfwTerminate(); return -1; } // Make the window's context current glfwMakeContextCurrent(window); // Set the keyboard input callback glfwSetKeyCallback(window, key_callback); // Initialize GLEW glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cerr << "Failed to initialize GLEW" << std::endl; return -1; } //glfwGetFramebufferSize(window, &worldWidth, &worldHeight); setupOrthographicProjection(worldWidth, worldHeight); // Define the viewport dimensions glViewport(0, 0, worldWidth, worldHeight); // Set point size glPointSize(pixelSize); // Increase if you want the "pixel" to be bigger // Loop until the user closes the window while (!glfwWindowShouldClose(window) && !isCollision) { // Render here glClear(GL_COLOR_BUFFER_BIT); // Set the drawing color to blue glColor3f(1.0f, 0.0f, 1.0f); // RGB: Blue // Draw a point at the current position glBegin(GL_POINTS); glVertex2f(currX, currY); // Use the updated position glEnd(); // Swap front and back buffers glfwSwapBuffers(window); // Poll for and process events glfwPollEvents(); } glfwTerminate(); return 0; }
|php|twitter-bootstrap|tailwind-css|moodle|moodle-theme|
I'm trying to process multiple forms with fieldset inside This is a test for 40 questions, each question with 4 answers. I need to get each answer from radio button that the users picks and use it to count correct answers. I have some comments along the code to help out, if anything is needed let me know. Thanks for any help. My index.js code ``` import express from "express"; import bodyParser from "body-parser"; import pg from "pg"; const db = new pg.Client({ user: "postgres", host: "localhost", database: "world", password: "DQTD9YQ8", port: 5432, }); const pool = new pg.Pool({ user: "postgres", host: "localhost", database: "world", password: "DQTD9YQ8", port: 5432, }); const app = express(); const port = 3000; db.connect(); app.use(express.static("public")); app.use(bodyParser.urlencoded({ extended: true })); // Shuffling function based of fisher yates algorithm const shuffle = array => { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const temp = array[i]; array[i] = array[j]; array[j] = temp; } } let questions = []; app.get("/", async (req, res) => { //Generates random of questions IDs. for (let i = 0; i < 3; i++) { let questionId = Math.floor(Math.random() * 70); questions.push(questionId); }; // Query questions IDs from DB and shuffles the answers let arrayToShuff = []; let shuffledArray = []; const result = await pool.query(`SELECT * FROM theoryhebrew WHERE questionid = ANY($1::int[])`, [questions]); for (let i = 0; i < 3; i++) { arrayToShuff = [result.rows[i].answer1, result.rows[i].answer2, result.rows[i].answer3, result.rows[i].answer4]; shuffle(arrayToShuff); shuffledArray = [arrayToShuff[0], arrayToShuff[1], arrayToShuff[2], arrayToShuff[3]]; result.rows[i].answer1 = shuffledArray[0]; result.rows[i].answer2 = shuffledArray[1]; result.rows[i].answer3 = shuffledArray[2]; result.rows[i].answer4 = shuffledArray[3]; }; return res.render("index.ejs", { questionsResults: result.rows, answersShuffled: shuffledArray }); }); for (let i = 0; i < 3; i++) { let questionId = Math.floor(Math.random() * 70); questions.push(questionId); }; app.post("/submit", async (req, res) => { const submittedAnswer = req.body.answer; res.send(req.body); console.log(req.body); const result2 = await db.query(`SELECT answer1 FROM theoryhebrew WHERE questionid = ANY($1::int[])`, [questions]); const correctAnswer = result2.rows[0].answer1; if (submittedAnswer == correctAnswer) { console.log("This is correct"); } else { console.log("Sorry, this is incorrect"); } }); app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); }); ``` My index.ejs file. ``` <!DOCTYPE html> <html lang="he" dir="rtl"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>שאלות תאוריה</title> <link rel="stylesheet" href="/styles/main.css"> </head> <body> <% questionsResults.forEach(question=> { %> <form action="/submit" method="post" name="<%= question.questionid %>"> <fieldset form="<%=question.questionid %>"> <legend> <%= question.questiontext %> </legend> <div> <input type="radio" id="answer1" name="answer" value="<%= question.answer1 %>" checked /> <label for="answer1"> <%= question.answer1 %> </label> </div> <div> <input type="radio" id="answer2" name="answer" value="<%= question.answer2 %>" /> <label for="answer2"> <%= question.answer2 %> </label> </div> <div> <input type="radio" id="answer3" name="answer" value="<%= question.answer3 %>" /> <label for="answer3"> <%= question.answer3 %> </label> </div> <div> <input type="radio" id="answer4" name="answer" value="<%= question.answer4 %>" /> <label for="answer4"> <%= question.answer4 %> </label> </div> <h2> מספר שאלה לפי מאגר שאלות: <%= question.questionid %> </h2> </fieldset> </form> <% }) %> <button type="submit">שלח תשובה</button> <!-- <form class="container" action="/submit" method="post"> <div class="horizontal-container"> <h3> Total Score: <span id="score"> </span> </h3> </div> </form> <script> var wasCorrect = "<%= locals.wasCorrect %>"; console.log(wasCorrect) if (wasCorrect === "false") { alert('Game over! Final best score: <%= locals.totalScore %>'); document.getElementById("app").innerHTML = '<a href="/" class="restart-button">Restart</a>' } </script> --> </body> </html> ```
Processing multiple forms in nodejs and postgresql
|node.js|postgresql|express|body-parser|
null
Git's `vimdiff` mergetool shows you all four versions (ours, base, theirs, results-so-far), you can step through the changes, including all the automerged ones, with `]c` and `[c` and see everything, `1do` to take the local version, `2do` to take the base version, `3do` to take the remote version.
I have a [MERN][1] stack application which I deployed to Render (server side as web service and front end as static). \ In my application, I have a profile where users can upload avatar image. I store an image as a URL string in my MongoDB [Atlas_][2] in User model. Images are saved on the server in uploads folder. The image upload works fine and image fetches successfully, from both deployment and local environment. But after a while I start to get Internal server error when fetching same image. What is the reason and how to solve this issue? Or is there a better way of storing images in MongoDB Atlas without using cloud or [GridFS][3]? Here's how I set the user avatar: ``` const setUserAvatar = async (req, res) => { try { if (!req.user || !req.user.id) { return res.status(401).json({ message: 'Unauthorized' }); } const user = await User.findById(req.user.id); if (!user) { return res.status(404).json({ message: 'User not found' }); } if (!req.file) { return res.status(400).json({ message: 'No file uploaded' }); } const fileName = `avatar_${user.id}_${Date.now()}.png`; const filePath = path.join(__dirname, '..', 'uploads', fileName); fs.writeFileSync(filePath, req.file.buffer); user.avatar = { data: fileName }; await user.save(); res.status(200).json({ message: 'Avatar uploaded successfully' }); } catch (error) { console.error('Error uploading avatar', error); res.status(500).json({ message: 'Internal Server Error' }); } }; ``` And get: ``` const getUserAvatar = async (req, res) => { const userId = req.user.id; try { const user = await User.findById(userId); if (user.avatar.data === null) { return res.status(404).json({ message: 'No avatar found' }) } if (!user || !user.avatar.data) { res.send(user.avatar.data) } else { const filePath = path.join(__dirname, '..', 'uploads', user.avatar.data); const avatarData = fs.readFileSync(filePath); res.setHeader('Content-Type', 'image/*'); res.send(avatarData); } } catch (error) { console.error('Error fetching avatar', error); res.status(500).json({ message: 'Internal Server Error' }); } }; ``` How I handle an avatar change on the front end: ``` const handleAvatarChange = async (e) => { const token = localStorage.getItem('token'); if (token) { try { const formData = new FormData(); formData.append('avatar', e.target.files[0]) const response = await fetch('RENDERLINK/avatar', { 'method': 'POST', 'headers': { 'Authorization': `Bearer ${token}`, }, 'body': formData, 'credentials': 'include' }) if (response.status === 200) { getUser() toast.success('Avatar changed successfully') } else if (response.status === 400) { toast.error('No file selected') } else { toast.error('Error changing avatar') } } catch (error) { toast.error('Oops! Something went wrong. Please try again later.') } } else { console.log('No token found') navigate('/login') } } ``` Fetching user data including the avatar: ``` const getUser = async () => { const token = localStorage.getItem('token'); if (token) { try { const response = await fetch('RENDERLINK/profile', { 'method': 'POST', 'headers': { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`, }, 'credentials': 'include' }) if (response.ok) { const data = await response.json(); setUser({ username: data.username, email: data.email, avatar: data.avatar.data }) if (data.avatar.data !== null) { // Fetch and set the avatar image const avatarResponse = await fetch('RENDERLINK/get_avatar', { headers: { 'Authorization': `Bearer ${token}`, }, credentials: 'include', }); const avatarBlob = await avatarResponse.blob(); const avatarUrl = URL.createObjectURL(avatarBlob); setUser((prevUser) => ({ ...prevUser, avatar: avatarUrl })); setLoading(false) } } else if (response.status === 500) { toast.error('Oops! Something went wrong. Please try again later.') } } catch (error) { toast.error('Oops! Something went wrong. Please try again later.') } } else { console.log('No token found') navigate('/login') } } ``` [1]: https://en.wikipedia.org/wiki/Solution_stack#Examples [2]: https://en.wikipedia.org/wiki/MongoDB#MongoDB_Atlas [3]: https://en.wikipedia.org/wiki/MongoDB#File_storage
spring-cloud-stream-binder-kafka-streams consumer shuts down when RuntimeException occurs
I am migrating my deprecated spring security code and I am facing a problem : after the user's authentication (and he is authenticated), the spring contextHolder seems to be lost and the authentication vanishes. Therefore my connection does not work and the first api call redirects again to the login page I followed this documentation to migrate from WebSecurityConfigurerAdapter to the new spring security way : https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter I removed all complex code to start fresh from base username/password authentication. This is the whole SecurityConfiguration file I have. I still have the same problem : <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> @EnableWebSecurity @Slf4j @EnableConfigurationProperties(ApiPathProperties.class) public class SecurityConfiguration { private static final String HTTP_AUTHENTICATION = "/api/authentication"; private static final String API_PAYMENTS_FEEDBACK = "/api/payments/feedback"; private static final String WEBSOCKET = "/websocket/**"; private static final String SUPER_ADMINISTRATOR_AUTHORITY = "ADMIN_ADVANCED"; @Nonnull private final ApiPathProperties apiPathProperties; @Nonnull private final AjaxAuthenticationFailureHandler ajaxAuthenticationFailureHandler; @Nonnull private final Http401UnauthorizedEntryPoint authenticationEntryPoint; @Nonnull private final SecuritySettings securitySettings; @Nonnull private final AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler; @Nonnull private final AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler; @Nullable private final SamlSettings samlSettings; @Nonnull private final Environment environment; private final CurrentTimeService currentTimeService; @SuppressWarnings({ "OptionalUsedAsFieldOrParameterType", "squid:S00107" }) public SecurityConfiguration( @Nonnull ApiPathProperties apiPathProperties, @Nonnull AjaxAuthenticationFailureHandler ajaxAuthenticationFailureHandler, @Nonnull AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler, @Nonnull Http401UnauthorizedEntryPoint authenticationEntryPoint, @Nonnull SecuritySettings securitySettings, @Nonnull CurrentTimeService currentTimeService, @Nonnull AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler, @Nonnull Optional<SamlSettings> samlSettings, @Nonnull Environment environment ) { this.apiPathProperties = apiPathProperties; this.ajaxAuthenticationFailureHandler = ajaxAuthenticationFailureHandler; this.authenticationEntryPoint = authenticationEntryPoint; this.securitySettings = securitySettings; this.currentTimeService = currentTimeService; this.ajaxAuthenticationSuccessHandler = ajaxAuthenticationSuccessHandler; this.ajaxLogoutSuccessHandler = ajaxLogoutSuccessHandler; this.samlSettings = samlSettings.orElse(null); this.environment = environment; } @Configuration @Order(2) public class HttpSecurityConfiguration { @Bean public AuthenticationManager authenticationManager( UserDetailsService userDetailsService, PasswordEncoder passwordEncoder ) { // Ensure that DaoAuthenticationProvider is always registered as it is the fallback. DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); authenticationProvider.setUserDetailsService(userDetailsService); authenticationProvider.setPasswordEncoder(passwordEncoder); ProviderManager providerManager = new ProviderManager(authenticationProvider); providerManager.setEraseCredentialsAfterAuthentication(false); return new ProviderManager(authenticationProvider); } @Bean public WebSecurityCustomizer webSecurityCustomizer() { return web -> web .ignoring() .antMatchers("/i18n/**") .antMatchers("/assets/**") .antMatchers(apiPathProperties.getApiDocs() + "/**") .antMatchers("/test/**") .antMatchers("/jms/**") .antMatchers("/api/print-queue/**") .antMatchers("/api/update/**"); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { boolean csrfEnabled = !environment.acceptsProfiles(Constants.SPRING_PROFILE_E2E); if (csrfEnabled) { if (samlSettings != null) { http .csrf() .ignoringAntMatchers( WEBSOCKET, HTTP_AUTHENTICATION, API_PAYMENTS_FEEDBACK, samlSettings.getBaseEndPoint() + "/**" ); } else { http .csrf() .ignoringAntMatchers(WEBSOCKET, HTTP_AUTHENTICATION, API_PAYMENTS_FEEDBACK); } http.addFilterAfter( new CsrfCookieGeneratorFilter(securitySettings.isSecure()), CsrfFilter.class ); } else { http.csrf().disable(); } http .exceptionHandling() .accessDeniedHandler(accessDeniedHandler()) .authenticationEntryPoint(authenticationEntryPoint) .and() .formLogin() .loginProcessingUrl(HTTP_AUTHENTICATION) .successHandler(ajaxAuthenticationSuccessHandler) .failureHandler(ajaxAuthenticationFailureHandler) .usernameParameter("j_username") .passwordParameter("j_password") .permitAll() .and() .logout() .logoutUrl("/api/logout") .logoutSuccessHandler(ajaxLogoutSuccessHandler) .deleteCookies("JSESSIONID", "CSRF-TOKEN") .permitAll() .and() .headers() .xssProtection() .disable() .frameOptions() .sameOrigin() .and() .authorizeRequests() .antMatchers("/oauth/authorize") .permitAll() .antMatchers("/cas/redirect") .permitAll() .antMatchers("/api/authenticate") .permitAll() .antMatchers("/api/account/prepare-password-reset") .permitAll() .antMatchers("/api/account/reset-password") .permitAll() .antMatchers("/api/password-score") .permitAll() .antMatchers(API_PAYMENTS_FEEDBACK) .permitAll() .antMatchers("/public/**") .permitAll() .antMatchers(HttpMethod.GET, "/api/templates/**") .permitAll() .antMatchers("/api/logs/**") .hasAuthority(SUPER_ADMINISTRATOR_AUTHORITY) .antMatchers("/api/**") .authenticated() .antMatchers(WEBSOCKET) .authenticated() .antMatchers("/actuator/**") .hasAuthority(SUPER_ADMINISTRATOR_AUTHORITY) .antMatchers("/protected/**") .authenticated() .antMatchers(apiPathProperties.getPublicApi() + "/**") .authenticated(); http.addFilterBefore( new RateLimitingFilter( securitySettings.getRateLimiting(), currentTimeService, HTTP_AUTHENTICATION ), UsernamePasswordAuthenticationFilter.class ); return http.build(); } } @Configuration static class UserDetailsServiceConfiguration { @Bean public UserDetailsInitializer userDetailsInitializer( UserRepository userRepository, GroupRepository groupRepository, UserGroupRepository userGroupRepository, AuthorityProfileRepository authorityProfileRepository, DozerBeanConverter dozerBeanConverter, ParameterService parameterService, PasswordEncoder passwordEncoder ) { return new UserDetailsInitializer( userRepository, groupRepository, userGroupRepository, authorityProfileRepository, dozerBeanConverter, passwordEncoder, parameterService ); } } @Configuration static class PasswordEncoderConfiguration { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } @Bean public AccessDeniedHandler accessDeniedHandler() { return new CustomAccessDeniedHandler(); } } <!-- end snippet --> This is the logs I get : ``` 11:53:03.998 [http-nio-8080-exec-9] [super] DEBUG [org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter] - Set SecurityContextHolder to UsernamePasswordAuthenticationToken [Principal=User(login=super, firstName=Super, lastName=User, email=supervisor@localhost, langKey=fr), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[...]] 11:53:03.998 [http-nio-8080-exec-9] [super] TRACE [org.springframework.security.web.header.writers.HstsHeaderWriter] - Not injecting HSTS header since it did not match request to [Is Secure] 11:53:03.999 [http-nio-8080-exec-9] [] DEBUG [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - Created HttpSession as SecurityContext is non-default 11:53:03.999 [http-nio-8080-exec-9] [] DEBUG [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - Stored SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=User(login=super, firstName=Super, lastName=User, email=supervisor@localhost, langKey=fr), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[...]]] to HttpSession [org.apache.catalina.session.StandardSessionFacade@5f08292c] 11:53:03.999 [http-nio-8080-exec-9] [] DEBUG [org.springframework.security.web.context.SecurityContextPersistenceFilter] - Cleared SecurityContextHolder to complete request 11:53:04.004 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.FilterChainProxy] - Trying to match request against DefaultSecurityFilterChain [RequestMatcher=Ant [pattern='/i18n/**'], Filters=[]] (1/8) 11:53:04.005 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.FilterChainProxy] - Trying to match request against DefaultSecurityFilterChain [RequestMatcher=Ant [pattern='/assets/**'], Filters=[]] (2/8) 11:53:04.005 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.FilterChainProxy] - Trying to match request against DefaultSecurityFilterChain [RequestMatcher=Ant [pattern='/docs/**'], Filters=[]] (3/8) 11:53:04.005 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.FilterChainProxy] - Trying to match request against DefaultSecurityFilterChain [RequestMatcher=Ant [pattern='/test/**'], Filters=[]] (4/8) 11:53:04.005 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.FilterChainProxy] - Trying to match request against DefaultSecurityFilterChain [RequestMatcher=Ant [pattern='/jms/**'], Filters=[]] (5/8) 11:53:04.005 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.FilterChainProxy] - Trying to match request against DefaultSecurityFilterChain [RequestMatcher=Ant [pattern='/api/print-queue/**'], Filters=[]] (6/8) 11:53:04.005 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.FilterChainProxy] - Trying to match request against DefaultSecurityFilterChain [RequestMatcher=Ant [pattern='/api/update/**'], Filters=[]] (7/8) 11:53:04.005 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.FilterChainProxy] - Trying to match request against DefaultSecurityFilterChain [RequestMatcher=any request, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter@522f62ed, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@55b7b825, org.springframework.security.web.context.SecurityContextPersistenceFilter@15aeecf8, org.springframework.security.web.header.HeaderWriterFilter@14f45b8c, org.springframework.security.web.csrf.CsrfFilter@2279eff9, com.ecervo.business.web.filter.CsrfCookieGeneratorFilter@4f15ae1a, org.springframework.security.web.authentication.logout.LogoutFilter@19ba072f, com.ecervo.business.security.ratelimit.RateLimitingFilter@149551d9, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@79576e59, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4d291aff, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@7f1568d6, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3d8471ac, org.springframework.security.web.session.SessionManagementFilter@2181ab54, org.springframework.security.web.access.ExceptionTranslationFilter@71c0896c, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@705d4cad]] (8/8) 11:53:04.005 [http-nio-8080-exec-4] [] DEBUG [org.springframework.security.web.FilterChainProxy] - Securing GET /api/account?cacheBuster=1711536784002 11:53:04.005 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking DisableEncodeUrlFilter (1/15) 11:53:04.005 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking WebAsyncManagerIntegrationFilter (2/15) 11:53:04.005 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking SecurityContextPersistenceFilter (3/15) 11:53:04.005 [http-nio-8080-exec-4] [] TRACE [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - Retrieved SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=User(login=super, firstName=Super, lastName=User, email=supervisor@localhost, langKey=fr), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[...]]] from SPRING_SECURITY_CONTEXT 11:53:04.005 [http-nio-8080-exec-4] [super] DEBUG [org.springframework.security.web.context.SecurityContextPersistenceFilter] - Set SecurityContextHolder to SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=User(login=super, firstName=Super, lastName=User, email=supervisor@localhost, langKey=fr), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[...]]] 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking HeaderWriterFilter (4/15) 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking CsrfFilter (5/15) 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.csrf.CsrfFilter] - Did not protect against CSRF since request did not match And [CsrfNotRequired [TRACE, HEAD, GET, OPTIONS], Not [Or [Ant [pattern='/websocket/**'], Ant [pattern='/api/authentication'], Ant [pattern='/api/payments/feedback'], Ant [pattern='/saml/**']]]] 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking CsrfCookieGeneratorFilter (6/15) 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking LogoutFilter (7/15) 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.authentication.logout.LogoutFilter] - Did not match request to Ant [pattern='/api/logout', POST] 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking RateLimitingFilter (8/15) 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking UsernamePasswordAuthenticationFilter (9/15) 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter] - Did not match request to Ant [pattern='/api/authentication', POST] 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking RequestCacheAwareFilter (10/15) 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.savedrequest.HttpSessionRequestCache] - No saved request 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking SecurityContextHolderAwareRequestFilter (11/15) 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking AnonymousAuthenticationFilter (12/15) 11:53:04.005 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking SessionManagementFilter (13/15) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking ExceptionTranslationFilter (14/15) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.FilterChainProxy] - Invoking FilterSecurityInterceptor (15/15) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to ExactUrl [processUrl='/api/authentication'] - [permitAll] (1/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to ExactUrl [processUrl='/login'] - [permitAll] (2/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to Ant [pattern='/api/logout', POST] - [permitAll] (3/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to Ant [pattern='/oauth/authorize'] - [permitAll] (4/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to Ant [pattern='/cas/redirect'] - [permitAll] (5/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to Ant [pattern='/api/authenticate'] - [permitAll] (6/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to Ant [pattern='/api/account/prepare-password-reset'] - [permitAll] (7/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to Ant [pattern='/api/account/reset-password'] - [permitAll] (8/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to Ant [pattern='/api/password-score'] - [permitAll] (9/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to Ant [pattern='/api/payments/feedback'] - [permitAll] (10/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to Ant [pattern='/public/**'] - [permitAll] (11/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to Ant [pattern='/api/templates/**', GET] - [permitAll] (12/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] - Did not match request to Ant [pattern='/api/logs/**'] - [hasAuthority('ADMIN_ADVANCED')] (13/18) 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Did not re-authenticate UsernamePasswordAuthenticationToken [Principal=User(login=super, firstName=Super, lastName=User, email=supervisor@localhost, langKey=fr), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[...]] before authorizing 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Authorizing filter invocation [GET /api/account?cacheBuster=1711536784002] with attributes [authenticated] 11:53:04.006 [http-nio-8080-exec-4] [super] DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Authorized filter invocation [GET /api/account?cacheBuster=1711536784002] with attributes [authenticated] 11:53:04.006 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Did not switch RunAs authentication since RunAsManager returned null 11:53:04.006 [http-nio-8080-exec-4] [super] DEBUG [org.springframework.security.web.FilterChainProxy] - Secured GET /api/account?cacheBuster=1711536784002 11:53:04.011 [http-nio-8080-exec-4] [super] TRACE [org.springframework.security.web.access.ExceptionTranslationFilter] - Sending to authentication entry point since authentication failed org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:350) at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:214) at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708) ```
# Goal I want to have two search bars, and each of them can: - Display suggestions as typing - Use arrow keys to select item - Each item can be customized Because of the last bullet I don't want to use [`<datalist>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist "&lt;datalist&gt;: The HTML Data List element - HTML: HyperText Markup Language | MDN") tag as it's limited in style. I also use Deno Fresh, which is based on Preact, which is based on React. At the time I wasn't aware of guides on navigate through list by arrow keys [in React](https://stackoverflow.com/q/42036865/3416774), only [in vanilla JS](https://deepak-pundir.hashnode.dev/how-to-navigate-a-list-with-arrow-keys-in-vanilla-js "How to navigate a list with arrow keys in vanilla js ?"), and I think using the vanilla version will be simpler, so currently I'm using it. If you are interested in how to achieve the goal in general and not the question in title, check out [my final solution](https://stackoverflow.com/a/78231149/3416774). # Problem When a list is navigated by keyboard, the other is also triggered. My idea is to have the script targets different lists, and when users unfocus an input field it will be deactivated. I try having this on the script: ```ts if (list === 'deactivate') return ``` And on each handler I have: ```ts onBlur={(e) => script('deactivate')} ``` But it still doesn't work. Do you have any suggestion? # Code **`search.jsx`**: ```js export default function SearchBar() { const [keyword1, setKeyword1] = useState(""); const [keyword2, setKeyword2] = useState(""); const list1 = [ 'rabbits', 'raccoons', 'reindeer', 'red pandas', 'rhinoceroses', 'river otters', 'rattlesnakes', 'roosters' ] const list2 = [ 'jacaranda', 'jacarta', 'jack-o-lantern orange', 'jackpot', 'jade', 'jade green', 'jade rosin', 'jaffa' ] return ( <div className="search-bar-container"> <input type="text" placeholder={'Search list 1'} value={keyword1} onInput={(e) => { setKeyword1(e.target.value); script('1'); }} onBlur={(e) => script('deactivate')} /> <br /> <ul id={'Suggested list 1'}> {keyword1 !== '' ? list1.filter(keyword => keyword.includes(keyword1)).map( (item) => <li>{item}</li>, ) : ''} </ul> <div> Your selected item is :<span id="Item 1"></span> </div> <input type="text" placeholder={'Search list 2'} value={keyword2} onInput={(e) => { setKeyword2(e.target.value); script('2'); }} onBlur={(e) => script('deactivate') } /> <br /> <ul id={'Suggested list 2'}> {keyword2 !== '' ? list2.filter(keyword => keyword.includes(keyword2)).map( (item) => <li>{item}</li>, ): ''} </ul> <div> Your selected item is :<span id="Item 2"></span> </div> </div> ); } ``` **`script.ts`**: ```ts export function script(list: "1" | "2" | 'deactivate') { if (list === 'deactivate') return if (window !== undefined) { const ul = document.getElementById(`Suggested list ${list}`); const result = document.getElementById(`Item ${list}`); //the rest of the script ``` [Full code](https://codesandbox.io/p/devbox/zen-wind-mjnngm). Somehow CodeSandbox keeps having twind error even when I don't. This does run in my machine. ![Screenshot (GIF)](https://i.imgur.com/NU4FEkX.gif)
just for me, I'm experimenting with GLFW (compiling with **g++ -o nxtBluePixel nxtBluePixel.cpp -lglfw -lGLEW -lGL** ) to simply draw a blue box and moving it up/down/left/right. I want to output a message "out of bounds" when the box touches the edges of the visible area, which should logically be -1 or 1 (in those so-called normalized OpenGL coords, so i read). But the box keeps continuing to move in a "invisible" region outside (and is invisible) but no message is displayed until a while (at least 10 hits or so on a key outside the edge boundary ... ChatGPT 4 can't help me, it says: *"Correct Boundary Check: If you want the "out of bounds" message to appear as soon as the point is about to leave the visible area, your original check without the large epsilon is logically correct. However, if the message appears too late or too early, it might be due to how the point's position is updated or rendered, not the boundary check itself."* any ideas ? I never use OpenGL so I wanted to try... but this is typically the kind of very annoying problems i hate! and here my code: #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> #include <cctype> GLint worldWidth = 400; GLint worldHeight = 300; // Starting position of the pixel float currX = 0.0f; float currY = 0.0f; float stepSize = 1.0f / worldWidth; float speed = 2.0f; void updateWorld(char keyPressed, float speed){ switch (keyPressed) { case 'W': //up currY += stepSize*speed; break; case 'A': //left currX -= stepSize*speed; break; case 'S': //down currY -= stepSize*speed; break; case 'D': //right currX += stepSize*speed; break; } //using openGL 'normalized' coords i.e. between -1 and 1 if (currX >= 1.0 || currX <= -1.0 || currY >= 1.0 || currY <= -1.0){ printf("OUT OF BOUNDS !!!!"); } } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { char key_str = '0'; if (action == GLFW_PRESS || action == GLFW_REPEAT) { switch (key) { case GLFW_KEY_W: key_str = 'W'; break; case GLFW_KEY_A: key_str = 'A'; break; case GLFW_KEY_S: key_str = 'S'; break; case GLFW_KEY_D: key_str = 'D'; break; case GLFW_KEY_Q: printf("Bye ..."); glfwSetWindowShouldClose(window, GL_TRUE); break; default: printf("unknown key pressed \n"); break; } updateWorld(key_str, speed); } } int main(void) { GLFWwindow* window; // Initialize the library if (!glfwInit()) return -1; //remove win frame //glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); // Create a windowed mode window and its OpenGL context window = glfwCreateWindow(worldWidth, worldHeight, "Move Pixel with Keyboard", NULL, NULL); if (!window) { glfwTerminate(); return -1; } // Make the window's context current glfwMakeContextCurrent(window); // Set the keyboard input callback glfwSetKeyCallback(window, key_callback); // Initialize GLEW glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cerr << "Failed to initialize GLEW" << std::endl; return -1; } //glfwGetFramebufferSize(window, &worldWidth, &worldHeight); // Define the viewport dimensions glViewport(0, 0, worldWidth, worldHeight); // Set point size glPointSize(10.0f); // Increase if you want the "pixel" to be bigger // Loop until the user closes the window while (!glfwWindowShouldClose(window)) { // Render here glClear(GL_COLOR_BUFFER_BIT); // Set the drawing color to blue glColor3f(0.0f, 0.0f, 1.0f); // RGB: Blue // Draw a point at the current position glBegin(GL_POINTS); glVertex2f(currX, currY); // Use the updated position glEnd(); // Swap front and back buffers glfwSwapBuffers(window); // Poll for and process events glfwPollEvents(); } glfwTerminate(); return 0; }
Experimenting with GLFW library: window boundary problem and normalized coordinates
|c++|opengl|
null
Aren't you meant to be passing a **blob-URL** for the image instead of just blob-data? Because it doesn't look like you're converting the blob to a URL with this... canvas.toBlob(function (blob){ jQuery.ajax({ url:"//domain.com/wp-admin/admin-ajax.php", type: "POST", data: {action: "addblobtodb", image: blob}, success: function(id) {console.log("Succesfully inserted into DB: " + id); } }); So I would try this... canvas.toBlob((blob)=>{ let Url=URL.createObjectURL(blob); jQuery.ajax({ url:"//domain.com/wp-admin/admin-ajax.php", type: "POST", data: {action: "addblobtodb", image: Url}, // <-- Image blob url passed here success: function(id) {console.log("Succesfully inserted into DB: " + id);} }); },'image/png',1); // <--- specify the type & quality of image here
My device is Xiaomi 11 Lite 5G NE (lisa) and I am using the defconfig from ./arch/arm64/configs/vendor/lahaina-qgki_defconfig. I am using clang as CC and CLANG_TRIPLE as aarch64-linux-gnu- (both from proton-clang) while using aarch64-linux-android- as CROSS_COMPILE (from here https://github.com/ibnudz/aarch64-linux-android-4.9) I am trying to build a kernel of that device but I faced some errors (https://github.com/renoir-development/android_kernel_xiaomi_sm8350/tree/lineage-19.1) During the compilation, I got undefined error for these functions `get_hw_country_version, get_hw_version_platform, get_hw_version_build, get_hw_version_major, get_hw_version_minor` in ./drivers/soc/qcom/icnss2/qmi.o By doing `grep -r "get_hw_country_version"`, I was able to locate the function was declared in ./drivers/misc/hwid.c while the header file is located in ./include/linux/hwid.h I found that qmi.c (mentioned above) already has hwid.h included and some defined values in hwid.h successfully be used by qmi.c, but I am still getting the undefined reference error for those functions. How do I fix this issue?