Consume API and inject values to Elementor Posted: 07 May 2021 08:04 AM PDT I'd like to dev a plugin to access a REST API an inject the values to Elementor. Elementor allows to use dynamic content in the theme builder. Can I map values from the API to dynamic tags of Elementor ? Thanks |
Javascript executor code is being skipped Posted: 07 May 2021 08:04 AM PDT I'm using the Pytest Framework to automate Selenium tests using Python. When I run my script, this portion of the code gets skipped and I'm not sure why. I get no error messages. Example from test file: fle = BequestRequest(self.driver) chkfile = fle.selFile() self.driver.execute_script("arguments[0].click();",chkfile) What this is trying to do is just check off a checkbox. I tried using click(), but that didn't work which is why I'm using JS. Any suggestions as to why this part of the code is being skipped? |
Wildcard Query Search Google Sheets Posted: 07 May 2021 08:03 AM PDT I am looking to add wildcard ability. Current formula =query('data set',"select E where B contains '"&B37&"'",0) . The issue is the data set may have s light variation of the referenced cell and I want to accomodate for that. |
Vue ref/reactive with default value Posted: 07 May 2021 08:03 AM PDT I am using Vue3 composition API. I have an input field which needs to be in sync with store, incase the data changes in store it should be updated Code const store = useStore() const savedAge = computed(() => store.state.profile.age) // The saved is async and can be updated at anytime in store const age = ref(savedAge.value) <!-- template --> <input v-model="age" /> // here the age is null event if savedAge value has updated in store Please note I don't want two way binding with store, I want my reactive property to update if store value has been updated How do I achieve this? |
ERROR CS0122 | "xxx" is inaccessible due to its protection level | But all methods are public Posted: 07 May 2021 08:03 AM PDT i am getting the error above. I read all the postings about CS0122 they said its because my methods are not public but they are. Hope somebody can help me with this. Code attatched. I just want to code an adapter to read the values of an XBOX controller like mentioned here: How to use xbox one controller in C# application Sounds really easy and i am not a very beginner, but i cant figure this out. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using SharpDX.XInput; namespace Own3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } public class XInputController { public Controller controller; public Gamepad gamepad; public bool connected = false; public int deadband = 2500; public Point leftThumb, rightThumb = new Point(0, 0); public float leftTrigger, rightTrigger; public XInputController() { controller = new Controller(UserIndex.One); connected = controller.IsConnected; } // Call this method to update all class values public void Update() { if (!connected) return; gamepad = controller.GetState().Gamepad; leftThumb.x = (Math.Abs((float)gamepad.LeftThumbX) < deadband) ? 0 : (float)gamepad.LeftThumbX / short.MinValue * -100; leftThumb.y = (Math.Abs((float)gamepad.LeftThumbY) < deadband) ? 0 : (float)gamepad.LeftThumbY / short.MaxValue * 100; rightThumb.y = (Math.Abs((float)gamepad.RightThumbX) < deadband) ? 0 : (float)gamepad.RightThumbX / short.MaxValue * 100; rightThumb.x = (Math.Abs((float)gamepad.RightThumbY) < deadband) ? 0 : (float)gamepad.RightThumbY / short.MaxValue * 100; leftTrigger = gamepad.LeftTrigger; rightTrigger = gamepad.RightTrigger; } } } |
Cargo configuration changes when copying libp2p example Posted: 07 May 2021 08:03 AM PDT When I ran the libp2p ping example with cargo run with Cargo.toml as follows, I got an error error: the 'cargo.exe' binary, normally provided by the 'cargo' component, is not applicable to the 'stable-x86_64-pc-windows-msvc' toolchain in cargo. Please tell me how to prevent this phenomenon from happening. Cargo.toml: [dependencies] futures = "0.3.14" libp2p = "0.37.1" OS: Windows10 Home rustc: 1.52.0 stable cargo: 1.52.0 libp2p example ping: https://github.com/libp2p/rust-libp2p/blob/master/Cargo.toml |
Inheritance and vector of multiple elements Posted: 07 May 2021 08:03 AM PDT void TextViwerH::dessine(Chain const& autre) const{ for(auto element: autre.get_Chain()){ if(element->get_type()){ Chain* ch = element; dessine(*ch); } } } Chain is a class containing type Mountain. The type mountain is an abstract class. Class Montagne and Chain inherites the class Mountain. The compiler prints that I can not use an abstract class with the function dessine even if I use pointers. Some suggestion and proposals please? |
application(:didFinishLaunchingwithOptions:) does not get called if apps is killed and opened immediately Posted: 07 May 2021 08:03 AM PDT I have noticed that if I kill the app from the multitasking view and open it immediately application(:didFinishLaunchingwithOptions:) lifecycle method is not called but the sceneDelegate's scene(:willConnectTo:) method is called. As far as I know, the above implies the app is not deinitialised and still in memory even after killing and reopening the app. And because of the above behaviour the NSPersistentContainer object is still in memory and my Core Data stack setup code is present in scene(:willConnectTo:) , so it's again initialised and it causes a crash with the following error : Failed to load the Persistent Store due to: Optional(Error Domain=NSCocoaErrorDomain Code=134081 "(null)" UserInfo={NSUnderlyingException=Can't add the same store twice}) Here is my Core Data Stack setup: func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) // Show splash screen let viewController = UIStoryboard(name: "AppLoading", bundle: Bundle.main).instantiateViewController(withIdentifier: "AppLoadingViewController") window.rootViewController = viewController CoreDataManager.shared.setup { // Always present the UI from a Main Thread DispatchQueue.main.async { if AppSettings.shared.onboardingFinished { self.presentHomeUI(using: window) } else { self.presentOnboardingUI(using: window) } } } self.window = window window.makeKeyAndVisible() } } Is this normal behaviour of application(:didFinishLaunchingwithOptions:) not when app is killed an opened immediately ? another mystery is that this issue only affects iPhone X and above at least according to our crash logs. If the above behaviour cannot be avoided then which method should be an ideal place for Core Data Setup ? Here is a video of the crash that I am able to reproduce on a device: https://file.re/2021/05/07/sampleprojectappcrashvideo/ And here is a sample project that I created which demonstrate the crash: https://github.com/nik6018/CrashDemo (can only reproduce crash on iPhone X and above) |
Shopify Api Client store Posted: 07 May 2021 08:03 AM PDT I have collaborator access to the store of a client and want to access it from the my private test app how to do that? I tried calling api by creating my own private app and test development store and it works on Postman. But how to call api for client store ? Will I have to create private app on client's store also? |
Can non-asynchronous execution paths return synchronous results in an "async" method Posted: 07 May 2021 08:02 AM PDT Consider the following method: public async Task<string> GetNameOrDefault(string name) { if (name.IsNullOrDefault()) { return await GetDefaultAsync(); } return name; } When name is provided, no awaiting will occur in the method execution, yet this method will compile correctly. However, this method will produce the build error shown below: public async Task<string> GetDefaultAsync() { return "foobar"; } [CS1998] This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. Why is it that GetNameOrDefault can return without ever awaiting, and not result in a compiler error, but GetDefaultAsync must await in order to compile? |
Check sequences by id on a large data set R Posted: 07 May 2021 08:02 AM PDT I need to check if values for year are consecutive in a large data set. This is how the data look: b <- c(2011,2012,2010, 2009:2011, 2013,2015,2017, 2010,2010, 2011) dat <- data.frame(cbind(a,b)) dat a b 1 1 2011 2 1 2012 3 1 2010 4 2 2009 5 2 2010 6 2 2011 7 3 2013 8 3 2015 9 3 2017 10 4 2010 11 4 2010 12 5 2011 This is the function I wrote. It works very well on the small data set. However the real data set is very large 200k ids and it is taking a very long time. What can I do to make it faster? seqyears <- function(id, year, idlist) { year <- as.numeric(year) year_values <- year[id==idlist] year_sorted <- year_values[order(year_values)] year_diff <- diff(year_sorted) answer <- unique(year_diff) if(length(answer)==0) {return("single line")} else { # length 0 means that there is only value and hence no diff can be computed if(length(answer)==1 & answer==1) {return("sequence ok")} else { return("check sequence")}} } to get a vector of values unlist(lapply(c(1:5), FUN=seqyears, id=dat$a, year=dat$b)) Thanks in advance for any suggestions |
Docker - "no-new-privileges" Posted: 07 May 2021 08:03 AM PDT I am having a little challenge around using the --security-opt=no-new-privileges flag for Docker. I am trying to follow this guide to build a Docker home server, and I managed to do everything. But in order to get things running, I had to turn off said flag. As for where I enable it, the container does not create and the log shows "standard_init_linux.go:211: exec user process caused "operation not permitted"" error. As I am getting this when directly running a container: fabrice@docker-01 ~ 1 sudo docker run -ti --security-opt=no-new-privileges --name test fedora:25 bash standard_init_linux.go:211: exec user process caused "operation not permitted" fabrice@docker-01 ~ 1 I am assuming it is not an error in the guide or the docker-compose, but in my Docker installation. I am just not entirely sure how to troubleshoot it or resolve it. (I have installed Docker at the initial package selection of the Ubuntu 20.04 OS install, and added Docker Compose to the system using this guide.) |
React.js is ignoring apostrophes when inside an query Posted: 07 May 2021 08:03 AM PDT I'm having trouble making my code understand that ' is to be a text and not to be interpreted. The need is: do a select in mysql to show some information. from there, in REACT, I click on the line I need more detailed information. React send to this new file.js an ID. in this ID is the part of the command mysql needs to execute on the second query. 1 - First select mount the code to be used in the second select (detailing a product) let condition= " ' and product.product_number= '" let projection = : `product.*, CONCAT( product.product_name,${condition},product.product_number) as id_search 2 - at the final portion of the select code, it receives the ID, containing the portion to make the WHOLE where condition: where product.product_name ? `, { product_name : id }, callback ) } catch (err) { console.log(err) } } 3 - In the MYSQL log, i can see the select getting like this: where `product.product_name ` = 'butter and product.product_number= 989887' BUT, it should be: where `product.product_name ` = 'butter' and product.product_number= '989887' This is a workaround because I dont find a way of working with 2 conditions when using a "ONCLIK" this is where I call the detailed search: <td style={{ textAlign: "left", minWidth: 200 }} onClick={() => seedetails(result.id_search)}> <a href="#!">{result.product_name }</a> </td> if any IDEAS to work around it.. I thik I try everything... |
Make sure the value of Authorization header is formed correctly including the signature Posted: 07 May 2021 08:04 AM PDT When using the Azure Storage API to access file services, we are getting the following errors. <?xml version="1.0" encoding="utf-8"?> <Error> <Code>AuthenticationFailed</Code> <Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:5a7f5ef2-a01a-0023-134e-436c77000000 Time:2021-05-07T14:36:32.7067133Z</Message> <AuthenticationErrorDetail>Unversioned authenticated access is not allowed.</AuthenticationErrorDetail> </Error> We've followed the documentation and believe we have all the correct headers but obviously missing something. Signature string we're encoding: GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:Fri, 07 May 2021 15:29:49 GMT\nx-ms-version:2020-04-08\n/*our_azure_resource*\ncomp:metadata Code using CryptoJS that we're using to do the encoding let signature = CryptoJS.HmacSHA256(CryptoJS.enc.Utf8.parse(stringToSign).toString(), this.key) .toString(CryptoJS.enc.Base64); Value of Authorization header: SharedKey storageaccountname:decodedstring |
How does interrupt differ from subroutine calls? Posted: 07 May 2021 08:03 AM PDT A subroutine is called by a program instruction to perform a function needed by the calling program. While Interrupt is initiated by an event such as an input operation or a hardware error. But how does the processor differentiate between them? |
Type hint for custom class atributes Posted: 07 May 2021 08:02 AM PDT I'm quite new to using type hints in python. I have an app with multiple modules in a package and classes associated to them. I've been trying to find some type hint explanation of how it works when there are multiple scripts and the type defined comes from an object whos script is loaded in another module. Here is a very simplified version for this confusion on the use of type hints. Given that there is a script for the main app like this: from modules.FigureFormatter import FigureFormatter from modules.Plotter import Plotter class MainApp: def __init__(self): formatter = FigureFormatter() plotter = Plotter() plotter.plot_figure(formatter.styler['light']) The modules package contains two modules: class FigureFormatter: def __init__(self): self.styler = {'light': {'prop1': 1, 'prop2': 2}, 'dark': {'prop1': 1, 'prop2': 2}} and from typing import Dict class Plotter: def __inti__(self): # Some initialization stuff pass def plot_figure(self, styler: Dict): # Plotting figure pass What should be the type hint for the styler argument in plot_figure method? Essentially it is a dictionary. Obviously it shouldn't be any dictionary, but a dictionary that is an attribute of the FigureFormatting class instance. Should that module be also imported into Plotter modules, so the class name could be referenced? |
Ruby on Rails content_tag is deprecated, but I can't replicate its nesting capabilities using tag Posted: 07 May 2021 08:03 AM PDT The project I'm working on requires some of the data table's column titles to be referenced/defined in a footnote below the table. As it's dynamic content that will be looped over depending on how many of the column titles require footnotes, I need to handle most of this in via models/helpers. I have been able to replicate the html our US designer wants using content_tag , but rubocop is whining about the use of content tag and says I should be using tag instead. But I can't get the nesting of the html tags to work at all using the tag method. The section html I'm trying to produce is this (which will be repeated for as many footnotes are needed): <li id="id" class="p-2"> <dl class="m-0"><dt class="d-inline">Unusual term: </dt> <dd class="d-inline">Text with the definition of the term.<a href="#id-ref" aria-label="Back to content">↵</a></dd> </dl> </li> And the content_tag based code that works to produce it is this: content_tag(:li, content_tag(:dl, [ content_tag(:dt, 'Unusual term: ', class: "d-inline"), content_tag(:dd, [ 'Text with the definition of the term.', content_tag(:a, '↵', href: '#id-ref', aria: { label: "Back to content" }) ].join.html_safe, class: "d-inline") ].join.html_safe, class: "m-0"), id: 'id', class: "p-2") When I switch to using tag , the problem I'm coming up against is getting both the <dt> and <dd> tags, which both have content, to nest inside the <dl> tag (and also the <a> tag, which also has content, to nest within the aforementioned <dd> tag). The tag method only seems to output the last piece of nested content and ignores any other content that precedes it. This is the nesting of the tag method that I've tried: tag.li id: 'id', class: 'p-2' do tag.dl class: 'm-0' do (tag.dt 'Unusual term: ', class: 'd-inline') + (tag.dd 'Text with the definition of the term.', class: 'd-inline' do (tag.a arrow, href: anchor, aria: { label: 'Back to content' }) end) end end And this is the output it's giving me. <li id="id" class="p-2"> <dl class="m-0"><dt class="d-inline">Unusual term: </dt> <dd class="d-inline"><a href="#id-ref" aria-label="Back to content">↵</a></dd> </dl> </li> As you can see, it's close, but it's missing the text content of the <dd> tag, which should be output just before the <a> tag starts. Can anyone help? Is there a way to nest tags without losing content? Or should I just give up and write a partial with the actual html code written out...? |
jQuery previous month jumps to random month instead of previous month Posted: 07 May 2021 08:03 AM PDT I have one application with 2 different tabs where calendar/date-picker is used. If I switch from one tab to another by using calendar functionality then I see one issue. The issue is, when I try to click on previous month icon then it jumps to any random month instead of previous month. e.g. Current month is May 2021 (07/05/2021) and if I click on previous month then it will jump to October 2020. I did some analysis and found that there is bug in jQuery UI library. Following are the links for the same. https://bugs.jqueryui.com/ticket/15129 , https://bugs.jqueryui.com/ticket/7288 , https://bugs.jqueryui.com/ticket/9923#comment:4 I tried using different versions of jQuery UI libraries. But I can see the same issue with all the libraries. Following are the libraries that I used. jquery-ui-1.8.23.custom.min.js jquery-ui-1.9.2.custom.min.js jquery-ui-1.10.4.custom.min.js jquery-ui-1.11.4.custom.min.js jquery-ui-1.12.1.custom.min.js Is that bug fixed in any recent version. If it is already fixed then can you please help me what exactly I am missing here? |
Move last 3 items towards the right [duplicate] Posted: 07 May 2021 08:02 AM PDT I would like to move the last three items towards the right, but I do not know how to. I tried using margin-right. .header-right { float: right; padding-right: 20px; } @import url('https://fonts.googleapis.com/css2?family=Open+Sans&display=swap'); body { margin: 0; padding: 0; } .txt10 { font-family: 'Open Sans', sans-serif; font-size: 12px; font-weight: bold; text-transform: uppercase; color: red; } .header-page { display: flex; flex-flow: row wrap; background-color: aqua; height: 20px; padding-top: 13px; padding-bottom: 13px; padding-left: 150px; } .header-left { padding-left: 14px; } .header-right { float: right; padding-right: 20px; } #dropDown-languages { width: 75px; height: 20px; margin-right: 20px; } <div class="header-page text10"> <div class="header-left"><i class="far fa-calendar"></i>138 running days</div> <div class="header-left"><i class="far fa-envelope"></i>admin@superbtc.biz</div> <select name="dropDown-languages" id="dropDown-languages"> <option value="english">English</option> <option value="french">French</option> </select> <div class="header-right"><i class="fas fa-angle-right"></i> deposit</div> <div class="header-right"><i class="fas fa-angle-right"></i> paidout</div> </div> |
How do I write & in a formula within quotation marks? Posted: 07 May 2021 08:02 AM PDT Im currently figuring out how to write "&" in a formula so that VBA recognizes it as a string and not as the &-operator. My formula looks like this: "=AVERAGEIF(RC[-4]:R[" & Total & "]C[-4],"">""&0.5*MAX(RC[-4]:R[" & Total & "]C[-4]))" But it should look something like this, as I want to use the variable z instead of 0.5 "=AVERAGEIF(RC[-4]:R[" & Total & "]C[-4],"">"" & Chr(34)& Chr(38) & Chr(34)& z & *MAX(RC[-4]:R[" & Total & "]C[-4]))" As you see I already tried to write the "" and the & as ASCII but it seems that even this doenst work. Thanks in advance for your help! EDIT: The result should look like this: =AVERAGEIF(C31:C6413;">"&0.5*MAX(C31:C6413)) |
How do you dockerize a maven desktop project [closed] Posted: 07 May 2021 08:04 AM PDT How can I dockerize a Maven desktop project written in Java? PS: I don't know how to dockerize programs in general,and I'm new to docker ,I found some posts about it, the step that I'm struggling with is how to configure the dockerfile inside my maven project and how to build an image of it ,thanks guys |
Adding text from a file in the middle of a url Posted: 07 May 2021 08:04 AM PDT I have a text in a file id.txt and I want to add the contents of the file to a curl link: curl localhost:1337/id.txt/map/maze-of-doom?type=csv In a bash script. I don't want it to be added to the end or beginning. I want it to be added in the place where id.txt is written in the code. |
Parsing a String with quoted Fields like a CSV-line in Powershell Posted: 07 May 2021 08:02 AM PDT I have to parse a variable input-string into a string-array. The input is a CSV-style comma-separated field-list where each field has its own quoted string. Because I dont want to write my own full-blown CSV-parser the only working solution I could create till now is this one: $input = '"Miller, Steve", "Zappa, Frank", "Johnson, Earvin ""Magic"""' Add-Type -AssemblyName Microsoft.VisualBasic $enc = [System.Text.Encoding]::UTF8 $bytes = $enc.GetBytes($input) $stream = [System.IO.MemoryStream]::new($bytes) $parser = [Microsoft.VisualBasic.FileIO.TextFieldParser]::new($stream) $parser.Delimiters = ',' $parser.HasFieldsEnclosedInQuotes = $true $list = $parser.ReadFields() $list Output looks like this: Miller, Steve Zappa, Frank Johnson, Earvin "Magic" Is there any better solution available via another .NET-library for Powersell? In best case I could avoid this extra bytes-array and stream. I am also not sure if this VisualBasic-Assembly will be avail on a long term. Any ideas here? |
Falling left and right inconsistencies in pygame platformer Posted: 07 May 2021 08:02 AM PDT I am trying to make a 2D Minecraft like game. I found this bug that I don't know how to fix (the details are below), I kinda like things to be perfect so I can't continue with this bug present. First of all here is the code: import pygame from pygame.locals import * from random import * from math import * import json import os import opensimplex FPS = 60 WIDTH, HEIGHT = 600, 300 SCR_DIM = (WIDTH, HEIGHT) GRAVITY = 0.25 SLIDE = 0.15 TERMINAL_VEL = 12 BLOCK_SIZE = 32 CHUNK_SIZE = 8 SEED = randint(-2147483648, 2147483647) def loading(): font = pygame.font.SysFont('Comic Sans MS', 60) textsurface = font.render('Generating World...', True, (255, 255, 255)) screen.blit(textsurface, (25, 100)) display.blit(pygame.transform.scale(screen, (WIDTH*2, HEIGHT*2)), (0, 0)) pygame.display.flip() pygame.init() display = pygame.display.set_mode((WIDTH*2, HEIGHT*2), HWSURFACE | DOUBLEBUF) pygame.display.set_caption("2D Minecraft") screen = pygame.Surface(SCR_DIM) loading() clock = pygame.time.Clock() mixer = pygame.mixer.init() vec = pygame.math.Vector2 noise = opensimplex.OpenSimplex(seed=SEED) seed(SEED) font12 = pygame.font.SysFont("consolas", 12) block_textures = {} for img in os.listdir("res/textures/blocks/"): block_textures[img[:-4]] = pygame.image.load("res/textures/blocks/"+img).convert_alpha() for image in block_textures: block_textures[image] = pygame.transform.scale(block_textures[image], (BLOCK_SIZE, BLOCK_SIZE)) block_data = {} for j in os.listdir("res/block_data/"): block_data[j[:-5]] = json.loads(open("res/block_data/"+j, "r").read()) player_head_img = pygame.image.load("res/textures/player/head.png").convert_alpha() player_body_img = pygame.image.load("res/textures/player/body.png").convert_alpha() player_arm_img = pygame.image.load("res/textures/player/arm.png").convert_alpha() player_leg_img = pygame.image.load("res/textures/player/leg.png").convert_alpha() head_size = vec(player_head_img.get_width()*2, player_head_img.get_height()*2) body_size = vec(player_body_img.get_width()*2, player_body_img.get_height()*2) arm_size = vec(player_arm_img.get_width()*2, player_arm_img.get_height()*2) leg_size = vec(player_leg_img.get_width()*2, player_leg_img.get_height()*2) player_head = pygame.Surface(head_size, SRCALPHA) player_body = pygame.Surface(body_size, SRCALPHA) player_arm = pygame.Surface(arm_size, SRCALPHA) player_leg = pygame.Surface(leg_size, SRCALPHA) player_head.blit(player_head_img, (head_size/4)) player_body.blit(player_body_img, (body_size/4)) player_arm.blit(player_arm_img, (arm_size/2+vec(-2, -2))) player_leg.blit(player_leg_img, (leg_size/2+vec(-2, 0))) def intv(vector): return vec(int(vector.x), int(vector.y)) def inttup(tup): return (int(tup[0]), int(tup[1])) def text(text, color=(0, 0, 0)): return font12.render(text, True, color) def block_collide(ax, ay, width, height, b): a_rect = pygame.Rect(ax-camera.offset.x, ay-camera.offset.y, width, height) b_rect = pygame.Rect(b.pos.x-camera.offset.x, b.pos.y-camera.offset.y, BLOCK_SIZE, BLOCK_SIZE) if a_rect.colliderect(b_rect): return True return False def remove_block(pos): pos = inttup(pos) chunk = (pos[0] // CHUNK_SIZE, pos[1] // CHUNK_SIZE) try: del blocks[pos] del chunks[chunk].block_data[pos] except: pass def set_block(pos, name): pos = inttup(pos) chunk = (pos[0] // CHUNK_SIZE, pos[1] // CHUNK_SIZE) try: blocks[pos] = Block(chunks[chunk], pos, name) chunks[chunk].block_data[pos] = name except: pass def is_occupied(pos): pos = inttup(pos) try: blocks[pos] except: if pygame.Rect(vec(pos)*BLOCK_SIZE, (BLOCK_SIZE, BLOCK_SIZE)).colliderect(pygame.Rect(player.pos, player.size)): return True return False else: try: blocks[pos].data["replaceable"] except: return True else: return False return True def is_supported(pos, data, neighbors): if data["support"]: supports = data["support"] for support in supports: try: blocks[neighbors[support]] except: return False else: if blocks[neighbors[support]].name == supports[support]: return True return False return True def is_placable(pos, data, neighbors): if not is_occupied(pos) and is_supported(pos, data, neighbors): return True return False class Camera(pygame.sprite.Sprite): def __init__(self, master): self.master = master self.actual_offset = self.master.size / 2 self.offset = intv(self.actual_offset) self.actual_offset = self.master.pos - self.offset - vec(SCR_DIM) / 2 + self.master.size / 2 def update(self): tick_offset = self.master.pos - self.offset - vec(SCR_DIM) / 2 + self.master.size / 2 if -1 < tick_offset.x < 1: tick_offset.x = 0 if -1 < tick_offset.y < 1: tick_offset.y = 0 self.actual_offset += tick_offset / 10 self.offset = intv(self.actual_offset) class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((0, 0)) self.size = vec(0.225*BLOCK_SIZE, 1.8*BLOCK_SIZE) self.width, self.height = self.size.x, self.size.y self.start_pos = vec(0, 3) * BLOCK_SIZE self.pos = vec(self.start_pos) self.coords = self.pos // BLOCK_SIZE self.vel = vec(0, 0) self.max_speed = 2.6 self.jumping_max_speed = 3.2 self.rect = pygame.Rect((0, 0, 0.225*BLOCK_SIZE, 1.8*BLOCK_SIZE)) self.bottom_bar = pygame.Rect((self.rect.x+1, self.rect.bottom), (self.width-2, 1)) self.on_ground = False self.holding = "grass_block" def update(self): keys = pygame.key.get_pressed() if keys[K_a]: if self.vel.x > -self.max_speed: self.vel.x -= SLIDE elif self.vel.x < 0: self.vel.x += SLIDE if keys[K_d]: if self.vel.x < self.max_speed: self.vel.x += SLIDE elif self.vel.x > 0: self.vel.x -= SLIDE if keys[K_w] and self.on_ground: self.vel.y = -4.6 self.vel.x *= 1.1 if self.vel.x > self.jumping_max_speed: self.vel.x = self.jumping_max_speed elif self.vel.x < -self.jumping_max_speed: self.vel.x = -self.jumping_max_speed if -SLIDE < self.vel.x < SLIDE: self.vel.x = 0 self.vel.y += GRAVITY if self.vel.y > TERMINAL_VEL: self.vel.y = TERMINAL_VEL self.move() self.bottom_bar = pygame.Rect((self.rect.left+1, self.rect.bottom), (self.width-2, 1)) for block in blocks: if self.bottom_bar.colliderect(blocks[block].rect): self.on_ground = True break else: self.on_ground = False self.coords = self.pos // BLOCK_SIZE self.rect.topleft = self.pos - camera.offset def draw(self, screen): # screen.blit(self.image, self.rect.topleft) pass def move(self): coords = self.pos // BLOCK_SIZE for y in range(4): for x in range(3): try: block = blocks[(int(coords.x-1+x), int(coords.y-1+y))] except: pass else: if block.data["collision_box"] == "full": if self.vel.y < 0: if block_collide(self.pos.x, self.pos.y+self.vel.y, self.width, self.height, block): self.pos.y = (block.pos.y + BLOCK_SIZE) self.vel.y = 0 elif self.vel.y >= 0: if block_collide(self.pos.x, ceil(self.pos.y+self.vel.y), self.width, self.height, block): self.pos.y = ceil(block.pos.y - self.height) self.vel.y = 0 if self.vel.x < 0: if block_collide(self.pos.x+self.vel.x, self.pos.y, self.width, self.height, block): self.pos.x = (block.pos.x + BLOCK_SIZE) self.vel.x = 0 elif self.vel.x >= 0: if block_collide(ceil(self.pos.x+self.vel.x), self.pos.y, self.width, self.height, block): self.pos.x = ceil(block.pos.x - self.width) self.vel.x = 0 self.pos += self.vel class Block(pygame.sprite.Sprite): def __init__(self, chunk, pos, name): pygame.sprite.Sprite.__init__(self) blocks[tuple(pos)] = self self.name = name self.data = block_data[self.name] self.chunk = chunk self.coords = vec(pos) self.pos = self.coords * BLOCK_SIZE self.neighbors = { "up": inttup((self.coords.x, self.coords.y-1)), "down": inttup((self.coords.x, self.coords.y+1)), "left": inttup((self.coords.x-1, self.coords.y)), "right": inttup((self.coords.x+1, self.coords.y)) } self.image = block_textures[self.name] if self.data["collision_box"] == "full": self.rect = pygame.Rect(self.pos, (BLOCK_SIZE, BLOCK_SIZE)) elif self.data["collision_box"] == "none": self.rect = pygame.Rect(self.pos, (0, 0)) def update(self): if not is_supported(self.pos, self.data, self.neighbors): remove_blocks.append(self.coords) self.rect.topleft = self.pos - camera.offset def draw(self, screen): screen.blit(self.image, self.rect.topleft) class Chunk(object): def __init__(self, pos): self.pos = pos self.block_data = generate_chunk(pos[0], pos[1]) for block in self.block_data: blocks[block] = Block(self, block, self.block_data[block]) def render(self): if self.pos in rendered_chunks: for block in self.block_data: try: blocks[block] except: blocks[block] = Block(self, block, self.block_data[block]) blocks[block].update() blocks[block].draw(screen) def debug(self): pygame.draw.rect(screen, (255, 255, 0), (self.pos[0]*CHUNK_SIZE*BLOCK_SIZE-camera.offset[0], self.pos[1]*CHUNK_SIZE*BLOCK_SIZE-camera.offset[1], CHUNK_SIZE*BLOCK_SIZE, CHUNK_SIZE*BLOCK_SIZE), width=1) def generate_chunk(x, y): chunk_data = {} for y_pos in range(CHUNK_SIZE): for x_pos in range(CHUNK_SIZE): target = (x * CHUNK_SIZE + x_pos, y * CHUNK_SIZE + y_pos) block_name = "" height = int(noise.noise2d(target[0]*0.1, 0)*5) if target[1] == 5-height: block_name = "grass_block" elif 5-height < target[1] < 10-height: block_name = "dirt" elif target[1] >= 10-height: block_name = "stone" elif target[1] == 4-height: if randint(0, 2) == 0: block_name = "grass" if block_name != "": chunk_data[target] = block_name return chunk_data blocks = {} chunks = {} player = Player() camera = Camera(player) remove_blocks = [] def draw(): screen.fill((135, 206, 250)) for chunk in rendered_chunks: chunks[chunk].render() player.draw(screen) screen.blit(text(f"Holding: {player.holding}", color=(255, 255, 255)), (0, HEIGHT-12)) if debug: for chunk in rendered_chunks: chunks[chunk].debug() pygame.draw.rect(screen, (255, 255, 255), player.rect, width=1) screen.blit(text(f"Seed: {SEED}"), (0, 0)) screen.blit(text(f"Velocity: {(round(player.vel.x, 3), round(player.vel.y, 3))}"), (0, 12)) screen.blit(text(f"Position: {inttup(player.coords)}"), (0, 24)) screen.blit(text(f"Camera offset: {inttup(player.pos-camera.offset-vec(SCR_DIM)/2+player.size/2)}"), (0, 36)) mpos = vec(pygame.mouse.get_pos()) block_pos = (player.pos+(mpos/2-player.rect.topleft))//BLOCK_SIZE screen.blit(text(f"Chunk: {inttup(player.coords//CHUNK_SIZE)}"), (0, 48)) screen.blit(text(f"Chunks loaded: {len(chunks)}"), (0, 60)) screen.blit(text(f"Rendered blocks: {len(blocks)}"), (0, 72)) try: screen.blit(text(f"{blocks[inttup(block_pos)].name.replace('_', ' ')}", color=(255, 255, 255)), (mpos[0]/2, mpos[1]/2-12)) except: pass display.blit(pygame.transform.scale(screen, (WIDTH*2, HEIGHT*2)), (0, 0)) pygame.display.flip() running = True debug = True while running: dt = clock.tick(FPS) / 16 pygame.display.set_caption(f"2D Minecraft | FPS: {int(clock.get_fps())}") for event in pygame.event.get(): if event.type == QUIT: running = False if event.type == MOUSEBUTTONDOWN: mpos = vec(pygame.mouse.get_pos()) block_pos = (player.pos+(mpos/2-player.rect.topleft))//BLOCK_SIZE if event.button == 1: remove_block(block_pos) if event.button == 3: if not is_occupied(block_pos): set_block(block_pos, player.holding) blocks[inttup(block_pos)].update() if event.type == KEYDOWN: if event.key == K_1: player.holding = "grass_block" elif event.key == K_2: player.holding = "dirt" elif event.key == K_3: player.holding = "stone" elif event.key == K_4: player.holding = "grass" if event.key == K_F5: debug = not debug rendered_chunks = [] for y in range(int(HEIGHT/(CHUNK_SIZE*BLOCK_SIZE)+2)): for x in range(int(WIDTH/(CHUNK_SIZE*BLOCK_SIZE)+2)): chunk = ( x - 1 + int(round(camera.offset.x / (CHUNK_SIZE * BLOCK_SIZE))), y - 1 + int(round(camera.offset.y / (CHUNK_SIZE * BLOCK_SIZE))) ) rendered_chunks.append(chunk) if chunk not in chunks: chunks[chunk] = Chunk(chunk) unrendered_chunks = [] for chunk in chunks: if chunk not in rendered_chunks: unrendered_chunks.append(chunk) for chunk in unrendered_chunks: for block in chunks[chunk].block_data: if block in blocks: blocks[block].kill() del blocks[block] for block in remove_blocks: remove_block(block) remove_blocks = [] camera.update() player.update() draw() pygame.quit() quit() When I make a setup like and stand on top of the center block, and jump to the right side, I should fall into the 2 blocks tall gap, but instead, I slide pass the gap and fall down and end up like this It used to happen on both sides but I seemed to have fixed the left side by swapping the y-axis collision detection and the x-axis if self.vel.y < 0: if block_collide(self.pos.x, self.pos.y+self.vel.y, self.width, self.height, block): self.pos.y = (block.pos.y + BLOCK_SIZE) self.vel.y = 0 elif self.vel.y >= 0: if block_collide(self.pos.x, ceil(self.pos.y+self.vel.y), self.width, self.height, block): self.pos.y = ceil(block.pos.y - self.height) self.vel.y = 0 if self.vel.x < 0: if block_collide(self.pos.x+self.vel.x, self.pos.y, self.width, self.height, block): self.pos.x = (block.pos.x + BLOCK_SIZE) self.vel.x = 0 elif self.vel.x >= 0: if block_collide(ceil(self.pos.x+self.vel.x), self.pos.y, self.width, self.height, block): self.pos.x = ceil(block.pos.x - self.width) self.vel.x = 0 But I couldn't figure out how to prevent it from happening on the right side too. Any help would be greatly appreciated :) |
how to remove X-Y values in this fl-chart flutter Posted: 07 May 2021 08:03 AM PDT **I am working on fl-chart (line charts) and I want to remove X-Y labels in this chart as well as grey lines to make a clear look of the chart but I didn't find any customisation in this package. So how can I achieve this task if fl-cart has this option or is there any different package available ? And also I want to achieve this task so if there is any alternative way please tell me |
Is there an R function to implement column variables row by row in an already existing function and loop that? Posted: 07 May 2021 08:04 AM PDT :) The title is rather complicated but so is the problem. Short: I have a command in R to print a T-Value for a spefific raw-value and a specific age-value. So raw + age = T-Value. I have to do that for 999 subjects. The data is in jamovi and R. So thats free of choice. The R-package is cNORM and the used command is: predictNorm(Raw,Age,model1,minNorm = 0,maxNorm = 100) It usually seems not intended to put in the column names. So usually the program expects you to fill in sole values. Is there a way to write a sort of loop that iterates through the two rows "raw" and "age" and fills the nescessary spaces of the command with those values row by row? And in the best case prints it directly? If something is still unclear, feel free to ask. I am glad for any help. |
Google AdMob new SDK setup for iOS : SKAdNetworkItems, NSUserTrackingUsageDescription, ATTrackingManager setup Posted: 07 May 2021 08:03 AM PDT Google AdMob now shows below warning. Prepare your apps for iOS 14 Apple announced the new AppTrackingTransparency framework, which requires changes to your iOS apps. Implement the GMA SDK 7.64.0 (or later) and set up consent messaging to help prevent a significant loss in ad revenue. Some apps haven't been configured to use Apple's SKAdNetwork To ensure you're getting credit for all ads activity, like app installs, be sure to configure SKAdNetwork with Google's network IDs. Some of your iOS apps require a GMA SDK update To keep ads serving normally and minimize a loss in ad revenue, implement the GMA SDK 7.64.0 (or later) for your iOS apps. And configure the SKAdNetwork in your apps with Google's network ID. For this I did these changes - Updated GoogleMobileAds SDK to 8.0
2.Updated app's Info.plist file with these 3 keys: 1. GADApplicationIdentifier key with a string value of AdMob app ID. 2. Added SKAdNetworkItems in plist as mentioned here https://developers.google.com/admob/ios/ios14 3. NSUserTrackingUsageDescription key with value 'Game_Name would like to access IDFA for thirdparty advertising purpose' info.plist screenshot Also added App Tracking Transparancy Alert: - (void)requestIDFA { if (@available(iOS 14.0, *)) { [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) { // Admob Ads [self loadAdmob_Ads]; [self loadRewardedInterstitial]; [self requestAppOpenAd]; }]; } else { // Admob Ads [self loadAdmob_Ads]; [self loadRewardedInterstitial]; [self requestAppOpenAd]; } } Is there anything else I need to do in Xcode ? See below image from Appstoreconnect, Am I need to set Yes Or No?(Yes, we use advertising data for tracking purpose?) we are not tracking user, not sure about Google AdMob. Data Used to Track You ( Identifiers, Usage Data ), Data Linked to You ( Identifiers, Usage Data ). Is it right settings for Google AdMob ? Recent AppStore Rejection Message: Guideline 5.1.2 - Legal - Privacy - Data Use and Sharing We noticed you do not use App Tracking Transparency to request the user's permission before tracking their activity across apps and websites. The app privacy information you provided in App Store Connect indicates you collect data in order to track the user, including Device ID and Advertising Data. Starting with iOS 14.5, apps on the App Store need to receive the user's permission through the AppTrackingTransparency framework before collecting data used to track them. This requirement protects the privacy of App Store users. Updates: Game approved by Apple. Here is game with latest admob ads (GADInterstitialAd, GADAppOpenAd, GADRewardedInterstitialAd, GADRewardedAd): https://apps.apple.com/us/app/gravity-ball-twist-3d-games/id1504676172 |
How to get the value of a var of another file in flutter? Posted: 07 May 2021 08:03 AM PDT I am trying to get the val of a var in a different file in flutter, I tried to do something like this : New x = New(); 'New is my class', x.variable = ... This didn't work for me. Any ideas how I can make something like this work? import 'auth/LoginPage.dart' as login; class WelcomePage extends StatefulWidget { @override _WelcomePageState createState() => _WelcomePageState(); } class _WelcomePageState extends State<WelcomePage> { final PageController _pageController = PageController(); var x = login.userType; |
Log warning: Thread starvation or clock leap detected (housekeeper delta=springHikariConnectionPool) Posted: 07 May 2021 08:03 AM PDT I'm using HikariCP 2.4.6 and at Tomcat 8 startup, I get a warning message: 01-Aug-2016 11:18:01.599 INFO [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring FrameworkServlet 'Spring MVC Dispatcher Servlet' [2016-08-01 11:18:01,654] Artifact blueberry:war exploded: Artifact is deployed successfully [2016-08-01 11:18:01,655] Artifact blueberry:war exploded: Deploy took 33,985 milliseconds Aug 01 2016 11:26:52.802 AM [DEV] (HikariPool.java:614) WARN : com.zaxxer.hikari.pool.HikariPool - 9m13s102ms - Thread starvation or clock leap detected (housekeeper delta=springHikariConnectionPool). I don't see any other errors or issues reading/writing from the DB. Is this something to be concerned about? I tried searching around, but no luck. We're also using Hibernate 4.3.8.Final over MySQL 5 and the MySQL 5.1.39 connector with Spring 4.1.0.RELEASE. We're working to upgrade to Hibernate 5 and will see whether this goes away, but don't know whether that will matter. |
How do I change intellij idea to compile with scala 2.11? Posted: 07 May 2021 08:02 AM PDT I am using Intellij Idea 13.1.4. I have a scala sbt project. It is currently being compiled with Scala 2.10. I would like to change this to Scala 2.11. In my build.sbt, I have: libraryDependencies ++= Seq( "org.scala-lang" % "scala-compiler" % "2.11.0", ... ) When I build my project, it still builds as a Scala 2.10 project. Also, under my Project Settings->Modules->Scala->Facet 'Scala'->Compiler library , Intellij still shows scala-compiler-bundle:2.10.2 . There is no option for a 2.11.x bundle. How would I get an option for Scala 2.11.x? Thanks! |
No comments:
Post a Comment