White page after successful routing with Spring Cloud Gateway Posted: 31 Jul 2021 08:24 AM PDT Due to a certain lack of support between two technologies I wanted to implement, I find myself in the need to look for a "smarter" proxy server than the current Apache solution I implemented. After some quick digging I found out about Spring Cloud Gateway and Zuul. As I wanted to keep things simple with dependencies, I choose Spring's option. After some tries in my local environment with an API I had for a different purpose, I managed to get the routing right and a static page when the root is hit. Then I rolled it to my test environment and after dealing with some slightly annoying things I didn't know about Spring Cloud, the proxy worked with another API I have in that environment. I must add, this test were done in curl. The problem I have now is that the Gateway is supposed to be used to proxy to other, non-boot application deployed in Tomcat. The routing itself works as stated in the title, but nothing is displayed. I double checked the servers were up and access to them properly directly from my browser. Then I tried to hit the test API, also deployed in a Tomcat, with my browser and found that the Get request worked ok but the Post request return 405 error (No error is logged in the prompt). I've been looking around about this but haven't found anything yet. My initial, uneducated guess was that Spring Cloud Gateway was ment/designed to work with API based applications and/or the front end framework we use is not supported somehow, but I highly doubt that is the case. As you see, I'm diving into this a bit blindly but the examples I've seen so far aren't particulary deep either, probably because it is fairly simple to understand. My Java code is nothing but the Bean necesary for the Static content. I moved from Java config to yaml config as this gateway will need to be implemented in two servers with different apps on them. I'll share it anyway for the sake of completeness. Java code: @SpringBootApplication public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } @Bean public RouterFunction<ServerResponse> statucResourceLocator(@Value("classpath:/static/index.html") Resource index) { return route(GET("/"), request -> ok().contentType(MediaType.TEXT_HTML).bodyValue(index)); } } application.yml server: port: 8080 spring: cloud: gateway: routes: # Non-boot app - id: app1 uri: localhost:8081 predicates: - Path=/app1/** # Non-boot app - id: app2 <- Non-boot app uri: localhost:8082 predicates: - Path=/app2/** - id: api uri: http://localhost:8000 predicates: - Path=/api/** Is there something I missed from the Spring tutorial on this? Or is there a certain filter I need to add for other type of content to be displayed? We are using ZK Framework, Java 8 and our Spring version for the current projects is 4.3.8. Yes, we have a bit too much work done to make drastic updates or to change the backend. |
CallTrace issue related to a crash Posted: 31 Jul 2021 08:24 AM PDT If there's an application(P1) which got an SIGABORT from other appication P2. It's normal that P1 to have calltrace as if it would crash by itself ? |
(Weird) - ORA-12516 - TNS:listener could not find available handler with matching protocol stack [with only one active connection] Posted: 31 Jul 2021 08:24 AM PDT I am trying to run a Spring loader. That loader will take the data from the csv file and insert into oracle database. It starts well, after processing some records, i am getting the below error. 'ORA-12516 - TNS:listener could not find available handler with matching protocol stack' Note : No other jobs were running at that time. Only this job was running. processes -- 45 (CURRENT_UTILIZATION) -- 51 (MAX_UTILIZATION) sessions -- 53 (CURRENT_UTILIZATION) -- 61 (MAX_UTILIZATION) show parameter processes (processes - integer - 300) show parameter session (sessions - integer - 480) The thing is, the same batch program is running fine in another server, which has the same set of above configurations. Since its a new server, anything i am missing in regards to oracle.? Can someone guide. |
fails with using array.element Posted: 31 Jul 2021 08:24 AM PDT Wanted to check can I interact with just one part of the array so tried to work with boolean called 'completed' (element of the array), but it is undefined so the code is: import React from 'react' function App() { let mass = [ {id: 1, completed: false, title: "text1"}, {id: 2, completed: false, title: "text2"}, {id: 3, completed: false, title: "text3"} ] console.log(mass.completed) return 1 } export default App; How to fix and if possible, interact with just 1 element which is identical to others. |
How to add ads on recyclerview click in admob sdk 20.1.0 Posted: 31 Jul 2021 08:24 AM PDT How to add ads on recyclerview item click in admob sdk 20.1.0.plz Explain me |
How to resolve an invalid xml file signature error? Posted: 31 Jul 2021 08:24 AM PDT I'm signing the xml files based on SHA1, my code is below: foreach (XmlNode infAlvara in ListInfAlvara) { string id = infAlvara.Attributes.GetNamedItem("Id").InnerText; XmlNode nodeForSigning = infAlvara.ParentNode; // It's necessary to create a namespace manager to use with SelectNode methods, // otherwise they won't work, because the node has a specific namespace. var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); nsmgr.AddNamespace("ns", nodeForSigning.NamespaceURI); nsmgr.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNode nodeWithTheId = nodeForSigning.SelectSingleNode($"ns:{"infAlvara"}", nsmgr); if (nodeWithTheId == null) { throw new Exception($"The tag with ID attribute '{"infAlvara"}' does not exist in the XML file. (Error code: 4)"); } foreach (XmlNode node in nodeForSigning.SelectNodes("ds:Signature", nsmgr)) { node.ParentNode.RemoveChild(node); } SignedXml signedXml = new SignedXml((XmlElement)nodeForSigning); signedXml.SigningKey = certificate.PrivateKey; signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url; Reference reference = new Reference("#" + id); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigC14NTransform()); reference.DigestMethod = SignedXml.XmlDsigSHA1Url; signedXml.AddReference(reference); signedXml.KeyInfo = new KeyInfo(); signedXml.KeyInfo.AddClause(new KeyInfoX509Data(certificate)); signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); nodeForSigning.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true)); } But I'm getting the following message from the webservice that the signature is invalid. Below is my signature in the xml file: </infAlvara> <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <Reference URI=""> <Transforms> <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/> <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <DigestValue>bzwbgu3I/501qrSfv4aaA78Qhy4=</DigestValue> </Reference> </SignedInfo> <SignatureValue>Z0lW2dWsje0gLVeHQqdc+TtmT3lJOaFs6wIRyim68/+TTD/nAXnT12HviuQtYi1KfD9aDcXD9UBKJCp0kkijzvYeEN+OewsHNRQX5i+V23Lf0+cU8IvS3wRLurIYma0NanoiSpoJ7jMkWIUBsk9HB0n3ZarY+S85o4UjHRSDDQHQWP67zefkIzyHcHRF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UhqzARpESQK6NknL5TOk/Loga7L71U/uZDo7V0FOzEx+AGt2CflLCqpcrooH/MHozFZ959PjdYlAkCMDV1pVLJ1qCj+W660UrbtjSUA0zfA5Wc+nRAPn8vSLm2oq3N2ZNDwiHo5l70oFGJDJXv6GaBrer5nloQ2XtKOr5Bb3jC4mgX78NDmW22yIte+u6MM/4riCF9sp4CMv46Uvdx+bQQ1JK6ijKlYJ1RIhTWxxuunFJE3AnKUa4o0A8nrFf0s6uQr6GyaNG/wEHgJnW6eczem7JQVcI35R7ApxoH4hEVDlRsS/bbuI0IhsFc1IhBEbTZw/cv0kiBaFfr5HDR/b6Xjj20EY4DvAk6Gj45+aOKkhxZRr++4VIzVv4XBHo0IYW17I2re2ehfJZHlt1Xyom5gHtFLjx6gsbnpMBzQ+DWbRWco2l45VqcQs6uwssNjOgg0+Qtn6xn95t9V7y9wXqvSS6hH6FW+M1l52vd9FPTkdRM6m0cw==</X509Certificate> </X509Data> </KeyInfo> </Signature> I have a certificate with 2048 bits KeySize and in the webservice documentation asks for 1024 bits, but I think that doesn't hurt. Can someone help me please??? |
Fitting numerical data in Python Posted: 31 Jul 2021 08:24 AM PDT Hello I have more than 100,000 numbers to analyze in Python. Part of it is given in this sample: 84.49, 60.885, 33.6, 0, 6.4, 89.361, 0, 0, 5.6, 0, 39.828. The sum of this sample is 320.164 and I want to scale so that the new figures add up to 500 and plot these values. I previously divided my desired sum (500) by the old sum (320.164) and multiplied each value. The 0 values remain 0 since 0 cannot be "scaled". Is there a way to do this in Python? And will it be possible to plot the new histogram/distribution? Can you give some examples? Thank you! |
Appending new Immutable Map value to Immutable List Posted: 31 Jul 2021 08:23 AM PDT I have below a piece of code wherein I need to push a new Immutable Map value to an Immutable List on each forEach iteration. The flow goes into if condition as expected, but nothing is being pushed to the listOfFiles List. The console at the end of the forEach print list as List[0]. Any hint, on what should be corrected over here so it works fine? Code const formatListOfFilesObjectForAPI = (selectedListOfFileIds, allFilesData) => { const listOfFiles = new Immutable.List(); selectedListOfFileIds.forEach(fileId => { const fileObject = allFilesData.getIn([fileId, 'result']); if(fileObject && fileObject.size > 0) { if(fileObject.get('provider') === 'intranet') { listOfFiles.push(new Immutable.Map({ file_id: fileObject.get('fileId'), provider: fileObject.get('provider') })); } else { listOfFiles.push(new Immutable.Map({ file_id: fileObject.get('fileId'), provider: fileObject.get('provider'), name: fileObject.get('basename'), type: fileObject.get('extension'), size: fileObject.get('size'), version: fileObject.get('version'), })); } } else { listOfFiles.push(new Immutable.Map({ file_id: fileId, provider: 'intranet' })); } }); console.log('listOfFiles', listOfFiles); return listOfFiles; }; |
Problem with checkboxes (all checked) when listing items from an API in Angular v12 Posted: 31 Jul 2021 08:22 AM PDT I have a list of items from a query from an API (php file listall.php), from that list I need to select through checkbox the ones that are needed for the next process. The bad thing is that when I show the list of items, they all appear with the checkboxes checked. My code in HTML component: ... <tr *ngFor="let art of articles"> <th scope="row"> <input name="{{art.url}}" type="checkbox" (change)="onChange()" [(ngModel)]="art.isselected"></th> <td><font style="color: rgb(0, 97, 177)">{{art.url}}</font></td></tr> ... TS Component: import { Component, OnInit } from '@angular/core'; import { ArticlesService } from '../../articles.service'; @Component({ selector: 'app-manage-url', templateUrl: './manage-url.component.html', styleUrls: ['./manage-url.component.scss'] }) export class ManageUrlComponent implements OnInit { articles: any = null; art: any = { num: null, url: null, isselected: false, }; clearfield() { this.art.url = ""; } constructor(private articlesService: ArticlesService) {} ngOnInit() { this.listAll(); this.art.url = ""; } onChange(){ console.log(this.articles); } listAll() { this.articlesService.listAll().subscribe(result => this.articles = result); } insert() { this.articlesService.insert(this.art).subscribe(datos => { if (data['result']=='OK') { alert(data['message']); this.listAll(); } }); } select(num: number) { this.articlesService.select(num).subscribe(result => this.art = result[0]); this.listAll(); } Thereisarticles() { return true; } } |
add 20 days to start date of subscription Posted: 31 Jul 2021 08:22 AM PDT After callback from pay service (when user has paid the new subscription) I want to save his new subscription to his/her account in DB. Using Mongoose I want to save new subscription start and end Dates in the user account like this: const start = Date.now(); const end = ? const subscription = { start: start, end: end, } account.subscriptions.push(subscription); await account.save(); I can get the subscription start date using const start = Date.now(); But how can I calculate the end date of subscription if this is a 20 days package? I should add 20 days to start date how can I do this? |
WebP images are not loading in WatchOS Using swiftUI Posted: 31 Jul 2021 08:24 AM PDT WebP images are not loading in WatchOS Using swiftUI Tried to load WebP Image like, guard let uiImage = UIImage(data: webpImageData) else { return } Image(uiImage: uiImage) Above code is working fine in iOS App target but uiImage will be nil always in WatchOS Extension target. Note: WatchOS version 7+ Note: Above code works for other types of images like jpg, png |
I need to disable background-color behind text Posted: 31 Jul 2021 08:22 AM PDT I am using Css3. I am trying to learn how to achieve div transparent background in order I could see background image of the div located behind it. (background-color: transparent !important => does not help). Is it event possible to achieve it? There is a picture here describing my problem: html code: <div> <div className='body'> <div> <h1>Some title</h1> </div> <div /> // here is set the background image </div> <div className='text'> Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque arcu. Ut tempus purus at lorem. Nam quis nulla. Aenean placerat. Mauris suscipit, ligula sit amet pharetra semper, nibh ante cursus purus, vel sagittis velit mauris vel metus. Fusce tellus. Praesent id justo in neque elementum ultrices. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam. architecto beatae vitae dicta sunt explicabo. Nulla est. Curabitur bibendum justo non orci. Aenean placerat. Praesent in mauris eu tortor porttitor accumsan. Maecenas libero. Phasellus enim erat, vestibulum vel, aliquam a, posuere eu, velit. Etiam commodo dui eget wisi. Fusce dui leo, imperdiet in, aliquam sit amet, feugiat eu, orci. Nemo enim </div> </div> css code: .body { display: flex; padding-top: 11rem; div { &:first-child { flex-basis: 45%; h1 { font-size: 48px; } h4 { text-transform: uppercase; color: #0F33FF; } } &:nth-child(2) { flex-basis: 55%; background-image: url('../img/notebook-smaller.png'); background-position: 0px 0px; background-repeat: no-repeat; } } } .text { background-color: transparent !important; column-count: 2; } |
How do I convert xml.gz format to JSON? Posted: 31 Jul 2021 08:24 AM PDT I'm new to xml and I need to make a get request to an endpoint to get some data. There's quite a large amount of data and it's being sent back in xml.gz format. Is there a way for me to change this to JSON on my node server? Sorry if this doesn't make sense, I'm too new to this to even know if this question is right. |
Cloud Run Client Request IP address gets overridden by proxy Python Fast API Posted: 31 Jul 2021 08:24 AM PDT There is an issue of getting real user request IP address inside web application that is running on Cloud Run service. By some reason the web application obtains the same IP address for all users requests - 169.254.8.129 . I'm assuming it's a load balancer in front of cloud run service overrides requests IPs with his own. I have double checked already this issue with different apps on Flask, FastApi and ASP.NET Core in Cloud Run. All apps returning the same results and all having the same issue. But, when I am checking those apps on VM and everything works fine there. How can I get the user's IP-Address in my Cloud-Run Flask app? I have found some part of the answer, but still cannot handle the same for FastApi. |
How to start mining on windows 7 Posted: 31 Jul 2021 08:23 AM PDT I have a computer with an amd radeon r7 series 200 video card. The operating system of my computer is windows 7 64. The driver for the video card is installed from amd. I downloaded the mining program "PhenixMiner" (5.6), but it gave me an error: No CUDA driver found OpenCL driver version: 21.1-2.x Unable to use OpenCL device AMD Radeon R7 200 series for Ethash mining No avilible GPUs for mining. Please check your drivers and/or hardware I understand that the error is due to the video card driver, but I do not have enough experience to understand how to solve it. All the drivers that I found on the Internet are either official or dummy with viruses. I would like to start the mining process with this or any other program. This is my first experience of mining, I do it with the aim of gaining experience, not profit. Please tell me a way to solve the problem or give me some advice. |
Rest api for this port an ip address 10.32.31.46:5555 is accesible from browser but not on php Curl script what can I do Posted: 31 Jul 2021 08:24 AM PDT Am a new PHP codder on a share hosting services trying to connect my android http_sms_gateway app with REST API but connection always refused $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'http://10.32.31.46:5555/services/api/messaging/?to=131&message=hello', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "to": "08039800458" }', CURLOPT_HTTPHEADER => array( 'Content-Type: application/json' ), )); $response = curl_exec($curl); curl_close($curl); echo $response; When testing my code from postman Rest API service and url visit, everything works fine. But curl connect is refused. Can anyone fixed it for me or suggest me an alternative options to get this Done? Thanks in advanced. |
How to make a voice channel with europe regoin - discord.js Posted: 31 Jul 2021 08:24 AM PDT How to make a voice channel with europe regoin? help me, I've tried to do it with stRETCH Region: ('europe'), but it doesn't work; } }) async function jointocreatechannel(user) { console.log(" :: " + user.member.user.username + "#" + user.member.user.discriminator + " :: Created a Room") await user.guild.channels.create(`${user.member.user.username} ini temp ajg`, { type: 'voice', parent: user.channel.parent.id, **setRTCRegion: ('europe'),** }).then(async vc => { user.setChannel(vc); jointocreatemap.set(`tempvoicechannel_${vc.guild.id}_${vc.id}`, vc.id); await vc.overwritePermissions([ { id: user.id, allow: ['MANAGE_CHANNELS'], }, { id: user.guild.id, allow: ['VIEW_CHANNEL'], }, ]); }) } } |
Failed to obtain response using Selenium python to automate visiting a website Posted: 31 Jul 2021 08:22 AM PDT Basically what I want to do is to automate visiting this website. If you visit using Chrome, manually picking report type and date, a download link will appear. I tried to automate this process using python + selenium by following the suggestions in the linked question. But selenium clicking the Get Data button didn't work. I don't know why. Please help. Please see this link https://stackoverflow.com/a/68598528/12469120 for more context about how to use DatePicker. Her is my code. from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys import time driver = webdriver.Firefox() driver.get("https://www.nseindia.com/products/content/derivatives/equities/archieve_fo.htm") time.sleep(5) datepicker = driver.find_element_by_id("date") datepicker.click() selectMonth = driver.find_element_by_xpath('//select[@class="ui-datepicker-month"]') for option in selectMonth.find_elements_by_tag_name('option'): if option.text == 'Mar': option.click() break selectYear = driver.find_element_by_xpath('//select[@class="ui-datepicker-year"]') for option in selectYear.find_elements_by_tag_name('option'): if option.text == '2017': option.click() break days = driver.find_elements_by_xpath('//a[@class="ui-state-default"]') days[4].click() time.sleep(2) select = Select(driver.find_element_by_id('h_filetype')) select.select_by_visible_text('Market Activity Report') wait = WebDriverWait(driver, 10) element = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'getdata-button'))) element.click() time.sleep(20) |
Building an AJAX button on follow laravel Posted: 31 Jul 2021 08:24 AM PDT my blade view so I was working on updating the follow button in real-time so I noticed if I clicked on unfollow automatically it update to follow , but when i click on follow it's does nothing until I refresh the page manually please kindly assist <button data-id="{{ $user->id }}" class="w-1/2 px-3 py-2 text-base text-white border rounded-lg action-follow bg-blue-lite hover:bg-blue"> <strong> @if (auth()->user()->isFollowing($user)) UnFollow @else Follow @endif </strong> </button> $(document).ready(function() { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('.action-follow').click(function(){ var user_id = $(this).data('id'); var cObj = $(this); var c = $(this).parent("div").find(".tl-follower").text(); $.ajax({ type:'POST', url:'/profile/follow', data:{user_id:user_id}, success:function(data){ console.log(data.success); if(jQuery.isEmptyObject(data.data)){ cObj.find("strong").text("Follow"); cObj.parent("div").find(".tl-follower").text(parseInt(c)-1); }else{ cObj.find("strong").text("UnFollow"); cObj.parent("div").find(".tl-follower").text(parseInt(c)+1); } } }); }); }); My Controller public function follwUserRequest(Request $request){ $user = User::find($request->user_id); $response = auth()->user()->toggleFollow($user); return response()->json(['success'=>$response]); } |
My CS50 Lab 8 Trivia Website's buttons aren't working Posted: 31 Jul 2021 08:23 AM PDT <!DOCTYPE html>
Trivia! <script> // TODO: Add code to check answers to questions //run the script once the DOM is loaded document.addEventListener('DOMContentloaded', function(){ //when correct answer is clicked change button colour to green let correct = document.querySelector('.correct'); correct.addEventListner('click', function(){ correct.style.backgroundColor = 'green'; document.querySelector('#feedback1').innerHTML = 'Correct!'; }); //When any incorrect answer is clicked, change color to red. let incorrects = document.querySelectorAll('.incorrect'); for (let i=0; i < incorrects.length; i++){ incorrects[i].addEventListener('click', function() { incorrects[i].style.backgroundColor = 'red'; document.querySelector('#feedback1').innerHTML = 'Incorrect'; }); } //check free response submission document.querySelector('#check').addEventListner('click', function(){ let input = document.querySelector('input'); if (input.value === 'Switzerland'){ input.style.backgroundColor = 'green'; document.querySelector('#feedback2').innerHTML = 'Correct!'; }else{ input.style.backgroundColor = 'red'; document.querySelector('#feedback2').innerHTML = 'Incorrect'; } }); }); </script> </head> <body> <div class="jumbotron"> <h1>Trivia!</h1> </div> <div class="container"> <div class="section"> <h2>Part 1: Multiple Choice </h2> <hr> <!-- TODO: Add multiple choice question here --> <h3>What is the approximate ratio of people to sheep in New zealand?</h3> <button class="incorrect">6 people per 1 sheep</button> <button class="incorrect">3 people per 1 sheep</button> <button class="incorrect">1 person per 1 sheep</button> <button class="incorrect">1 person per 3 sheep</button> <button class="correct">1 person per 6 sheep</button> <p id="feedback1"></p> </div> <div class="section"> <h2>Part 2: Free Response</h2> <hr> <!-- TODO: Add free response question here --> <h3>In which country is it illegal to own one guinea pig, as a lone guinea pig might be lonely?</h3> <input type="text"></input> <button id="check">Check Answer</button> <p id="feedback2"></p> </div> </div> </body> This is the html and javascript code for my Trivia website which has 2 questions. The first question has 4 buttons containing 4 options out of which there is only 1 correct answer. And the second question is text based free response answer. When I click on the buttons for the question 1 or the "Check answer" button for question 2 nothing happens. Any help would be appreciated. Also I am new to stack overflow and this is my first question so if it's formatted incorrectly kindly excuse. |
Cannot rerun compiled script in V8 C++ embedding Posted: 31 Jul 2021 08:24 AM PDT I'm attempting to rerun a V8 script in a given context/scope, but I'm getting a segmentation fault. If I compile other scripts and run in succession it works. int loadScript(const char * scriptCode) { v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, scriptCode, v8::NewStringType::kNormal) .ToLocalChecked(); // Compile the source code. script = v8::Script::Compile(context, source).ToLocalChecked(); return 0; } std::string executeScript() { // Run the script to get the result. v8::Local<v8::Value> result = script->Run(context).ToLocalChecked(); // Convert the result to an UTF8 string and print it. v8::String::Utf8Value utf8(isolate, result); return std::string(*utf8); } //// sv8i.loadScript("let a = 1; \ let b = 2; \ JSON.stringify({a, b}); \ "); printf("%s\n", sv8i.executeScript().c_str()); printf("%s\n", sv8i.executeScript().c_str()); // Seg fault Result is: {"a":1,"b":2} Thread 1 "spirit_v8_test" received signal SIGSEGV, Segmentation fault. 0x000055555585c9c8 in v8::internal::ScriptContextTable::Lookup(v8::internal::Isolate*, v8::internal::ScriptContextTable, v8::internal::String, v8::internal::VariableLookupResult*) () (gdb) backtrace #0 0x000055555585c9c8 in v8::internal::ScriptContextTable::Lookup(v8::internal::Isolate*, v8::internal::ScriptContextTable, v8::internal::String, v8::internal::VariableLookupResult*) () #1 0x00005555556e3cfc in v8::internal::(anonymous namespace)::Invoke(v8::internal::Isolate*, v8::internal::(anonymous namespace)::InvokeParams const&) () #2 0x00005555556e36a6 in v8::internal::Execution::Call(v8::internal::Isolate*, v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Object>, int, v8::internal::Handle<v8::internal::Object>*) () #3 0x0000555555651990 in v8::Script::Run(v8::Local<v8::Context>) () #4 0x00005555556444b9 in SpiritV8Interface::executeScript[abi:cxx11]() (this=0x7fffffffe2b0) at ./spirit_bin_src/spirit_v8_interface.cpp:54 #5 0x00005555556446a9 in main (argc=1, argv=0x7fffffffe4a8) at ./spirit_bin_src/spirit_v8_interface.cpp:80 Why? |
image showing until mouse button is up in pygame? Posted: 31 Jul 2021 08:22 AM PDT when I click on the image it is supposed to show me an image on top of it and the image stays until the mouse button is up so i put if event.type == pygame.MOUSEBUTTONUP: then blit the image but still it stays for a second after the mouse button is up im sure its because of my if statement here is my code: where my problem is: for i in range(4): pygame.draw.rect(screen, (colors[i]), (17 + 80 * i, 265, 50, 50)) pygame.draw.rect(screen, (0,0,0), (17 + 80 * i, 265, 50, 50),5) if mouse_x > mouse_pos_x_left[i] and mouse_x < mouse_pos_x_right[i]: if mouse_y > 5.4 and mouse_y < 6.26: pygame.draw.rect(screen, (255,255,255), (17 + 80 * i, 265, 50, 50), 5) if event.type == pygame.MOUSEBUTTONDOWN: food_selected = foods[i] screen.blit(check, (17 + 80 * i, 210, 50, 50)) if event.type == pygame.MOUSEBUTTONUP: screen.blit(check, (17 + 80 * i, 210, 50, 50)) if click == 3: click = 0 all my code: import pygame import pdb import random as r pygame.init() screen = pygame.display.set_mode((325,325)) running = True colors = [(199,203,132), (255,0,0), (0,255,0), (84,87,44)] mouse_pos_x_left = [0.4, 1.98, 3.62, 5.22] mouse_pos_x_right = [1.26, 2.86, 4.46, 6.06] foods = ['bread', 'tomato', 'lettuce', 'ham'] food_selected = '' customer1 = pygame.image.load('customer1.png') food_box = pygame.image.load('food_box.png') check = pygame.image.load('check.png') same = False #rand random_num_1 = r.randint(1,4) random_num_2 = r.randint(1,4) randoms = [1,2,3,4] food_1 = '' food_2 = '' click = 0 able = False """Bugs: - when selected same food as customer and clicked on other food it removes checkmark - when clicked on food shows checkmark for a sec - when selected same food as customer and then chose another same food as customer first checkmark removes """ while running: same_foods = False for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((255,255,255)) pos = pygame.mouse.get_pos() mouse_x = pos[0] / 50 mouse_y = pos[1] / 50 mouse = pygame.mouse.get_pos() #draw foods: for i in range(4): pygame.draw.rect(screen, (colors[i]), (17 + 80 * i, 265, 50, 50)) pygame.draw.rect(screen, (0,0,0), (17 + 80 * i, 265, 50, 50),5) if mouse_x > mouse_pos_x_left[i] and mouse_x < mouse_pos_x_right[i]: if mouse_y > 5.4 and mouse_y < 6.26: pygame.draw.rect(screen, (255,255,255), (17 + 80 * i, 265, 50, 50), 5) if event.type == pygame.MOUSEBUTTONDOWN: food_selected = foods[i] screen.blit(check, (17 + 80 * i, 210, 50, 50)) if event.type == pygame.MOUSEBUTTONUP: screen.blit(check, (17 + 80 * i, 210, 50, 50)) if click == 3: click = 0 #customer: customer1_img = pygame.transform.scale(customer1, (150,150)) food_box_img = pygame.transform.scale(food_box, (100, 125)) screen.blit(customer1_img, (50,50)) screen.blit(food_box_img, (170,0)) #random food: for i in range(4): #if random number is == 1 if random_num_1 == randoms[i]: #then food_1 == to the first food food_1 = foods[i] #then draw the first food pygame.draw.rect(screen, (colors[i]), (195, 5, 50, 50)) if random_num_2 == randoms[i]: food_2 = foods[i] pygame.draw.rect(screen, (colors[i]), (195, 60, 50, 50)) if food_1 == food_2: same_foods = True if click == 1: img = pygame.transform.scale(check, (30,30)) screen.blit(img, (285, 10)) if click == 2: screen.blit(img, (285, 70)) if same_foods == False: if food_selected == food_1: same = True img = pygame.transform.scale(check, (30,30)) screen.blit(img, (285, 10)) else: same = False if food_selected == food_2: same = True img = pygame.transform.scale(check, (30,30)) screen.blit(img, (285, 70)) else: same = False if same: click = 0 pass pygame.display.flip() pygame.quit() ``` |
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'User.User' that has not been installed Posted: 31 Jul 2021 08:24 AM PDT I wanna use my custom user in my Django project and I wanna use the OTP system for login in my project so I deleted the username and password field of the user and the user should login with a phone number. But I am getting an error. These are my codes: class UserManager(BaseUserManager): def create_user(self, phone_number): user = self.model( phone_number = phone_number ) if not phone_number: raise ValueError('Phone number is required') user.save(using = self._db) user.is_superuser = False user.is_admin = False user.name = "green user" return user def create_superuser(self, phone_number): user = self.create_user( phone_number = phone_number ) user.is_superuser = True class User(AbstractUser): username = None password = None email = models.EmailField(null = True, blank = True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) phone_number = models.IntegerField(unique=True) is_owner = models.BooleanField(default=False) is_advisor = models.BooleanField(default=False) name = models.CharField(max_length=40) image = models.ImageField(blank = True, null=True) data_join = models.DateTimeField(default = timezone.now) code_agency = models.IntegerField(null=True, blank=True, default=0) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['phone_number',] objects = UserManager() def __str__(self): return self.phone_number class MyUserAdmin(UserAdmin): model = User list_display = ('phone_number', 'email') list_filter = ('phone_number', 'email') search_fields = ('phone_number') ordering = ('phone_number') filter_horizontal = () fieldsets = UserAdmin.fieldsets + ( (None, {'fields': ('phone_number',)}), ) In my setting I set AUTH_USER_MODEL = 'User.User' and this is my admin.py: admin.site.register(User, UserAdmin) But I get an error in the terminal: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'User.User' that has not been installed |
Select and display multiple columns by date and sum the columns automatically on google sheet Posted: 31 Jul 2021 08:24 AM PDT enter image description here enter image description here Hi im trying to create a simple google sheet with displaying daily dates automatically when I enter prices, =sort(transpose(QUERY(B23:G, "select SUM (D) where B is not null pivot B", 0)), 0, FALSE) this is my current formula what I'm trying to do is to display the column D and column G, but only the column D is displaying i need multiple columns displayed thanks |
How Eureka Server and Spring Cloud API Gateway communicates with each other? Posted: 31 Jul 2021 08:23 AM PDT In Spring Boot Microservices architecture, we generally register our each microservice (its many instances) into Eureka server by doing eureka.client.register-with-eureka=true , eureka.client.fetch-registry=true and eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka . So Eureka acts as service registry for these services (service-name, hostname and its IP). Spring Cloud API Gateway acts as a single point of entry for any microservice call. It can work as a proxy service to route a request to the concerned microservice, abstracting the producer details. It has route information only, then how Spring Cloud API gateway comes to know which microservice instance to call to? How API Gateway and Eureka communicates and load balance? spring: application: name: api-gateway cloud: gateway: discovery: locator: enabled: true lower-case-service-id: true routes: - id: user-service uri: lb://user-service predicates: - Path=/users/** - id: order-service uri: lb://department-service predicates: - Path=/departments/** |
Django 'AnonymousUser' object is not iterable after passing user context in context processor Posted: 31 Jul 2021 08:24 AM PDT I need to show few user info in my nav bar such as number of notification, user name etc. So I am passing context in my context processor. My nav bar located in my base.htm and I am extending my base.html in my all html page. I am getting this error if user isn't login 'AnonymousUser' object is not iterable .here is my code: settings.py 'context_processors': 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'notifications.views.Count_Notifications', #passing context from notifications app views.py def Count_Notifications(request): count_notifications_comment = 0 count_notifications_author = 0 blog_author = Blog.objects.filter(author=request.user) if request.user.is_authenticated: count_notifications_comment = Notifications.objects.filter(sender=request.user,is_seen=False).count() count_notifications_author = Notifications.objects.filter(user=request.user,is_seen_author_noti=False).count() return {'count_notifications_comment':count_notifications_comment,'count_notifications_author':count_notifications_author,'blog_author':blog_author} console error: raise ValueError( ValueError: Cannot assign "False": "Notifications.user" must be a "User" instance. [17/Jul/2021 02:18:08] "POST /admin/blog/blog/26/change/ HTTP/1.1" 500 160786 |
How to identify likely broken pdf pages before extracting its text? Posted: 31 Jul 2021 08:23 AM PDT TL;DR My workflow: - Download PDF
- Split it into pages using pdftk
- Extract text of each page using pdftotext
- Classify text and add metadata
- Send it to client in a structured format
I need to extract consistent text to jump from 3 to 4. If text is garbled, I have to OCR its page. But, OCR all pages is out of question. How to identify beforehand which pages should be OCRed? I've tried to run pdffonts and pdftohtml on each page. Isn't it expensive to run subprocess.run twice a page? What do I mean by broken page? A PDF page that is not possible to extract text from its source, maybe due to to_unicode conversion. Description I'm building an application that relies on the extraction of text from a thousand PDF files every day. The layout of text in each PDF is somewhat structured, therefore calling pdftotext from python works well in most cases. But, some PDF files from one or two resources bring pages with problematic fonts, which results in garbled text. I think that using OCR only on problematic pages would be ok to overcome such an issue. So, my problem is how to identify, before extracting text, which pages are likely to result in gibberish. First, I tried to identify garbled text, after extracting it, using regex (\p{Cc} or unlikely chars outside Latin alphabet), but it did not work because I found corrupted text with valid chars and numbers, i.e AAAAABS12 54c] $( JJJJ Pk , as well. Second, I tried to identify garbled text calling pdffonts - to identify name, encoding, embeddedness and existence of to_unicode map - on each page and parsing its output. In my tests, it kinda works well. But I found also necessary to count how many chars used likely problematic fonts, pdftohtml - Display each text block in p tag along with its font name - saved the day here. @LMC helped me to figure out how to do it, take a look at the answer. The bad part is I ended up calling subprocess.run two times for each pdf page, what is super expensive. It would be cheaper if I could just bind those tools. I'd like to know if it's possible and feasible to look at PDF source and validate some CMAP (uni yes and not custom font), if present, or maybe other heuristics to find problematic fonts before extracting text or OCR it. Wisdom I found researching: "In order to successfully extract text (or copy'n'paste it) from a PDF, the font should either use a standard encoding (not a Custom one), and it should have a /ToUnicode table associated with it inside the PDF" "Fonts are embedded as subsets (indicated by the XYZABC+- (random, unique) prefixes to their names, as well as by the yes in the emb and the sub columns)" "Most PDFs which are in the wild out there do not embed the full font anyway, but only subsets. Extracting a subset of a font is only useful in a very limited scope, if at all" "Even if a /ToUnicode table is there, text extraction may still pose a problem, because this table may be damaged, incorrect or incomplete -- as seen in many real-world PDF files" Example of garbled text in one of my PDF files: 0\n1\n2\n3\n4\n2\n0\n3\n0\n5 6\n6\nÿ\n89 ÿ\n4\n\x0e\n3\nÿ\n\x0f\x10\n\x11\n\x12\nÿ\n5\nÿ\n6\n6\n\x13\n\x11\n\x11\n\x146\n2\n2\n\x15\n\x11\n\x16\n\x12\n\x15\n\x10\n\x11\n\x0e\n\x11\n\x17\n\x12\n\x18\n\x0e\n\x17\n\x19\x0e\n\x1a\n\x16\n2 \x11\n\x10\n\x1b\x12\n\x1c\n\x10\n\x10\n\x15\n\x1d29 2\n\x18\n\x10\n\x16\n89 \x0e\n\x14\n\x13\n\x14\n\x1e\n\x14\n\x1f\n5 \x11\x1f\n\x15\n\x10\n! \x1c\n89 \x1f\n5\n3\n4\n"\n1\n1\n5 \x1c\n89\n#\x15\n\x1d\x1f\n5\n5\n1\n3\n5\n$\n5\n1 5\n2\n5\n%8&&#\'#(8&)\n*+\n\'#&*,\nÿ\n(*ÿ\n-\n./0)\n1\n*\n*//#//8&)\n*ÿ\n#/2#%)\n*,\nÿ\n(*/ÿ\n/#&3#40)\n*/ÿ\n#50&*-\n.()\n%)\n*)\n/ÿ\n+\nÿ\n*#/#\n&\x19\n\x12\nÿ\n\x1cÿ\n,\x1d\n\x12\n\x1b\x10\n\x15\n\x116\nÿ\n\x15\n7\nÿ\n8\n9\n4\n6\nÿ\n%\x10\n\x15\n\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10\nR\x11\n\x16\n\x10\n+\x10\nÿ\n\x15ÿ\n/*-\n2\n2\'<\nÿ\n+\nÿ\n#S\n\x11\n\x16\n\x12\n\x17\n\x19\n\x1c \x12\n\x18\nÿ\n*\x1c\n\x1b\x15\x11\n\x16\n\x12\n\x11\n\x1d\x0e\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\nÿ\n*\x11\n\x10\n\x15 \x12\n\x1b\x10\n\x15\n\x11\n\x10\n6\nTU\nV\nWU\nXÿ\nYXÿ\nTU\nV\nW\nX\nXYZU\n[U\nT\\]X\\U\nW\nX\nVD\n^\n_\n`\nÿ\nab\nÿ\nXGb\nc\nE^\nd\nO\nP\nO\nQ\nP\ne\nO\nf\nP\nf\nJ\nf\nP\ne\ng\nGb\nh_\nEGI\niaA\nYjTk\nXlm@ YjTk\nXlmX] ]jTk@[Yj] U\nZk]U\nZU\n] X]noU\nW\nX] W@V\n\\\nX]\nÿ\n89\nÿ\n89\np ÿ\nq\n(\x10\x14\n\x12\x13\n8r\nIOV\x11\x03\x14\n(VWH\x03GRFXPHQWR\x03p\x03FySLD\x03GR\x03RULJLQDO\x03DVVLQDGR\x03GLJLWDOPHQWH\x03SRU\x03(00$18(/$\x030$5,$\x03&$/$\'2\x03\'(\x03)$5,$6\x036,/9$\x11\x033DUD\x03FRQIHULU\x03R\x03RULJLQDO\x0f\x03DFHVVH\x03R\x03VLWH\x03\x0f\x03LQIRUPH\x03R\x03SURFHVVR\x03\x13\x13\x13\x13\x16\x17\x18\x10\x1a\x18\x11\x15\x13\x15\x14\x11\x1b\x11\x13\x15\x11\x13\x13\x1a\x16\x03H\x03R\x03\nFyGLJR\x03\x17(\x14\x14\x16\x14\x13\x11\x03 The text above was extracted from page 25 of this document using pdftotext. For that page, pdffonts outputs: name type encoding emb sub uni object ID ------------------------------------ ----------------- ---------------- --- --- --- --------- [none] Type 3 Custom yes no no 13 0 DIIDPF+ArialMT CID TrueType Identity-H yes yes yes 131 0 DIIEDH+Arial CID TrueType Identity-H yes yes no 137 0 DIIEBG+TimesNewRomanPSMT CID TrueType Identity-H yes yes yes 142 0 DIIEDG+Arial CID TrueType Identity-H yes yes no 148 0 Arial TrueType WinAnsi yes no no 159 0 It's easy to identify that [none] named font as problematic. My take so far, given the data I've analysed, is to mark fonts with custom or identity-h encoding, no to_unicode map or none named as likely problematic. But, as I said, I also found cases with ToUnicode table and not Custom encoding fonts, problematic as well. As far as I know, it's also possible to find, for example, a single char that is defined for a broken font, but does not affect the overall readability of the page, so maybe it would be not necessary to OCR that page. In other words, if a font, in a given page, does not have ToUnicode convertion, it does not mean that the text of the page is totally affected. I'm looking for a solution that is better than regex garbled text. Examples of PDF pages that I had to OCR All pages bellow contains text in portuguese, but if you try to copy the text and paste somewhere you will see universal gibberish. |
Pacman Game Using Pygame on Mac [duplicate] Posted: 31 Jul 2021 08:23 AM PDT Im building a pacman game using pygame on my MacBook, I've written the code in visual studio code and have used pip install pygame in the terminal, however, when I run the python script for my game I get an error. all my files are in one folder called PacMan files I have so far (3 in total) main.py: from app_class import * if __name__ == '__main__': app = App() app.run() app_class.py: import pygame import sys from settings import * pygame.init() vec = pygame.math.Vector2 class App: def __init__(self): self.screen = pygame.display.set_mode((WIDTH, HEIGHT)) self.clock = pygame.time.Clock() self.running = True self.state = 'start' def run(self): while self.running: if self.state == 'start': self.start_events() self.start_update() self.start_draw() self.clock.tick(FPS) pygame.quit() sys.exit() ############################################################### Helper Functions ############################ def draw_text(self, words, screen, pos, size, colour, font_name, centered=False): font = pygame.font.SysFont(font_name, size) text = font.render(words, False, colour) text_size = text.get_size() if centered: pos[0] = pos[0]-text_size[0]//2 pos[1] = pos[1]-text_size[1]//2 screen.blit(text, pos) ############################################################### INTRO Functions ############################ def start_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_Space: self.state = 'playing' def start_update(self): pass def start_draw(self): self.screen.fill(BLACK) self.draw_text('PUSH SPACE BAR',self.screen, (WIDTH//2, HIEGHT//2), START_TEXT_SIZE, (170, 132, 58), START_FONT) pygame.display.update() settings.py: #screen settings WIDTH, HEIGHT = 448, 596 FPS = 60 #colour settings BlACK = (0,0,0) #font settings START_TEXT_SIZE = 16 START_FONT = 'arial black' #player settings #mob settings but i keep getting this error when i run main.py from my python Traceback (most recent call last): File "/Users/therealfawcett/Documents/University/Third-Year/ICP - 3025 - Apps Artificial Intelligence/Assignments /PacMan/main.py", line 1, in <module> from app_class import * File "/Users/therealfawcett/Documents/University/Third-Year/ICP - 3025 - Apps Artificial Intelligence/Assignments /PacMan/app_class.py", line 1, in <module> import pygame ModuleNotFoundError: No module named 'pygame' does anyone know why? |
Flutter Command - Powershell.exe not in PATH error message Posted: 31 Jul 2021 08:23 AM PDT I have flutter installed and everything works fairly alight but every time I run a flutter command I get the following message before the command actually runs. Error: PowerShell executable not found. Either pwsh.exe or PowerShell.exe must be in your PATH. I added the Powershell.exe path to my PATH variable (both System & User) and also added C:\Windows\System32 as I read that on one of the Github/SO forums. Any idea how to get rid of this? I am following a Udemy course and have followed every instruction to the dot but the instructor does not get this message. |
Breadth-First Search on Pacman maze Posted: 31 Jul 2021 08:24 AM PDT I'm currently building a program that eats all the food on a pacman maze. However, my program is called everytime Pacman makes a new move, so no memory will be saved when the program ends, and it only returns a move: L,R,U or Down. I'm new on AI and also new on java programming. I know, from searching on Google, that the best way to do it is with BFS. The question is: how do I do this? Do I have to create a LinkedList for every position that I visit, containing the path that took me there? por example: UULLDDLRRL. Another doubt that I have is, how do I make pacman search for the nearest food? here is my code, I deleted the input part of the code, that doesn't matter for my question. I'm saving the map from Pacman on a char[][]. class position{ int pX=0; int pY=0; char direction; Boolean visited = false; position(int pY, int pX, char direcao,Boolean visited) { this.pX=pX; this.pY=pY; this.direcao=direction; this.direction=direction; } position() { pX=0; pY=0; direction='N'; visited=false; } } position current = new position(pacmany,pacmanx,'N',false); LinkedList<position> analise = new LinkedList<position>(); analise.addLast(current); while(!analise.isEmpty()) { if(m[current.pY-1][current.pX]!='#') { analise.addLast(new position(current.pY-1,current.pX,'U',false)); } if(m[current.pY][current.pX+1]!='#') { analise.addLast(new position(current.pY,current.pX+1,'R',false)); } if(m[current.pY+1][current.pX]!='#') { analise.addLast(new position(current.pY+1,current.pX,'D',false)); } if(m[current.pY][current.pX-1]!='#') { analise.addLast(new position(current.pY,current.pX-1,'L',false)); } analise.get(i).visited=true; current=analise.get(i); analise.remove(); } } } |
No comments:
Post a Comment