filtering list by multiple conditions Posted: 31 Oct 2021 07:49 AM PDT there is a list of users filterData = [ {"position":"lawyer", "department_positions":[],"group_positions":[{"group":{"id":2,"code":"234","name":"group1"},"lead":false},{"group":{"id":1,"code":"123","name":"group12"},"lead":true}]}, {"position":"director", department_positions":[{"department":{"id":3,"code":"333","name":"subDep"},"lead":false}],"group_positions":[{"group":{"id":2,"code":"234","name":"group1"},"lead":false},{"group":{"id":1,"code":"123","name":"group12"},"lead":true}]}, {"position":"director","department_positions":[],"group_positions":[]} ] and list of filters categories = {"position":["lawyer","director"], "group_positions":["group1","group12"], "department_positions":["generalDep", "subDep"] } It is necessary to filter users taking into account the fact that several filters can be selected at the same time. For example, i want to find user with position = "director" and AND group_positions = "group1" AND department_positions = "subDep" my code doesn't allow filtering by multiple conditions. how can i fix it? this.filter = this.filterData.filter(item => { for (let key in this.categories) { if (item[key].find(el => this.categories[key].includes(el.group?.name || el.department?.name))) { return true } } return false }) } |
Python Multiprocessing error: TypeError: 'AttrDict' object is not callable Posted: 31 Oct 2021 07:49 AM PDT I have a class which works well when run as a single process. I want it to be started as another process so I subclassed Process . import redis from pprint import pprint from cryptofeed import FeedHandler from cryptofeed.defines import ORDER_INFO from cryptofeed.exchanges import FTX from cryptofeed.types import OrderInfo from yapic import json from multiprocessing import Process class OMS(Process): def __init__(self): super().__init__() self.orders = {} self.redis = None self.fh = FeedHandler() async def order(self, oi: OrderInfo, receipt_timestamp): print(oi) self.save_unfilled_notl_to_redis(oi.exchange, oi.symbol) def initial_snapshot(self): pprint("initial snapshot") def save_unfilled_notl_to_redis(self, exchange, symbol): key = f"{exchange}:{symbol}" self.redis.hset("UNFILLED_ORDERS", key, json.dumps(0)) def start_feed(self): self.fh.add_feed( FTX(config="config.yaml", channels=[ORDER_INFO], symbols=FTX.symbols(), callbacks={ORDER_INFO: self.order})) self.fh.run() def run(self): self.redis = redis.Redis() self.initial_snapshot() self.start_feed() def main(): oms = OMS() oms.start() oms.join() if __name__ == '__main__': main() However, when I try and run the above code, I get this error: Traceback (most recent call last): File "/Users/mc/Library/Application Support/JetBrains/PyCharmCE2021.2/scratches/scratch_1.py", line 48, in <module> main() File "/Users/mc/Library/Application Support/JetBrains/PyCharmCE2021.2/scratches/scratch_1.py", line 43, in main oms.start() File "/Users/mc/.pyenv/versions/3.9.1/lib/python3.9/multiprocessing/process.py", line 121, in start self._popen = self._Popen(self) File "/Users/mc/.pyenv/versions/3.9.1/lib/python3.9/multiprocessing/context.py", line 224, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "/Users/mc/.pyenv/versions/3.9.1/lib/python3.9/multiprocessing/context.py", line 284, in _Popen return Popen(process_obj) File "/Users/mc/.pyenv/versions/3.9.1/lib/python3.9/multiprocessing/popen_spawn_posix.py", line 32, in __init__ super().__init__(process_obj) File "/Users/mc/.pyenv/versions/3.9.1/lib/python3.9/multiprocessing/popen_fork.py", line 19, in __init__ self._launch(process_obj) File "/Users/mc/.pyenv/versions/3.9.1/lib/python3.9/multiprocessing/popen_spawn_posix.py", line 47, in _launch reduction.dump(process_obj, fp) File "/Users/mc/.pyenv/versions/3.9.1/lib/python3.9/multiprocessing/reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) TypeError: 'AttrDict' object is not callable What am I doing wrong? As far as I can tell, this is how many online examples subclass Process . |
.NET Core website shutting down unexpectedly Posted: 31 Oct 2021 07:49 AM PDT I've got a .NET Core website hosted by IONOS on Windows which seemingly shuts down unexpectedly at random. I'm logging the following events as well as all incoming requests: - IHostApplicationLifetime.ApplicationStarted
- IHostApplicationLifetime.ApplicationStopping
- IHostApplicationLifetime.ApplicationStopped
As a result, I can see that my website restarts after receiving the following request: http://127.0.0.1:37065/iisintegration I've got no idea which process is behind this request, however given it uses 127.0.0.1 as the IP address, it must be local to the server. Does anyone know anything about requests to iisintegration ? Is it part of the ASP.NET Core stack? Any idea who might be sending such request? Could it be specific to IONOS? (their support is unhelpful). |
Kill All Child Processes But Not The Parent Processes Upon Timeout Error Posted: 31 Oct 2021 07:49 AM PDT while True: pid = os.getpid() try: pool = mp.Pool(processes=1, maxtasksperchild=1) result = pool.apply_async(my_func, args=()) result.get(timeout=60) pool.close() except multiprocessing.context.TimeoutError: traceback.print_exc() kill_proc_tree(pid) def kill_proc_tree(pid): parent = psutil.Process(pid) children = parent.children(recursive=True) for child in children: child.kill() I am using the multiprocessing library and am trying to spawn a new process everytime my_func finishes running, throws an exception, or has ran longer than 60 seconds (result.get(timeout=60) should throw an exception). Since I want to keep the while loop running but also avoid having zombie processes, I need to be able to keep the parent process running but at the same time, kill all child processes if an exception is thrown in the parent process or the child process, or the child process finishes before spawning a new process.The kill_proc_tree function that I found online was supposed to tackle the issue which it seemed to do at first (my_func opens a new window when a process begins and closes the window when the process supposedly ends), but then I realized that in my Task Manager, the Python Script is still taking up my memory and after enough multiprocessing.context.TimeoutError errors (they are thrown by the parent process), my memory becomes full. So what I should I do to solve this problem? Any help would be greatly appreciated! |
How to use data from multiple forms to create record with react-admin? Posted: 31 Oct 2021 07:49 AM PDT How to use data from multiple forms to create record ? Hi, My goal is to make a page that looks like this: on the left a form, in the middle an 'add' button and on the right a list of item. At the top, there will be a 'form type' select field. When I change the form type, the form changes (there are 5-6 types of forms). When I fill the form and click 'add', an item (showing some of the infos from the filled form) is added to the list on the right. All forms have something in common: a 'name' field. The final ressource that is created will look like this: (example if I filled 3 different forms, but in reality there could be many more objects, some of them with the same structure) { "here_name_in_form1":{ "app_name":"name of app", "client":"someone", "id":"", "some_date":"20210101" }, "here_name_filled_in_form2":{ "param1":"value1", "test":true, "id":"1", "date":"20210101", "random_input":1232 }, "here_name_filled_in_form3":{ "another_random_field":8382 "a_bool_value":false } } The part where I have a form changing according to the 'form type' button is easy, but how do I deal with the list ? I don't want to create the ressource until the user has clicked a 'saved' button at the bottom. How can I achieve this ? |
Collecting multiple flows into one Posted: 31 Oct 2021 07:49 AM PDT I am collecting data from datastore in flows in nested launch{}. viewLifecycleOwner.lifecycleScope.launchWhenStarted { launch { DataStore.userName.collect { Log.e(TAG, it ) } } launch { DataStore.userPhone.collect { Log.e(TAG, it ) } } launch { DataStore.userAddress.collect { Log.e(TAG, it ) } } } Is there a better way to collect flows in fragments ? Like collecting all data in single launch{} block. |
[c#][wpf] how to update textblock with method Posted: 31 Oct 2021 07:49 AM PDT I have a textbox that provide user to input string. how can i pass that string to method and toUpper() it. and pass back the string to textblock in the main window that both of the box and block update in real time? |
PHP exec function with mtr traceroute wait for response Posted: 31 Oct 2021 07:49 AM PDT I'm using the exec function in PHP to run the Linux mtr command (for traceroutes), but when I run it, I get a status code of 1 when I pass my domain into the command, but if I pass the --help flag or --version flag then I get a result instantly and it shows in my JSON. How can I make the exec function essentially wait until it's returned the result of the traceroute since I fear that's the issue here? Works: gives me a code of 0 and a result in out $cmd = 'mtr --help'; exec($cmd, $out, $code); Works: gives me a code of 0 and a result in out $cmd = 'mtr --version'; exec($cmd, $out, $code); Failing: gives me a code of 1 and no result $cmd = 'mtr --json google.com'; exec($cmd, $out, $code); Failing: gives me a code of 1 and no result $cmd = 'mtr google.com'; exec($cmd, $out, $code); If I run mtr from the command line, all the failing ones above will work as expected, granted, that a traceroute could take up-to 30 seconds to run, surely the exec waits though? How can I resolve this? |
Building libosmocore on FreeBSD Posted: 31 Oct 2021 07:48 AM PDT I've configured the source with these arguments: autoreconf -fi ./configure --disable-pcsc --disable-libmnl --disable-gb And it went just well, and then after running 'make' command and in middle of building I get these errors: gmake[2]: Entering directory '/usr/home/test_usr/libosmocore-1.5.2/utils' CCLD osmo-arfcn ld: error: ../src/.libs/libosmocore.so: undefined reference to osmo_timerfd_disable [--no-allow-shlib-undefined] ld: error: ../src/.libs/libosmocore.so: undefined reference to osmo_timerfd_schedule [--no-allow-shlib-undefined] ld: error: ../src/.libs/libosmocore.so: undefined reference to osmo_timerfd_setup [--no-allow-shlib-undefined] cc: error: linker command failed with exit code 1 (use -v to see invocation) gmake[2]: *** [Makefile:545: osmo-arfcn] Error 1 gmake[2]: Leaving directory '/usr/home/test_usr/libosmocore-1.5.2/utils' gmake[1]: *** [Makefile:708: all-recursive] Error 1 gmake[1]: Leaving directory '/usr/home/test_usr/libosmocore-1.5.2' gmake: *** [Makefile:487: all] Error 2 Has anybody faced this issue ? How can i resolve this ? Thanks, |
Spring JPA hibernate persist RestFull Object @OneToMany children (remove, add, or update) issues? Posted: 31 Oct 2021 07:48 AM PDT I have read a lot of article and I searched every where but I didn't get any a 100% solution. This is summary of concerned entities @Entity public class Ingredient { //omitted code @OneToMany(mappedBy = "embId.ingredientId", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true) private Set<IngrSubIngredient> ingrSubIngredients = new HashSet<IngrSubIngredient>(); //omitted code getters and setters..... } @Entity public class IngrSubIngredient { @EmbeddedId private SubIngredientKey embId = new SubIngredientKey(); @ManyToOne(fetch = FetchType.EAGER) @MapsId("ingredientId") private Ingredient ingredient; @ManyToOne(fetch = FetchType.EAGER) @MapsId("subIngredientId") private Ingredient subIngredient; private double quantity; //omitted code getters and setters..... } @Embeddable public class IngSubIngredientKey implements Serializable{ private Long ingredientId; private Long subIngredientId; /** * @return the ingredientId */ public IngSubIngredientKey () {} public IngSubIngredientKey ( Long ingredientId, Long subIngredientId) { this.ingredientId = ingredientId; this.subIngredientId = subIngredientId; } //omitted code } and this is the logic code @PutMapping("/ingredients") public void updateIngredient(@Valid @RequestBody Ingredient ingredient) { this.ingredientRepository.save(ingredient); } when I try to update ingredient with new IngrSubIngredients children. The old IngrSubIngredients cause this error 'javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.example.Resto.domain.IngrSubIngredient#com.example.Resto.domain.SubIngredientKey@49c]'. but when I tried the same changes to an attached ingredient object like in the code above I don't get that error. //this ingredient have an ingrSubIngredient child Ingredient ingredient = ingredientRepository.getOne((long) 7); Ingredient subIngredient = ingredientRepository.getOne((long) 1); //create new IngrSubIngredient IngrSubIngredient ingrSubIngredient = new IngrSubIngredient(); ingrSubIngredient.setIngredient(ingredient); ingrSubIngredient.setSubIngredient(subIngredient); ingrSubIngredient.setQuantity(73); //add the new ingrSubIngredient to ingrSubIngredients children ingredient.addIngrSubIngredient(ingrSubIngredient); ingredientRepository.save(ingredient); but event with attached ingredient object the change made to an old IngrSubIngredient child (quantity) don't persist the data base. Any help will be appreciated and thank you in advance. |
Runs with dynamically predefined thread names are sticks in pytest-parallel Posted: 31 Oct 2021 07:48 AM PDT I work with pytest-parallel plugin (https://github.com/browsertron/pytest-parallel) and would like to set thread name dynamically like : pytest_parallel/__init__.py ..... import time class ThreadWorker(threading.Thread): def __init__(self, queue, session, errors): _name = "Thread_" + str(time.time()) threading.Thread.__init__(self, name=_name) self.queue = queue self.session = session self.errors = errors ..... But it is always stucks on Ubuntu. What is the right way to set the thread name? Can you help please? |
Absinthe middleware not applying/running on query Posted: 31 Oct 2021 07:48 AM PDT I have Absinthe middleware that checks the context for an authenticated user, like so: defmodule CliftonWeb.Middlewares.CheckAuth do @behaviour Absinthe.Middleware require Logger def call(resolution, _config) do case resolution.context do %{current_user: _} -> resolution _ -> resolution |> Absinthe.Resolution.put_result({:error, "unauthenticated"}) end end end This is then applied in my schema: defmodule CliftonWeb.Schema do # Imports and plugin setup etc... def middleware(middleware, _field, %{identifier: :student_queries} = object) do [CliftonWeb.Middlewares.CheckAuth | middleware ] end def middleware(middleware, _field, object), do: middleware query do import_fields :student_queries # etc... end end However the middleware is never called when I make a query. Is it possible to match on any identifier, or only query , mutation etc? In addition, is this the best way to only apply middlewares to certain groups of queries/mutations? |
Read metrics from Prometheus instance - Java Spring Posted: 31 Oct 2021 07:48 AM PDT I would like to write a microservice, which will be able to read and analyze data from Prometheus instance. Is there a Java library (client), which exposes a simple API to build some basic PromQL queries? Queries for 'Instant Vector', 'Range Vector' and 'Scalar'? Example of PromQL query: http_requests_total{job="prometheus",group="canary"} |
small shell script display users who logged in, who logged out Posted: 31 Oct 2021 07:47 AM PDT task:write a program that outputs information about users in the system after a certain time interval: who entered, who left. I tried to do it differently.by comparing two files.I don't know how well I do it. comm is not very good here, I know. I tried using diff , but her output to the console is incomprehensible to me.and i tried diff -q ,but i got only this line Files 1.txt and 2.txt differ please help me. #!/bin/bash while (true) do who > 1.txt sleep 10s who > 2.txt (comm -13 1.txt 2.txt) > 3.txt (comm -23 2.txt 1.txt) > 4.txt echo IN : cat 3.txt echo OUT : sleep 10s cat 4.txt echo [______________________________________________________________] done |
HTML: Submit button Posted: 31 Oct 2021 07:47 AM PDT Ritesh is your friend and wants to adopt a dog. Create a form with the following fields and the field name will be written in the placeholder. You need to use a form tag for this. - Name ( use id 'name', placeholder 'Name', type 'text' for this)
- Phone Number ( use id 'phone', placeholder 'Phone Number', type 'text' for this)
- Address ( use id 'address', placeholder 'Address', type 'text' for this)
- Have you ever lived with a Dog before? (its type should be 'checkbox', use id 'checkbox' and value should be 'Have you ever lived with a Dog before? ')
- Please select your preferred breeds ( make this as a multi-select box with at least 3 options, use a select tag for this with id "multiSelect" )
- Submit ( use id 'submit', type 'submit' ,value 'Submit' for this )
My code <!Doctype html> <html> <head> <body> <form> <input type="text" id="name" placeholder="Name" type="text"><br><br> <input type="text" id="phone" placeholder="Phone Number" type="phone"><br><br> <input type="text" id="address" placeholder="Address" type="address"><br><br> Have you ever lived with a Dog before? <input type="checkbox" id="checkbox" value="Have you ever lived with a Dog before?"> <label for="Have you ever lived with a Dog before?"> Yes </label> <input type="checkbox" id="checkbox" value="Have you ever lived with a Dog before?"> <label for="Have you ever lived with a Dog before?"> No </label><br><br> <label for="breed">Choose a dog:</label> <select name="dog" id="multiSelect"> <option value="dog1">dog1</option> <option value="dog2">dog2</option> <option value="dog3">dog3</option> <option value="dog4">dog4</option> </select><br><br> </form> <input type="submit" id="submit" value="Submit"><br><br> </body> </head> </html> i am getting error in submit code can anyone help |
How to convert DispatchQueue debounce to Swift Concurrency task? Posted: 31 Oct 2021 07:49 AM PDT I have an existing debouncer utility using DispatchQueue . It accepts a closure and executes it before the time threshold is met. It can be used like this: let limiter = Debouncer(limit: 5) var value = "" func sendToServer() { limiter.execute { print("\(Date.now.timeIntervalSince1970): Fire!") } } value.append("h") sendToServer() // Waits until 5 seconds value.append("e") sendToServer() // Waits until 5 seconds value.append("l") sendToServer() // Waits until 5 seconds value.append("l") sendToServer() // Waits until 5 seconds value.append("o") sendToServer() // Waits until 5 seconds print("\(Date.now.timeIntervalSince1970): Last operation called") // 1635691696.482115: Last operation called // 1635691701.859087: Fire! The Debouncer instance is configured to hold for 5 seconds no matter how many times it is called. The closure is passed into the execute(block:) method: final class Debouncer { private let limit: TimeInterval private let queue: DispatchQueue private var workItem: DispatchWorkItem? private let syncQueue = DispatchQueue(label: "Debouncer", attributes: []) init(limit: TimeInterval, queue: DispatchQueue = .main) { self.limit = limit self.queue = queue } @objc func execute(block: @escaping () -> Void) { syncQueue.async { [weak self] in if let workItem = self?.workItem { workItem.cancel() self?.workItem = nil } guard let queue = self?.queue, let limit = self?.limit else { return } let workItem = DispatchWorkItem(block: block) queue.asyncAfter(deadline: .now() + limit, execute: workItem) self?.workItem = workItem } } /// Cancels all work items to allow future work items to be executed with the specified delayed. func reset() { syncQueue.async { [weak self] in self?.workItem?.cancel() self?.workItem = nil } } } How can I convert this into a concurrent operation so it can be called like below, or maybe there's a better approach to do this? func execute(block: @escaping () -> Void) async {...} ... let limit = Debouncer(limit: 5) await limit.execute {...suspended for 5 seconds...} await limit.execute {...suspended for 5 seconds...} |
Unable to push css in heroku service Posted: 31 Oct 2021 07:48 AM PDT What I am doing ? - I am trying to deploy a django web application on heroku server.
Problem I am not able to push css files in heroku server using git push heroku main . When I remove css file from static folder, then everything is going well. remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: -----> $ python manage.py collectstatic --noinput remote: Post-processing 'CSS/style.css' failed! remote: Traceback (most recent call last): remote: File "/tmp/build_31834d76/manage.py", line 10, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 134, in collect remote: raise processed remote: whitenoise.storage.MissingFileError: The file 'CSS/images/mobile-app.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f8a24943cd0>. remote: The CSS file 'CSS/style.css' references a file which could not be found: remote: CSS/images/mobile-app.png remote: Please check the URL references in this CSS file, particularly any remote: relative paths which might be pointing to the wrong location. remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to trichhpali. remote: To https://git.heroku.com/trichhpali.git ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/trichhpali.git' Thank you for your help 🤗 |
Could not create server TCP listening socket *:6383 bind: Cannot assign requested address in redis clustering on docker (in windows) Posted: 31 Oct 2021 07:49 AM PDT I'm trying to set up redis clustring on windows docker. it works fine only in redis-cli -h 127.0.0.1 -p 6383 inside docker container CLI all nodes are fine and cluster has no problem. this is one of the redis.config file nodes redis.config file port 6383 bind 0.0.0.0 cluster-enabled yes cluster-config-file nodes.conf cluster-node-timeout 5000 appendonly yes The problem is with the above configuration, it's not possible to access the clustering with the application because it's not reachable for app (this app works fine in redis single mode) when I change "bind" redis.conf file to my computer ip which is 192.168.3.205 i get this error enter image description here I have tried the following: - open the above port in the firewall roll
- with telnet command it seems nobody listennign on this port
telnet 192.168.3.205 6383 and 127.0.0.1 6383 3. in netstat prot 6383 not used by anyone and this is my .yml file version: "3.8" networks: default: name: amin-cluster services: redis0: container_name: node-0 image: mnadeem/redis network_mode: "host" volumes: - C:\Windows\System32\6379\redis.conf:/usr/local/etc/redis/redis.conf command: ["redis-server", "/usr/local/etc/redis/redis.conf"] build: context: . dockerfile: Dockerfile hostname: node-0 restart: always redis1: container_name: node-1 image: mnadeem/redis network_mode: "host" volumes: - C:\Windows\System32\6380\redis.conf:/usr/local/etc/redis/redis.conf command: ["redis-server", "/usr/local/etc/redis/redis.conf"] build: context: . dockerfile: Dockerfile hostname: node-1 restart: always redis2: container_name: node-2 image: mnadeem/redis network_mode: "host" volumes: - C:\Windows\System32\6381\redis.conf:/usr/local/etc/redis/redis.conf command: ["redis-server", "/usr/local/etc/redis/redis.conf"] build: context: . dockerfile: Dockerfile hostname: node-2 restart: always redis3: container_name: node-3 image: mnadeem/redis network_mode: "host" volumes: - C:\Windows\System32\6382\redis.conf:/usr/local/etc/redis/redis.conf command: ["redis-server", "/usr/local/etc/redis/redis.conf"] build: context: . dockerfile: Dockerfile hostname: node-3 restart: always redis4: container_name: node-4 image: mnadeem/redis network_mode: "host" volumes: - C:\Windows\System32\6383\redis.conf:/usr/local/etc/redis/redis.conf command: ["redis-server", "/usr/local/etc/redis/redis.conf"] build: context: . dockerfile: Dockerfile hostname: node-4 restart: always redis5: container_name: node-5 image: mnadeem/redis network_mode: "host" volumes: - C:\Windows\System32\6384\redis.conf:/usr/local/etc/redis/redis.conf command: ["redis-server", "/usr/local/etc/redis/redis.conf"] build: context: . dockerfile: Dockerfile hostname: node-5 restart: always |
laravel auto logout session flash message not showing Posted: 31 Oct 2021 07:47 AM PDT I'm using Laravel 8 I decided to implement auto logout when the session has been timeout, i follow that code from https://laracasts.com/discuss/channels/laravel/auto-logout-if-no-activity-in-given-time?page=1&replyId=484851 $(document).ready(function () { const timeout = 900000; // 900000 ms = 15 minutes var idleTimer = null; $('*').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () { clearTimeout(idleTimer); idleTimer = setTimeout(function () { document.getElementById('logout-form').submit(); }, timeout); }); $("body").trigger("mousemove"); }); my form for logout: <form action="/logout" method="POST" id="logout-form"> @csrf </form> my routes: Route::group(["middleware" => "auth"], function(){ Route::post('/logout', [Controller::class, "logout"]); }); Route::group(["middleware" => "guest"], function(){ Route::get('/login', [Controller::class, "index"])->name("login"); }); and in my controller: public function logout(){ Auth::logoutCurrentDevice(); request()->session()->invalidate(); request()->session()->regenerateToken(); return redirect('/login')->with("danger", "You have been automatically logged out due to inactivity of ".config('session.lifetime')." minutes. Once you log in again, you should be able to resume the work where you left off."); } and it's working. BUT the problem is when I waited for that autologout to work, I minimized the browser, when I back to my application, its logouted and redirected to /login page, but that session flash data not showing. and after that, I submit the login form, when I submitted that login form, the session flash data is now showing. and when I waiting for my application session timeout without minimizing the browser, that session flash data worked and showed. I think it's not good for user experiences and kinda annoying. it's a bug or whatever? let me know thanks. |
Java: How can I queue up asynchronous calls to be executed when a certain condition is met? Posted: 31 Oct 2021 07:49 AM PDT TL;DR: I want to perform an asynchronous Call to a REST-API. The standard call would give me a CompleteableFuture<Response>, however because the API has a limit on how many calls it allows in a certain amount of time I want to be able to queue up calls to 1. execute them in order and 2. execute them only when I am not exceeding the APIs limits at that current moment, otherwise wait. Long verson: I am using Retrofit to perform Rest calls to an API and Retrofit returns a CompleteableFuture<WhateverResponseClassIDeclare> when I call it. However due to limitations of the API I am calling I want to have tight control over when and in what order my calls go out to it. In detail, too many calls in a certain timeframe would cause me to get IP banned. Similarly I want to maintain the order of my calls, even if they won't get executed immediately. The goal is to call a Wrapper of the API that returns a CompleteableFuture just like the original API but performs those in-between steps asynchronously. I was playing around with BlockingQueues, Functions, Callables, Suppliers and everything inbetween, but I couldn't get it to work yet. Following there is my currently NON FUNCTIONAL code I created as a Mockup to test the concept. import java.util.concurrent.BlockingDeque; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.LinkedBlockingDeque; import java.util.function.Function; public class Sandbox2 { public static void main(String[] args) throws ExecutionException, InterruptedException { MockApi mockApi = new MockApi(); CompletableFuture<Integer> result1 = mockApi.requestAThing("Req1"); CompletableFuture<Integer> result2 = mockApi.requestAThing("Req2"); CompletableFuture<Integer> result3 = mockApi.requestAThing("Req3"); System.out.println("Result1: " + result1.get()); System.out.println("Result2: " + result2.get()); System.out.println("Result3: " + result3.get()); } public static class MockApi { ActualApi actualApi = new ActualApi(); BlockingDeque<Function<String, CompletableFuture<Integer>>> queueBlockingDeque = new LinkedBlockingDeque(); public CompletableFuture<Integer> requestAThing(String req1) { Function<String, CompletableFuture<Integer>> function = new Function<String, CompletableFuture<Integer>>() { @Override public CompletableFuture<Integer> apply(String s) { return actualApi.requestHandler(s); } }; return CompletableFuture .runAsync(() -> queueBlockingDeque.addLast(function)) .thenRun(() -> waitForTheRightMoment(1000)) .thenCombine(function) } private void waitForTheRightMoment(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } } public static class ActualApi { public CompletableFuture<Integer> requestHandler(String request) { return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return Integer.parseInt(request.substring(3)); }); } } } |
Is it ok to perform a full collection scan on a low volume firestore collection? Posted: 31 Oct 2021 07:49 AM PDT My mobile application's backend is a few small firebase/google cloud functions which perform various CRUD operations on my firestore database. I have come into the issue where I require to update all documents in a collection daily. I have a cron job which triggers the function every day at a specified time. To avoid doing a full collection scan, I tried a few hacky ways to get around not being able to self invoke functions like with AWS lambdas. Ultimately these did not work. As I am not expecting high volumes of data (each document up to around 8 string fields; expecting a max of 10,000 documents) I was thinking maybe a full collection scan wouldn't actually be that expensive. Has anyone had experience with full table scans on firestore, and what was the performance like? |
Trouble Importing a 3th party maven library from github to Intellij Posted: 31 Oct 2021 07:48 AM PDT So this is my first time doing this, i am trying to import this project https://github.com/binance-exchange/binance-java-api to my new clean intellij maven project. i set my system variable MAVEN_HOME to: - C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.3.2\plugins\maven\lib
And then im trying to install the 3th party library to my local m2 repository. mvn install:install-file -Dfile=C:\Users\Leroy\.m2\repository -DgroupId=com.binance.api - DartifactId=binance-api-client -Dversion=1.0.0 -Dpackaging=jar cmd gives me the message that 'mvn is not recognized as an internal or external command' What am i doing wrong here? thank you in advance! |
Reversing exponents in lua Posted: 31 Oct 2021 07:48 AM PDT I have a algorithm to calculate the desired exp for reach a level. But I didn't know how get the desired level based on his EXP. local function NextLevelXP(level) return math.floor(1000 * (level ^ 2.0)) end print(NextLevelXP(7)) -- output: 49000 Now I want the level based on his EXP, with something like: local function MagicFunctionThatWillLetMeKnowTheLevel(exp) return --[[math magics here]] end print(MagicFunctionThatWillLetMeKnowTheLevel(49000)) --output: 7 print(MagicFunctionThatWillLetMeKnowTheLevel(48999)) --output: 6 I've tried some worse and weird algorithms, but no success. |
How to use the LSTM model for multi-step forecasting? Posted: 31 Oct 2021 07:47 AM PDT I developed a time series model with LSTM. I can't use it for predicting stock price in future days. I want to use it for predicting stock price for next year and plot it. How to use it for forecasting stock price in future (next year)? df=pd.read_csv('foolad.csv') df=df.set_index(pd.DatetimeIndex(df['Date'].values)) data=df.filter(['Close']) dataset=data.values training_data_len=math.ceil(len(dataset)*0.8) scaler=MinMaxScaler(feature_range=(0,1)) scaled_data=scaler.fit_transform(dataset) scaled_data training_data=scaled_data[0:training_data_len , :] xtrain=[] ytrain=[] n = 60 for i in range(n,len(training_data)): xtrain.append(training_data[i-n:i , 0]) ytrain.append(training_data[i,0]) xtrain , ytrain = np.array(xtrain) , np.array(ytrain) xtrain=np.reshape(xtrain , (xtrain.shape[0],xtrain.shape[1],1)) xtrain.shape model=Sequential() model.add(LSTM(50,return_sequences=True,input_shape=(xtrain.shape[1],1))) model.add(LSTM(50,return_sequences=False)) model.add(Dense(25)) model.add(Dense(1)) model.compile(loss='mean_squared_error',optimizer='adam') model.fit(xtrain,ytrain,epochs=1,batch_size=1) test_data=scaled_data[training_data_len - n : , :] xtest=[] ytest=dataset[training_data_len : , :] for i in range(n , len(test_data)): xtest.append(test_data[i-n : i , 0]) xtest=np.array(xtest) xtest=np.reshape(xtest , (xtest.shape[0],xtest.shape[1],1)) prediction=model.predict(xtest) prediction=scaler.inverse_transform(prediction) #for future 360 days what can I do?.... |
Laravel GraphQl getting Could not connect to websocket endpoint error Posted: 31 Oct 2021 07:48 AM PDT After implementing a simple GraphQl query such as a simple Mutation and Subscription I get this error when I try to run this subscription into graphql-playground : subscription { userCreated{ name username password } } I get this error: { "error": "Could not connect to websocket endpoint ws://127.0.0.1:8000/graphql. Please check if the endpoint url is correct." } GraphQl Schema: #... type User { id: Int! name: String email: String product : [Product!] } type Mutation { createUser( name: String! password: String! email : String! ): User @field(resolver:"UserMutator@create") @broadcast(subscription: "userCreated") } type Subscription { userCreated: User } UserMutator class: class UserMutator{ public function create($_ , array $args){ $user = User::create($args); Subscription::broadcast('userCreated',$user); //return $user; } UserCreated Subscription class UserCreated extends GraphQLSubscription { public function authorize(Subscriber $subscriber, Request $request): bool { return true; } public function filter(Subscriber $subscriber, $root): bool { return true; } } |
Invalid hook call with Next.JS Posted: 31 Oct 2021 07:47 AM PDT In my _document.js file, I'm getting an invalid hook call error on line 28, but I'm pretty sure I'm using not using a hook. I tried adding brackets around originalRenderPage, but that just causes other errors. There's a useEffect hook in my _app.js file, but that looks right to me too. Any ideas on how to fix this? _document.js import React from "react"; import Document, { Html, Head, Main, NextScript } from "next/document"; import { ServerStyleSheets } from "@material-ui/core/styles"; export default class MyDocument extends Document { render() { return ( <Html lang="en"> <Head> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } MyDocument.getInitialProps = async (ctx) => { const sheets = new ServerStyleSheets(); const originalRenderPage = ctx.renderPage; ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => sheets.collect(<App {...props} />), }); const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, // Styles fragment is rendered after the app and page rendering finish. styles: [ ...React.Children.toArray(initialProps.styles), sheets.getStyleElement(), ], }; }; _app.js: import "../styles/globals.css"; import { StoreProvider } from "../components/Store"; import NProgress from "nprogress"; import "nprogress/nprogress.css"; import Router from "next/router"; import { useEffect } from "react"; Router.events.on("routeChangeStart", () => NProgress.start()); Router.events.on("routeChangeComplete", () => NProgress.done()); Router.events.on("routeChangeError", () => NProgress.done()); function MyApp({ Component, pageProps }) { useEffect(() => { // Remove the server-side injected CSS. const jssStyles = document.querySelector("#jss-server-side"); if (jssStyles) { jssStyles.parentElement.removeChild(jssStyles); } }, []); return ( <StoreProvider> <Component {...pageProps} /> </StoreProvider> ); } export default MyApp; MyApp.getInitialProps = async () => { return { pageProps: { commercePublicKey: process.env.COMMERCE_PUBLIC_KEY, }, }; }; |
Python typing class type in single quotes [duplicate] Posted: 31 Oct 2021 07:49 AM PDT class Person: def __init__(self, ...... def make_friend(self, friend: 'Person') -> None: ..... I'm learning python and I don't understand this example. Why type condition for friend should be in single quotes? Why not friend: Person ? How it can works? Does it have something common with type class shortcut? |
Error "302 Moved Temporarily" in "Test as add-on" mode (Telegram) Posted: 31 Oct 2021 07:49 AM PDT - The spreadsheet contains project 1, deployed as a webapp with permissions:
Execute as: Me, Who has access: Anyone . Webapp function doPost(e) { myLog('Received from Addon: ' + JSON.stringify(e)); // console.log('parameters from caller ' + JSON.stringify(e)); return ContentService.createTextOutput(JSON.stringify(e)); } A webhook aTelegram-bot and this webapp is set. - I am using this spreadsheet for testing (as add-on) of another project 2.
Add-on function sendPost() { var sheetURL = SpreadsheetApp.getActiveSpreadsheet().getUrl(); // var webAppUrl = "https://script.google.com/macros/s/#####/exec"; // 7: Part_1 - WebApp: My var webAppUrl = "https://script.google.com/macros/s/###/exec"; // 7: Part_1 - WebApp: Tester // var auth = ScriptApp.getOAuthToken(); // var header = { 'Authorization': 'Bearer ' + auth }; var payload = { scriptName: 'updateData', sheetURL: 'sheetURL' }; var options = { method: 'post', // headers: header, muteHttpExceptions: true, payload: payload }; var resp = UrlFetchApp.fetch(webAppUrl, options); var respCode = resp.getResponseCode(); console.log('resp: ' + respCode); myLog(respCode); var respTxt = resp.getContentText(); myLog('Response from webApp: ' + respTxt); console.log('resp: ' + respTxt); } Here is a short video of the process (EN-subtitles). - I run sendPost() and everything works fine. Project 2 sends data to the webapp, which returns it. Since this is a Container-bound script and not a standalone one, I cannot watch the logs in the GCC logger. Therefore, I look at them in the custom logger and the entries are added normally.
Also https://api.telegram.org/bot{API_token}/getWebhookInfo shows that there are no errors: {"ok":true,"result": {"url":"https://script.google.com/macros/s/###/exec", "has_custom_certificate":false, "pending_update_count":0, "max_connections":40,"ip_address":"142.250.***.***"}} - Now I am sending a message from the chat with the bot. The doPost(e) function in the webapp accepts it and writes it to the spreadsheet. However, everything is not limited to one message. Requests from the bot come and come, and the logger creates more and more new rows in the spreadsheet. This happens until I redeploy the webapp with the doPost () function commented out. I tried to figure out if this is a limited loop or not. My patience was only enough for 20 such iterations, because as a result, the messages start repeating at intervals of about 1 minute. Then I have to reinstall the webhook.
In any case, it interferes with testing the addon. - GetWebhookInfo is now showing that there is a "Wrong response from the webhook: 302 Moved Temporarily" error:
{"ok":true,"result": {"url":"https://script.google.com/macros/s/###/exec", "has_custom_certificate":false, "pending_update_count":1, "last_error_date":1635501472, "last_error_message":"Wrong response from the webhook: 302 Moved Temporarily", "max_connections":40,"ip_address":"142.250.1***.***"}} - Googling revealed several possible reasons. From url to the script has changed to MITM in your network. I do not really believe in MITM and I suppose that this is due to the fact that the spreadsheet is open in testing mode as add-on and the URL of the webapp has changed in this mode. If so, then I'm not sure if this is the correct behavior of the testing system. In theory, such a situation should have been provided for and the webap url should remain unchanged. But maybe I'm wrong and the reason is different, so
QUESTION: Has anyone come across such a situation and will suggest a workaround on how to test a script as an addon in such conditions? |
Why is the statusText of my XHR empty? Posted: 31 Oct 2021 07:48 AM PDT When I perform an XHR on our production system, the statusText in the response will be an empty string. However, on our development system, the statusText will reflect the status correctly. According to the documentation for XMLHttpRequest.statusText , it should only be empty while the request is being processed. However, I am seeing this behavior in the onload handler. Additionally, this behavior can only be observed in Chrome and Edge. Firefox will display the correct text. So, how is the content of the statusText actually determined? |
How do I reverse the order of an array using v-for and orderBy filter in Vue JS? Posted: 31 Oct 2021 07:49 AM PDT I am using Vue JS to do viewmodel bindings. In my data object I have an array of items that are sorted in ascending order (oldest to newest) and I'd like to keep it that way for code-based reasons. var v = new Vue({ el: '#app', data: { items: [ {id: 51, message: 'first'}, {id: 265, message: 'second'}, {id: 32, message: 'third'} ], } } However, when I display the array in the template I'd like to reverse the order so that it's descending (newest to oldest). I tried the following: <ol> <li v-for="item in items | orderBy -1" track-by="id"> This didn't work since the orderBy filter seems to require a field name as its first argument. Is there any way to accomplish this in the template using the v-for syntax using the orderBy filter? Or am I going to have to create a custom reverse filter? |
No comments:
Post a Comment