Can we use C++ boost libraries in IDEs like dev and vs code? Posted: 18 Jul 2021 08:26 AM PDT Can we use C++ boost libraries in IDEs like dev and vs code? Or it only works in Microsoft visual studios? |
Pytorch Custom Loss Function with If Statement Posted: 18 Jul 2021 08:26 AM PDT I am trying to create a custom loss function in Pytorch that evaluates each element of a tensor with an if statement and acts accordingly. def my_loss(outputs,targets,fin_val): if (outputs.detach()-fin_val.detach())*(targets.detach()-fin_val.detach())<0: loss=3*(outputs-targets)**2 else: loss=0.3*(outputs-targets)**2 return loss I have also tried: def my_loss(outputs,targets,fin_val): if torch.gt((outputs.detach()-fin_val.detach())*(targets.detach()-fin_val.detach()),0): loss=0.3*(outputs-targets)**2 else: loss=3*(outputs-targets)**2 return loss In both cases, I get the following error: RuntimeError: Boolean value of Tensor with more than one value is ambiguous TIA |
what is correct and efficient usage of CustomScrollView in Flutter Posted: 18 Jul 2021 08:26 AM PDT CustomScrollView in flutter takes an argument as "slivers" which is an array of widgets (sliver widgets to be precise) everywhere i see developers put a single SliverList as the only element in that array, and put all the scrollable content inside the delegate. What happens if i put multiple SliverLists and SliverGrids and SlivertoBoxAdapters inside? i know it works but i wanna know about efficiency and recycling behavior of the ScrollView. SliverList delegate does some recycling and lazy-building for its own children but what about the entire Scrollable Content? return CustomScrollView( slivers: [ header1, // SliverToBoxAdapter sliverList1, sliverStaggeredGrid1, header2, // SliverToBoxAdapter sliverList2, header3, // SliverToBoxAdapter sliverGrid1, footer, // SliverToBoxAdapter ], ); - does it build all the slivers(the ones directly inside slivers array) even if they are not visible?
- if it does, do they build their children ( im using delegates, but what about BoxAdapters? )
- what should i do if i have multiple grids and lists and other content and want it smooth? i cant put them inside a single SliverList because i have grids inside that need recycling behavior
|
Embed functional spreadsheet to blog Posted: 18 Jul 2021 08:25 AM PDT I have created the following spreadsheet: https://1drv.ms/x/s!Am71ONow-2zblhLZ1dyrX32cwo-d?e=qeAE0g And I would like to embed the C2:F13 range of cells into my blog, but I want it to be fully functional. Like a calculator, I want to be able to select something from a drop-down list, lock the other cells and have my formulas calculate the result. Finally, I want the changes to be made topically and not on the original sheet. I have tried to convert it to HTML but it is not interactive. I have also tried to embed the file but the changes become to the file. How can I achieve that? Should I convert it to HTML? What do you think? Thank you for your suggestions. |
i've made a calculator in vue i want it to get the last operator entered and change the previous (something wrong with js) Posted: 18 Jul 2021 08:25 AM PDT i have this data value: '', numbers: ['C','*','/','-',7,8,9,'+',4,5,6,'%',1,2,3,'=',0,'.'], operator: '', newvalue: '', actually it's working when you type this "8+9" but i want my calculator to changes the operartor when you type "8+-" it must delete the + and replace it with - but my code is working like "8+-9" with this if statement if (['/','*','-','+','%'].includes(x)) { this.operator = x; if (this.value == this.operator) { this.value = this.operator }else { this.value += this.operator; } } if (x === '=') { this.value = eval( this.newvalue + this.operator + this.value ); this.newvalue = ''; this.operator = ''; } } here is my complete code on github i would be grateful if anybody could help https://github.com/rozhansh43/vue-calculator/blob/master/src/components/Calculator.vue |
How to track users using sessions/cookies using PHP Posted: 18 Jul 2021 08:25 AM PDT I want to make a user counter on website. I think the best is to use sessions or cookies and I want to do it like this: - when user access the website set session or cookie with ip;
- then if user loged in edit this cookie for cookie with user's nickname
- when user leaves delete cookie
But i don't know is it a good idea (if not please give me better) and I don't know how can i count cookies/sessions from all visitors on website in php. |
Rinkeby Smart Contract Posted: 18 Jul 2021 08:25 AM PDT looking to create a challenge for a CTF, where I give the user a smart contract for a piece of art that requires a minimum cost of 20 ether. Once the payment has been accepted, he gets by return the flag. The code below works and checks balances against the account in remix but how can I get it to return the flag if the payment is correct? Any help and pointers would be appreciated. // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; contract payment_for_art { function invest() external payable { if(msg.value < 20 ether) { revert(); } } function balance_of() external view returns(uint) { return address(this).balance; } } Regards K |
"Jedis NOAUTH Authentication required"-spam after Java 16 upgrade Posted: 18 Jul 2021 08:25 AM PDT recently we migrated all our systems to java 16 due to customer requirements. So this is a unchangeable decision. Now after the upgrade our jedis connection starts to spam the terminal with this error code: [17:17:31 ERROR]: [redis.clients.jedis.JedisFactory] Error while validating pooled Jedis object. redis.clients.jedis.exceptions.JedisDataException: NOAUTH Authentication required. at redis.clients.jedis.Protocol.processError(Protocol.java:135) ~[?:?] at redis.clients.jedis.Protocol.process(Protocol.java:169) ~[?:?] at redis.clients.jedis.Protocol.read(Protocol.java:223) ~[?:?] at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:352) ~[?:?] at redis.clients.jedis.Connection.getStatusCodeReply(Connection.java:270) ~[?:?] at redis.clients.jedis.BinaryJedis.ping(BinaryJedis.java:379) ~[?:?] at redis.clients.jedis.JedisFactory.validateObject(JedisFactory.java:214) ~[?:?] at org.apache.commons.pool2.impl.GenericObjectPool.evict(GenericObjectPool.java:810) ~[?:?] at org.apache.commons.pool2.impl.BaseGenericObjectPool$Evictor.run(BaseGenericObjectPool.java:1160) ~[?:?] at org.apache.commons.pool2.impl.EvictionTimer$WeakRunner.run(EvictionTimer.java:213) ~[?:?] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) ~[?:?] at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305) ~[?:?] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305) ~[?:?] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[?:?] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[?:?] at java.lang.Thread.run(Thread.java:831) [?:?] System informations: Debian buster (10) Java version: 16.0.1 Jedis version: 4.0.0-SNAPSHOT (Also tried with 3.6.x and 3.5.x) Redis version of remote server: 5.0.3 Commons pool: 2.9.0 (Also tried 2.5.0) Code for connection: Jedis jedis = null; try { jedisPool = new JedisPool("XXX.XXX.XXX.XXX", XXX, 10000); jedis = MasterMind.getInstance().getJedisPool().getResource(); jedis.auth("<SuperSafePass>"); jedis.exists("test"); Bukkit.getLogger().info("Connection build"); } catch (Exception e) { e.printStackTrace(); Bukkit.getLogger().warning("Connection failure"); } finally { if (jedis != null) jedis.close(); } As you see, I auth correctly. Connection gets build. After ~30 seconds it starts to spam the error (around 10 times every 30 seconds) |
How to avoid "null" values in a Json Object , when looping over it Posted: 18 Jul 2021 08:27 AM PDT I am learning vainilla JS (sorry in advance if I don't use some concepts properly), and while doing so, I am practising DOM manipulation and API fetching, with a free API i was given. I have JSON with an structure similar to the one below, in which sometimes some fields get the value null ,or even change the structure of the attribute (as you can see in the 'Image Gallery' from the 3rd elelement. I am looping through it to do different things, like creating a table, buidling some cards, and create an img gallery displaying the images from that element when clicking a button. But whenever the loop finds the "null" value, it stops, and gives me a Cannot read property 'length' of null The object is similar to this : myObject = [ { "field one": "something ", "Image Gallery": [ { "src": "anImage.jpg", "title": "more text" }, { "src": null, "title": "a title here" }, { "src": "otherImg.jpg", "title": null } ], "Management": null, "Scientific Name": "Urophycis tenuis", "Species Illustration Photo": { "src": null, }, "last_update": "05/19/2021 - 13:04" }, { "Habitat Impacts": "something ", "Image Gallery": null, "Management": 'some value', "Scientific Name": null, "Species Illustration Photo": { "src": 'img.jpg', }, "last_update": "05/19/2021 - 13:04" }, { "Habitat Impacts": "something ", "Image Gallery": // Note that the Image gallery structure is a string here { "src": "anImage.jpg", "alt": "some text", "title": "more text" }, , "Management": 'some value', "Scientific Name": "Urophycis tenuis", "Species Illustration Photo": { "src": 'img.jpg', }, "last_update": "05/19/2021 - 13:04" }] My Javascript code in which I get the error is : function createCards(myObject) { let cardContainer = document.getElementById('cardContainer'); for (let i = 0; i < myObject.length; i++) { aInfoButtonLeft.onclick = function () { for (let x = 0; x < myObject[i]["Image Gallery"].length; x++) { console.log(myObject[i]['Image Gallery'][x]["src"]) } } } } How could I prevent the different "null" values to break the iteration, or to skip them and follow with the next value? The only way I can think of is to write if conditions, but I would need one per every kind of attribute which might contain a Null |
I want a button which shows when i click on radio button after that it will display Posted: 18 Jul 2021 08:26 AM PDT I want this button whenever I clicked on perfect address: |
How can i align my components vertically and 3 in a row? Posted: 18 Jul 2021 08:25 AM PDT On my react project i want align my components to vertical. But when i use div and make it flex , my component width is changing and looking bad. what should i do ? I using tailwindcss but if you dont know it you can tell normal css too. I can use normal css too. My component : <div className=""> <div className="mt-6 ml-5 bg-gray-50 border rounded-lg border-gray-200 shadow-md w-3/12 h-full mb-10"> <div className="flex mt-2"> <div className="border border-gray-500 ml-2 mt-2 pl-1 pr-1 pt-2 "> <FontAwesomeIcon icon={faEtsy} className="text-2xl text-red-600" /> </div> <div className="relative"> <span className="ml-3 pt-2 relative text-xl font-medium"> {prop.PharmacyName} </span> <br /> <span className="ml-4 text-blue-800">{prop.PharmacyNumber}</span> </div> </div> <Divider /> <div className=""> <p className="px-2 py-1 font-medium text-base text-gray-700"> {prop.PharmacyAdress} </p> </div> </div> </div> How i calling my component : data.map((x, index) => { return ( <div className="flex align-center"> <PharmacyCard className="relative" key={index} props={x} /> </div> )}) How its looks like : https://prnt.sc/1covi9m How i want : https://prnt.sc/1cow1sq I using that component like 30-40 times with mapping. So i want to see like 3 component in a row. Thanks for all replies! |
Return name and id property value of all arrays inside object Posted: 18 Jul 2021 08:25 AM PDT How to return name and id property value of all arrays? The idea is to make a single map of all these arrays and return the id and name? Something like this filters.[key].map((option, index) => ( <ItemFilter key={index}>{option}</ItemFilter> )) I have this array object filters: { "services": [ { "id": "1b975589-7111-46a4-b433-d0e3c0d7c08c", "name": "Bank" }, { "id": "91d4637e-a17f-4b31-8675-c041fe06e2ad", "name": "Income" } ], "accountTypes": [ { "id": "1f34205b-2e5a-430e-982c-5673cbdb3a68", "name": "Digital Account" } ], "channels": [ { "id": "875f8350-073e-4a20-be20-38482a86892b", "name": "Chat" } ] } |
Http request how to return a list of objects Posted: 18 Jul 2021 08:25 AM PDT So I have moved from working with Java to C# and man is Spring boot different from C#. I am trying to return a list of objects to a rest API using mongodb database. But the result does not return a list, but rather some object containing my list. Brand class [BsonIgnoreExtraElements] public class Brand { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string _id { get; set; } public string name { get; set; } } Controller [HttpGet("getAllBrands")] public async Task<IActionResult> Get() { var brands = await _brandRepository.getAllBrands(); List<Brand> list = (List<Brand>) brands; return new JsonResult(list); } Brand Repository public async Task<IEnumerable<Brand>> getAllBrands() { var brands = await _brands.Find(_ => true).ToListAsync(); return brands; } What I expect [ { "_id": "60d235f60f8c98376ba5b67d", "name": "Some brand 1" }, { "_id": "60d24d6b0f8c98376ba5b68c", "name": "Some brand 2" }, { "$id": "6", "_id": "60d24e4b0f8c98376ba5b68d", "name": "Some brand 3" } ] What I'm actually getting { "$id": "1", "$values": [ { "$id": "2", "_id": "60d235f60f8c98376ba5b67d", "name": "Some brand 1" }, { "$id": "4", "_id": "60d24d6b0f8c98376ba5b68c", "name": "Some brand 2" }, { "$id": "6", "_id": "60d24e4b0f8c98376ba5b68d", "name": "Some brand 1" } ] } How do I just return a simple list of objects as my result and not that? Thanks |
Rendering single thing without having to clear entire screen in sdl Posted: 18 Jul 2021 08:25 AM PDT I'm new to SDL and I'm wondering if there are layers to sdl or something? by layers I mean like in photoshop we have multiple layer and can draw on one without effecting the other, for example if I had a main_layer , a background_layer & an enemy_layer where the main player reandering (like moving the character by user), a static background rendering & enemies rendering can take place respectively? instead of having to clear the entire screen then placing everything back again over and over? i.e. changing a single thing without effecting the other? can someone point me in the right direction? |
How do I save the state of CheckedTextView checkbox so it stays checked after exiting? Posted: 18 Jul 2021 08:27 AM PDT So I kinda screwed up while making the checkedtextviews, didn't realise i needed to save the state, I don't know how exactly to do it. Any advice would be greatly appreciated. CheckedTextView C1,C2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_anime2); C1 = findViewById(R.id.C1); C2 = findViewById(R.id.C2); C1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View V) { C1.toggle(); if(C1.isChecked() == true) { C1.setBackgroundResource(R.drawable.cb_background); } else { C1.setBackgroundResource(R.drawable.cb_background_default); } } }); C2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { C2.toggle(); if(C2.isChecked() == true) { C2.setBackgroundResource(R.drawable.cb_background); } else { C2.setBackgroundResource(R.drawable.cb_background_default); } } }); |
CountIFS with filter Posted: 18 Jul 2021 08:26 AM PDT Syntax : CountIfS(Range1,condition1,Range2,Condition2,....So on) Can we use FILTER function to retrieve a Value. I am trying below function =COUNTIFS(A2:A610,"Yes",$B$2:$B$610,filter(Sheet2!14:14,Sheet2!2:2=G1)) output is not correct answer, neither the its throwing any error. I could save the output of filter(OS!14:14,OS!2:2=G1) in different cell and refer that cell in 2nd condition. But for that I need make plethora cells as I need to use this countifs function in every coulumn. PS : filter(Sheet2!14:14,Sheet2!2:2=G1) returns the correct value. |
Is there a way to simplify this IF statement Posted: 18 Jul 2021 08:26 AM PDT Is there any way to simplify this if statement? if(num1 != 1 && num1 != 2 && num1 != 3 && num1 != 4 && num1 != 5 && num1 != 6 && num1 != 7 && num1 != 8 && num1 != 9 && num1 != 0){ printf("Invalid Number"); return 0; } The value of num1 will be from user input, and I want to only allow numbers as value and if the user tries to input anything other than number, I want Invalid Number to be printed. |
Declaring elements without them being inside a function Posted: 18 Jul 2021 08:26 AM PDT Hi guys am having trouble with this, When I declare the elements outside the loop the script ends up being broken. I plan to use the elements in several functions. Tried a lot of times but didn't find a solution. Broke the project a few times while doing guess work. Also If there's any idea on how to shorten this or to make it work better please give me a heads up :) async function loadTable() { try { while(dpTable.firstChild) dpTable.removeChild(dpTable.firstChild); const result = await fetch('http://localhost:5000/users/student_data', { method: 'GET' }); const table = await result.json(); table.forEach((res) => { //Create Table elements and then load results into the elements const tr = document.createElement('tr'); const studentNo = document.createElement('td'); const name = document.createElement('td'); const surname = document.createElement('td'); const date_joined = document.createElement('td'); const fees_paid = document.createElement('td'); const fees_owing = document.createElement('td'); const is_owing = document.createElement('td'); const trash_btn = document.createElement('button'); const trash_Icon = document.createElement('i'); tr.id = 'Content'; studentNo.id = res.id; name.id = 'fname'; surname.id = 'lname'; fees_paid.id = 'amount_paid'; fees_owing.id = 'amount_owing'; is_owing.id = 'debt'; //Enter the data from the response studentNo.innerText = res.id; name.innerText = res.fname; surname.innerText = res.lname; fees_paid.innerText = res.amount_paid; fees_owing.innerText = res.amount_owing; date_joined.innerText = res.date_joined; is_owing.innerText = res.is_owing; trash_btn.innerText = 'Delete'; //Add Classes for elements studentNo.classList.add('trContent'); name.classList.add('trContent'); surname.classList.add('trContent'); fees_paid.classList.add('trContent'); fees_owing.classList.add('trContent'); date_joined.classList.add('trContent'); is_owing.classList.add('trContent'); trash_Icon.classList.add('fas'); trash_Icon.classList.add('fa-trash'); trash_Icon.classList.add('trash-btn'); //Append table row elements to main table tr.append(studentNo); tr.append(name); tr.append(surname); tr.append(fees_paid); tr.append(fees_owing); tr.append(date_joined); tr.append(is_owing); tr.append(trash_btn); //Event Listeners trash_btn.addEventListener('click', async (e) => { if (window.confirm('Delete')) { console.log('trash icon clicked'); const jsonReq = {}; jsonReq.id = res.id; const result = await fetch('http://localhost:5000/users/student_data', { method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify(jsonReq), }); alert('Deleted Record'); window.location.reload(); } }); //Append the table as a child to the main element dpTable.appendChild(tr); }); } catch (e) { console.log(`Cant load List ${e}`); } } |
Highlight duplicates and copy to new sheet Posted: 18 Jul 2021 08:24 AM PDT I have a large sheet of server names, ~12,000 rows. I need to highlight any duplicate server names and then copy them to a new sheet. I have a script to highlight the cells, that works great (thank you Kurt Kaiser). But, I can't figure out how to write the duplicates (all instances) to a new sheet. Here's the snippet of the code that highlights the duplicates. // Highlight all instances of duplicate values in a column function highlightColumnDuplicates(indexes) { var column = 1; for (n = 0; n < indexes.length; n++) { sheet.getRange(indexes[n] + 1, column).setBackground("yellow"); } } Any help would be appreciated. |
"_id" field is set to an int, but bson error is thrown for invalid document key with "." Posted: 18 Jul 2021 08:24 AM PDT I'm trying to insert a document into an empty mongoDB (key does not already exist), the bson object has the "_id" field set to an int, but when calling insert_many , its throwing an error: bson.errors.InvalidDocument: key 'NC_012920.1:8119:C:A' must not contain '.' I understand why documents cannot contain '.', but when printed the document has: {'_id': 8963, ...} Is there a different "key" I'm unaware of? Why would this string be chosen as the document key? Full object: {'refsnp_id': '8936', 'create_date': '2000-09-19T17:02Z', 'last_update_date': '2021-04-27T08:18Z', 'last_update_build_id': '155', 'dbsnp1_merges': [], 'citations': [], 'lost_obs_movements': [], 'present_obs_movements': [{'component_ids': [{'type': 'subsnp', 'value': '35324609'}], 'observation': {'seq_id': 'NC_001807.4', 'position': 8120, 'deleted_sequence': 'C', 'inserted_sequence': 'C'}, 'allele_in_cur_release': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'C'}, 'other_rsids_in_cur_release': [], 'previous_release': {'allele': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'C'}, 'rsids': ['8936']}, 'last_added_to_this_rs': '125'}, {'component_ids': [{'type': 'subsnp', 'value': '35324609'}], 'observation': {'seq_id': 'NC_001807.4', 'position': 8120, 'deleted_sequence': 'C', 'inserted_sequence': 'A'}, 'allele_in_cur_release': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'A'}, 'other_rsids_in_cur_release': [], 'previous_release': {'allele': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'A'}, 'rsids': ['8936']}, 'last_added_to_this_rs': '125'}], 'primary_snapshot_data': {'placements_with_allele': [{'seq_id': 'NC_012920.1', 'is_ptlp': True, 'placement_annot': {'seq_type': 'refseq_chromosome', 'mol_type': 'mitochondrion', 'seq_id_traits_by_assembly': [{'assembly_name': 'GRCh37.p13', 'assembly_accession': 'GCF_000001405.25', 'is_top_level': True, 'is_alt': False, 'is_patch': False, 'is_chromosome': True}, {'assembly_name': 'GRCh38.p13', 'assembly_accession': 'GCF_000001405.39', 'is_top_level': True, 'is_alt': False, 'is_patch': False, 'is_chromosome': True}], 'is_aln_opposite_orientation': False, 'is_mismatch': False}, 'alleles': [{'allele': {'spdi': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'C'}}, 'hgvs': 'NC_012920.1:m.8120='}, {'allele': {'spdi': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'A'}}, 'hgvs': 'NC_012920.1:m.8120C>A'}]}, {'seq_id': 'YP_003024029.1', 'is_ptlp': False, 'placement_annot': {'seq_type': 'refseq_prot', 'mol_type': 'protein', 'seq_id_traits_by_assembly': [], 'is_aln_opposite_orientation': False, 'is_mismatch': False}, 'alleles': [{'allele': {'spdi': {'seq_id': 'YP_003024029.1', 'position': 178, 'deleted_sequence': 'L', 'inserted_sequence': 'L'}}, 'hgvs': 'YP_003024029.1:p.Leu179='}, {'allele': {'spdi': {'seq_id': 'YP_003024029.1', 'position': 178, 'deleted_sequence': 'L', 'inserted_sequence': 'M'}}, 'hgvs': 'YP_003024029.1:p.Leu179Met'}]}], 'allele_annotations': [{'frequency': [], 'clinical': [], 'submissions': ['35324609'], 'assembly_annotation': [{'seq_id': 'NC_012920.1', 'annotation_release': 'Homo sapiens Annotation Release 109', 'genes': [{'name': 'mitochondrially encoded ATP synthase 6', 'id': 4508, 'locus': 'MT-ATP6', 'is_pseudo': False, 'orientation': 'plus', 'sequence_ontology': [{'name': '2KB_upstream_variant', 'accession': 'SO:0001636'}], 'rnas': [{'id': 'NC_012920.1', 'codon_aligned_transcript_change': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'C'}, 'sequence_ontology': [], 'product_id': 'YP_003024031.1', 'hgvs': 'NC_012920.1:m.8120='}]}, {'name': 'mitochondrially encoded ATP synthase 8', 'id': 4509, 'locus': 'MT-ATP8', 'is_pseudo': False, 'orientation': 'plus', 'sequence_ontology': [{'name': '2KB_upstream_variant', 'accession': 'SO:0001636'}], 'rnas': [{'id': 'NC_012920.1', 'codon_aligned_transcript_change': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'C'}, 'sequence_ontology': [], 'product_id': 'YP_003024030.1', 'hgvs': 'NC_012920.1:m.8120='}]}, {'name': 'mitochondrially encoded cytochrome c oxidase II', 'id': 4513, 'locus': 'MT-CO2', 'is_pseudo': False, 'orientation': 'plus', 'sequence_ontology': [], 'rnas': [{'id': 'NC_012920.1', 'codon_aligned_transcript_change': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'CTA', 'inserted_sequence': 'CTA'}, 'sequence_ontology': [{'name': 'coding_sequence_variant', 'accession': 'SO:0001580'}], 'product_id': 'YP_003024029.1', 'protein': {'variant': {'spdi': {'seq_id': 'YP_003024029.1', 'position': 178, 'deleted_sequence': 'L', 'inserted_sequence': 'L'}}, 'sequence_ontology': []}, 'hgvs': 'NC_012920.1:m.8120='}]}, {'name': 'mitochondrially encoded cytochrome c oxidase III', 'id': 4514, 'locus': 'MT-CO3', 'is_pseudo': False, 'orientation': 'plus', 'sequence_ontology': [{'name': '2KB_upstream_variant', 'accession': 'SO:0001636'}], 'rnas': [{'id': 'NC_012920.1', 'codon_aligned_transcript_change': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'C'}, 'sequence_ontology': [], 'product_id': 'YP_003024032.1', 'hgvs': 'NC_012920.1:m.8120='}]}, {'name': 'mitochondrially encoded NADH dehydrogenase 3', 'id': 4537, 'locus': 'MT-ND3', 'is_pseudo': False, 'orientation': 'plus', 'sequence_ontology': [{'name': '2KB_upstream_variant', 'accession': 'SO:0001636'}], 'rnas': [{'id': 'NC_012920.1', 'codon_aligned_transcript_change': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'C'}, 'sequence_ontology': [], 'product_id': 'YP_003024033.1', 'hgvs': 'NC_012920.1:m.8120='}]}]}]}, {'frequency': [], 'clinical': [], 'submissions': ['35324609'], 'assembly_annotation': [{'seq_id': 'NC_012920.1', 'annotation_release': 'Homo sapiens Annotation Release 109', 'genes': [{'name': 'mitochondrially encoded ATP synthase 6', 'id': 4508, 'locus': 'MT-ATP6', 'is_pseudo': False, 'orientation': 'plus', 'sequence_ontology': [{'name': '2KB_upstream_variant', 'accession': 'SO:0001636'}], 'rnas': [{'id': 'NC_012920.1', 'codon_aligned_transcript_change': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'A'}, 'sequence_ontology': [], 'product_id': 'YP_003024031.1', 'hgvs': 'NC_012920.1:m.8120C>A'}]}, {'name': 'mitochondrially encoded ATP synthase 8', 'id': 4509, 'locus': 'MT-ATP8', 'is_pseudo': False, 'orientation': 'plus', 'sequence_ontology': [{'name': '2KB_upstream_variant', 'accession': 'SO:0001636'}], 'rnas': [{'id': 'NC_012920.1', 'codon_aligned_transcript_change': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'A'}, 'sequence_ontology': [], 'product_id': 'YP_003024030.1', 'hgvs': 'NC_012920.1:m.8120C>A'}]}, {'name': 'mitochondrially encoded cytochrome c oxidase II', 'id': 4513, 'locus': 'MT-CO2', 'is_pseudo': False, 'orientation': 'plus', 'sequence_ontology': [], 'rnas': [{'id': 'NC_012920.1', 'codon_aligned_transcript_change': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'CTA', 'inserted_sequence': 'ATA'}, 'sequence_ontology': [{'name': 'coding_sequence_variant', 'accession': 'SO:0001580'}], 'product_id': 'YP_003024029.1', 'protein': {'variant': {'spdi': {'seq_id': 'YP_003024029.1', 'position': 178, 'deleted_sequence': 'L', 'inserted_sequence': 'M'}}, 'sequence_ontology': [{'name': 'missense_variant', 'accession': 'SO:0001583'}]}, 'hgvs': 'NC_012920.1:m.8120C>A'}]}, {'name': 'mitochondrially encoded cytochrome c oxidase III', 'id': 4514, 'locus': 'MT-CO3', 'is_pseudo': False, 'orientation': 'plus', 'sequence_ontology': [{'name': '2KB_upstream_variant', 'accession': 'SO:0001636'}], 'rnas': [{'id': 'NC_012920.1', 'codon_aligned_transcript_change': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'A'}, 'sequence_ontology': [], 'product_id': 'YP_003024032.1', 'hgvs': 'NC_012920.1:m.8120C>A'}]}, {'name': 'mitochondrially encoded NADH dehydrogenase 3', 'id': 4537, 'locus': 'MT-ND3', 'is_pseudo': False, 'orientation': 'plus', 'sequence_ontology': [{'name': '2KB_upstream_variant', 'accession': 'SO:0001636'}], 'rnas': [{'id': 'NC_012920.1', 'codon_aligned_transcript_change': {'seq_id': 'NC_012920.1', 'position': 8119, 'deleted_sequence': 'C', 'inserted_sequence': 'A'}, 'sequence_ontology': [], 'product_id': 'YP_003024033.1', 'hgvs': 'NC_012920.1:m.8120C>A'}]}]}]}], 'support': [{'id': {'type': 'subsnp', 'value': 'ss35324609'}, 'revision_added': '125', 'create_date': '2005-05-24T13:00Z', 'submitter_handle': 'SSAHASNP'}], 'anchor': 'NC_012920.1:0000008119:1:snv', 'variant_type': 'snv', 'ga4gh': {'NC_012920.1:8119:C:A': {'location': {'type': 'SequenceLocation', 'interval': {'type': 'SimpleInterval', 'start': 8119, 'end': 8120}, 'sequence_id': 'refseq:NC_012920.1'}, 'state': {'type': 'SequenceState', 'sequence': 'A'}, 'type': 'Allele'}, 'NC_012920.1:8119:C:C': {'location': {'type': 'SequenceLocation', 'interval': {'type': 'SimpleInterval', 'start': 8119, 'end': 8120}, 'sequence_id': 'refseq:NC_012920.1'}, 'state': {'type': 'SequenceState', 'sequence': 'C'}, 'type': 'Allele'}, 'YP_003024029.1:178:L:L': {'location': {'type': 'SequenceLocation', 'interval': {'type': 'SimpleInterval', 'start': 178, 'end': 179}, 'sequence_id': 'refseq:YP_003024029.1'}, 'state': {'type': 'SequenceState', 'sequence': 'L'}, 'type': 'Allele'}, 'YP_003024029.1:178:L:M': {'location': {'type': 'SequenceLocation', 'interval': {'type': 'SimpleInterval', 'start': 178, 'end': 179}, 'sequence_id': 'refseq:YP_003024029.1'}, 'state': {'type': 'SequenceState', 'sequence': 'M'}, 'type': 'Allele'}}}, 'mane_select_ids': [], '_id': 8936} I'm sure this is a quick fix, I just dont understand why the '_id' field is no long being treated as the primary key. This code used to work fine so this could be related to a version change - if that helps at all. Thanks! |
How to install TeX live at newest version? Posted: 18 Jul 2021 08:25 AM PDT I installed TeX Live following the guide on their website using the install-tl script two times. Before the second install I followed the pre-install instructions on that same website, and before any installation I removed the 2017 version that had been installed through Debian repositories. I need a version of TeX Live >2019. I assumed the install script would install the newest version, but apparently that's not the case, since: $ tlmgr --version tlmgr revision 49885 (2019-01-31 20:27:00 +0100) tlmgr using installation: /usr/share/texlive TeX Live (http://tug.org/texlive) version 2018 However, my TeX Live installation is in ./usr/local/texlive/2021 . There is no other directory with a year name in ./usr/local/texlive/ . I'm really running out of ideas, but I do need a newer version of TeX Live. I'm on Debian 10. |
How to plot an isosurface of a 3D complex field with Mayavi avoiding color interpolation artifacts? Posted: 18 Jul 2021 08:27 AM PDT Taking as a basis the Atomic orbital example in the example gallery, I'm trying to visualize a 3D arbitrary complex field using an isosurface, in the way the cyclic HSV colormap illustrates the phase of the field. However, there is a problem in the points where the phase-field takes values near pi and -pi , which in the following plot, corresponds to the red color: In these points, there is a sharp discontinuity between pi and -pi , and mayavi seems to be interpolating between these values, and this results in "noisy color lines" that appear in the above plot. My question: is there a way to fix this problem, for example, by disabling the color interpolation? Code to reproduce the plot: import numpy as np from mayavi import mlab L = 1.0 N = 150 xx, yy, zz = np.mgrid[-L:L:N*1j, -L:L:N*1j, -L:L:N*1j] 𝜇 = 0.0 σ = 0.30 V = np.exp((-(xx-𝜇)**2 -(yy)**2 -(zz)**2 ) / (2*σ**2)) density = V/np.amax(np.abs(V)) phi = np.arctan2(yy,xx) density = density *np.exp(6*phi*1j) figure = mlab.figure('Phase Plot',bgcolor=(0, 0, 0), size=(700, 700)) field = mlab.pipeline.scalar_field(np.abs(density),vmin= 0.0 ,vmax= 1.0) colour_data = (np.angle(density.T.ravel())) field.image_data.point_data.add_array(colour_data) field.image_data.point_data.get_array(1).name = 'phase' field.update() field2 = mlab.pipeline.set_active_attribute(field, point_scalars='scalar') contour = mlab.pipeline.contour(field2) contour.filter.contours= [0.1,] contour2 = mlab.pipeline.set_active_attribute(contour, point_scalars='phase') mlab.pipeline.surface(contour2, colormap='hsv', vmin= -np.pi ,vmax= np.pi) mlab.colorbar(title='Phase', orientation='vertical', nb_labels=3) φ = 30 mlab.view(azimuth= φ, distance = N*4) mlab.show() Another way I was thinking to solve this problem is by manually setting the colors on the surface using this function, which returns an array of RGB colors from a complex array Z: from matplotlib.colors import hsv_to_rgb import numpy as np def complex_to_rgb(Z): r = np.abs(Z) arg = np.angle(Z) h = (arg + np.pi) / (2 * np.pi) s = np.ones(h.shape) v = r / np.amax(r) #alpha c = hsv_to_rgb( np.moveaxis(np.array([h,s,v]) , 0, -1) ) # --> tuple return c However, I don't know if there is a mayavi inbuilt method to allow direct input of an array with the RGB colors of the surface. |
Materialize Datepicker Updating Issue Posted: 18 Jul 2021 08:26 AM PDT I'm using Materialize Datepicker for toggling holidays in a list. According to my code, when i click on a day, the event is added/removed to/from the list simultaneously. However as for the style in the datepicker, it is updated only when i click another day or restart the datepicker. I added 1 and 20 July as an example. You can try to add/remove some other days. I'd like the style in the datepicker also to be updated simultaneously like the list. Any ideas? Thanks in advance. var holidays = [1625086800000, 1626728400000]; var datepicker = document.querySelector('#addHoliday') var options = { showClearBtn: true, events : holidays.map ((day) => {return new Date(day).toDateString()}), onSelect : function (day) { var index = holidays.indexOf(day.valueOf()) if(index > -1) { holidays.splice(index,1) } else { holidays.push(day.valueOf()) holidays.sort() }; M.Datepicker.getInstance(document.querySelector('#addHoliday')).options.events = holidays.map ((day) => {return new Date(day).toDateString()}) disposeHolidays() } } M.Datepicker.init(datepicker, options) disposeHolidays() function disposeHolidays () { holidaysList.innerHTML = holidays.map ((day) => { return '<li class="collection-item">' + new Date(day).toDateString() + '</li>'}).join('') } .has-event { background : #FF6666 !important } <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <div class="row"> <div class="input-field col s6 l3 offset-s1 offset-l1"> <input type="text" class="datepicker" id="addHoliday"> <label for="addHoliday">Pick a date</label> <div class="row"> <ul class="collection" id="holidaysList"> </ul> </div> </div> </div> |
NEAT AI doesn't have incentive to get food Posted: 18 Jul 2021 08:26 AM PDT I'm trying to create a snake AI using the NEAT library in Python. But for some reason, the snake doesn't want to get food. I've passed it as data to the system, and I've also introduced a system where if the snake doesn't get food, they lose a fitness point, but the snake either does nothing or it keeps moving left and right rapidly so that it stays in the same spot and continues staying alive. How do I make the snake want to get the food? code for snake movement: for index, snake in enumerate(snakes): output = nets[index].activate(snake.getData()) i = output.index(max(output)) xChange = 0 yChange = 0 print(i, index) if i == 0: xChange = 10 elif i == 1: xChange = -10 elif i == 2: yChange = 10 else: yChange = -10 snake.definePosChange(xChange, yChange) snake.game() code for adding fitness to snake remainSnake = 0 for i, snake in enumerate(snakes): if snake.getAlive(): remainSnake += 1 genomes[i][1].fitness += snake.getReward() function that get "reward" for snake def getReward(self): if self.score <= 0: return -1 return self.score * 100 function that gets data for snake def getData(self): data = [self.x_position, self.y_position, self.food_x, self.food_y] return data For the data I passed it's x and y position, and the position of the food on the screen. The snake chooses to move away from the food, not sure why? I've gone to 50 generations and the snake still does nothing, it barely moves around and doesn't ever go towards food. I've attempted to reload the file around 10 times, and the snake has only gotten food once and it was accidental. EDIT: I've added a reward based on the distance of the snake to the food (and then divided by 500) but this still doesn't change anything. EDIT AGAIN: I've added more snakes now, I first went to 20 my laptop couldn't handle it but I still tried it and it never helped, and now I'm on 5. EDIT AGAIN: I've given the snake the angle it has with its food, and it's distance, and it still doesn't change anything. The snake are sometimes moving around a bit more but they aren't aiming for the food for some reason. EDIT AGAIN: I still haven't been able to fix this issue. Can someone please give me suggestions, or somewhere where I could get some ideas. |
systemd, how to run with all user permissions? Posted: 18 Jul 2021 08:25 AM PDT I've created a user [jupyterhub] to run jupyterhub, setting the relevant permissions. So running it in a terminal [jupyterhub@pc ~]$ /usr/bin/jupyterhub everything works without problems. I'm trying to create a simple systemd service file, for the same purpose: [Service] User=jupyterhub Group=jupyterhub ExecStart=/usr/bin/jupyterhub The script runs, but the jupyter server can't be launched. I've narrowed down the problem with issues with file read/write permissions. Since the user and group are set to be the same, this is unexpected. What am I missing here? I apologise for being generic. I can, of course, provide logs and error messages, but I was looking for a general way to make sure the systemd service file runs exactly as running it from the user console would. My search provided individual examples for setting Environmental variables, device access, etc., but I couldn't find a complete reference for this seemingly straightforward application. |
Is it possible to show steps of calculation in Excel? Posted: 18 Jul 2021 08:24 AM PDT Let's say for example that I have these number in diffetent cells : 5 , 3 , 2. In different cell I type "=SUM(cells of my numbers)". So my question is : is it possible that result will be shown as "5 + 3 + 2" instead of just "10"? BTW: I know that it's rather strange question. |
How can I group recyclerview item by category in android studio Posted: 18 Jul 2021 08:26 AM PDT I want to group my recyclerview by date in android studio without using any library, I did something but I am not getting what I wanted. I have uploaded my result image so I want to group it with "getDateSection". But here DateSection is displaying above each item not according to the dates. I just want to show each date once at the top of the corresponding data group: This is my codes. DowntimeReportingAdapter.java public class DowntimeReportingAdapter extends RecyclerView.Adapter<DowntimeReportingAdapter.MyViewHolder> implements Filterable { public List<DowntimeReportingUri> downtimeReportingUriList; private final List<DowntimeReportingUri> downtimeUriFilter; GridLayoutManager mLayoutManager; private final Context context; private DowntimeReportingFilter filter; Activity mContext; Context ctx; public DowntimeReportingAdapter(List<DowntimeReportingUri> downtimeReportingUriList, Context context) { this.downtimeReportingUriList = downtimeReportingUriList; this.downtimeUriFilter = downtimeReportingUriList; this.context = context; } @NotNull @Override public MyViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.downtime_reporting_item, parent, false); return new MyViewHolder(view); } @SuppressLint({"CheckResult", "SetTextI18n"}) @Override public void onBindViewHolder(final MyViewHolder myViewHolder, int position) { if(downtimeReportingUriList.get(position).getDatesection().isEmpty()){ myViewHolder.mDateSection.setVisibility(View.GONE) ; } else { myViewHolder.mDateSection.setText(downtimeReportingUriList.get(position).getDatesection()); } RequestOptions requestOptions1 = new RequestOptions(); requestOptions1.skipMemoryCache(true); requestOptions1.diskCacheStrategy(DiskCacheStrategy.ALL); requestOptions1.placeholder(R.drawable.full_image_blue); requestOptions1.error(R.drawable.full_image_blue); Glide.with(context) .load(downtimeReportingUriList.get(position).getPicture()) .apply(requestOptions1) .into(myViewHolder.mPicture); myViewHolder.issue.setText(downtimeReportingUriList.get(position).getIssues()); myViewHolder.factory.setText(downtimeReportingUriList.get(position).getFactory()); myViewHolder.line.setText(downtimeReportingUriList.get(position).getLine()); myViewHolder.createdBy.setText(downtimeReportingUriList.get(position).getCreatedby()); myViewHolder.modifiedBy.setText(downtimeReportingUriList.get(position).getModifiedby()); myViewHolder.description.setText(downtimeReportingUriList.get(position).getDescription()); myViewHolder.section.setText(downtimeReportingUriList.get(position).getSection()); myViewHolder.mIssues.setText(downtimeReportingUriList.get(position).getIssues()); myViewHolder.mCreated.setText(downtimeReportingUriList.get(position).getCreated()); myViewHolder.mType.setText(downtimeReportingUriList.get(position).getStatus() + " | " + downtimeReportingUriList.get(position).getDifference() + " | " + downtimeReportingUriList.get(position).getFactory()); } @Override public int getItemCount() { return downtimeReportingUriList.size(); } @Override public Filter getFilter() { if (filter==null) { filter=new DowntimeReportingFilter((ArrayList<DowntimeReportingUri>) downtimeUriFilter,this); } return filter; } public class MyViewHolder extends RecyclerView.ViewHolder { Space space; LikeButton mLove; DatabaseHandler db; LinearLayout linearLayout; private CircleImageView mPicture; private final ApiInterface apiInterface; CardView mRowContainer, mRowContainerGrid; ImageView mForward, mStatus; private HashMap<String, String> user = new HashMap<>(); TextView mIssues, mType, mCreated, issue, factory, line, createdBy, modifiedBy, description, section, mIssuesGrid, mDateSection; @SuppressLint("CutPasteId") public MyViewHolder(View itemView, int viewType) { super(itemView); apiInterface = ApiClient.getApiClient().create(ApiInterface.class); mPicture = itemView.findViewById(R.id.downtime_reporting_picture); mIssues = itemView.findViewById(R.id.downtime_reporting_issues); mIssues.setMovementMethod(new ScrollingMovementMethod()); mType = itemView.findViewById(R.id.downtime_reporting_type); mLove = itemView.findViewById(R.id.downtime_reporting_like); mStatus = itemView.findViewById(R.id.current_status); mCreated = itemView.findViewById(R.id.downtime_reporting_created); mRowContainer = itemView.findViewById(R.id.downtime_reporting_row_container); linearLayout = itemView.findViewById(R.id.linearLayout); issue = itemView.findViewById(R.id.issues); factory = itemView.findViewById(R.id.factory); line = itemView.findViewById(R.id.line); createdBy = itemView.findViewById(R.id.createdby); modifiedBy = itemView.findViewById(R.id.modifiedby); description = itemView.findViewById(R.id.description); section = itemView.findViewById(R.id.section); space = itemView.findViewById(R.id.space); mDateSection = itemView.findViewById(R.id.datesection); } } } DowntimeReporting.java public class DowntimeReporting extends Fragment { DatabaseHandler db; MaterialButton refresh; SessionManager session; ProgressDialog pDialog; private RadioGroup sortRG; ApiInterface apiInterface; private TextView textResult; TextView textName, textEmail; private RecyclerView recyclerView; private LinearLayout linearLayout; SwipeRefreshLayout mSwipeRefreshLayout; private ImageView sortB, goTop, filterB; ShimmerFrameLayout mShimmerViewContainer; FloatingActionButton floatingActionButton; private GridLayoutManager gridLayoutManager; HashMap<String,String> user = new HashMap<>(); private DowntimeReportingAdapter downtimeAdapter; private List<DowntimeReportingUri> downtimeUriList; private static final String TAG = DowntimeReporting.class.getSimpleName(); public DowntimeReporting() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ((Home) Objects.requireNonNull(getActivity())).setActionBarTitle("Downtime Reporting / Open Machine Issue"); View view = inflater.inflate(R.layout.downtime_reporting, container, false); textName = view.findViewById(R.id.name); textEmail = view.findViewById(R.id.email); view.findViewById(R.id.fab).setOnClickListener(v -> showPrompt()); pDialog = new ProgressDialog(getActivity()); pDialog.setCancelable(false); db = new DatabaseHandler(getActivity().getApplicationContext()); user = db.getUserDetails(); session = new SessionManager(getActivity().getApplicationContext()); if (!session.isLoggedIn()) { logoutUser(); } refresh = view.findViewById(R.id.refresh); refresh.setOnClickListener(v -> { onResume(); refresh.setVisibility(View.GONE); }); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); apiInterface = ApiClient.getApiClient().create(ApiInterface.class); recyclerView = view.findViewById(R.id.recyclerView); mShimmerViewContainer = view.findViewById(R.id.shimmer_view_container); mSwipeRefreshLayout = view.findViewById(R.id.swipeToRefresh); mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); mSwipeRefreshLayout.setOnRefreshListener(() -> { onResume(); mSwipeRefreshLayout.setRefreshing(false); refresh.setVisibility(View.GONE); }); gridLayoutManager = new GridLayoutManager(getActivity(), SPAN_COUNT_ONE); recyclerView.setLayoutManager(gridLayoutManager); linearLayout = view.findViewById(R.id.no_result); textResult = view.findViewById(R.id.text_result); floatingActionButton = view.findViewById(R.id.fab); floatingActionButton.setOnClickListener(view1 -> startActivity(new Intent(getActivity(), DowntimeReportingForm.class))); return view; } public void getDowntimes(){ Call<List<DowntimeReportingUri>> call = apiInterface.getDowntimes(); call.enqueue(new Callback<List<DowntimeReportingUri>>() { @SuppressLint("NonConstantResourceId") @Override public void onResponse(@NotNull Call<List<DowntimeReportingUri>> call, @NotNull Response<List<DowntimeReportingUri>> response) { mShimmerViewContainer.stopShimmer(); mShimmerViewContainer.setVisibility(View.GONE); downtimeUriList = response.body(); Log.i(DowntimeReporting.class.getSimpleName(), Objects.requireNonNull(response.body()).toString()); downtimeAdapter = new DowntimeReportingAdapter(downtimeUriList, gridLayoutManager, getActivity()); ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback); itemTouchHelper.attachToRecyclerView(recyclerView); Log.d(TAG, "Number Downtime Reporting Received: " + downtimeUriList.size()); recyclerView.setAdapter(downtimeAdapter); downtimeAdapter.notifyDataSetChanged(); } @Override public void onFailure(@NotNull Call<List<DowntimeReportingUri>> call, @NotNull Throwable t) { mShimmerViewContainer.stopShimmer(); refresh.setVisibility(View.VISIBLE); LayoutInflater inflater = Objects.requireNonNull(getActivity()).getLayoutInflater(); View layout = inflater.inflate(R.layout.custom_toast_message, getActivity().findViewById(R.id.custom_toast_container)); TextView text = layout.findViewById(R.id.text); text.setText(t.getMessage()); Toast toast = new Toast(getActivity().getApplicationContext()); CardView cardView = layout.findViewById(R.id.card_view); cardView.setBackgroundResource(R.drawable.error_style); ImageView toastImageView = layout.findViewById(R.id.toastImageView); toastImageView.setImageResource(R.drawable.error); toast.setGravity(Gravity.BOTTOM, 0, 40); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); toast.show(); } }); } @Override public void onResume() { super.onResume(); mShimmerViewContainer.startShimmer(); refresh.setVisibility(View.GONE); getDowntimes(); } @Override public void onPause() { super.onPause(); mShimmerViewContainer.stopShimmer(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { setHasOptionsMenu(true); super.onCreate(savedInstanceState); } @Override public void onCreateOptionsMenu(@NotNull Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.downtime_reporting_menu, menu); SearchManager searchManager = (SearchManager) Objects.requireNonNull(getActivity()).getSystemService(Context.SEARCH_SERVICE); final SearchView searchView = (SearchView) menu.findItem(R.id.downtime_reporting_search).getActionView(); LinearLayout searchBar = searchView.findViewById(R.id.search_bar); searchBar.setLayoutTransition(new LayoutTransition()); MenuItem searchMenuItem = menu.findItem(R.id.downtime_reporting_search); searchView.setSearchableInfo( searchManager.getSearchableInfo(getActivity().getComponentName()) ); searchView.setQueryHint("Search DownTime Reporting Activity..."); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(final String query) { downtimeAdapter.getFilter().filter(query); return false; } @Override public boolean onQueryTextChange(String newText) { if(newText!=null) downtimeAdapter.getFilter().filter(newText); if(downtimeAdapter.getItemCount()<1){ recyclerView.setVisibility(View.GONE); linearLayout.setVisibility(View.VISIBLE); textResult.setText(R.string.no_result); } else { recyclerView.setVisibility(View.VISIBLE); downtimeAdapter.getFilter().filter(newText); linearLayout.setVisibility(View.GONE); } return false; } }); searchMenuItem.getIcon().setVisible(false, false); } @Override public boolean onOptionsItemSelected(@NotNull MenuItem item) { int id = item.getItemId(); if (id == R.id.downtime_reporting_menu_switch_layout) { switchLayout(); switchIcon(item); return true; } return super.onOptionsItemSelected(item); } } downtime_reporting_item.xml <LinearLayout xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/datesection" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="2dp" android:layout_marginTop="2dp" android:gravity="center" android:text="@string/currently_not_available" android:layout_gravity="center" android:textColor="@color/mainText" android:textSize="16sp"/> <androidx.cardview.widget.CardView android:id="@+id/downtime_reporting_row_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:backgroundTint="@color/card_bg" card_view:cardCornerRadius="12dp" card_view:cardElevation="2dp" android:layout_weight="2" android:layout_marginTop="10dp" android:layout_marginRight="4dp" android:layout_marginLeft="4dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <RelativeLayout android:layout_width="wrap_content" android:layout_height="110dp" android:layout_gravity="center" android:orientation="vertical"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="2dp" android:layout_alignParentEnd="true"> <ImageView android:id="@+id/btmDialog" android:layout_width="20dp" android:layout_height="20dp" android:background="?attr/selectableItemBackgroundBorderless" android:src="@drawable/ic_baseline_more_horiz_24" /> <Space android:layout_width="15dp" android:layout_height="wrap_content"/> <ImageView android:id="@+id/dropdown" android:layout_width="20dp" android:layout_height="20dp" android:background="?attr/selectableItemBackgroundBorderless" android:src="@drawable/ic_baseline_arrow_drop_down_24" /> <Space android:layout_width="15dp" android:layout_height="wrap_content"/> <ImageView android:id="@+id/current_status" android:layout_width="20dp" android:layout_height="20dp" android:padding="2dp" android:src="@drawable/open_status" /> <Space android:layout_width="15dp" android:layout_height="wrap_content"/> <ImageView android:id="@+id/forward" android:layout_width="20dp" android:layout_height="20dp" android:background="?attr/selectableItemBackgroundBorderless" android:padding="2dp" android:visibility="gone" android:src="@drawable/forward" /> <Space android:id="@+id/space" android:layout_width="15dp" android:layout_height="wrap_content" android:visibility="gone"/> </LinearLayout> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/downtime_reporting_picture" android:layout_width="70dp" android:layout_height="70dp" android:layout_centerVertical="true" android:layout_marginStart="16dp" android:src="@drawable/full_image_blue" android:transitionName="@string/simple_activity_transition" /> <LinearLayout android:id="@+id/layoutName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignTop="@+id/downtime_reporting_picture" android:layout_alignParentStart="true" android:layout_marginStart="90dp" android:layout_marginEnd="15dp" android:layout_marginBottom="5dp" android:gravity="top" android:orientation="horizontal" android:weightSum="100"> <TextView android:id="@+id/downtime_reporting_issues" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="100" android:scrollbars="vertical" android:singleLine="true" android:ellipsize="end" android:paddingTop="5dp" android:inputType="textPersonName" android:text="@string/currently_not_available" android:textColor="@color/mainText" android:textStyle="bold" android:transitionName="@string/title_transition" /> <Space android:layout_width="5dp" android:layout_height="wrap_content"/> <TextView android:id="@+id/downtime_reporting_created" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="10" android:gravity="end" android:paddingTop="5dp" android:text="@string/currently_not_available" android:textColor="@color/date" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/layoutName" android:layout_alignStart="@+id/layoutName" android:layout_alignBottom="@+id/downtime_reporting_picture" android:layout_marginEnd="15dp" android:gravity="top" android:layout_centerInParent="true" android:orientation="horizontal" android:weightSum="2"> <TextView android:id="@+id/downtime_reporting_type" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:singleLine="true" android:ellipsize="end" android:layout_gravity="center" android:scrollbars="vertical" android:gravity="start" android:text="@string/currently_not_available" android:textColor="@color/mainText" android:transitionName="descTransition" /> <com.like.LikeButton app:liked="false" android:id="@+id/downtime_reporting_like" android:background="?attr/selectableItemBackgroundBorderless" android:layout_width="40dp" android:layout_height="40dp" android:layout_gravity="center" android:layout_weight="1" app:icon_type="thumb" app:is_enabled="false"/> </LinearLayout> </RelativeLayout> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:animateLayoutChanges="true" android:orientation="vertical" android:visibility="gone"> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="fitXY" /> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="15dp"> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/issue" android:textColor="@color/mainText" /> <TextView android:id="@+id/issues" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/mainText" android:text="@string/currently_not_available" android:textStyle="bold" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Factory " android:textColor="@color/mainText" /> <TextView android:id="@+id/factory" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/mainText" android:text="@string/currently_not_available" android:textStyle="bold" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/mainText" android:text="Line " /> <TextView android:id="@+id/line" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/currently_not_available" android:textColor="@color/mainText" android:textStyle="bold" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Section " android:textColor="@color/mainText"/> <TextView android:id="@+id/section" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/mainText" android:text="@string/currently_not_available" android:textStyle="bold" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/mainText" android:text="Created By " /> <TextView android:id="@+id/createdby" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/currently_not_available" android:textColor="@color/mainText" android:textStyle="bold" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/mainText" android:text="Modified By " /> <TextView android:id="@+id/modifiedby" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/currently_not_available" android:textColor="@color/mainText" android:textStyle="bold" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Description " android:textColor="@color/mainText"/> <TextView android:id="@+id/description" android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textMultiLine" android:textColor="@color/mainText" android:text="@string/currently_not_available" android:textStyle="bold" /> </TableRow> </TableLayout> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> </LinearLayout> DowntimeReportingUri.java public class DowntimeReportingUri { @SerializedName("id") private int id; @SerializedName("createdby") private String createdby; @SerializedName("issues") private String issues; @SerializedName("description") private String description; @SerializedName("datesection") private String datesection; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getIssues() { return issues; } public void setIssues(String issues) { this.issues = issues; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDatesection() { return datesection; } public void setDatesection(String datesection) { this.datesection = datesection; } } |
Using SQLAlchemy ORM for a non-primary key, unique, auto-incrementing id Posted: 18 Jul 2021 08:25 AM PDT When I run the following code, I am expecting the first_name, and last_name to be a composite primary key and for the id to be an autoincrementing index for the row, but not to act as the primary key, as there the information in the rest of the table is what I need to define it's uniqueness, rather than the given ID. Base = declarative_base() Session = sessionmaker(bind=db) session = Session() class Person(Base): __tablename__ = "people" id = Column(Integer, index=True, unique=True, autoincrement=True, primary_key=False) first_name = Column(String(30), primary_key=True) last_name = Column(String(30), primary_key=True) if __name__ == "__main__": Base.metadata.create_all(db) session.add_all([ Person(first_name="Winston", last_name="Moy"), Person(first_name="Bill", last_name="Gates"), Person(first_name="Steve", last_name="Jobs"), Person(first_name="Quinten", last_name="Coldwater") ]) session.commit() The problem I view the results in DataGrip, I'm getting the following table. The data is not in the order added, and the id column is null, instead of the auto-incrementing integer I'm expecting it to be. To be clear: My question is: How would I make an auto-incrementing index for a SQLAlchemy ORM class that is not a primary key? |
integrate real-time a/v chat into construct 2 game or embed construct 2 into app Posted: 18 Jul 2021 08:27 AM PDT I would like to incorporate QuickBlox or Twilio WebRTC chat and A/V calling into the same Angular apps running on a web page or inside a Cordova/Crosswalk app, as a Construct 2 game. I would like to have an audio/video chat running during game play. Can I embed Construct 2 games into an Ionic view or simple DOM element and then render the video chat over it? Or, should I be integrating the WebRTC chat sessions into Construct 2? Or can I simply display both canvases in the same page? Thanks in advance. See: https://quickblox.com/developers/Sample-webrtc-cordova |
What is the best way to translate a big amount of text data? [closed] Posted: 18 Jul 2021 08:26 AM PDT I have a lot of text data and want to translate it to different languages. Possible ways I know: The problem is that all these services have limitations on text length, number of calls, etc. which makes them inconvenient in use. What services / ways you could advice to use in this case? |
No comments:
Post a Comment