Onclick button Javascript Posted: 26 Jun 2021 09:25 AM PDT In HTML I can have <button id = "1" class = "btn" onClick="reply_click(this.id)"> for a certain number of buttons. But I want to create n buttons (from user input) with Javascript and I want to do the same thing for all buttons created. function createButtons(n) { for (let i = 0; i < n; ++i) { btn = document.createElement("button"); btn.innerHTML = i + 1; btn.id = i + 1; document.body.appendChild(btn); btn.setAttribute("reply_click", "this.id"); } } How can I check the id of the clicked button, for example if the id of the clicked button is equal to 1? With the code I have written nothing happens when I click a button. |
How to save data from matplotlib script in a dat file? Posted: 26 Jun 2021 09:25 AM PDT I have a matplotlib scrip and it shows a figure using below code: if True: from matplotlib.pylab import * figure(figsize = (3.2, 2.5), dpi = 200) semilogx(WIDTH_array*1e6, DATA_list) xlabel('WIDTH ($\mu m$)') ylabel('YEAR') minorticks_on() ax=gca() ax.set_xlim(0.01, ax.get_xlim()[1]) ax.set_ylim(0, ax.get_ylim()[1]) tight_layout(pad = 0.5) show() It is showing the figure with the x-axis on a log scale. I want these data in a case.dat file where all data should be on a normal scale? |
How to save Json data to mongoose in node js Posted: 26 Jun 2021 09:25 AM PDT The below is the route am using to receive the json data but the problem is i don't know how i can save it to mongoose router.post('/payment, async(req, res)=>{ var secret = secret; var event = req.body; console.log(event) res.sendStatus(200) }); So how can i save the event am receiving to mongoose? |
laravel mail with queue Posted: 26 Jun 2021 09:25 AM PDT i want to send mail when i create a new article it works without queue but i when i use queue it failed also i want to send the article that i create via email i did this php artisan queue:work --queue=high,default php artisan make:mail contents and class contents extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public $article; public function __construct($article) { $this->article = $article; } /** * Build the message. * * @return $this */ public function build() { return $this->view('admin.content.mail.index')->with( [ 'article' => $this->article, 'title' => $this->article->title, 'body' => $this->article->body, 'image' => $this->article->image ] ); } } and php artisan queue:table php artisan migrate php artisan make:job ProcessMails and class ProcessMails implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $article; protected $mails; /** * Create a new job instance. * * @return void */ public function __construct($mails ,$article) { $this->article = $article; $this->mails = $mails; } /** * Execute the job. * * @return void */ public function handle() { Mail::to($this->mails)->send(new contents($this->article)); } } and it is code in article controller when status is active send massage public function status(Request $request, $id) { $article = Article::find($id); $article->status = $request->status; $article->save(); if ($request->status == "active") { $users = User::all(); foreach ($users as $user) { $mails[] = $user->email; } $news = Newsletters::all(); foreach ($news as $new) { $mailsnew = $new->email; array_push($mails, $mailsnew); } ProcessMails::dispatch($mails , $article); } return redirect()->route('article.index')->with('success', 'record create successfully'); } and finally i type this command php artisan queue:listen and when the status is active it show in the powershell [2021-06-23 19:38:46][68] Processing: App\Jobs\ProcessMails [2021-06-23 19:38:46][68] Failed: App\Jobs\ProcessMails in addition i use smtp |
Amazon Polly doesn't speak Posted: 26 Jun 2021 09:24 AM PDT environment - Spring Boot2.4.5
- EC2(Ubuntu20.04) with snd-aloop
I implement Amazon Polly based on AWS sdk for java 2.0. It speaks in local environment, but in production it doesn't although no errors occur. Source is as follows: @GetMapping("/sound/{chinese}") public void getSound(@PathVariable("chinese") String chinese) throws IOException { ResourceBundle rb = ResourceBundle.getBundle(RESOURCE_NAME); final String accessKey = rb.getString("pollyAccessKey"); final String secretKey = rb.getString("pollySecretKey"); AwsBasicCredentials awsCreds = AwsBasicCredentials.create(accessKey, secretKey); final String REGION = rb.getString("region"); try { PollyClient polly = PollyClient.builder() .credentialsProvider(StaticCredentialsProvider.create(awsCreds)) .region(Region.of(REGION)) .build(); DescribeVoicesRequest describeVoiceRequest = DescribeVoicesRequest.builder() .languageCode("cmn-CN") .engine("standard") .build(); DescribeVoicesResponse describeVoicesResult = polly.describeVoices(describeVoiceRequest); Voice voice = describeVoicesResult.voices().get(0); InputStream stream = synthesize(polly, chinese, voice, OutputFormat.MP3); FactoryRegistry factoryRegistry = javazoom.jl.player.FactoryRegistry.systemRegistry(); javazoom.jl.player.FactoryRegistry.systemRegistry().createAudioDevice()); AdvancedPlayer player = new AdvancedPlayer(stream, javazoom.jl.player.FactoryRegistry.systemRegistry().createAudioDevice()); player.play(); polly.close(); } catch (PollyException | JavaLayerException | IOException e) { System.out.println(e.getStackTrace()); System.exit(1); } } I have spent around a week solving this, but it doesn't work. I have no idea anymore. Thanks in advance. |
Module not found , its been showing the given below error even after i reinstalled and checked every address Posted: 26 Jun 2021 09:24 AM PDT ./src/components/showStudent/showStudent.js Module not found: Can't resolve '@material-ui/data-grid' in 'C:\Users\USER\Desktop\Database\client\src\components\showStudent Code below in showstudent was copied directly from materialui website for tables |
How to get an item from list Posted: 26 Jun 2021 09:24 AM PDT Am trying to get the required item from list(looks like list of dict). would like to know if there is a better way to do this. I feel have used too many split to get the Gender value. >>> record = ['{"Name": "Jack", "Gender": "Male"}'] >>> >>> type(record) <class 'list'> >>> >>> for item in record: ... Gen = item.split(",")[1].split()[1].rstrip("}") ... >>> print(Gen) "Male" >>> Thanks, |
someone can improve the code, need a lot of ideas. ES6, arrow function, remove the console.log [closed] Posted: 26 Jun 2021 09:26 AM PDT I'd love having a lot of solutions on how to improve this code. Removing console.log but returning the string? using arrow function? thanks everyone! ''' const be = "Yourself" const her = "Happy" const trueLove = " " let isTrue = "My world is Complete" let isFalse = "Stay strong" function happiness() { if (be === "Yoursel" && her === "Happy" && trueLove === " ") return (console.log(isTrue)) else { return (console.log(isFalse))} } happiness() ''' |
open png file with adobeacrobat pro dc vba Posted: 26 Jun 2021 09:23 AM PDT Last night I achieve to open png files with adobeacrobat pro dc and save them in pdf format. It works perfectly, I set a folder and it search on every folder and subfolder for png files and when it found someone it opens with acrobat and then saved it in pdf format. Today nothing works, moreover, the original code which only works on a single file doesn't works neither Sub OpenHow() Dim Acroapp As New Acrobat.Acroapp Dim pddoc As New Acrobat.AcroPDDoc Set Acroapp = CreateObject("AcroExch.App") Set pddoc = CreateObject("AcroExch.pddoc") pddoc.Open ("C:/1.png") pddoc.Save PDSaveFull, "C:/1.pdf" Acroapp.Exit End Sub Any clue of what might have gone wrong?:S Thanks in advance |
How to modify inner text in class Selenium Posted: 26 Jun 2021 09:23 AM PDT I have this element, and i want to change text inside class by Selenium driver from New York to Paris. How can i do that? Element: <a href="javascript:void(0);" class="get_city_select">New York</a> This is my code but it doesn't work: element = driver.find_element_by_class_name("get_city_select") driver.execute_script("arguments[0].innerText = 'Paris'", element) Thanks for help! |
Receive session enabled messages Azure Bus Service Posted: 26 Jun 2021 09:23 AM PDT I currently have a standard process that sends messages to a queue using: var queueHandler = new QueueHandler(new QueueManager(messageRequest.queueName)); queueHandler.AddMessage(jsonContent); Everything is fine, receiving messages on a function Bus Service aware: public static async void Run([ServiceBusTrigger("MyQueueName")] string myQueueItem, ILogger log) So it works auto on the server. Now I need to use session enabled queues, which can't be set up like this. How do you set up the Functions to be automatically triggered based on those messages? Do I have to periodically read the sessions? Do I have to schedule a function? The documentation says nothing about this, they just use console applications, which won't work on my scenario, I need them to be automatically processed, based on create or every X time. What are the best practises for this? Thank you. |
Is there any way to use input for a mathematical function? Posted: 26 Jun 2021 09:26 AM PDT My numerical analysis professor gave me a project on programming several numerical methods in python. And he asked me to run the program for some given functions so he can see the results of the methods. My question is : Is there any way so we can code somthing which the user input any chosen function and see the wanted results? Or we must define the wanted function in the program specifically and there isn't any way to do so ? |
Timing how frequently a function is called ignoring the time spent in the function itself in multiprocessing Posted: 26 Jun 2021 09:23 AM PDT The problem I have been stuck on is more towards logical thinking. Consider a resource R. R can be produced programatically and has three characteristics: - Each unit of R takes an almost constant time T to produce
- Each unit of R costs money to produce
- Each unit of R becomes obselete if it is not used within 60s of production
Moreover, the workers that require R have two caveats as well: - They need R to carry out their tasks. Hence, they block until they recieve a unit.
- There can be multiple worker processes running concurrently.
Keeping these in mind, since production costs money, and there is an expiry time limit, my goal is to produce R in a quanitiy large enough so that the workers block for the least amount of time and small enough so the units don't expire. To manage this, I have the class RManager below: from multiprocessing import Queue, Manager, Lock, managers import logging from functools import wraps from inspect import signature import queue as Q class RManager: minimum = 1 T = 20 # Amount of time required to produce expiryT = 60 # Amount of time after which, if unused, the unit of R becomes useless def __init__(self, q): m = Manager() # The Queue that in which we send requests to produce R self.requestQueue = q # The Queue in which we receive units of R after production self.responseQueue = m.Queue() # To handle concurrent accesss self.instanceLock = Lock() # These will be defined as they are used self.processing = 0 self.total = 0 self.RequestRate = {'rate': 0.0, 'num': 0, 'total_time': 0.0, 'last_request': time.time()} def get_request(self, timeout=60): """ This function is called by workers to request a unit of R""" # We update information about how frequently this method is called in the atrribute 'RequestRate', to gauge how frequently # do the worker(s) require resource R. Basically, we add the time difference between successive calls of this method # and divide that by the number of times this method is called. This gives us the rate of this method being called. with self.instanceLock: self.RequestRate['total_time'] += time.time() - self.RequestRate['last_request'] self.RequestRate['num'] += 1 self.RequestRate['last_request'] = time.time() self.RequestRate['rate'] = self.RequestRate['total_time'] / self.RequestRate['num'] try: R = self.responseQueue.get(timeout=timeout) # We got a unit of R, so we increment the total units recieved. with self.instanceLock: self.total += 1 return R except Q.Empty: return 'timeout' def send_request(self): """ This function is called by workers periodically. It decides how many requests to send to produce resource R based on usage data """ instructions = {'improtant': 'things', 'response': self.responseQueue, 'time': time.time()} # Instructions on how to produce R to_send = RManager.minimum # Number of units of R that would be requested, initialized as minimum allowed if self.total >= 3: # We only go here if have enough collected data about usage with self.instanceLock: # In this we check status of resource availability after time RManager.T to see how many requests we should send # Currently, self.processing number of units of R are being produced. These all units will be definitly finish # production by time RManager.T to_add = self.processing # During the production time RManager.T, there will be units used up as well. This is given by below to_subtract = RManager.T // self.RequestRate['rate'] # We then find the amount of units finally available after time RManager.T keeping in mind there may already be some # present in the responseQueue future_available = self.responseQueue.qsize() + to_add - to_subtract # Now we calculate the amount of time these units will require to be used up total_time = future_available * self.RequestRate['rate'] # Now if the time to use them all up is below expiry time, we can request more units to be added. To do this, we # calculate the optimal amount of units that will need to be produced to keep up with the rate of request. # The number of units needed is then the difference between this value and the units that would actually be available # after RManager.T seconds. if total_time < RManager.expiryT - 15: optimal_future_available = (RManager.expiryT - 15) // self.RequestRate['rate'] to_send = min(optimal_future_available - future_available) # Send requests to produce R for _ in range(to_send): self.requestQueue.put(instructions) # Increment the counter which tells how many units are going to be ready soon with self.instanceLock: self.processing += to_send @staticmethod def requestsManager(requestQueue): """ This staticmethod is called in a separate process from the worker processes which produces R upon request. All requests for units of R are answered within RManager.T time regardless of quantity because production happens simultaneously.""" reqs = [] # Get all requests from queue and store them in a list while True: while True: try: r = requestQueue.get(block=False) except Q.Empty: break else: reqs.append(r) # Mimic production of R. It sends back a supposed unit of R when time for production is over for index, request in enumerate(reqs): if time.time() - request['time'] >= 20: request['response'].put({'R': 'value'}) # Mark request for deletion after it has been services reqs[index] = None # Remove completed requests reqs = [x for x in reqs if x] Basically, I find out how frequently do the workers require R by finding the avg time, RequestRate , between successive calls to get_request function (check comments in get_request function). Using that, I try to predict how many units I would need to procure to keep up (see the comments in send_request function). Hence, if RequestRate is large, lesser requests would be sent to produce R. However, I run into a logical flaw here. The thing is, the get_request function, as mentioned, blocks until a unit of R is recieved. Hence, if production of R is too low, the function will block more frequently for longer times and RequestRate will become larger and larger. This would mean that the production will slow even more since the send_function considers the large RequestRate to mean that not many units of R are required, when infact the converse is True. This issue will be solved if somehow I could remove the time the workers spend inside the get_request function when calculating RequestRate . I cannot just simply calculate the time each worker spends inside the function and subtract that when calculating RequestRate because there could be multiple workers running. In that case RequestRate would most probably be smaller than the time each worker spent inside the function. So my question, as stated in the title, is finding out how frequently (in seconds) a class method is called ignoring the time spent in the function itself given that the function can be accessed by multiple instances concurrently. If this is not possible, can someone suggest a way for me to achieve my original goal, i.e, predicting how much R to produce so that the workers block the least amount of time and it expires the least number of times? |
Upcasting elements in a list of subclasses Posted: 26 Jun 2021 09:25 AM PDT I'm trying to loop through an array of subclasses that have different properties but because my method has to have only one list parameter I only see the properties of the superclass not the other subclasses. I'm trying upcasting the elements (objects) in a loop but that's where I got stuck. public static void printReceipt(ArrayList<Product> list, String time_and_date) { System.out.println("Date: " + time_and_date + "\n"); System.out.println("---Products---" + "\n"); for (int i = 0; i < list.size(); i++) { if (list.get(i) instanceof Clothes) { Product p = new Clothes(); Clothes p2 = (Clothes) p; System.out.println(p2.getColor()); } } } |
python function to transform data to JSON Posted: 26 Jun 2021 09:24 AM PDT Can I check how do we convert the below to a dictionary? code.py message = event['Records'][0]['Sns']['Message'] print(message) # this gives the below and the type is <class 'str'> { "created_at":"Sat Jun 26 12:25:21 +0000 2021", "id":1408763311479345152, "text":"@test I\'m planning to buy the car today \ud83d\udd25\n\n", "language":"en", "author_details":{ "author_id":1384883875822907397, "author_name":"\u1d04\u0280\u028f\u1d18\u1d1b\u1d0f\u1d04\u1d1c\u0299 x NFTs \ud83d\udc8e", "author_username":"cryptocurrency_x009", "author_profile_url":"https://xxxx.com", "author_created_at":"Wed Apr 21 14:57:11 +0000 2021" }, "id_displayed":"1", "counter_emoji":{ } } I would need to add in additional field called "status" : 1 such that it looks like this: { "created_at":"Sat Jun 26 12:25:21 +0000 2021", "id":1408763311479345152, "text":"@test I\'m planning to buy the car today \ud83d\udd25\n\n", "language":"en", "author_details":{ "author_id":1384883875822907397, "author_name":"\u1d04\u0280\u028f\u1d18\u1d1b\u1d0f\u1d04\u1d1c\u0299 x NFTs \ud83d\udc8e", "author_username":"cryptocurrency_x009", "author_profile_url":"https://xxxx.com", "author_created_at":"Wed Apr 21 14:57:11 +0000 2021" }, "id_displayed":"1", "counter_emoji":{ }, "status": 1 } Wanted to know what is the best way of doing this? Update: I managed to do it for some reason. I used ast.literal_eval(data) like below. D2= ast.literal_eval(message) D2["status"] =1 print(D2) #This gives the below { "created_at":"Sat Jun 26 12:25:21 +0000 2021", "id":1408763311479345152, "text":"@test I\'m planning to buy the car today \ud83d\udd25\n\n", "language":"en", "author_details":{ "author_id":1384883875822907397, "author_name":"\u1d04\u0280\u028f\u1d18\u1d1b\u1d0f\u1d04\u1d1c\u0299 x NFTs \ud83d\udc8e", "author_username":"cryptocurrency_x009", "author_profile_url":"https://xxxx.com", "author_created_at":"Wed Apr 21 14:57:11 +0000 2021" }, "id_displayed":"1", "counter_emoji":{ }, "status": 1 } Is there any better way to do this? Im not sure so wanted to check... |
handling arrays in javascript Posted: 26 Jun 2021 09:24 AM PDT I'm new to javascript and react I have an array of data as follows const data = [ { folder_name: "folder 002", file_name: "anh 1.jpg" }, { folder_name: "folder 002", file_name: "anh 2.jpg" }, { folder_name: "folder 002", file_name: "anh 3.jpg" }, { folder_name: "folder 002", file_name: "anh 4.jpg" }, { folder_name: "folder 001", file_name: "anh 1.jpg" }, { folder_name: "folder 001", file_name: "anh 2.jpg" }, { folder_name: "folder 001", file_name: "anh 3.jpg" } ] Please help me split into array like this. Please help me to return the array like this The result I wanted const images = [ { folder_name: 'folder 001', file_name: ['anh 1','anh 2','anh 3'] }, { folder_name: 'folder 002', file_name: ['anh 1','anh 2','anh 3','anh 4'] } ] Thanks you very much |
How to send JSON response object from custom class to another activity android Posted: 26 Jun 2021 09:26 AM PDT I am fetching API data in a custom class (non-activity class). Now I want to parse my JSON response object to Activity Class, but not able to do the same. Kindly held how to send response object from non activity class to Activity Class: Note: I don't want to use Sharedpreference. My Custom Class: public class APIHelper { private static final String baseurl = "myUrl"; private static final String loginAPI = "auth/login"; public void getAPIResponse(Context context, View view, JSONObject parameters) { JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, baseurl + loginAPI, parameters, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { //I want to send this response to another activity... } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { NetworkResponse response = error.networkResponse; if (error instanceof ServerError && response != null) { try { String res = new String(response.data, HttpHeaderParser.parseCharset(response.headers, "utf-8")); JSONObject jsonObject = new JSONObject(res); Utility.showSnackBar(view, jsonObject.getString("message"), "top", "error"); } catch (UnsupportedEncodingException | JSONException e) { e.printStackTrace(); } } } }); RequestQueue queue = Volley.newRequestQueue(context); queue.add(jsonObjectRequest); } } |
I am getting this error when I press the details action link of an item [duplicate] Posted: 26 Jun 2021 09:25 AM PDT Every time I click on details for an item it gives me the error and the id is equal to 0, but if change the id number to anything greater than 1 within the number of items I have it runs properly Here is my method public PhoneModel GetPhone(int id) { using(var context = new ElectronicsDataBaseEntities()) { var result = context.Phone .Where(x => x.Id == id) .Select(x => new PhoneModel() { Name = x.Name, Phonemodel = x.Model, DateReleased = x.DateReleased, Desicription = x.Desicription }) .FirstOrDefault(); return result; } } and this my action method in the controller public ActionResult Details(int id) { var result = repository.GetPhone(id); return View(result); } Index The error idex code index |
Extract chunks from a video Posted: 26 Jun 2021 09:26 AM PDT Based un this answer https://stackoverflow.com/a/52916510/8879659 I wrote the following script #!/bin/bash if [ ! $# -eq 4 ] then echo Usage: ./extractVideoChunk.sh \<inputVideo\> \<chunkStartTime\> \<chunkEndTime\> \<outputFileName\> else toSeconds() { awk -F: 'NF==3 { print ($1 * 3600) + ($2 * 60) + $3 } NF==2 { print ($1 * 60) + $2 } NF==1 { print 0 + $1 }' <<< $1 } StartSeconds=$(toSeconds $2) EndSeconds=$(toSeconds $3) Duration=$(bc <<< "(${EndSeconds} + 0.01) - ${StartSeconds}" | awk '{ printf "%.4f", $0 }') ffmpeg -y -ss $StartSeconds -i $1 -t $Duration -vcodec copy -acodec copy $4 fi # Command usage with 'file input' # file: 'chunks.txt' # input---------------start-----------end-------------output # > Webinar.mp4 0:00:20 0:34:00 Chunk1.mp4 # > Webinar.mp4 0:35:03 1:03:17 Chunk2.mp4 # > Webinar.mp4 1:04:12 1:28:44 Chunk3.mp4 # shell command line # while read l; do echo $l | xargs ./extractVideoChunk.sh; wait; done < chunks.txt It worked for me but it took to long to get it running. The main problem was the last line: how to read input arguments from a file. Is there a more staigthforward solution? |
Stop line animation from run the whole web css Posted: 26 Jun 2021 09:26 AM PDT I need the animation on my page to not float up the whole page but start from where the border above about me section. Code |
Cleanest way to compare a range of two variables? [duplicate] Posted: 26 Jun 2021 09:26 AM PDT So I am new to code and c# and for my first app I have made a basic Console Number Guessing game. Now currently my range for a user to input is between 1-100 which makes it quite difficult for player two to guess this number so I wanted to add some code that allowed for a clue if the user was close or far away (hot and cold) Below I will attach my main method, the methods are just returning a number and currently for test purposes I have stored them in a and b the range statement lower down is what I have tried from looking at others solutions but I think I am just confusing myself. Any explanation would be super helpful and this is my first time using stack so if I am doing something wrong in this post alos public static void Main(string[] args) { var attemps = 0; Opening(); int a = numberProvider(); whitespace(); Nextplayer(); int b = numberguess(); while (a != b) { attemps++; Console.WriteLine("Incorrect please try again you have had " + attemps + " attempts"); if (Enumerable.Range(a, 30).Contains(b)) { Console.WriteLine("You are warm"); } string test = Console.ReadLine(); b = Convert.ToInt32(test); } |
Laravel livewire DOM PDF the file save but not downloaded Posted: 26 Jun 2021 09:24 AM PDT ** I am using DOM PDF to print the html invoice page, the method call by livewire method, The file save correctly to the public folder but i need to download it through browser instead of save it. ** HTML blade view : <div class="m-3 ml-auto"> <button wire:click="exportPDF()" type="button" class="border border-indigo-500 text-indigo-500 rounded-md px-4 py-2 m-2 transition duration-500 ease select-none hover:text-white hover:bg-indigo-600 focus:outline-none focus:shadow-outline"> {{ __('Export PDF') }} </button> </div> livewire method: public function exportPDF() { $order = $this->order; $view = view('order')->with(compact('order')); $html = $view->render(); $pdf = PDF::loadHTML($html)->save(public_path() . '/order.pdf'); ///return $pdf->download('download.pdf'); // $pdf= PDF::loadHTML($html); // return $pdf->download('order.pdf'); } |
How to update a users dat in firebase from android studio Posted: 26 Jun 2021 09:24 AM PDT So basically I created a page where the user can edit his name and email but it doesn't work when and the data remains the same in firebase. I tried calling the update function inside the on-create but that doesn't seem to work I even tried writing the whole code directly inside the on-create but the app crashed so I had decided to create the function update() and I tried calling the the update() function inside on-click but even that didnt work this is my code public class Profile extends AppCompatActivity { private FirebaseUser user; private DatabaseReference reference; private String userID; EditText Username,email; String name,mail; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); Username=findViewById(R.id.Username1); email=findViewById(R.id.emailadress); button=findViewById(R.id.editinfo); user= FirebaseAuth.getInstance().getCurrentUser(); reference= FirebaseDatabase.getInstance().getReference("Users"); userID=user.getUid(); reference.child("Driver").child(userID).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { Users usersnapshot=snapshot.getValue(Users.class); if(usersnapshot!=null){ String username=usersnapshot.getUsername(); String Email=usersnapshot.getMail(); String password=usersnapshot.getPassword(); Username.setText(username); email.setText(Email); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); button.setOnClickListener(new android.view.View.OnClickListener() { @Override public void onClick(android.view.View v) { } }); } public void update(){ if(isNamechanged()||isEmailchanged()){ Toast.makeText(this,"Data has been updated",Toast.LENGTH_LONG).show(); } } public void onCancelled(@NonNull DatabaseError databaseError) { throw databaseError.toException(); } private boolean isEmailchanged() { if (!mail.equals(email.getText().toString())) { reference.child("Driver").child(userID).child("mail").setValue(email.getText().toString()); mail=email.getText().toString(); return true; } else { return false; } } private boolean isNamechanged() { if (!name.equals(Username.getText().toString())) { reference.child("Driver").child(userID).child("username").setValue(Username.getText().toString()); name=Username.getText().toString(); return true; } else { return false; } } } This is my database { "Users" : { "Customer" : { "0awTFPGUkIdzAaZEgYZMmGv1zwk1" : { "mail" : "1@gmai.com", "username" : "1234" } }, "Driver" : { "S04QBZx3PxYaLfDWBC3j3otM5ml1" : { "mail" : "m.yusuf7423@gmail.com", "username" : "YUSUF" } } } } Also now my app started to crash and I get this problem in logcat Process: com.example.deliveryapp, PID: 12806 java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference Edit:in the layout page I added On-click option to call update so now it doesn't crash and doesn't throw any error but now nothing happens at all like I can here the sound of the button being clicked(which happens when there is an onclick function) but nothing happens at all this is the layout of that button <Button android:id="@+id/editinfo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="228dp" android:layout_marginLeft="228dp" android:layout_marginTop="456dp" android:onClick="update" android:text="edit" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> |
How can I fix Face Recognition operands error? Posted: 26 Jun 2021 09:26 AM PDT import face_recognition from PIL import Image, ImageDraw burak_image= face_recognition.load_image_file("C:/Users/EMRE/Desktop/codfacerecog-master/codfacerecog-master/recognize/friends2/burak1.jpg") burak_face_encoding = face_recognition.face_encodings(burak_image) cansu_image= face_recognition.load_image_file("C:/Users/EMRE/Desktop/codfacerecog-master/codfacerecog-master/recognize/friends2/cansu1.jpg") cansu_face_encoding = face_recognition.face_encodings(cansu_image) elif_image= face_recognition.load_image_file("C:/Users/EMRE/Desktop/codfacerecog-master/codfacerecog-master/recognize/friends2/elif2.jpg") elif_face_encoding = face_recognition.face_encodings(elif_image) mert_image= face_recognition.load_image_file("C:/Users/EMRE/Desktop/codfacerecog-master/codfacerecog-master/recognize/friends2/mert2.jpg") mert_face_encoding = face_recognition.face_encodings(mert_image) merve_image= face_recognition.load_image_file("C:/Users/EMRE/Desktop/codfacerecog-master/codfacerecog-master/recognize/friends2/merve1.jpg") merve_face_encoding = face_recognition.face_encodings(merve_image) known_face_encodings = [ burak_face_encoding, cansu_face_encoding, elif_face_encoding, mert_face_encoding, merve_face_encoding ] known_face_names = [ "BURAK", "CANSU", "ELIF" , "MERT" , "MERVE" ] image = face_recognition.load_image_file("C:/Users/EMRE/Desktop/codfacerecog-master/codfacerecog-master/recognize/friends2/friends2.jpg") face_locations = face_recognition.face_locations(image) face_encodings = face_recognition.face_encodings(image, face_locations) pil_image = Image.fromarray(image) draw = ImageDraw.Draw(pil_image) for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): name = "UNKNOWN" for i,f in enumerate(known_face_encodings): matches = face_recognition.compare_faces(f, face_encoding) if True in matches: name = known_face_names[i] break if True in matches: first_match_index = matches.index(True) name = known_face_names[first_match_index] draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 255)) text_width, text_height = draw.textsize(name) draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(48, 63, 159), outline=(48, 63, 159)) draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 0)) del draw pil_image.show() pil_image pil_image.save("image_with_boxes.jpg") MY PROBLEM IS that It shows only one person's name on identified faces.It only shows first known_face_names("BURAK")shows only one person's name on all identified faces; tags of identified people with the same name. |
How can I get the all of the img src by using scrapy? Posted: 26 Jun 2021 09:25 AM PDT try to do in scrapy shell >>>scrapy shell 'https://www.trendyol.com/trendyolmilla/cok-renkli-desenli-elbise-twoss20el0573-p-36294862' >>> response.css("div.slick-slide img").xpath("@src").getall() Output is : ['/Content/images/defaultThumb.jpg', '/Content/images/defaultThumb.jpg', '/Content/images/defaultThumb.jpg', '/Content/images/defaultThumb.jpg', '/Content/images/defaultThumb.jpg', 'https://cdn.dsmcdn.com/mnresize/415/622/ty124/product/media/images/20210602/12/94964657/64589619/1/1_org_zoom.jpg', 'https://cdn.dsmcdn.com/mnresize/415/622/ty124/product/media/images/20210602/12/94964657/64589619/1/1_org_zoom.jpg'] only collect one image but in provided link have 5 image. Please help me to out this problem. How to find all of the image src. |
Use AD B2C and MSAL v2 with Angular allowing selective unprotected Web API calls Posted: 26 Jun 2021 09:23 AM PDT My goal is to allow users to freely browse an Angular 11+ site, reading data called from a .NET Web API as they navigate. Only users who wish to post data or access particular features would need to sign up and sign in, using AD B2C identity services. Accordingly, controllers in the backend app service are marked with [Authorize] or [AllowAnonymous] as appropriate. The site successfully supports browsing and posting for signed-in users, copying the approach from the AzureAD sample. export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration { const protectedResourceMap = new Map<string, Array<string>>(); protectedResourceMap.set(apiConfig.uri, apiConfig.scopes); return { interactionType: InteractionType.Redirect, protectedResourceMap }; } However, using that approach, the Msal's httpInterceptor evidently fires for every database call, forcing a B2C signup/login event on all endpoints, defeating the effort to support anonymous browsing. MSAL v1 apparently supported an unprotectedResource array, but that was deprecated for v2. It also apparently supported the use of null patterns such as const resourceMap: [string, string[]][] = [ [`${apiBaseUrl}/health`, null], [`${apiBaseUrl}`, ['scope1', 'scope2']], ]; Since that v1 object has a different shape I tried it this way in v2, but to no avail const protectedResourceMap = new Map<string, Array<string>>(); protectedResourceMap.set(apiConfig.uri + '/myreadabledata', []); protectedResourceMap.set(apiConfig.uri, apiConfig.scopes); I've tried other approaches such as setting the protectedResourceMap exclusively for the controllers that require authorization. That failed as well. const protectedResourceMap = new Map<string, Array<string>>(); protectedResourceMap.set(apiConfig.uri + '/mycloseddata1' , apiConfig.scopes); protectedResourceMap.set(apiConfig.uri + '/mycloseddata2' , apiConfig.scopes); What is the correct way to achieve this? |
How to use stencil buffer to achieve hierarchical clipping Posted: 26 Jun 2021 09:24 AM PDT What I'm trying to achieve is illustrated on the image below: Let's say we have stencil buffer in a state so only red section is filled at the moment. What actions do I need to perform when I update stencil buffer with a section which is marked yellow, so in the end only green section would be the final state of the stencil buffer? I need this to achieve nested element content clipping, to prevent content of the element to be rendered beyond the boundaries of them both combined. So far I have tried various boolean operations involving stencil test to no avail, which brought more confusion than any progress. Please note that scissor test is not actual for this task, because elements may have arbitrary shape and rotation. |
Symfony getData event subscriber is null Posted: 26 Jun 2021 09:24 AM PDT I know this question has been asked already a couple of times, but there hasn't been an answer that actually helped me solving my problem. I've got three EventSubscribers for three Dropdowns who are dependent on each other. So in my FormType I say: public function buildForm(FormBuilderInterface $builder, array $options) { // solution showmethecode $pathToAgencies = 'agencies'; // $builder ->addEventSubscriber(new AddChannel1Subscriber($pathToAgencies)) ->addEventSubscriber(new AddChannel3Subscriber($pathToAgencies)) ->addEventSubscriber(new AddAgencySubscriber($pathToAgencies)); } and one of my EventSubscribers looks like that: ... ... public static function getSubscribedEvents() { return array( FormEvents::PRE_SET_DATA => 'preSetData', FormEvents::PRE_SUBMIT => 'preSubmit' ); } private function addChannel1Form($form, $channel1s = null) { $formOptions = array( 'class' => 'AppBundle:Channel1', 'property' => 'name', 'label' => 'label.channel1s', 'empty_value' => 'label.select_channel1s', 'mapped' => false, 'expanded' => false, 'translation_domain' => 'UploadProfile', 'multiple' => true, 'required' => false, 'attr' => array( 'class' => 'channel1s' ), ); if ($channel1s){ $formOptions['data'] = $channel1s; } $form->add('channel1s', 'entity', $formOptions); } public function preSetData(FormEvent $event) { $data = $event->getData(); $form = $event->getForm(); if (null === $data) { return; } $accessor = PropertyAccess::createPropertyAccessor(); $agency = $accessor->getValue($data, $this->pathToAgency); $channel1s = ($agency) ? $agency->getChannel3s()->getChannel1s() : null; $this->addChannel1Form($form, $channel1s); } public function preSubmit(FormEvent $event) { $form = $event->getForm(); $this->addChannel1Form($form); } ... Now I'm getting the error "Attempted to call an undefined method named "getChannel3s" of class "Doctrine\Common\Collections\ArrayCollection"." and (I think) this is because my $data in my preSetData is NULL but I don't know why it's null. Am I looking at the wrong spot or where is my mistake here? |
Laravel DB::table AND statement? Posted: 26 Jun 2021 09:26 AM PDT I'm very new to Laravel and don't quite understand the DB::table method in conjuction with an AND clause. So I have this query at the moment: $query = DB::select( DB::raw("SELECT * FROM tablethis WHERE id = '$result' AND type = 'like' ORDER BY 'created_at' ASC")); It is working, but I'd like to use Laravel's Query Builder to produce something like: $query = DB::table('tablethis')->where('id', '=', $result)->where('type', '=', 'like')->orderBy('created_at', 'desc') But this seems to ignore the second where() completely. So, basically how do I make this work? |
.htaccess redirect all pages to new domain Posted: 26 Jun 2021 09:23 AM PDT Which redirect rule would I use to redirect all pages under olddomain.example to be redirected to newdomain.example ? The site has a totally different structure, so I want every page under the old domain to be redirected to the new domain index page. I thought this would do (under olddomain.example base directory): RewriteEngine On RewriteRule ^(.*)$ http://newdomain.example/ [R=301] But if I navigate to olddomain.example/somepage I get redirected to newdomain.example/somepage . I am expecting a redirect only to newdomain.example without the page suffix. How do I keep the last part out? |
No comments:
Post a Comment