Regex invert selection Posted: 06 May 2021 08:17 AM PDT I looked around quit a bit but was unable to find an answer to this question. I'm trying to select everything from a string except white spaces that repeat over a certain number of times. I've found a regex to select the white spaces, and what I was hoping for was an easy way to get the exact inverse of this, but I haven't found a way to do that yet. I'm ultimately going to implement this in python if that matters. Below is my test string, current regex, and link to the regex test site I was using. Current regex test string: 'All: Day and Night Vulnerabilities\\Personnel vulnerabilities\\Outdoor vulnerability 1E-09 /AvgeYear \x1a' Regex: [ ]{50,} |
Oracle PLSQL cursor function Posted: 06 May 2021 08:17 AM PDT I have the below function. CREATE OR REPLACE FUNCTION pick_values RETURN t1_table PIPELINED IS TYPE t2_type IS TABLE OF t2%rowtype; t2_data t2_type; BEGIN -- https://stackoverflow.com/a/67398434/1509264 -- License: CC BY-SA 4.0 SELECT * BULK COLLECT INTO t2_data FROM t2; FOR cur IN ( SELECT * FROM t1 ORDER BY r ) LOOP DECLARE a_freqs int_list := int_list(); cum_freq INT := 0; taken string_list := split_string(cur.an, ', '); idx INT; c t2.a%TYPE; BEGIN a_freqs.extend(t2_data.count); FOR i IN 1..t2_data.count LOOP IF ( t2_data(i).a = cur.ay AND t2_data(i).c > 0 ) OR ( cur.ay IS NULL AND t2_data(i).a NOT MEMBER OF taken AND t2_data(i).c > 0 ) THEN a_freqs(i) := cum_freq + t2_data(i).c; cum_freq := cum_freq + t2_data(i).c; ELSE a_freqs(i) := cum_freq; END IF; END LOOP; IF cum_freq > 0 THEN idx := floor(dbms_random.value(0, cum_freq)); FOR i IN 1..t2_data.count LOOP IF idx < a_freqs(i) THEN c := t2_data(i).a; t2_data(i).c := t2_data(i).c - 1; EXIT; END IF; END LOOP; END IF; PIPE ROW ( t1_data(cur.vk, cur.ay, cur.an, cur.r, c) ); END; END LOOP; END; However, I'm struggling to understand the below lines: a_freqs(i) := cum_freq + t2_data(i).c; cum_freq := cum_freq + t2_data(i).c; ELSE a_freqs(i) := cum_freq; Could you please help me on what do these lines do? A line over the code with a brief explanation would do. Thanks! PD: kindly let me know if you need additional info. However, there's the link to the original SO question in the function code. |
capture values in the parentheses and breackpair with regexp Posted: 06 May 2021 08:17 AM PDT ello guys my problem is as follows, I'm making a sort of transpiler in js, which turns my language into js, and i'm using regexp for substitutions, the replacement you want to do is this: when(teste =="teste"){ console.put(teste) console.put(teste2) } and i expect enventer.on($1,()=>{$2}) i'am use replace in js for this, but i can't include when the break a new line, the regexp not capture I want to get the values in parentheses after the when, and the value inside the braces |
ArchUnit test importOptions DoNotIncludeTests not working Posted: 06 May 2021 08:17 AM PDT I'm using ArchUnit 0.18 and archunit-junit5 from a Spring 2.3.8 application. For some reason I can't find, ImportOption.DoNotIncludeTests.class is not working as expected and test classes are also included. I can only get the ArchUnit test working by commenting the code in those tests classes. ArchUnit test is: import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.core.importer.ImportOption; import com.tngtech.archunit.junit.AnalyzeClasses; import org.junit.jupiter.api.Test; @AnalyzeClasses(packages = "com.petproject", importOptions = { ImportOption.DoNotIncludeTests.class }) class ArchitectureTest { @Test public void some_architecture_rule() { JavaClasses classes = new ClassFileImporter().importPackages("com.petproject"); layeredArchitecture() .layer("Controller").definedBy("com.petproject.controller") .layer("Validators").definedBy("com.petproject.validations.validators") .layer("Service").definedBy("com.petproject.service") .layer("Persistence").definedBy("com.petproject.repository") .whereLayer("Controller").mayNotBeAccessedByAnyLayer() .whereLayer("Service").mayOnlyBeAccessedByLayers("Controller", "Validators") .check(classes); } } Am I missing some step in order to not get into account test classes? Thanks! |
How to add custom color scheme for syntax highlighting in a Text Editor using gtk source view and XML Posted: 06 May 2021 08:16 AM PDT I had built a text editor using gtk . It is a very simple text editor. I want to add syntax highlighting using gtk source view (probably). I want to use a custom style sheet in XML file format which I made for this text editor. How can I add syntax highlighting to my text editor ? And want to use my custom color scheme. And where to put that XML file ? Please any suggestions ! |
Combine multiple selectors with the same attribute selector into one selector in CSS Posted: 06 May 2021 08:18 AM PDT Is it possible in CSS/SASS/LESS to combine multiple selectors with the same attribute into one selector without repeating the attribute? For example: div.foo[data="123"] { color: red; } p.bar[data="123"] { color: red; } p.bar[data="123"], div.foo[data="123"]{ color: red; } Combine them somehow? Such as this invalid scenario: (div.foo, p.bar)[data = "123"] { color: red; } |
How do I find the largest empty space in such images? Posted: 06 May 2021 08:17 AM PDT I would like to find the empty spaces in similar images to the one I've posted below, where I have randomly sized blocks scattered in it. By empty spaces, I refer to such possible open fields ( i have no particular lower bound on the area, but I would like to extract the top 3-4 largest ones present in the image.) There is also no restriction on the geometric shape they can take, but these empty spaces must not contain any of these blocks. What is the best way to go about this? What I've done till now: My original image actually looks like this. I identified all the points, grouped them based on a certain distance threshold and applied a convex hull around them. I'm unsure how to proceed further. Any help would be greatly appreciated. Thank you! |
How can I combine two react objects? Posted: 06 May 2021 08:17 AM PDT const a = [ 0: {market: "KRW-BTC", korean_name: "비트코인", english_name: "Bitcoin"} 1: {market: "KRW-ETH", korean_name: "이더리움", english_name: "Ethereum"} 2: {market: "KRW-NEO", korean_name: "네오", english_name: "NEO"} 3: {market: "KRW-MTL", korean_name: "메탈", english_name: "Metal"} 4: {market: "KRW-LTC", korean_name: "라이트코인", english_name: "Litecoin"} 5: {market: "KRW-XRP", korean_name: "리플", english_name: "Ripple"} 6: {market: "KRW-ETC", korean_name: "이더리움클래식", english_name: "Ethereum Classic"} 7: {market: "KRW-OMG", korean_name: "오미세고", english_name: "OmiseGo"} 8: {market: "KRW-SNT", korean_name: "스테이터스네트워크토큰", english_name: "Status Network Token"} 9: {market: "KRW-WAVES", korean_name: "웨이브", english_name: "Waves"} 10: {market: "KRW-XEM", korean_name: "넴", english_name: "NEM"} 11: {market: "KRW-QTUM", korean_name: "퀀텀", english_name: "Qtum"} 12: {market: "KRW-LSK", korean_name: "리스크", english_name: "Lisk"} ] const b = [ 0: {market: "KRW-BTC", trade_date: "20210506", trade_time: "144435", trade_date_kst: "20210506", trade_time_kst: "234435", …} 1: {market: "KRW-ETH", trade_date: "20210506", trade_time: "144436", trade_date_kst: "20210506", trade_time_kst: "234436", …} 2: {market: "KRW-NEO", trade_date: "20210506", trade_time: "144436", trade_date_kst: "20210506", trade_time_kst: "234436", …} 3: {market: "KRW-MTL", trade_date: "20210506", trade_time: "144432", trade_date_kst: "20210506", trade_time_kst: "234432", …} 4: {market: "KRW-LTC", trade_date: "20210506", trade_time: "144433", trade_date_kst: "20210506", trade_time_kst: "234433", …} 5: {market: "KRW-XRP", trade_date: "20210506", trade_time: "144436", trade_date_kst: "20210506", trade_time_kst: "234436", …} 6: {market: "KRW-ETC", trade_date: "20210506", trade_time: "144437", trade_date_kst: "20210506", trade_time_kst: "234437", …} 7: {market: "KRW-OMG", trade_date: "20210506", trade_time: "144437", trade_date_kst: "20210506", trade_time_kst: "234437", …} 8: {market: "KRW-SNT", trade_date: "20210506", trade_time: "144434", trade_date_kst: "20210506", trade_time_kst: "234434", …} 9: {market: "KRW-WAVES", trade_date: "20210506", trade_time: "144436", trade_date_kst: "20210506", trade_time_kst: "234436", …} 10: {market: "KRW-XEM", trade_date: "20210506", trade_time: "144436", trade_date_kst: "20210506", trade_time_kst: "234436", …} 11: {market: "KRW-QTUM", trade_date: "20210506", trade_time: "144436", trade_date_kst: "20210506", trade_time_kst: "234436", …} 12: {market: "KRW-LSK", trade_date: "20210506", trade_time: "144436", trade_date_kst: "20210506", trade_time_kst: "234436", …} ] There are two like this, and I want to merge them based on the 'market'. Is there any way to merge?? I'm not sure because I'm a beginner in React. |
Center div over canvas element Posted: 06 May 2021 08:16 AM PDT Using react-globe , I'm trying to center a div with a message over the canvas element that can also be removed once a user interacts with the globe. I have the div in the page, but can't get it centered over the canvas element. Current state: Link |
DomXPath Matching an element that it shouldn't [duplicate] Posted: 06 May 2021 08:16 AM PDT i'm trying to match any element which has the class app . However for some reason some HTML is being match which doesn't have that class. This is the HTML: <div class="page-hdr page-hdr--{BODY_ID} lazy-background"> <h1>{PAGE_H1_TAG}</h1> </div>dsdsadsa <div id="page-warrior"> <div id="{BODY_ID}-pg"> <div class="wrapper"> <div class="container"> <div class="row"> <script src="js-src/themev2/dsada.js"></script> {PAGE_TEXT}dsadsadsadsaddsdsadsadsadadsadas </div> </div> </div> </div> </div> This is the code i'm using to match: $document = new \DOMDocument(); @$document->loadHTML($content); $finder = new \DomXPath($document); $nodes = $finder->query('//*[contains(@class, "app")]'); $lastComponentId = null; /** @var \DOMElement $node */ foreach ($nodes as $node) { dd($node->getLineNo()); The dd displays: 6 However none of that HTML actually has the class of app ... |
Python convert daily column into a new dataframe with year as index week as column Posted: 06 May 2021 08:17 AM PDT I have a data frame with the date as an index and a parameter. I want to convert column data into a new data frame with year as row index and week number as column name and cells showing weekly mean value. I would then use this information to plot using seaborn https://seaborn.pydata.org/generated/seaborn.relplot.html . My data: df = data 2019-01-03 10 2019-01-04 20 2019-05-21 30 2019-05-22 40 2020-10-15 50 2020-10-16 60 2021-04-04 70 2021-04-05 80 My code: # convert the df into weekly averaged dataframe wdf = df.groupby(df.index.dt.strftime('%Y-%W')).data.mean() wdf 2019-01 15 2019-26 35 2020-45 55 2021-20 75 Expected answer: Column name denotes the week number, index denotes the year. Cell denotes the sample's mean in that week. 01 20 26 45 2019 15 NaN 35 NaN # 15 is mean of 1st week (10,20) in above df 2020 NaN NaN NaN 55 2021 NaN 75 NaN NaN No idea on how to proceed further to get the expected answer from the above-obtained solution. |
Is there any solution for 2D arrays? Posted: 06 May 2021 08:17 AM PDT Create a .NET application for Following Using 2 D Array. | 1 2 3 | | 9 8 7 | | 10 10 10 | | 2 3 4 | + | 8 7 6 | = | 10 10 10 | | 5 6 7 | | 5 4 3 | | 10 10 10 | My attempt:: Module arrayApl Sub Main() ' an array with 3 rows and 3 columns Dim a(,) As Integer = {{1, 2,3}, {2,3,4}, {5,6,7}} Dim b(,) As Integer = {{9,8,7}, {8,7,6}, {5,4,3}} Dim i, j As Integer ' output each array element's value ' For i = 0 To 4 For j = 0 To 1 Console.WriteLine("a[{0},{1},{2}]+b[{0},{1},{2}] = {3}", i, j, a(i, j)) Next j Next i Console.ReadKey() End Sub End Module I had tried my best but wont get it. |
How can we identify the timezone of date & time we are getting in MS Graph API response? Posted: 06 May 2021 08:17 AM PDT I am getting the following response from MS Graph API while fetching all sections. ( [id] => 0-92b00000!86-AAAAAAAAAAAF1FC8!132 [self] => https://graph.microsoft.com/v1.0/users/testtt [createdDateTime] => 2021-03-19T09:37:35Z [title] => ABCDEF [createdByAppId] => [contentUrl] => https://graph.microsoft.com/v1.0/users/aaaaa [lastModifiedDateTime] => 2021-03-19T09:37:49Z ) In the above part of response, I want to identify the timezone of the server or this "lastModifiedDateTime". Advance thanks for your help. |
Dropdown not appearing on click Posted: 06 May 2021 08:17 AM PDT I am trying to add a dropdown menu so when the page is viewed on mobile the user can click and access all the pages available. I am not getting any type of error code, just no response. Below are the snippets of HTML, CSS and JavaScript that should be affecting the code. Thanks for taking the time to read through this. /*When user clicks name on shows dropdown menu allowing for nav on smaller viewports */ function dropDown() { document.getElementById("dropNav").classList.toggle("show"); } //close drop down if clicked outside window.onclick = function(event) { if (!event.target.matches('dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } .dropbtn { background-color: white; color: #000; padding: 8px 16px; font-size: 16px; border: none; cursor: pointer; } .dropbtn:hover .dropbtn:focus { background-color: #f1f1f1; } /* menu below button*/ .dropdown { position: relative; display: inline-block; } /* hidden dropdown, using z to plac in front of other elements */ .dropdown-content { display: none; position: absolute; background-color: #f1f1f1; min-width: 100px; box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover { background-color: goldenrod } .show { display: block; } <div class="dropdown"> <button onclick="dropDown()" class="dropbtn"><b>AH</b>NAME</button> <div id="dropNav" class="dropdown-content"> <a href="index2.html">Portfolio</a> <a href="about.html">About</a> <a href="contact.html">Contact</a> <a href="Travels.html">Travels</a> <a href="webSecurity.html">Web Security Information</a> </div> </div> |
Invalid salt in bcrypt(python) after updating password in mongoengine Posted: 06 May 2021 08:16 AM PDT I was using bcrypt to hash the passwords before storing in mongoDb using mongoengine. The login was also working fine after storing the initial user. I added an option to update password and after I try to do the login with the updated password I get the following error which matching the password- ValueError: Invalid salt I am attaching the Document class below: class Donator(Document): meta = {'collection': 'Donator'} user_name = StringField(required=True, unique=True) password = StringField(required=True) date_last_update = DateTimeField(default=datetime.utcnow) This is how I am doing the POST, PUT and login salt = bcrypt.gensalt(8) def add_donator_from_request(request): donor_old = get_donator_from_username(request.form['user_name']) if donor_old is not None: return "Donor already exist with username : " + str(request.form['user_name']), 401 hashed = bcrypt.hashpw(request.form['password'].encode("utf-8"), salt) donor = Donator(password=hashed, user_name=request.form['user_name']) donor.save() return donor.to_json(), 201 def login(request): donor = get_donator_from_username(request.form['user_name']) if donor is None: return "Donor does not exist with username: " + str(request.form['user_name']), 404 else: password_utf8 = request.form['password'].encode("utf-8") if bcrypt.checkpw(password_utf8, donor.password.encode("utf-8")): return donor.to_json(), 200 else: return "Wrong password for given username: " + str(request.form['user_name']), 401 def update_password_from_request(request): donor = get_donator_from_username(request.form["user_name"]) if donor is None: return "Donor does not exist with username: " + str(request.form['donator_id']), 404 else: hashed = bcrypt.hashpw(request.form['password'].encode("utf-8"), salt) donor.update(password=str(hashed), date_last_update=datetime.utcnow) donor.reload() return donor.to_json(), 201 If I don't put the str() on hashed password while updating I get the following error mongoengine.errors.ValidationError: StringField only accepts string values But while making the object initially the same line of code works fine without any issue. I am unable to understand where I am going wrong. Thanks |
tkinter does not properly display data with check buttons Posted: 06 May 2021 08:17 AM PDT I'm making something like to do list with check buttons which idicates status of task (done or to do). Check button makes callback and change status. I think everything connected with 'backyard' works. When I click button, status in object changes, but it doesn't display properly. When I display list of tasks for the first time, it displays everything correctly, but trouble comes up when I add another task to existing list and trying to display it. I figure it out that maybe somehow it overwrites task on existing objects, but honsetly I have no clue how to fix this.... Here is code: c_body (file with class): import datetime class CalendarObj: def __init__(self, task, date, time, stat = False): self.task = task self.stat = stat self.date = date self.time = time def displayObj(self): return self.task + ' ' + self.date + ' ' + self.time def nowDate(): date = datetime.datetime.today().strftime("%d %B") return date def nowTime(): time = datetime.datetime.today().strftime("%H:%M") return time c_view: import c_body from tkinter import * calendar = [] status = [] checkbuttons = [] textlist = [] def config(): global listback, main_root, button_display_list, button_add_task, button_delete_task, button_delete_all_done, button_exit_app main_root = Tk() main_root.title('Lista zadan') main_root.geometry("500x500") button_display_list = Button(main_root, text='Display Tasks', width=12, command=display) button_display_list.grid(column=0, row=4) button_add_task = Button(main_root, text='Add Task', width=12, command=add) button_add_task.grid(column=0, row=0) button_delete_task = Button(main_root, text='Delete Task', width=12) button_delete_task.grid(column=0, row=1) button_delete_all_done = Button(main_root, text='Delete All Done', width=12) button_delete_all_done.grid(column=0, row=2) button_exit_app = Button(main_root, text='EXIT', width=12, command=exit_window) button_exit_app.grid(column=0, row=3) def exit_window(): main_root.destroy() def add(): global task, button_add insert_root = Tk() insert_root.title('Dodaj zadanie:') task = Entry(insert_root, width=80) task.grid(column=0, row=0, padx=20, pady=20) def add_task(): global task_obj, calendar date = c_body.CalendarObj.nowDate() time = c_body.CalendarObj.nowTime() task_obj = c_body.CalendarObj(task.get(), date, time) calendar.append(task_obj) insert_root.destroy() button_add = Button(insert_root, text='dodaj zadanie', command=add_task) button_add.grid(column=0, row=1, sticky=E, padx=20, pady=20) insert_root.mainloop() def callback_on_checkbutton_click(): print("One of the Checkbuttons clicked!") for i in range(len(calendar)): print('\tOld calendar[' + str(i) + '] state: ' + calendar[i].displayObj()) calendar[i].stat = status[i].get() print('\t\tNew calendar[' + str(i) + '] state: ' + calendar[i].displayObj()) def display(): for i in range(len(calendar)): lp = i + 1 print("status dla:", lp, calendar[i].stat) x = (str(lp) + '. ' + calendar[i].displayObj()) textlist.append(x) status.append(BooleanVar()) if calendar[i].stat == False: print("display() called. For index i: ", i, ' setting checkbutton value to checked (onvalue=0)') status[i].set(False) elif calendar[i].stat == True: print("display() called. For index i: ", i, ' setting checkbutton value to unchecked (offvalue=1)') status[i].set(True) checkbuttons.append( Checkbutton( master=main_root, text=textlist[i], variable=status[i], onvalue=True, offvalue=False, command=callback_on_checkbutton_click ) ) checkbuttons[i].grid(column=1, row=i, sticky=W) if __name__ == '__main__': config() main_root.mainloop() |
Zero-padding an image Posted: 06 May 2021 08:17 AM PDT I am trying to do zero-padding manually but getting the following error: ValueError: operands could not be broadcast together with shapes (2,) (512,3) If someone can correct this code or provide a manual without the use of a built in function. Thanks. def pad(img,layers): #img should be rectangular return [[0]*(len(img[0])+2*layers)]*layers + \ [[0]*layers+r+[0]*layers for r in img] + \ [[0]*(len(img[0])+2*layers)]*layers pad(img,2) |
Splitting columns by values in a lookup table in R Posted: 06 May 2021 08:17 AM PDT I have a table, one one line per hpo_term so a single patient can have many lines per ID. ID hpo_term 123 kidney failure 123 hand tremor 123 kidney transplant 432 hypertension 432 exotropia 432 scissor gait I have two other tables, one with kidney terms and other with non kidney terms, the kidney one looks like this: kidney failure kidney transplant hypertension The non kidney one looks like this: hand tremor exotropia scissor gait My desired outcome would be a table like this: ID kidney_hpo_term non_kidney_hpo_term 123 kidney failure;kidney transplant hand tremor 432 hypertension exotropia;scissor gait In reality there are hundreds of patients and hundreds of HPO terms. I have access to base R; dplyr but I really don't know how one would approach this problem. Your help would be much appreciated. Many thanks |
How add point when my ball touch basket? how to determine the touch of the ball and basket? Posted: 06 May 2021 08:17 AM PDT how can I detect the touch of the ball and basket and add a point to the score? I have a ball and basket. the basket moves on the x-axis. Ball - y-axis when pressed Please, help me override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val basket: ImageView = findViewById(R.id.imageViewBasket) val basketball: ImageView = findViewById(R.id.imageViewBasketball) val textViewScore: TextView = findViewById(R.id.textViewScore) var score = 0 val wm: WindowManager = windowManager val disp: Display = wm.defaultDisplay val size = Point() disp.getSize(size) val screenWidth = size.x val screenHeight = size.y var ballY = basketball.y var ballX = basketball.x val basketX = basket.x val basketY = basket.y var ballCenterX = ballX + basketball.width /2f val ballCenterY = ballY + basketball.height /2 val animationFromLeftToRight = TranslateAnimation(0f, 750f, 0f, 0f) animationFromLeftToRight.apply { duration = 2000 repeatMode = Animation.RELATIVE_TO_PARENT repeatCount = -1 } basket.startAnimation(animationFromLeftToRight) basketball.setOnClickListener { val ballUp = TranslateAnimation(0f, 0f, 0f, -1500f) ballUp.apply { duration = 700 repeatMode = Animation.RESTART } basketball.startAnimation(ballUp) } } |
Image in android home screen widget loaded through Picasso only updates sometimes Posted: 06 May 2021 08:17 AM PDT I am working on an Android home screen widget, which selects a random image url from an array of urls (obtained from firebase database), and displays that image. The widget updates every 30 minutes, and should, therefore, display a new image every 30 minutes or so. I'm using Picasso to display the image from the url. RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget); if (currentWidget.url.length() > 0) { final RoundCornersTransformation transformation = new RoundCornersTransformation(50, 0); Picasso.get().load(currentWidget.url).memoryPolicy(MemoryPolicy.NO_CACHE).transform(transformation).into(new Target() { @Override public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from){ Log.d("PICASSO", "Bitmap Loaded"); views.setImageViewBitmap(R.id.appwidget_image, bitmap); } @Override public void onBitmapFailed(Exception e, Drawable errorDrawable) { Log.d("PICASSO", "Bitmap Failed"); } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { Log.d("PICASSO", "Bitmap Prepared"); } }); } I have tested the url, and it is updating regularly, and there is no logical error in the code, as the image is displayed sometimes. But, most of the times, even when the url updates and I get "Bitmap Loaded" in the console, the image in the widget does not update. |
Terraform Merge two list with identical structure Posted: 06 May 2021 08:17 AM PDT Need help on this : How to merge two identical app - id & Values [App Role & Oauth scope] for same app. Any help is appreciated !!! oauth_merge_permissions = [ { App1 = { role1 = "729e1819-d582-d503-deff-2be33394cee5" role2 = "fb9b9a2d-2653-ad21-556b-67b40742f4e1" role3 = "f9dbd854-e42e-298e-c7d6-ba068d67261d" role4 = "5324f064-ac54-db19-16c0-0510a3b979dc" role5 = "d1577294-3870-e465-c433-e036bd2d624c" role6 = "c13d1bc7-ffc2-dd8c-001e-c42c7c1b32cc" } }, { App1 = { test = "da2a01d8-9865-412b-b7ef-f48f1e56e481" user_impersonation = "7b31ca60-1333-4620-9582-012f25f4da05" } }, { App2 = { role5 = "d1577294-3870-e465-c433-e036bd2d624c" role6 = "c13d1bc7-ffc2-dd8c-001e-c42c7c1b32cc" } } ] Desired Output: I would get below output so that i can able to utilize this output in azuread_application API permission. Result = [ { App1 = { role1 = "729e1819-d582-d503-deff-2be33394cee5" role2 = "fb9b9a2d-2653-ad21-556b-67b40742f4e1" role3 = "f9dbd854-e42e-298e-c7d6-ba068d67261d" role4 = "5324f064-ac54-db19-16c0-0510a3b979dc" role5 = "d1577294-3870-e465-c433-e036bd2d624c" role6 = "c13d1bc7-ffc2-dd8c-001e-c42c7c1b32cc" test = "70efda02-14a2-48f2-9297-8d86e7737438" user_impersonation = "e100b04b-fb46-b764-8ae9-513e1f1cd469" } }, { App2 = { role5 = "d1577294-3870-e465-c433-e036bd2d624c" role6 = "7b31ca60-1333-4620-9582-012f25f4da05" } } ] |
How to "inverse" list in python? Like Inverse Function Posted: 06 May 2021 08:16 AM PDT I have some complicated function called dis(x) , which returns a number. I am making two lists called let's say ,,indices'' and ,,values''. So what I do is following: for i in np.arange(0.01,4,0.01): values.append(dis(i)) indices.append(i) So i have following problem, how do i find some index j (from indices), which dis(j) (from values) is closest to some number k. |
Bars are showing up even when value is zero - Google Charts Posted: 06 May 2021 08:18 AM PDT I have created a monthly chart using Google charts but the bars are showing up even when the value is zero. Here is the screenshot of it and here is the code and I know code is vulnerable to SQL Injection. You can ignore it. This is only for testing purpose Previously order_total_amount column was set to "VARCHAR" datatype, then someone suggested that it should set to the "INT". So I changed it from Varchar to Int. But that didn't solved the problem. Bar is still showing up despite having 0 value <script type="text/javascript"> google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Monthly', 'Sales'], <?php $sale_chart = "SELECT SUM(IF(month = 'Jan', total, 0)) AS 'Jan', SUM(IF(month = 'Feb', total, 0)) AS 'Feb', SUM(IF(month = 'Mar', total, 0)) AS 'Mar', SUM(IF(month = 'Apr', total, 0)) AS 'Apr', SUM(IF(month = 'May', total, 0)) AS 'May', SUM(IF(month = 'Jun', total, 0)) AS 'Jun', SUM(IF(month = 'Jul', total, 0)) AS 'Jul', SUM(IF(month = 'Aug', total, 0)) AS 'Aug', SUM(IF(month = 'Sep', total, 0)) AS 'Sep', SUM(IF(month = 'Oct', total, 0)) AS 'Oct', SUM(IF(month = 'Nov', total, 0)) AS 'Nov', SUM(IF(month = 'Dec', total, 0)) AS 'Dec' FROM (SELECT MIN(DATE_FORMAT(order_date, '%b')) AS month, SUM(order_total_amount) AS total FROM invoice_order WHERE user_id = '$user_id' GROUP BY YEAR(order_date) , MONTH(order_date) ORDER BY YEAR(order_date) , MONTH(order_date)) AS sale"; $sale_chart_query = mysqli_query($connection,$sale_chart) or die(mysqli_error($connection)); $sale_chart_array = mysqli_fetch_assoc($sale_chart_query); foreach($sale_chart_array as $x => $val) { ?> ['<?php echo $x; ?>','<?php echo $val; ?>'], <?php } ?> ]); var options = { }; var chart = new google.charts.Bar(document.getElementById('chart_div')); chart.draw(data, google.charts.Bar.convertOptions(options)); } </script> After replacing zero with null, that is how it showing up the result |
Determine the value of data paths from a given instruction Posted: 06 May 2021 08:16 AM PDT During a particular clock cycle, consider the CPU shown in the drawing. Assume that the following initial data is present (all values are shown in decimal, DM is Data Memory):x3=8, x14=40 During the cycle in question, assume that the following instruction is executed (the first column is the instruction's address; all values are shown in decimal): 50788 beq x3,x14,80 How to determine the value of L1, L2 and L3
As per what I understand the L1 will have the program counter But how do I determine the value of program counter L2 will have 0 or 1 depending upon whether it uses MemtoReg Now sure about L3. Although above is a guesswork. Any hints or pointers how to procees on this ? |
Using a Javascript DOM Parser extract the list of Layers from the XML response.data of an WMS GetCapabilities request Posted: 06 May 2021 08:16 AM PDT I am trying to extract the list of the names of available layers of a WMS server. I have done so for the GeoMet WMS by sending a GetCapabilities which returns a "application/xml" object that then I parse using a DOM parser. My problem is the Layer tags are nested on two levels. Basically the top level layer contains multiple children layers. How would I extract only the children or list of the parent Layers. I managed to hack together this by realising the children had an attribute that the parent Node did not, but there has to be a better way. EDIT : I am interested in getting the full list of layers that can be added to an interactive map. Basically all Layer tags that do not have Layer children. axios.get('https://geo.weather.gc.ca/geomet?lang=en&service=WMS&version=1.3.0&request=GetCapabilities').then((response) => { // console.log(response.headers) const parser = new DOMParser() const dom = parser.parseFromString(response.data, 'application/xml') let layerGroups = dom.querySelectorAll('[cascaded="0"]') let layerNames = [] layerGroups.forEach(function (domel) { layerNames.push(domel.getElementsByTagName('Name')[0].innerHTML) }) console.log(layerNames.length) this.mylayerlist = layerNames }) |
How can i rotate admin.conf in kubernetes? Posted: 06 May 2021 08:17 AM PDT I need to rotate admin.conf for a cluster so old users who used that as their kubeconfig wouldn't be allowed to perform actions anymore. How can i do that? |
How to make dataset from images and labels stored in csv file in Keras Posted: 06 May 2021 08:17 AM PDT I am making CNN AI that will get price from the image and for this I need to create a dataset. I already have all images in images directory and prices stored in csv file. In this csv file I have 2 columns, first is file name and second is price. For example: Labels: Name|Price Rows: 1.jpg|1230 2.jpg|840 3.jpg|3200 I searched in a lot of guides and had not found any code that will help in my example. So does anyone know how to create traning dataset from this? |
Frequency table from two filters and two summarise in dplyr Posted: 06 May 2021 08:17 AM PDT How can I combine the following codes to into one: df %>% group_by(year) %>% filter(MIAPRFCD_J8==1 | MIAPRFCD_55==1) %>% summarise (Freq = n()) df %>% group_by(year) %>% filter(sum==1 | (MIAPRFCD_J8==1 & MIAPRFCD_55==1)) %>% summarise (reason_lv = n()) So output will be one table (or df) which is grouped by year and two columns of frequencies based on the above filters. Here is the sample data: df<- read.table(header=T, text='Act year MIAPRFCD_J8 MIAPRFCD_55 sum 1 2015 1 0 1 2 2016 1 0 1 3 2016 0 1 2 6 2016 1 1 3 7 2016 0 0 2 9 2015 1 0 1 11 2015 1 0 1 12 2015 0 1 2 15 2014 0 1 1 20 2014 1 0 1 60 2013 1 0 1') Output after combing the codes would be: year Freq reason_lv 2013 1 1 2014 2 2 2015 4 3 2016 3 2 |
Save attachment from Gmail to Google Drive AND give it another name Posted: 06 May 2021 08:17 AM PDT I am using Amit Agarwal's fantastic script to extract attachments from Google Mail and save them to Google Drive. It saves the attachment under its name and saves the Subject Line of the mail in the "Description" of the file (together with the Message ID). Instead, I would like to name the file whatever is written in the subject line of the email with the attachment. An example: The attachment is named abc.pdf, the subject line is "Invoice-February.pdf". As it is, the script would create a file in Google Drive called abc.pdf. Instead, I would like it to name the file "Invoice-February.pdf". This is the original code: for (var x=0; x<threads.length; x++) { var message = threads[x].getMessages()[0]; var desc = message.getSubject() + " #" + message.getId(); var att = message.getAttachments(); for (var z=0; z<att.length; z++) { try { if (check) { var name = att[z].getName(); if (name.indexOf(".") != -1) { var extn = name.substr(name.lastIndexOf(".")+1).toLowerCase(); if (valid.indexOf(extn) != -1) { file = folder.createFile(att[z]); file.setDescription(desc); } else { Logger.log("Skipping " + name); } } } else { file = folder.createFile(att[z]); file.setDescription(desc); } } The createFile function has no way to add a different name to a blog and I have not found a "renameFile". Does anyone know how to do that? |
Setting the JDK for Eclipse in MAC Posted: 06 May 2021 08:17 AM PDT I bought a MacBookPro and I'am newbie with this OS.I downloaded the JDK from Oracle's website and installed it (/Library/Java/JavaVirtualMachines/jdk_1.7...) so everything is fine when I enter "java -version" in Terminal it says : 1.7. But I could not set the 1.7 JRE on Eclipse.When I try to Add the JDK at "Java/InstalledJREs/Add" in Eclipse it doesn't accept the Home directory of jdk_1.7/Contents/Home.. What am I doing wrong, couldn't find the way to solve. Also After installation of 1.7, eclipse cant compile a simple HelloWorld.java file.It gives error something like; "java.lang.UnixProcess" If I remove the 1.7 it works and "java -version" says 1.6 |
No comments:
Post a Comment