qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
15,516,429
I just want to create a dynamic URL. I am calling the listServices method and it is working as expected where as the getPortNumber which i am calling from listService is not working. I added dubug point in getPortNumber method. I am getting value for domainValue but I am not able to debug after $(document).ready(function(). The control directly goes to return portNumber and in the final URL i am getting the port number value as undefined. I checked and validated the port\_url (json file). my json file looks like this ``` { "servers": [ { "listeningPort": "6080", "shutdownPort": "8180", "redirectPort": "8443", "sslPort": "8443", "openWirePort": "61610", "jmxPort": "9332", "category": "Test A" } } ``` I got struck. I hope this issue is not becoz of calling javascript method from another method. ``` function getPortNumber() { var portNumber; var domainValue = $("#domain").val(); $(document).ready(function() { $.getJSON(port_url, function(result) { $.each(result, function() { $.each(this, function(k, v) { if (v.category == domainValue) { portNumber = v.listeningPort; return false; } }); }); }); }); return portNumber; } function listServices() { $(document).ready(function() { $("#list").text(""); var jList = $("#list"); var listOfServers = $("#servers").text(); var serverArray = listOfServers.split(","); for (var i = 0; i < serverArray.length; i++) { var port = getPortNumber(); var tempURL = "http://"+serverArray[i].trim().toLowerCase()+".javaworkspace.com:"+port+"/services/listServices"; jList.append("<li><a href="+tempURL+" target='_blank'>"+tempURL+"</a></li>"); } }); } ```
2013/03/20
[ "https://Stackoverflow.com/questions/15516429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2189478/" ]
you don't need to call `document.ready` inside a function.....since (i bet) that function is called after document is ready... remove that ``` function getPortNumber() { var portNumber; var domainValue = $("#domain").val(); $.getJSON(port_url, function(result) { $.each(result, function() { $.each(this, function(k, v) { if (v.category == domainValue) { portNumber = v.listeningPort; return false; } }); }); }); return portNumber; } ``` and do the same for the other one..
After removing $(document).ready(function() from getPortNumber the debug skip code after $.getJSON(port\_url, function(result) {. Firebug is not reporting any errors.
15,516,429
I just want to create a dynamic URL. I am calling the listServices method and it is working as expected where as the getPortNumber which i am calling from listService is not working. I added dubug point in getPortNumber method. I am getting value for domainValue but I am not able to debug after $(document).ready(function(). The control directly goes to return portNumber and in the final URL i am getting the port number value as undefined. I checked and validated the port\_url (json file). my json file looks like this ``` { "servers": [ { "listeningPort": "6080", "shutdownPort": "8180", "redirectPort": "8443", "sslPort": "8443", "openWirePort": "61610", "jmxPort": "9332", "category": "Test A" } } ``` I got struck. I hope this issue is not becoz of calling javascript method from another method. ``` function getPortNumber() { var portNumber; var domainValue = $("#domain").val(); $(document).ready(function() { $.getJSON(port_url, function(result) { $.each(result, function() { $.each(this, function(k, v) { if (v.category == domainValue) { portNumber = v.listeningPort; return false; } }); }); }); }); return portNumber; } function listServices() { $(document).ready(function() { $("#list").text(""); var jList = $("#list"); var listOfServers = $("#servers").text(); var serverArray = listOfServers.split(","); for (var i = 0; i < serverArray.length; i++) { var port = getPortNumber(); var tempURL = "http://"+serverArray[i].trim().toLowerCase()+".javaworkspace.com:"+port+"/services/listServices"; jList.append("<li><a href="+tempURL+" target='_blank'>"+tempURL+"</a></li>"); } }); } ```
2013/03/20
[ "https://Stackoverflow.com/questions/15516429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2189478/" ]
It sounds like you need to learn the art of stepping into callback functions in the javascript debugger. It doesn't quite work the simple way you'd like. It won't step into a callback function even thought the callback function looks like the logical next line of execution. Technically it isn't. When you say to step over a line of code, it steps over everything that line of code does including any callback functions that it calls. When you step over `$(document).ready(function()` and the document is not yet ready, it does NOT execute the callback function and the debugger does not go into that function. So, if you want to see what happens when that callback function is actually executed, you have to manually put a breakpoint in that callback function. You can't just step into it line by line. The same is true of your `$.getJSON(port_url, function(result) {` call and your `$.each()` call. When you say to step over the `$.each()` function, it literally steps over that function and onto the next line after that function. That skips the entire callback. If you want to step into the `$.each()`, you have to either manually set a breakpoint in the callback or you have to single step into the `$.each()` implementation in jQuery and watch it eventually call your callback. So in this code: ``` function getPortNumber() { var portNumber; var domainValue = $("#domain").val(); $(document).ready(function() { $.getJSON(port_url, function(result) { $.each(result, function() { $.each(this, function(k, v) { if (v.category == domainValue) { portNumber = v.listeningPort; return false; } }); }); }); }); return portNumber; } ``` If you want to see what happens in the inner `$.each()` loop, you will have to set a breakpoint on this line `if (v.category == domainValue) {` and let the code run until it hits that breakpoint. Single stepping through getPortNumber() in the debugger will encounter problems at each of the four places that you use callback functions: `$(document).ready()`, `$.getJSON()`, `$.each()` and `$.each()`. So, to get inside of those, you will want to set a breakpoint inside them and let the code run until it hits that breakpoint.
If some error exist there then it will skip. Why you used `$(document).ready(function()`
15,516,429
I just want to create a dynamic URL. I am calling the listServices method and it is working as expected where as the getPortNumber which i am calling from listService is not working. I added dubug point in getPortNumber method. I am getting value for domainValue but I am not able to debug after $(document).ready(function(). The control directly goes to return portNumber and in the final URL i am getting the port number value as undefined. I checked and validated the port\_url (json file). my json file looks like this ``` { "servers": [ { "listeningPort": "6080", "shutdownPort": "8180", "redirectPort": "8443", "sslPort": "8443", "openWirePort": "61610", "jmxPort": "9332", "category": "Test A" } } ``` I got struck. I hope this issue is not becoz of calling javascript method from another method. ``` function getPortNumber() { var portNumber; var domainValue = $("#domain").val(); $(document).ready(function() { $.getJSON(port_url, function(result) { $.each(result, function() { $.each(this, function(k, v) { if (v.category == domainValue) { portNumber = v.listeningPort; return false; } }); }); }); }); return portNumber; } function listServices() { $(document).ready(function() { $("#list").text(""); var jList = $("#list"); var listOfServers = $("#servers").text(); var serverArray = listOfServers.split(","); for (var i = 0; i < serverArray.length; i++) { var port = getPortNumber(); var tempURL = "http://"+serverArray[i].trim().toLowerCase()+".javaworkspace.com:"+port+"/services/listServices"; jList.append("<li><a href="+tempURL+" target='_blank'>"+tempURL+"</a></li>"); } }); } ```
2013/03/20
[ "https://Stackoverflow.com/questions/15516429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2189478/" ]
It sounds like you need to learn the art of stepping into callback functions in the javascript debugger. It doesn't quite work the simple way you'd like. It won't step into a callback function even thought the callback function looks like the logical next line of execution. Technically it isn't. When you say to step over a line of code, it steps over everything that line of code does including any callback functions that it calls. When you step over `$(document).ready(function()` and the document is not yet ready, it does NOT execute the callback function and the debugger does not go into that function. So, if you want to see what happens when that callback function is actually executed, you have to manually put a breakpoint in that callback function. You can't just step into it line by line. The same is true of your `$.getJSON(port_url, function(result) {` call and your `$.each()` call. When you say to step over the `$.each()` function, it literally steps over that function and onto the next line after that function. That skips the entire callback. If you want to step into the `$.each()`, you have to either manually set a breakpoint in the callback or you have to single step into the `$.each()` implementation in jQuery and watch it eventually call your callback. So in this code: ``` function getPortNumber() { var portNumber; var domainValue = $("#domain").val(); $(document).ready(function() { $.getJSON(port_url, function(result) { $.each(result, function() { $.each(this, function(k, v) { if (v.category == domainValue) { portNumber = v.listeningPort; return false; } }); }); }); }); return portNumber; } ``` If you want to see what happens in the inner `$.each()` loop, you will have to set a breakpoint on this line `if (v.category == domainValue) {` and let the code run until it hits that breakpoint. Single stepping through getPortNumber() in the debugger will encounter problems at each of the four places that you use callback functions: `$(document).ready()`, `$.getJSON()`, `$.each()` and `$.each()`. So, to get inside of those, you will want to set a breakpoint inside them and let the code run until it hits that breakpoint.
After removing $(document).ready(function() from getPortNumber the debug skip code after $.getJSON(port\_url, function(result) {. Firebug is not reporting any errors.
54,740,667
I have a "source.fasta" file that contains information in the following format: ``` >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG >TRINITY_DN83_c0_g1_i1 len=371 path=[1:0-173 152:174-370] [-1, 1, 152, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTATCGAGTAAGTTTACAGTCGTAAATAAAGAATCTGCCTTGAACAAACCTTATTCCTTTTTATTCTAAAAGAGGCCTTTGCGTAGTAGTAACATAGTACAAATTGGTTTATTTAACGATTTATAAACGATATCCTTCCTACAGTCGGGTGAAAAGAAAGTATTCGAAATTAGAATGGTTCCTCATATTACACGTTGCTG >TRINITY_DN83_c0_g1_i2 len=218 path=[1:0-173 741:174-217] [-1, 1, 741, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTACCGAGTAAGTTTCCAGTCGTAAATAAAGAATCTGCCAGATCGGA >TRINITY_DN99_c0_g1_i1 len=326 path=[1:0-242 221:243-243 652:244-267 246:268-325] [-1, 1, 221, 652, 246, -2] ATCGGTACTATCATGTCATATATCTAGAAATAATACCTACGAATGTTATAAGAATTTCATAACATGATATAACGATCATACATCATGGCCTTTCGAAGAAAATGGCGCATTTACGTTTAATAATTCCGCGAAAGTCAAGGCAAATACAGACCTAATGCGAAATTGAAAAGAAAATCCGAATATCAGAAACAGAACCCAGAACCAATATGCTCAGCAGTTGCTTTGTAGCCAATAAACTCAACTAGAAATTGCTTATCTTTTATGTAACGCCATAAAACGTAATACCGATAACAGACTAAGCACACATATGTAAATTACCTGCTAAA >TRINITY_DN90_c0_g1_i1 len=1240 path=[1970:0-527 753:528-1239] [-1, 1970, 753, -2] GTCGATACTAGACAACGAATAATTGTGTCTATTTTTAAAAATAATTCCTTTTGTAAGCAGATTTTTTTTTTCATGCATGTTTCGAGTAAATTGGATTACGCATTCCACGTAACATCGTAAATGTAACCACATTGTTGTAACATACGGTATTTTTTCTGACAACGGACTCGATTGTAAGCAACTTTGTAACATTATAATCCTATGAGTATGACATTCTTAATAATAGCAACAGGGATAAAAATAAAACTACATTGTTTCATTCAACTCGTAAGTGTTTATTTAAAATTATTATTAAACACTATTGTAATAAAGTTTATATTCCTTTGTCAGTGGTAGACACATAAACAGTTTTCGAGTTCACTGTCG >TRINITY_DN84_c0_g1_i1 len=301 path=[1:0-220 358:221-300] [-1, 1, 358, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCACTTTTAAATCTTATAAACATGTGATCCGTCTGCTCATTTGGACGTTACTGCCCAAAGTTGGTACATGTTTCGTACTCACG >TRINITY_DN84_c0_g1_i2 len=301 path=[1:0-220 199:221-300] [-1, 1, 199, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCAGCTAACCAAAGATAAGTGTCTTGGCTTGGTATCTACAGATCTCTTTTCGTAATTTCGTGAGTACGAAACATGTACCAACT >TRINITY_DN72_c0_g1_i1 len=434 path=[412:0-247 847:248-271 661:272-433] [-1, 412, 847, 661, -2] GTTAATTTAGTGGGAAGTATGTGTTAAAATTAGTAAATTAGGTGTTGGTGTGTTTTTAATATGAATCCGGAAGTGTTTTGTTAGGTTACAAGGGTACGGAATTGTAATAATAGAAATCGGTATCCTTGAGACCAATGTTATCGCATTCGATGCAAGAATAGATTGGGAAATAGTCCGGTTATCAATTACTTAAAGATTTCTATCTTGAAAACTATTTCTAATTGGTAAAAAAACTTATTTAGAATCACCCATAGTTGGAAGTTTAAGATTTGAGACATCTTAAATTTTTGGTAGGTAATTTTAAGATTCTATCGTAGTTAGTACCTTTCGTTCTTCTTATTTTATTTGTAAAATATATTACATTTAGTACGAGTATTGTATTTCCAATATTCAGTCTAATTAGAATTGCAAAATTACTGAACACTCAATCATAA >TRINITY_DN75_c0_g1_i1 len=478 path=[456:0-477] [-1, 456, -2] CGAGCACATCAGGCCAGGGTTCCCCAAGTGCTCGAGTTTCGTAACCAAACAACCATCTTCTGGTCCGACCACCAGTCACATGATCAGCTGTGGCGCTCAGTATACGAGCACAGATTGCAACAGCCACCAAATGAGAGAGGAAAGTCATCCACATTGCCATGAAATCTGCGAAAGAGCGTAAATTGCGAGTAGCATGACCGCAGGTACGGCGCAGTAGCTGGAGTTGGCAGCGGCTAGGGGTGCCAGGAGGAGTGCTCCAAGGGTCCATCGTGCTCCACATGCCTCCCCGCCGCTGAACGCGCTCAGAGCCTTGCTCATCTTGCTACGCTCGCTCCGTTCAGTCATCTTCGTGTCTCATCGTCGCAGCGCGTAGTATTTACG ``` There are close to 400,000 sequences in this file. I have another file ids.txt in the following format: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 >TRINITY_DN15434_c5_g3_i1 >TRINITY_DN9323_c8_g3_i5 >TRINITY_DN11957_c1_g7_i1 >TRINITY_DN15373_c1_g1_i1 >TRINITY_DN22913_c0_g1_i1 >TRINITY_DN13029_c4_g5_i1 ``` I have 100 sequence ids in this file. When I match these ids to the source file I want an output that gives me the match for each of these ids with the entire sequence. For example, for an id: ``` >TRINITY_DN80_c0_g1_i1 ``` I want my output to be: ``` >TRINITY_DN80_c0_g1_i1 CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` I want all hundred sequences in this format. I used this code: ``` while read p; do echo ''$p >> out.fasta grep -A 400000 -w $p source.fasta | sed -n -e '1,/>/ {/>/ !{'p''}} >> out.fasta done < ids.txt ``` But my output is different in that only the last id has a sequence and the rest dont have any sequence associated: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 .... >TRINITY_DN10309_c6_g3_i1 >TRINITY_DN6990_c0_g1_i1 TTTTTTTTTTTTTGTGGAAAAACATTGATTTTATTGAATTGTAAACTTAAAATTAGATTGGCTGCACATCTTAGATTTTGTTGAAAGCAGCAATATCAACAGACTGGACGAAGTCTTCGAATTCCTGGATTTTTTCAGTCAAGAGATCAACAGACACTTTGTCGTCTTCAATGACACACATGATCTGCAGTTTGTTGATACCATATCCAACAGGTACAAGTTTGGAAGCTCCCCAGAGGAGACCATCCATTTCGATGGTGCGGACCTGGTTTTCCATTTCTTTCATGTCTGTTTCATCATCCCATGGCTTGACGTCAAGGATTATAGATGATTTAGCAATGAGAGCAGGTTTCTTCGATTTTTTGTCAGCATAAGCTTTCAGACGTTCTTCACGAATTCTGGCGGCCTCTGCATCCTCTTCCTCGTCGCCAGATCCGAATAGGTCGACGTCATCATCGTCGTCATCCTTAGCAGCGGGTGCAGGTGCTGTGGTGGTCTTTCCGCCAGCGGTCAGAGGGCTAGCTCCAGCCGCCCAGGATTTGCGCTCCTCGGCATTGTAGGAGGCAATCTGGTTGTACCACCGGAGAGCGTGGGGCAAGCTTGCGCTCGGGGCCTTGCCGACTTGTTGGAACACTTGGAAATCGGCTTGAGTTGGTGTGTAACCTGACACATAACTCTTATCAGCTAAGAAATTGTTAAGCTCATTAAGGCCTTGTGCGGTTTTAACGTCTCCTACTGCCATTTTTATTTAAAAAAGTAGTTTTTTTCGAGTAATAGCCACACGCCCCGGCACAATGTGAGCAAGAAGGAATGAAAAAGAAATCTGACATTGACATTGCCATGAAATTGACTTTCAAAGAACGAATGAATTGAACTAATTTGAACGG ``` I am only getting the desired output for the 100th id from my ids.txt. Could someone help me on where my script is wrong. I would like to get all 100 sequences when i run the script. Thank you I have added google drive links to the files i am working with: [ids.txt](https://drive.google.com/open?id=1t1dv5GlbwD-qfN2EYVRSVYxo2XPxGHWx) [Source.fasta](https://drive.google.com/open?id=1gMjwOjUAgmr04EFpZDKpkEHMcC3YlzlR)
2019/02/18
[ "https://Stackoverflow.com/questions/54740667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296702/" ]
Only with GNU grep and sed: ``` grep -A 1 -w -F -f ids.txt source.fasta | sed 's/ .*//' ``` --- See: `man grep`
First group all id's as one expression separated by | like this ``` cat ids.txt | tr '\n' '|' | awk "{print "\"" $0 "\""}' ``` Remove the last | symbol from the expression. Now you can grep using the output you got from previous command like this ``` egrep -E ">TRINITY_DN14840_c10_g1_i1|>TRINITY_DN8506_c0_g1_i1|>TRINITY_DN12276_c0_g2_i1|>TRINITY_DN15434_c5_g3_i1|>TRINITY_DN9323_c8_g3_i5|>TRINITY_DN11957_c1_g7_i1|>TRINITY_DN15373_c1_g1_i1|>TRINITY_DN22913_c0_g1_i1|>TRINITY_DN13029_c4_g5_i1" source.fasta ``` This will print only the matching lines Editing as per tripleee comments Using the following is printing the output properly Assuming the ID and sequence are in different lined ``` tr '\n' '|' <ids.txt | sed 's/|$//' | grep -A 1 -E -f - source.fasta ```
54,740,667
I have a "source.fasta" file that contains information in the following format: ``` >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG >TRINITY_DN83_c0_g1_i1 len=371 path=[1:0-173 152:174-370] [-1, 1, 152, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTATCGAGTAAGTTTACAGTCGTAAATAAAGAATCTGCCTTGAACAAACCTTATTCCTTTTTATTCTAAAAGAGGCCTTTGCGTAGTAGTAACATAGTACAAATTGGTTTATTTAACGATTTATAAACGATATCCTTCCTACAGTCGGGTGAAAAGAAAGTATTCGAAATTAGAATGGTTCCTCATATTACACGTTGCTG >TRINITY_DN83_c0_g1_i2 len=218 path=[1:0-173 741:174-217] [-1, 1, 741, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTACCGAGTAAGTTTCCAGTCGTAAATAAAGAATCTGCCAGATCGGA >TRINITY_DN99_c0_g1_i1 len=326 path=[1:0-242 221:243-243 652:244-267 246:268-325] [-1, 1, 221, 652, 246, -2] ATCGGTACTATCATGTCATATATCTAGAAATAATACCTACGAATGTTATAAGAATTTCATAACATGATATAACGATCATACATCATGGCCTTTCGAAGAAAATGGCGCATTTACGTTTAATAATTCCGCGAAAGTCAAGGCAAATACAGACCTAATGCGAAATTGAAAAGAAAATCCGAATATCAGAAACAGAACCCAGAACCAATATGCTCAGCAGTTGCTTTGTAGCCAATAAACTCAACTAGAAATTGCTTATCTTTTATGTAACGCCATAAAACGTAATACCGATAACAGACTAAGCACACATATGTAAATTACCTGCTAAA >TRINITY_DN90_c0_g1_i1 len=1240 path=[1970:0-527 753:528-1239] [-1, 1970, 753, -2] GTCGATACTAGACAACGAATAATTGTGTCTATTTTTAAAAATAATTCCTTTTGTAAGCAGATTTTTTTTTTCATGCATGTTTCGAGTAAATTGGATTACGCATTCCACGTAACATCGTAAATGTAACCACATTGTTGTAACATACGGTATTTTTTCTGACAACGGACTCGATTGTAAGCAACTTTGTAACATTATAATCCTATGAGTATGACATTCTTAATAATAGCAACAGGGATAAAAATAAAACTACATTGTTTCATTCAACTCGTAAGTGTTTATTTAAAATTATTATTAAACACTATTGTAATAAAGTTTATATTCCTTTGTCAGTGGTAGACACATAAACAGTTTTCGAGTTCACTGTCG >TRINITY_DN84_c0_g1_i1 len=301 path=[1:0-220 358:221-300] [-1, 1, 358, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCACTTTTAAATCTTATAAACATGTGATCCGTCTGCTCATTTGGACGTTACTGCCCAAAGTTGGTACATGTTTCGTACTCACG >TRINITY_DN84_c0_g1_i2 len=301 path=[1:0-220 199:221-300] [-1, 1, 199, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCAGCTAACCAAAGATAAGTGTCTTGGCTTGGTATCTACAGATCTCTTTTCGTAATTTCGTGAGTACGAAACATGTACCAACT >TRINITY_DN72_c0_g1_i1 len=434 path=[412:0-247 847:248-271 661:272-433] [-1, 412, 847, 661, -2] GTTAATTTAGTGGGAAGTATGTGTTAAAATTAGTAAATTAGGTGTTGGTGTGTTTTTAATATGAATCCGGAAGTGTTTTGTTAGGTTACAAGGGTACGGAATTGTAATAATAGAAATCGGTATCCTTGAGACCAATGTTATCGCATTCGATGCAAGAATAGATTGGGAAATAGTCCGGTTATCAATTACTTAAAGATTTCTATCTTGAAAACTATTTCTAATTGGTAAAAAAACTTATTTAGAATCACCCATAGTTGGAAGTTTAAGATTTGAGACATCTTAAATTTTTGGTAGGTAATTTTAAGATTCTATCGTAGTTAGTACCTTTCGTTCTTCTTATTTTATTTGTAAAATATATTACATTTAGTACGAGTATTGTATTTCCAATATTCAGTCTAATTAGAATTGCAAAATTACTGAACACTCAATCATAA >TRINITY_DN75_c0_g1_i1 len=478 path=[456:0-477] [-1, 456, -2] CGAGCACATCAGGCCAGGGTTCCCCAAGTGCTCGAGTTTCGTAACCAAACAACCATCTTCTGGTCCGACCACCAGTCACATGATCAGCTGTGGCGCTCAGTATACGAGCACAGATTGCAACAGCCACCAAATGAGAGAGGAAAGTCATCCACATTGCCATGAAATCTGCGAAAGAGCGTAAATTGCGAGTAGCATGACCGCAGGTACGGCGCAGTAGCTGGAGTTGGCAGCGGCTAGGGGTGCCAGGAGGAGTGCTCCAAGGGTCCATCGTGCTCCACATGCCTCCCCGCCGCTGAACGCGCTCAGAGCCTTGCTCATCTTGCTACGCTCGCTCCGTTCAGTCATCTTCGTGTCTCATCGTCGCAGCGCGTAGTATTTACG ``` There are close to 400,000 sequences in this file. I have another file ids.txt in the following format: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 >TRINITY_DN15434_c5_g3_i1 >TRINITY_DN9323_c8_g3_i5 >TRINITY_DN11957_c1_g7_i1 >TRINITY_DN15373_c1_g1_i1 >TRINITY_DN22913_c0_g1_i1 >TRINITY_DN13029_c4_g5_i1 ``` I have 100 sequence ids in this file. When I match these ids to the source file I want an output that gives me the match for each of these ids with the entire sequence. For example, for an id: ``` >TRINITY_DN80_c0_g1_i1 ``` I want my output to be: ``` >TRINITY_DN80_c0_g1_i1 CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` I want all hundred sequences in this format. I used this code: ``` while read p; do echo ''$p >> out.fasta grep -A 400000 -w $p source.fasta | sed -n -e '1,/>/ {/>/ !{'p''}} >> out.fasta done < ids.txt ``` But my output is different in that only the last id has a sequence and the rest dont have any sequence associated: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 .... >TRINITY_DN10309_c6_g3_i1 >TRINITY_DN6990_c0_g1_i1 TTTTTTTTTTTTTGTGGAAAAACATTGATTTTATTGAATTGTAAACTTAAAATTAGATTGGCTGCACATCTTAGATTTTGTTGAAAGCAGCAATATCAACAGACTGGACGAAGTCTTCGAATTCCTGGATTTTTTCAGTCAAGAGATCAACAGACACTTTGTCGTCTTCAATGACACACATGATCTGCAGTTTGTTGATACCATATCCAACAGGTACAAGTTTGGAAGCTCCCCAGAGGAGACCATCCATTTCGATGGTGCGGACCTGGTTTTCCATTTCTTTCATGTCTGTTTCATCATCCCATGGCTTGACGTCAAGGATTATAGATGATTTAGCAATGAGAGCAGGTTTCTTCGATTTTTTGTCAGCATAAGCTTTCAGACGTTCTTCACGAATTCTGGCGGCCTCTGCATCCTCTTCCTCGTCGCCAGATCCGAATAGGTCGACGTCATCATCGTCGTCATCCTTAGCAGCGGGTGCAGGTGCTGTGGTGGTCTTTCCGCCAGCGGTCAGAGGGCTAGCTCCAGCCGCCCAGGATTTGCGCTCCTCGGCATTGTAGGAGGCAATCTGGTTGTACCACCGGAGAGCGTGGGGCAAGCTTGCGCTCGGGGCCTTGCCGACTTGTTGGAACACTTGGAAATCGGCTTGAGTTGGTGTGTAACCTGACACATAACTCTTATCAGCTAAGAAATTGTTAAGCTCATTAAGGCCTTGTGCGGTTTTAACGTCTCCTACTGCCATTTTTATTTAAAAAAGTAGTTTTTTTCGAGTAATAGCCACACGCCCCGGCACAATGTGAGCAAGAAGGAATGAAAAAGAAATCTGACATTGACATTGCCATGAAATTGACTTTCAAAGAACGAATGAATTGAACTAATTTGAACGG ``` I am only getting the desired output for the 100th id from my ids.txt. Could someone help me on where my script is wrong. I would like to get all 100 sequences when i run the script. Thank you I have added google drive links to the files i am working with: [ids.txt](https://drive.google.com/open?id=1t1dv5GlbwD-qfN2EYVRSVYxo2XPxGHWx) [Source.fasta](https://drive.google.com/open?id=1gMjwOjUAgmr04EFpZDKpkEHMcC3YlzlR)
2019/02/18
[ "https://Stackoverflow.com/questions/54740667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296702/" ]
Repeatedly looping over a large file is inefficient; you really want to avoid running `grep` (or `sed` or `awk`) more than once if you can avoid it. Generally speaking, `sed` and Awk will often easily allow you to specify actions for individual lines in a file, and then you run the script on the file just once. For this particular problem, the standard Awk idiom with `NR==FNR` comes in handy. This is a mechanism which lets you read a number of keys into memory (concretely, when `NR==FNR` it means that you are processing the first input file, because the overall input line number is equal to the line number within this file) and then check if they are present in subsequent input files. Recall that Awk reads one line at a time and performs all the actions whose conditions match. The conditions are a simple boolean, and the actions are a set of Awk commands within a pair of braces. ``` awk 'NR == FNR { s[$0]; next } # If we fall through to here, we have finished processing the first file. # If we see a wedge and p is 1, reset it -- this is a new sequence /^>/ && p { p = 0 } # If the prefix of this line is in s, we have found a sequence we want. ($1$2 in s) || ($1 in s) || ((substr($1, 1, 1) " " substr($1, 2)) in s) { if ($1 ~ /^>./) { print $1 } else { print $1 $2 }; p = 1; next } # If p is true, we want to print this line p' ids.txt source.fasta >out.fasta ``` So when we are reading `ids.txt`, the condition `NR==FNR` is true, and so we simply store each line in the array `s`. The `next` causes the rest of the Awk script to be skipped for this line. On subsequent reads, when `NR!=FNR`, we use the variable `p` to control what to print. When we see a new sequence, we set `p` to 0 (in case it was 1 from a previous iteration). Then when we see a new sequence, we check if it is in `s`, and if so, we set `p` to one. The last line simply prints the line if `p` is not empty or zero. (An empty action is a shorthand for the action `{ print }`.) The slightly complex condition to check if `$1` is in `s` might be too complicated -- I put in some normalizations to make sure that a space between the `>` and the sequence identifier is tolerated, regardless of there was one in `ids.txt` or not. This can probably be simplified if your files are consistently formatted.
Only with GNU grep and sed: ``` grep -A 1 -w -F -f ids.txt source.fasta | sed 's/ .*//' ``` --- See: `man grep`
54,740,667
I have a "source.fasta" file that contains information in the following format: ``` >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG >TRINITY_DN83_c0_g1_i1 len=371 path=[1:0-173 152:174-370] [-1, 1, 152, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTATCGAGTAAGTTTACAGTCGTAAATAAAGAATCTGCCTTGAACAAACCTTATTCCTTTTTATTCTAAAAGAGGCCTTTGCGTAGTAGTAACATAGTACAAATTGGTTTATTTAACGATTTATAAACGATATCCTTCCTACAGTCGGGTGAAAAGAAAGTATTCGAAATTAGAATGGTTCCTCATATTACACGTTGCTG >TRINITY_DN83_c0_g1_i2 len=218 path=[1:0-173 741:174-217] [-1, 1, 741, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTACCGAGTAAGTTTCCAGTCGTAAATAAAGAATCTGCCAGATCGGA >TRINITY_DN99_c0_g1_i1 len=326 path=[1:0-242 221:243-243 652:244-267 246:268-325] [-1, 1, 221, 652, 246, -2] ATCGGTACTATCATGTCATATATCTAGAAATAATACCTACGAATGTTATAAGAATTTCATAACATGATATAACGATCATACATCATGGCCTTTCGAAGAAAATGGCGCATTTACGTTTAATAATTCCGCGAAAGTCAAGGCAAATACAGACCTAATGCGAAATTGAAAAGAAAATCCGAATATCAGAAACAGAACCCAGAACCAATATGCTCAGCAGTTGCTTTGTAGCCAATAAACTCAACTAGAAATTGCTTATCTTTTATGTAACGCCATAAAACGTAATACCGATAACAGACTAAGCACACATATGTAAATTACCTGCTAAA >TRINITY_DN90_c0_g1_i1 len=1240 path=[1970:0-527 753:528-1239] [-1, 1970, 753, -2] GTCGATACTAGACAACGAATAATTGTGTCTATTTTTAAAAATAATTCCTTTTGTAAGCAGATTTTTTTTTTCATGCATGTTTCGAGTAAATTGGATTACGCATTCCACGTAACATCGTAAATGTAACCACATTGTTGTAACATACGGTATTTTTTCTGACAACGGACTCGATTGTAAGCAACTTTGTAACATTATAATCCTATGAGTATGACATTCTTAATAATAGCAACAGGGATAAAAATAAAACTACATTGTTTCATTCAACTCGTAAGTGTTTATTTAAAATTATTATTAAACACTATTGTAATAAAGTTTATATTCCTTTGTCAGTGGTAGACACATAAACAGTTTTCGAGTTCACTGTCG >TRINITY_DN84_c0_g1_i1 len=301 path=[1:0-220 358:221-300] [-1, 1, 358, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCACTTTTAAATCTTATAAACATGTGATCCGTCTGCTCATTTGGACGTTACTGCCCAAAGTTGGTACATGTTTCGTACTCACG >TRINITY_DN84_c0_g1_i2 len=301 path=[1:0-220 199:221-300] [-1, 1, 199, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCAGCTAACCAAAGATAAGTGTCTTGGCTTGGTATCTACAGATCTCTTTTCGTAATTTCGTGAGTACGAAACATGTACCAACT >TRINITY_DN72_c0_g1_i1 len=434 path=[412:0-247 847:248-271 661:272-433] [-1, 412, 847, 661, -2] GTTAATTTAGTGGGAAGTATGTGTTAAAATTAGTAAATTAGGTGTTGGTGTGTTTTTAATATGAATCCGGAAGTGTTTTGTTAGGTTACAAGGGTACGGAATTGTAATAATAGAAATCGGTATCCTTGAGACCAATGTTATCGCATTCGATGCAAGAATAGATTGGGAAATAGTCCGGTTATCAATTACTTAAAGATTTCTATCTTGAAAACTATTTCTAATTGGTAAAAAAACTTATTTAGAATCACCCATAGTTGGAAGTTTAAGATTTGAGACATCTTAAATTTTTGGTAGGTAATTTTAAGATTCTATCGTAGTTAGTACCTTTCGTTCTTCTTATTTTATTTGTAAAATATATTACATTTAGTACGAGTATTGTATTTCCAATATTCAGTCTAATTAGAATTGCAAAATTACTGAACACTCAATCATAA >TRINITY_DN75_c0_g1_i1 len=478 path=[456:0-477] [-1, 456, -2] CGAGCACATCAGGCCAGGGTTCCCCAAGTGCTCGAGTTTCGTAACCAAACAACCATCTTCTGGTCCGACCACCAGTCACATGATCAGCTGTGGCGCTCAGTATACGAGCACAGATTGCAACAGCCACCAAATGAGAGAGGAAAGTCATCCACATTGCCATGAAATCTGCGAAAGAGCGTAAATTGCGAGTAGCATGACCGCAGGTACGGCGCAGTAGCTGGAGTTGGCAGCGGCTAGGGGTGCCAGGAGGAGTGCTCCAAGGGTCCATCGTGCTCCACATGCCTCCCCGCCGCTGAACGCGCTCAGAGCCTTGCTCATCTTGCTACGCTCGCTCCGTTCAGTCATCTTCGTGTCTCATCGTCGCAGCGCGTAGTATTTACG ``` There are close to 400,000 sequences in this file. I have another file ids.txt in the following format: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 >TRINITY_DN15434_c5_g3_i1 >TRINITY_DN9323_c8_g3_i5 >TRINITY_DN11957_c1_g7_i1 >TRINITY_DN15373_c1_g1_i1 >TRINITY_DN22913_c0_g1_i1 >TRINITY_DN13029_c4_g5_i1 ``` I have 100 sequence ids in this file. When I match these ids to the source file I want an output that gives me the match for each of these ids with the entire sequence. For example, for an id: ``` >TRINITY_DN80_c0_g1_i1 ``` I want my output to be: ``` >TRINITY_DN80_c0_g1_i1 CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` I want all hundred sequences in this format. I used this code: ``` while read p; do echo ''$p >> out.fasta grep -A 400000 -w $p source.fasta | sed -n -e '1,/>/ {/>/ !{'p''}} >> out.fasta done < ids.txt ``` But my output is different in that only the last id has a sequence and the rest dont have any sequence associated: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 .... >TRINITY_DN10309_c6_g3_i1 >TRINITY_DN6990_c0_g1_i1 TTTTTTTTTTTTTGTGGAAAAACATTGATTTTATTGAATTGTAAACTTAAAATTAGATTGGCTGCACATCTTAGATTTTGTTGAAAGCAGCAATATCAACAGACTGGACGAAGTCTTCGAATTCCTGGATTTTTTCAGTCAAGAGATCAACAGACACTTTGTCGTCTTCAATGACACACATGATCTGCAGTTTGTTGATACCATATCCAACAGGTACAAGTTTGGAAGCTCCCCAGAGGAGACCATCCATTTCGATGGTGCGGACCTGGTTTTCCATTTCTTTCATGTCTGTTTCATCATCCCATGGCTTGACGTCAAGGATTATAGATGATTTAGCAATGAGAGCAGGTTTCTTCGATTTTTTGTCAGCATAAGCTTTCAGACGTTCTTCACGAATTCTGGCGGCCTCTGCATCCTCTTCCTCGTCGCCAGATCCGAATAGGTCGACGTCATCATCGTCGTCATCCTTAGCAGCGGGTGCAGGTGCTGTGGTGGTCTTTCCGCCAGCGGTCAGAGGGCTAGCTCCAGCCGCCCAGGATTTGCGCTCCTCGGCATTGTAGGAGGCAATCTGGTTGTACCACCGGAGAGCGTGGGGCAAGCTTGCGCTCGGGGCCTTGCCGACTTGTTGGAACACTTGGAAATCGGCTTGAGTTGGTGTGTAACCTGACACATAACTCTTATCAGCTAAGAAATTGTTAAGCTCATTAAGGCCTTGTGCGGTTTTAACGTCTCCTACTGCCATTTTTATTTAAAAAAGTAGTTTTTTTCGAGTAATAGCCACACGCCCCGGCACAATGTGAGCAAGAAGGAATGAAAAAGAAATCTGACATTGACATTGCCATGAAATTGACTTTCAAAGAACGAATGAATTGAACTAATTTGAACGG ``` I am only getting the desired output for the 100th id from my ids.txt. Could someone help me on where my script is wrong. I would like to get all 100 sequences when i run the script. Thank you I have added google drive links to the files i am working with: [ids.txt](https://drive.google.com/open?id=1t1dv5GlbwD-qfN2EYVRSVYxo2XPxGHWx) [Source.fasta](https://drive.google.com/open?id=1gMjwOjUAgmr04EFpZDKpkEHMcC3YlzlR)
2019/02/18
[ "https://Stackoverflow.com/questions/54740667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296702/" ]
the best way to do this is using either python or perl. I was able to make a script for extracting the ids using python as follows. ``` #script to extract sequences from a source file based on ids in another file #the source is a fasta file with a header and a sequence that follows in one line #the ids file contains one id per line #both the id and source file should contain the character '>' at the beginning that siginifies an id def main(): #asks the user for the ids file file1 = raw_input('ids file: '); #opens the ids file into the memory ids_file = open(file1, 'r'); #asks the user for the fasta file file2 = raw_input('fasta file: '); #opens the fasta file into memory; you need your memory to be larger than the filesize, or python will hard crash fasta_file = open(file2, 'r'); #ask the user for the file name of output file file3 = raw_input('enter the output filename: '); #opens output file with append option; append is must as you dont want to override the existing data output_file = open(file3, 'w'); #split the ids into an array ids_lines = ids_file.read().splitlines() #split the fasta file into an array, the first element will be the id followed by the sequence fasta_lines = fasta_file.read().splitlines() #initializing loop counters i = 0; j = 0; #while loop to iterate over the length of the ids file as this is the limiter for the program while j<len(fasta_lines) and i<len(ids_lines): #if statement to match ids from both files and bring matching sequences if ids_lines[i] == fasta_lines[j]: #output statements including newline characters output_file.write(fasta_lines[j]) output_file.write('\n') output_file.write(fasta_lines[j+1]) output_file.write('\n') #increment i so that we go for the next id i=i+1; #deprecate j so we start all over for the new id j=0; else: #when there is no match check the id, we are skipping the sequence in the middle which is j+1 j=j+2; ids_file.close() fasta_file.close() output_file.close() main()` ``` The code is not perfect but works for any number of ids. I have tested for my samples which contained 5000 ids in one of them and the program worked fine. If there are improvements to the code please do so, I am a relatively newbie at programming so the code is a bit crude.
This might work for you (GNU sed): ``` sed 's#.*#/^&/{s/ .*//;N;p}#' idFile | sed -nf - fastafile ``` Convert the idFile into a sed script and run it against the fastaFile.
54,740,667
I have a "source.fasta" file that contains information in the following format: ``` >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG >TRINITY_DN83_c0_g1_i1 len=371 path=[1:0-173 152:174-370] [-1, 1, 152, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTATCGAGTAAGTTTACAGTCGTAAATAAAGAATCTGCCTTGAACAAACCTTATTCCTTTTTATTCTAAAAGAGGCCTTTGCGTAGTAGTAACATAGTACAAATTGGTTTATTTAACGATTTATAAACGATATCCTTCCTACAGTCGGGTGAAAAGAAAGTATTCGAAATTAGAATGGTTCCTCATATTACACGTTGCTG >TRINITY_DN83_c0_g1_i2 len=218 path=[1:0-173 741:174-217] [-1, 1, 741, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTACCGAGTAAGTTTCCAGTCGTAAATAAAGAATCTGCCAGATCGGA >TRINITY_DN99_c0_g1_i1 len=326 path=[1:0-242 221:243-243 652:244-267 246:268-325] [-1, 1, 221, 652, 246, -2] ATCGGTACTATCATGTCATATATCTAGAAATAATACCTACGAATGTTATAAGAATTTCATAACATGATATAACGATCATACATCATGGCCTTTCGAAGAAAATGGCGCATTTACGTTTAATAATTCCGCGAAAGTCAAGGCAAATACAGACCTAATGCGAAATTGAAAAGAAAATCCGAATATCAGAAACAGAACCCAGAACCAATATGCTCAGCAGTTGCTTTGTAGCCAATAAACTCAACTAGAAATTGCTTATCTTTTATGTAACGCCATAAAACGTAATACCGATAACAGACTAAGCACACATATGTAAATTACCTGCTAAA >TRINITY_DN90_c0_g1_i1 len=1240 path=[1970:0-527 753:528-1239] [-1, 1970, 753, -2] GTCGATACTAGACAACGAATAATTGTGTCTATTTTTAAAAATAATTCCTTTTGTAAGCAGATTTTTTTTTTCATGCATGTTTCGAGTAAATTGGATTACGCATTCCACGTAACATCGTAAATGTAACCACATTGTTGTAACATACGGTATTTTTTCTGACAACGGACTCGATTGTAAGCAACTTTGTAACATTATAATCCTATGAGTATGACATTCTTAATAATAGCAACAGGGATAAAAATAAAACTACATTGTTTCATTCAACTCGTAAGTGTTTATTTAAAATTATTATTAAACACTATTGTAATAAAGTTTATATTCCTTTGTCAGTGGTAGACACATAAACAGTTTTCGAGTTCACTGTCG >TRINITY_DN84_c0_g1_i1 len=301 path=[1:0-220 358:221-300] [-1, 1, 358, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCACTTTTAAATCTTATAAACATGTGATCCGTCTGCTCATTTGGACGTTACTGCCCAAAGTTGGTACATGTTTCGTACTCACG >TRINITY_DN84_c0_g1_i2 len=301 path=[1:0-220 199:221-300] [-1, 1, 199, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCAGCTAACCAAAGATAAGTGTCTTGGCTTGGTATCTACAGATCTCTTTTCGTAATTTCGTGAGTACGAAACATGTACCAACT >TRINITY_DN72_c0_g1_i1 len=434 path=[412:0-247 847:248-271 661:272-433] [-1, 412, 847, 661, -2] GTTAATTTAGTGGGAAGTATGTGTTAAAATTAGTAAATTAGGTGTTGGTGTGTTTTTAATATGAATCCGGAAGTGTTTTGTTAGGTTACAAGGGTACGGAATTGTAATAATAGAAATCGGTATCCTTGAGACCAATGTTATCGCATTCGATGCAAGAATAGATTGGGAAATAGTCCGGTTATCAATTACTTAAAGATTTCTATCTTGAAAACTATTTCTAATTGGTAAAAAAACTTATTTAGAATCACCCATAGTTGGAAGTTTAAGATTTGAGACATCTTAAATTTTTGGTAGGTAATTTTAAGATTCTATCGTAGTTAGTACCTTTCGTTCTTCTTATTTTATTTGTAAAATATATTACATTTAGTACGAGTATTGTATTTCCAATATTCAGTCTAATTAGAATTGCAAAATTACTGAACACTCAATCATAA >TRINITY_DN75_c0_g1_i1 len=478 path=[456:0-477] [-1, 456, -2] CGAGCACATCAGGCCAGGGTTCCCCAAGTGCTCGAGTTTCGTAACCAAACAACCATCTTCTGGTCCGACCACCAGTCACATGATCAGCTGTGGCGCTCAGTATACGAGCACAGATTGCAACAGCCACCAAATGAGAGAGGAAAGTCATCCACATTGCCATGAAATCTGCGAAAGAGCGTAAATTGCGAGTAGCATGACCGCAGGTACGGCGCAGTAGCTGGAGTTGGCAGCGGCTAGGGGTGCCAGGAGGAGTGCTCCAAGGGTCCATCGTGCTCCACATGCCTCCCCGCCGCTGAACGCGCTCAGAGCCTTGCTCATCTTGCTACGCTCGCTCCGTTCAGTCATCTTCGTGTCTCATCGTCGCAGCGCGTAGTATTTACG ``` There are close to 400,000 sequences in this file. I have another file ids.txt in the following format: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 >TRINITY_DN15434_c5_g3_i1 >TRINITY_DN9323_c8_g3_i5 >TRINITY_DN11957_c1_g7_i1 >TRINITY_DN15373_c1_g1_i1 >TRINITY_DN22913_c0_g1_i1 >TRINITY_DN13029_c4_g5_i1 ``` I have 100 sequence ids in this file. When I match these ids to the source file I want an output that gives me the match for each of these ids with the entire sequence. For example, for an id: ``` >TRINITY_DN80_c0_g1_i1 ``` I want my output to be: ``` >TRINITY_DN80_c0_g1_i1 CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` I want all hundred sequences in this format. I used this code: ``` while read p; do echo ''$p >> out.fasta grep -A 400000 -w $p source.fasta | sed -n -e '1,/>/ {/>/ !{'p''}} >> out.fasta done < ids.txt ``` But my output is different in that only the last id has a sequence and the rest dont have any sequence associated: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 .... >TRINITY_DN10309_c6_g3_i1 >TRINITY_DN6990_c0_g1_i1 TTTTTTTTTTTTTGTGGAAAAACATTGATTTTATTGAATTGTAAACTTAAAATTAGATTGGCTGCACATCTTAGATTTTGTTGAAAGCAGCAATATCAACAGACTGGACGAAGTCTTCGAATTCCTGGATTTTTTCAGTCAAGAGATCAACAGACACTTTGTCGTCTTCAATGACACACATGATCTGCAGTTTGTTGATACCATATCCAACAGGTACAAGTTTGGAAGCTCCCCAGAGGAGACCATCCATTTCGATGGTGCGGACCTGGTTTTCCATTTCTTTCATGTCTGTTTCATCATCCCATGGCTTGACGTCAAGGATTATAGATGATTTAGCAATGAGAGCAGGTTTCTTCGATTTTTTGTCAGCATAAGCTTTCAGACGTTCTTCACGAATTCTGGCGGCCTCTGCATCCTCTTCCTCGTCGCCAGATCCGAATAGGTCGACGTCATCATCGTCGTCATCCTTAGCAGCGGGTGCAGGTGCTGTGGTGGTCTTTCCGCCAGCGGTCAGAGGGCTAGCTCCAGCCGCCCAGGATTTGCGCTCCTCGGCATTGTAGGAGGCAATCTGGTTGTACCACCGGAGAGCGTGGGGCAAGCTTGCGCTCGGGGCCTTGCCGACTTGTTGGAACACTTGGAAATCGGCTTGAGTTGGTGTGTAACCTGACACATAACTCTTATCAGCTAAGAAATTGTTAAGCTCATTAAGGCCTTGTGCGGTTTTAACGTCTCCTACTGCCATTTTTATTTAAAAAAGTAGTTTTTTTCGAGTAATAGCCACACGCCCCGGCACAATGTGAGCAAGAAGGAATGAAAAAGAAATCTGACATTGACATTGCCATGAAATTGACTTTCAAAGAACGAATGAATTGAACTAATTTGAACGG ``` I am only getting the desired output for the 100th id from my ids.txt. Could someone help me on where my script is wrong. I would like to get all 100 sequences when i run the script. Thank you I have added google drive links to the files i am working with: [ids.txt](https://drive.google.com/open?id=1t1dv5GlbwD-qfN2EYVRSVYxo2XPxGHWx) [Source.fasta](https://drive.google.com/open?id=1gMjwOjUAgmr04EFpZDKpkEHMcC3YlzlR)
2019/02/18
[ "https://Stackoverflow.com/questions/54740667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296702/" ]
Repeatedly looping over a large file is inefficient; you really want to avoid running `grep` (or `sed` or `awk`) more than once if you can avoid it. Generally speaking, `sed` and Awk will often easily allow you to specify actions for individual lines in a file, and then you run the script on the file just once. For this particular problem, the standard Awk idiom with `NR==FNR` comes in handy. This is a mechanism which lets you read a number of keys into memory (concretely, when `NR==FNR` it means that you are processing the first input file, because the overall input line number is equal to the line number within this file) and then check if they are present in subsequent input files. Recall that Awk reads one line at a time and performs all the actions whose conditions match. The conditions are a simple boolean, and the actions are a set of Awk commands within a pair of braces. ``` awk 'NR == FNR { s[$0]; next } # If we fall through to here, we have finished processing the first file. # If we see a wedge and p is 1, reset it -- this is a new sequence /^>/ && p { p = 0 } # If the prefix of this line is in s, we have found a sequence we want. ($1$2 in s) || ($1 in s) || ((substr($1, 1, 1) " " substr($1, 2)) in s) { if ($1 ~ /^>./) { print $1 } else { print $1 $2 }; p = 1; next } # If p is true, we want to print this line p' ids.txt source.fasta >out.fasta ``` So when we are reading `ids.txt`, the condition `NR==FNR` is true, and so we simply store each line in the array `s`. The `next` causes the rest of the Awk script to be skipped for this line. On subsequent reads, when `NR!=FNR`, we use the variable `p` to control what to print. When we see a new sequence, we set `p` to 0 (in case it was 1 from a previous iteration). Then when we see a new sequence, we check if it is in `s`, and if so, we set `p` to one. The last line simply prints the line if `p` is not empty or zero. (An empty action is a shorthand for the action `{ print }`.) The slightly complex condition to check if `$1` is in `s` might be too complicated -- I put in some normalizations to make sure that a space between the `>` and the sequence identifier is tolerated, regardless of there was one in `ids.txt` or not. This can probably be simplified if your files are consistently formatted.
This might work for you (GNU sed): ``` sed 's#.*#/^&/{s/ .*//;N;p}#' idFile | sed -nf - fastafile ``` Convert the idFile into a sed script and run it against the fastaFile.
54,740,667
I have a "source.fasta" file that contains information in the following format: ``` >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG >TRINITY_DN83_c0_g1_i1 len=371 path=[1:0-173 152:174-370] [-1, 1, 152, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTATCGAGTAAGTTTACAGTCGTAAATAAAGAATCTGCCTTGAACAAACCTTATTCCTTTTTATTCTAAAAGAGGCCTTTGCGTAGTAGTAACATAGTACAAATTGGTTTATTTAACGATTTATAAACGATATCCTTCCTACAGTCGGGTGAAAAGAAAGTATTCGAAATTAGAATGGTTCCTCATATTACACGTTGCTG >TRINITY_DN83_c0_g1_i2 len=218 path=[1:0-173 741:174-217] [-1, 1, 741, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTACCGAGTAAGTTTCCAGTCGTAAATAAAGAATCTGCCAGATCGGA >TRINITY_DN99_c0_g1_i1 len=326 path=[1:0-242 221:243-243 652:244-267 246:268-325] [-1, 1, 221, 652, 246, -2] ATCGGTACTATCATGTCATATATCTAGAAATAATACCTACGAATGTTATAAGAATTTCATAACATGATATAACGATCATACATCATGGCCTTTCGAAGAAAATGGCGCATTTACGTTTAATAATTCCGCGAAAGTCAAGGCAAATACAGACCTAATGCGAAATTGAAAAGAAAATCCGAATATCAGAAACAGAACCCAGAACCAATATGCTCAGCAGTTGCTTTGTAGCCAATAAACTCAACTAGAAATTGCTTATCTTTTATGTAACGCCATAAAACGTAATACCGATAACAGACTAAGCACACATATGTAAATTACCTGCTAAA >TRINITY_DN90_c0_g1_i1 len=1240 path=[1970:0-527 753:528-1239] [-1, 1970, 753, -2] GTCGATACTAGACAACGAATAATTGTGTCTATTTTTAAAAATAATTCCTTTTGTAAGCAGATTTTTTTTTTCATGCATGTTTCGAGTAAATTGGATTACGCATTCCACGTAACATCGTAAATGTAACCACATTGTTGTAACATACGGTATTTTTTCTGACAACGGACTCGATTGTAAGCAACTTTGTAACATTATAATCCTATGAGTATGACATTCTTAATAATAGCAACAGGGATAAAAATAAAACTACATTGTTTCATTCAACTCGTAAGTGTTTATTTAAAATTATTATTAAACACTATTGTAATAAAGTTTATATTCCTTTGTCAGTGGTAGACACATAAACAGTTTTCGAGTTCACTGTCG >TRINITY_DN84_c0_g1_i1 len=301 path=[1:0-220 358:221-300] [-1, 1, 358, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCACTTTTAAATCTTATAAACATGTGATCCGTCTGCTCATTTGGACGTTACTGCCCAAAGTTGGTACATGTTTCGTACTCACG >TRINITY_DN84_c0_g1_i2 len=301 path=[1:0-220 199:221-300] [-1, 1, 199, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCAGCTAACCAAAGATAAGTGTCTTGGCTTGGTATCTACAGATCTCTTTTCGTAATTTCGTGAGTACGAAACATGTACCAACT >TRINITY_DN72_c0_g1_i1 len=434 path=[412:0-247 847:248-271 661:272-433] [-1, 412, 847, 661, -2] GTTAATTTAGTGGGAAGTATGTGTTAAAATTAGTAAATTAGGTGTTGGTGTGTTTTTAATATGAATCCGGAAGTGTTTTGTTAGGTTACAAGGGTACGGAATTGTAATAATAGAAATCGGTATCCTTGAGACCAATGTTATCGCATTCGATGCAAGAATAGATTGGGAAATAGTCCGGTTATCAATTACTTAAAGATTTCTATCTTGAAAACTATTTCTAATTGGTAAAAAAACTTATTTAGAATCACCCATAGTTGGAAGTTTAAGATTTGAGACATCTTAAATTTTTGGTAGGTAATTTTAAGATTCTATCGTAGTTAGTACCTTTCGTTCTTCTTATTTTATTTGTAAAATATATTACATTTAGTACGAGTATTGTATTTCCAATATTCAGTCTAATTAGAATTGCAAAATTACTGAACACTCAATCATAA >TRINITY_DN75_c0_g1_i1 len=478 path=[456:0-477] [-1, 456, -2] CGAGCACATCAGGCCAGGGTTCCCCAAGTGCTCGAGTTTCGTAACCAAACAACCATCTTCTGGTCCGACCACCAGTCACATGATCAGCTGTGGCGCTCAGTATACGAGCACAGATTGCAACAGCCACCAAATGAGAGAGGAAAGTCATCCACATTGCCATGAAATCTGCGAAAGAGCGTAAATTGCGAGTAGCATGACCGCAGGTACGGCGCAGTAGCTGGAGTTGGCAGCGGCTAGGGGTGCCAGGAGGAGTGCTCCAAGGGTCCATCGTGCTCCACATGCCTCCCCGCCGCTGAACGCGCTCAGAGCCTTGCTCATCTTGCTACGCTCGCTCCGTTCAGTCATCTTCGTGTCTCATCGTCGCAGCGCGTAGTATTTACG ``` There are close to 400,000 sequences in this file. I have another file ids.txt in the following format: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 >TRINITY_DN15434_c5_g3_i1 >TRINITY_DN9323_c8_g3_i5 >TRINITY_DN11957_c1_g7_i1 >TRINITY_DN15373_c1_g1_i1 >TRINITY_DN22913_c0_g1_i1 >TRINITY_DN13029_c4_g5_i1 ``` I have 100 sequence ids in this file. When I match these ids to the source file I want an output that gives me the match for each of these ids with the entire sequence. For example, for an id: ``` >TRINITY_DN80_c0_g1_i1 ``` I want my output to be: ``` >TRINITY_DN80_c0_g1_i1 CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` I want all hundred sequences in this format. I used this code: ``` while read p; do echo ''$p >> out.fasta grep -A 400000 -w $p source.fasta | sed -n -e '1,/>/ {/>/ !{'p''}} >> out.fasta done < ids.txt ``` But my output is different in that only the last id has a sequence and the rest dont have any sequence associated: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 .... >TRINITY_DN10309_c6_g3_i1 >TRINITY_DN6990_c0_g1_i1 TTTTTTTTTTTTTGTGGAAAAACATTGATTTTATTGAATTGTAAACTTAAAATTAGATTGGCTGCACATCTTAGATTTTGTTGAAAGCAGCAATATCAACAGACTGGACGAAGTCTTCGAATTCCTGGATTTTTTCAGTCAAGAGATCAACAGACACTTTGTCGTCTTCAATGACACACATGATCTGCAGTTTGTTGATACCATATCCAACAGGTACAAGTTTGGAAGCTCCCCAGAGGAGACCATCCATTTCGATGGTGCGGACCTGGTTTTCCATTTCTTTCATGTCTGTTTCATCATCCCATGGCTTGACGTCAAGGATTATAGATGATTTAGCAATGAGAGCAGGTTTCTTCGATTTTTTGTCAGCATAAGCTTTCAGACGTTCTTCACGAATTCTGGCGGCCTCTGCATCCTCTTCCTCGTCGCCAGATCCGAATAGGTCGACGTCATCATCGTCGTCATCCTTAGCAGCGGGTGCAGGTGCTGTGGTGGTCTTTCCGCCAGCGGTCAGAGGGCTAGCTCCAGCCGCCCAGGATTTGCGCTCCTCGGCATTGTAGGAGGCAATCTGGTTGTACCACCGGAGAGCGTGGGGCAAGCTTGCGCTCGGGGCCTTGCCGACTTGTTGGAACACTTGGAAATCGGCTTGAGTTGGTGTGTAACCTGACACATAACTCTTATCAGCTAAGAAATTGTTAAGCTCATTAAGGCCTTGTGCGGTTTTAACGTCTCCTACTGCCATTTTTATTTAAAAAAGTAGTTTTTTTCGAGTAATAGCCACACGCCCCGGCACAATGTGAGCAAGAAGGAATGAAAAAGAAATCTGACATTGACATTGCCATGAAATTGACTTTCAAAGAACGAATGAATTGAACTAATTTGAACGG ``` I am only getting the desired output for the 100th id from my ids.txt. Could someone help me on where my script is wrong. I would like to get all 100 sequences when i run the script. Thank you I have added google drive links to the files i am working with: [ids.txt](https://drive.google.com/open?id=1t1dv5GlbwD-qfN2EYVRSVYxo2XPxGHWx) [Source.fasta](https://drive.google.com/open?id=1gMjwOjUAgmr04EFpZDKpkEHMcC3YlzlR)
2019/02/18
[ "https://Stackoverflow.com/questions/54740667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296702/" ]
Repeatedly looping over a large file is inefficient; you really want to avoid running `grep` (or `sed` or `awk`) more than once if you can avoid it. Generally speaking, `sed` and Awk will often easily allow you to specify actions for individual lines in a file, and then you run the script on the file just once. For this particular problem, the standard Awk idiom with `NR==FNR` comes in handy. This is a mechanism which lets you read a number of keys into memory (concretely, when `NR==FNR` it means that you are processing the first input file, because the overall input line number is equal to the line number within this file) and then check if they are present in subsequent input files. Recall that Awk reads one line at a time and performs all the actions whose conditions match. The conditions are a simple boolean, and the actions are a set of Awk commands within a pair of braces. ``` awk 'NR == FNR { s[$0]; next } # If we fall through to here, we have finished processing the first file. # If we see a wedge and p is 1, reset it -- this is a new sequence /^>/ && p { p = 0 } # If the prefix of this line is in s, we have found a sequence we want. ($1$2 in s) || ($1 in s) || ((substr($1, 1, 1) " " substr($1, 2)) in s) { if ($1 ~ /^>./) { print $1 } else { print $1 $2 }; p = 1; next } # If p is true, we want to print this line p' ids.txt source.fasta >out.fasta ``` So when we are reading `ids.txt`, the condition `NR==FNR` is true, and so we simply store each line in the array `s`. The `next` causes the rest of the Awk script to be skipped for this line. On subsequent reads, when `NR!=FNR`, we use the variable `p` to control what to print. When we see a new sequence, we set `p` to 0 (in case it was 1 from a previous iteration). Then when we see a new sequence, we check if it is in `s`, and if so, we set `p` to one. The last line simply prints the line if `p` is not empty or zero. (An empty action is a shorthand for the action `{ print }`.) The slightly complex condition to check if `$1` is in `s` might be too complicated -- I put in some normalizations to make sure that a space between the `>` and the sequence identifier is tolerated, regardless of there was one in `ids.txt` or not. This can probably be simplified if your files are consistently formatted.
First group all id's as one expression separated by | like this ``` cat ids.txt | tr '\n' '|' | awk "{print "\"" $0 "\""}' ``` Remove the last | symbol from the expression. Now you can grep using the output you got from previous command like this ``` egrep -E ">TRINITY_DN14840_c10_g1_i1|>TRINITY_DN8506_c0_g1_i1|>TRINITY_DN12276_c0_g2_i1|>TRINITY_DN15434_c5_g3_i1|>TRINITY_DN9323_c8_g3_i5|>TRINITY_DN11957_c1_g7_i1|>TRINITY_DN15373_c1_g1_i1|>TRINITY_DN22913_c0_g1_i1|>TRINITY_DN13029_c4_g5_i1" source.fasta ``` This will print only the matching lines Editing as per tripleee comments Using the following is printing the output properly Assuming the ID and sequence are in different lined ``` tr '\n' '|' <ids.txt | sed 's/|$//' | grep -A 1 -E -f - source.fasta ```
54,740,667
I have a "source.fasta" file that contains information in the following format: ``` >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG >TRINITY_DN83_c0_g1_i1 len=371 path=[1:0-173 152:174-370] [-1, 1, 152, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTATCGAGTAAGTTTACAGTCGTAAATAAAGAATCTGCCTTGAACAAACCTTATTCCTTTTTATTCTAAAAGAGGCCTTTGCGTAGTAGTAACATAGTACAAATTGGTTTATTTAACGATTTATAAACGATATCCTTCCTACAGTCGGGTGAAAAGAAAGTATTCGAAATTAGAATGGTTCCTCATATTACACGTTGCTG >TRINITY_DN83_c0_g1_i2 len=218 path=[1:0-173 741:174-217] [-1, 1, 741, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTACCGAGTAAGTTTCCAGTCGTAAATAAAGAATCTGCCAGATCGGA >TRINITY_DN99_c0_g1_i1 len=326 path=[1:0-242 221:243-243 652:244-267 246:268-325] [-1, 1, 221, 652, 246, -2] ATCGGTACTATCATGTCATATATCTAGAAATAATACCTACGAATGTTATAAGAATTTCATAACATGATATAACGATCATACATCATGGCCTTTCGAAGAAAATGGCGCATTTACGTTTAATAATTCCGCGAAAGTCAAGGCAAATACAGACCTAATGCGAAATTGAAAAGAAAATCCGAATATCAGAAACAGAACCCAGAACCAATATGCTCAGCAGTTGCTTTGTAGCCAATAAACTCAACTAGAAATTGCTTATCTTTTATGTAACGCCATAAAACGTAATACCGATAACAGACTAAGCACACATATGTAAATTACCTGCTAAA >TRINITY_DN90_c0_g1_i1 len=1240 path=[1970:0-527 753:528-1239] [-1, 1970, 753, -2] GTCGATACTAGACAACGAATAATTGTGTCTATTTTTAAAAATAATTCCTTTTGTAAGCAGATTTTTTTTTTCATGCATGTTTCGAGTAAATTGGATTACGCATTCCACGTAACATCGTAAATGTAACCACATTGTTGTAACATACGGTATTTTTTCTGACAACGGACTCGATTGTAAGCAACTTTGTAACATTATAATCCTATGAGTATGACATTCTTAATAATAGCAACAGGGATAAAAATAAAACTACATTGTTTCATTCAACTCGTAAGTGTTTATTTAAAATTATTATTAAACACTATTGTAATAAAGTTTATATTCCTTTGTCAGTGGTAGACACATAAACAGTTTTCGAGTTCACTGTCG >TRINITY_DN84_c0_g1_i1 len=301 path=[1:0-220 358:221-300] [-1, 1, 358, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCACTTTTAAATCTTATAAACATGTGATCCGTCTGCTCATTTGGACGTTACTGCCCAAAGTTGGTACATGTTTCGTACTCACG >TRINITY_DN84_c0_g1_i2 len=301 path=[1:0-220 199:221-300] [-1, 1, 199, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCAGCTAACCAAAGATAAGTGTCTTGGCTTGGTATCTACAGATCTCTTTTCGTAATTTCGTGAGTACGAAACATGTACCAACT >TRINITY_DN72_c0_g1_i1 len=434 path=[412:0-247 847:248-271 661:272-433] [-1, 412, 847, 661, -2] GTTAATTTAGTGGGAAGTATGTGTTAAAATTAGTAAATTAGGTGTTGGTGTGTTTTTAATATGAATCCGGAAGTGTTTTGTTAGGTTACAAGGGTACGGAATTGTAATAATAGAAATCGGTATCCTTGAGACCAATGTTATCGCATTCGATGCAAGAATAGATTGGGAAATAGTCCGGTTATCAATTACTTAAAGATTTCTATCTTGAAAACTATTTCTAATTGGTAAAAAAACTTATTTAGAATCACCCATAGTTGGAAGTTTAAGATTTGAGACATCTTAAATTTTTGGTAGGTAATTTTAAGATTCTATCGTAGTTAGTACCTTTCGTTCTTCTTATTTTATTTGTAAAATATATTACATTTAGTACGAGTATTGTATTTCCAATATTCAGTCTAATTAGAATTGCAAAATTACTGAACACTCAATCATAA >TRINITY_DN75_c0_g1_i1 len=478 path=[456:0-477] [-1, 456, -2] CGAGCACATCAGGCCAGGGTTCCCCAAGTGCTCGAGTTTCGTAACCAAACAACCATCTTCTGGTCCGACCACCAGTCACATGATCAGCTGTGGCGCTCAGTATACGAGCACAGATTGCAACAGCCACCAAATGAGAGAGGAAAGTCATCCACATTGCCATGAAATCTGCGAAAGAGCGTAAATTGCGAGTAGCATGACCGCAGGTACGGCGCAGTAGCTGGAGTTGGCAGCGGCTAGGGGTGCCAGGAGGAGTGCTCCAAGGGTCCATCGTGCTCCACATGCCTCCCCGCCGCTGAACGCGCTCAGAGCCTTGCTCATCTTGCTACGCTCGCTCCGTTCAGTCATCTTCGTGTCTCATCGTCGCAGCGCGTAGTATTTACG ``` There are close to 400,000 sequences in this file. I have another file ids.txt in the following format: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 >TRINITY_DN15434_c5_g3_i1 >TRINITY_DN9323_c8_g3_i5 >TRINITY_DN11957_c1_g7_i1 >TRINITY_DN15373_c1_g1_i1 >TRINITY_DN22913_c0_g1_i1 >TRINITY_DN13029_c4_g5_i1 ``` I have 100 sequence ids in this file. When I match these ids to the source file I want an output that gives me the match for each of these ids with the entire sequence. For example, for an id: ``` >TRINITY_DN80_c0_g1_i1 ``` I want my output to be: ``` >TRINITY_DN80_c0_g1_i1 CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` I want all hundred sequences in this format. I used this code: ``` while read p; do echo ''$p >> out.fasta grep -A 400000 -w $p source.fasta | sed -n -e '1,/>/ {/>/ !{'p''}} >> out.fasta done < ids.txt ``` But my output is different in that only the last id has a sequence and the rest dont have any sequence associated: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 .... >TRINITY_DN10309_c6_g3_i1 >TRINITY_DN6990_c0_g1_i1 TTTTTTTTTTTTTGTGGAAAAACATTGATTTTATTGAATTGTAAACTTAAAATTAGATTGGCTGCACATCTTAGATTTTGTTGAAAGCAGCAATATCAACAGACTGGACGAAGTCTTCGAATTCCTGGATTTTTTCAGTCAAGAGATCAACAGACACTTTGTCGTCTTCAATGACACACATGATCTGCAGTTTGTTGATACCATATCCAACAGGTACAAGTTTGGAAGCTCCCCAGAGGAGACCATCCATTTCGATGGTGCGGACCTGGTTTTCCATTTCTTTCATGTCTGTTTCATCATCCCATGGCTTGACGTCAAGGATTATAGATGATTTAGCAATGAGAGCAGGTTTCTTCGATTTTTTGTCAGCATAAGCTTTCAGACGTTCTTCACGAATTCTGGCGGCCTCTGCATCCTCTTCCTCGTCGCCAGATCCGAATAGGTCGACGTCATCATCGTCGTCATCCTTAGCAGCGGGTGCAGGTGCTGTGGTGGTCTTTCCGCCAGCGGTCAGAGGGCTAGCTCCAGCCGCCCAGGATTTGCGCTCCTCGGCATTGTAGGAGGCAATCTGGTTGTACCACCGGAGAGCGTGGGGCAAGCTTGCGCTCGGGGCCTTGCCGACTTGTTGGAACACTTGGAAATCGGCTTGAGTTGGTGTGTAACCTGACACATAACTCTTATCAGCTAAGAAATTGTTAAGCTCATTAAGGCCTTGTGCGGTTTTAACGTCTCCTACTGCCATTTTTATTTAAAAAAGTAGTTTTTTTCGAGTAATAGCCACACGCCCCGGCACAATGTGAGCAAGAAGGAATGAAAAAGAAATCTGACATTGACATTGCCATGAAATTGACTTTCAAAGAACGAATGAATTGAACTAATTTGAACGG ``` I am only getting the desired output for the 100th id from my ids.txt. Could someone help me on where my script is wrong. I would like to get all 100 sequences when i run the script. Thank you I have added google drive links to the files i am working with: [ids.txt](https://drive.google.com/open?id=1t1dv5GlbwD-qfN2EYVRSVYxo2XPxGHWx) [Source.fasta](https://drive.google.com/open?id=1gMjwOjUAgmr04EFpZDKpkEHMcC3YlzlR)
2019/02/18
[ "https://Stackoverflow.com/questions/54740667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296702/" ]
Only with GNU grep and sed: ``` grep -A 1 -w -F -f ids.txt source.fasta | sed 's/ .*//' ``` --- See: `man grep`
This might work for you (GNU sed): ``` sed 's#.*#/^&/{s/ .*//;N;p}#' idFile | sed -nf - fastafile ``` Convert the idFile into a sed script and run it against the fastaFile.
54,740,667
I have a "source.fasta" file that contains information in the following format: ``` >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG >TRINITY_DN83_c0_g1_i1 len=371 path=[1:0-173 152:174-370] [-1, 1, 152, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTATCGAGTAAGTTTACAGTCGTAAATAAAGAATCTGCCTTGAACAAACCTTATTCCTTTTTATTCTAAAAGAGGCCTTTGCGTAGTAGTAACATAGTACAAATTGGTTTATTTAACGATTTATAAACGATATCCTTCCTACAGTCGGGTGAAAAGAAAGTATTCGAAATTAGAATGGTTCCTCATATTACACGTTGCTG >TRINITY_DN83_c0_g1_i2 len=218 path=[1:0-173 741:174-217] [-1, 1, 741, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTACCGAGTAAGTTTCCAGTCGTAAATAAAGAATCTGCCAGATCGGA >TRINITY_DN99_c0_g1_i1 len=326 path=[1:0-242 221:243-243 652:244-267 246:268-325] [-1, 1, 221, 652, 246, -2] ATCGGTACTATCATGTCATATATCTAGAAATAATACCTACGAATGTTATAAGAATTTCATAACATGATATAACGATCATACATCATGGCCTTTCGAAGAAAATGGCGCATTTACGTTTAATAATTCCGCGAAAGTCAAGGCAAATACAGACCTAATGCGAAATTGAAAAGAAAATCCGAATATCAGAAACAGAACCCAGAACCAATATGCTCAGCAGTTGCTTTGTAGCCAATAAACTCAACTAGAAATTGCTTATCTTTTATGTAACGCCATAAAACGTAATACCGATAACAGACTAAGCACACATATGTAAATTACCTGCTAAA >TRINITY_DN90_c0_g1_i1 len=1240 path=[1970:0-527 753:528-1239] [-1, 1970, 753, -2] GTCGATACTAGACAACGAATAATTGTGTCTATTTTTAAAAATAATTCCTTTTGTAAGCAGATTTTTTTTTTCATGCATGTTTCGAGTAAATTGGATTACGCATTCCACGTAACATCGTAAATGTAACCACATTGTTGTAACATACGGTATTTTTTCTGACAACGGACTCGATTGTAAGCAACTTTGTAACATTATAATCCTATGAGTATGACATTCTTAATAATAGCAACAGGGATAAAAATAAAACTACATTGTTTCATTCAACTCGTAAGTGTTTATTTAAAATTATTATTAAACACTATTGTAATAAAGTTTATATTCCTTTGTCAGTGGTAGACACATAAACAGTTTTCGAGTTCACTGTCG >TRINITY_DN84_c0_g1_i1 len=301 path=[1:0-220 358:221-300] [-1, 1, 358, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCACTTTTAAATCTTATAAACATGTGATCCGTCTGCTCATTTGGACGTTACTGCCCAAAGTTGGTACATGTTTCGTACTCACG >TRINITY_DN84_c0_g1_i2 len=301 path=[1:0-220 199:221-300] [-1, 1, 199, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCAGCTAACCAAAGATAAGTGTCTTGGCTTGGTATCTACAGATCTCTTTTCGTAATTTCGTGAGTACGAAACATGTACCAACT >TRINITY_DN72_c0_g1_i1 len=434 path=[412:0-247 847:248-271 661:272-433] [-1, 412, 847, 661, -2] GTTAATTTAGTGGGAAGTATGTGTTAAAATTAGTAAATTAGGTGTTGGTGTGTTTTTAATATGAATCCGGAAGTGTTTTGTTAGGTTACAAGGGTACGGAATTGTAATAATAGAAATCGGTATCCTTGAGACCAATGTTATCGCATTCGATGCAAGAATAGATTGGGAAATAGTCCGGTTATCAATTACTTAAAGATTTCTATCTTGAAAACTATTTCTAATTGGTAAAAAAACTTATTTAGAATCACCCATAGTTGGAAGTTTAAGATTTGAGACATCTTAAATTTTTGGTAGGTAATTTTAAGATTCTATCGTAGTTAGTACCTTTCGTTCTTCTTATTTTATTTGTAAAATATATTACATTTAGTACGAGTATTGTATTTCCAATATTCAGTCTAATTAGAATTGCAAAATTACTGAACACTCAATCATAA >TRINITY_DN75_c0_g1_i1 len=478 path=[456:0-477] [-1, 456, -2] CGAGCACATCAGGCCAGGGTTCCCCAAGTGCTCGAGTTTCGTAACCAAACAACCATCTTCTGGTCCGACCACCAGTCACATGATCAGCTGTGGCGCTCAGTATACGAGCACAGATTGCAACAGCCACCAAATGAGAGAGGAAAGTCATCCACATTGCCATGAAATCTGCGAAAGAGCGTAAATTGCGAGTAGCATGACCGCAGGTACGGCGCAGTAGCTGGAGTTGGCAGCGGCTAGGGGTGCCAGGAGGAGTGCTCCAAGGGTCCATCGTGCTCCACATGCCTCCCCGCCGCTGAACGCGCTCAGAGCCTTGCTCATCTTGCTACGCTCGCTCCGTTCAGTCATCTTCGTGTCTCATCGTCGCAGCGCGTAGTATTTACG ``` There are close to 400,000 sequences in this file. I have another file ids.txt in the following format: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 >TRINITY_DN15434_c5_g3_i1 >TRINITY_DN9323_c8_g3_i5 >TRINITY_DN11957_c1_g7_i1 >TRINITY_DN15373_c1_g1_i1 >TRINITY_DN22913_c0_g1_i1 >TRINITY_DN13029_c4_g5_i1 ``` I have 100 sequence ids in this file. When I match these ids to the source file I want an output that gives me the match for each of these ids with the entire sequence. For example, for an id: ``` >TRINITY_DN80_c0_g1_i1 ``` I want my output to be: ``` >TRINITY_DN80_c0_g1_i1 CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` I want all hundred sequences in this format. I used this code: ``` while read p; do echo ''$p >> out.fasta grep -A 400000 -w $p source.fasta | sed -n -e '1,/>/ {/>/ !{'p''}} >> out.fasta done < ids.txt ``` But my output is different in that only the last id has a sequence and the rest dont have any sequence associated: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 .... >TRINITY_DN10309_c6_g3_i1 >TRINITY_DN6990_c0_g1_i1 TTTTTTTTTTTTTGTGGAAAAACATTGATTTTATTGAATTGTAAACTTAAAATTAGATTGGCTGCACATCTTAGATTTTGTTGAAAGCAGCAATATCAACAGACTGGACGAAGTCTTCGAATTCCTGGATTTTTTCAGTCAAGAGATCAACAGACACTTTGTCGTCTTCAATGACACACATGATCTGCAGTTTGTTGATACCATATCCAACAGGTACAAGTTTGGAAGCTCCCCAGAGGAGACCATCCATTTCGATGGTGCGGACCTGGTTTTCCATTTCTTTCATGTCTGTTTCATCATCCCATGGCTTGACGTCAAGGATTATAGATGATTTAGCAATGAGAGCAGGTTTCTTCGATTTTTTGTCAGCATAAGCTTTCAGACGTTCTTCACGAATTCTGGCGGCCTCTGCATCCTCTTCCTCGTCGCCAGATCCGAATAGGTCGACGTCATCATCGTCGTCATCCTTAGCAGCGGGTGCAGGTGCTGTGGTGGTCTTTCCGCCAGCGGTCAGAGGGCTAGCTCCAGCCGCCCAGGATTTGCGCTCCTCGGCATTGTAGGAGGCAATCTGGTTGTACCACCGGAGAGCGTGGGGCAAGCTTGCGCTCGGGGCCTTGCCGACTTGTTGGAACACTTGGAAATCGGCTTGAGTTGGTGTGTAACCTGACACATAACTCTTATCAGCTAAGAAATTGTTAAGCTCATTAAGGCCTTGTGCGGTTTTAACGTCTCCTACTGCCATTTTTATTTAAAAAAGTAGTTTTTTTCGAGTAATAGCCACACGCCCCGGCACAATGTGAGCAAGAAGGAATGAAAAAGAAATCTGACATTGACATTGCCATGAAATTGACTTTCAAAGAACGAATGAATTGAACTAATTTGAACGG ``` I am only getting the desired output for the 100th id from my ids.txt. Could someone help me on where my script is wrong. I would like to get all 100 sequences when i run the script. Thank you I have added google drive links to the files i am working with: [ids.txt](https://drive.google.com/open?id=1t1dv5GlbwD-qfN2EYVRSVYxo2XPxGHWx) [Source.fasta](https://drive.google.com/open?id=1gMjwOjUAgmr04EFpZDKpkEHMcC3YlzlR)
2019/02/18
[ "https://Stackoverflow.com/questions/54740667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296702/" ]
Repeatedly looping over a large file is inefficient; you really want to avoid running `grep` (or `sed` or `awk`) more than once if you can avoid it. Generally speaking, `sed` and Awk will often easily allow you to specify actions for individual lines in a file, and then you run the script on the file just once. For this particular problem, the standard Awk idiom with `NR==FNR` comes in handy. This is a mechanism which lets you read a number of keys into memory (concretely, when `NR==FNR` it means that you are processing the first input file, because the overall input line number is equal to the line number within this file) and then check if they are present in subsequent input files. Recall that Awk reads one line at a time and performs all the actions whose conditions match. The conditions are a simple boolean, and the actions are a set of Awk commands within a pair of braces. ``` awk 'NR == FNR { s[$0]; next } # If we fall through to here, we have finished processing the first file. # If we see a wedge and p is 1, reset it -- this is a new sequence /^>/ && p { p = 0 } # If the prefix of this line is in s, we have found a sequence we want. ($1$2 in s) || ($1 in s) || ((substr($1, 1, 1) " " substr($1, 2)) in s) { if ($1 ~ /^>./) { print $1 } else { print $1 $2 }; p = 1; next } # If p is true, we want to print this line p' ids.txt source.fasta >out.fasta ``` So when we are reading `ids.txt`, the condition `NR==FNR` is true, and so we simply store each line in the array `s`. The `next` causes the rest of the Awk script to be skipped for this line. On subsequent reads, when `NR!=FNR`, we use the variable `p` to control what to print. When we see a new sequence, we set `p` to 0 (in case it was 1 from a previous iteration). Then when we see a new sequence, we check if it is in `s`, and if so, we set `p` to one. The last line simply prints the line if `p` is not empty or zero. (An empty action is a shorthand for the action `{ print }`.) The slightly complex condition to check if `$1` is in `s` might be too complicated -- I put in some normalizations to make sure that a space between the `>` and the sequence identifier is tolerated, regardless of there was one in `ids.txt` or not. This can probably be simplified if your files are consistently formatted.
``` $ awk 'NR==FNR{a[$1];next} $1 in a{c=2} c&&c--' ids.txt source.fasta >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` The above was run using your posted source.fasta and this ids.txt: ``` $ cat ids.txt >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN80_c0_g1_i1 ```
54,740,667
I have a "source.fasta" file that contains information in the following format: ``` >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG >TRINITY_DN83_c0_g1_i1 len=371 path=[1:0-173 152:174-370] [-1, 1, 152, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTATCGAGTAAGTTTACAGTCGTAAATAAAGAATCTGCCTTGAACAAACCTTATTCCTTTTTATTCTAAAAGAGGCCTTTGCGTAGTAGTAACATAGTACAAATTGGTTTATTTAACGATTTATAAACGATATCCTTCCTACAGTCGGGTGAAAAGAAAGTATTCGAAATTAGAATGGTTCCTCATATTACACGTTGCTG >TRINITY_DN83_c0_g1_i2 len=218 path=[1:0-173 741:174-217] [-1, 1, 741, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTACCGAGTAAGTTTCCAGTCGTAAATAAAGAATCTGCCAGATCGGA >TRINITY_DN99_c0_g1_i1 len=326 path=[1:0-242 221:243-243 652:244-267 246:268-325] [-1, 1, 221, 652, 246, -2] ATCGGTACTATCATGTCATATATCTAGAAATAATACCTACGAATGTTATAAGAATTTCATAACATGATATAACGATCATACATCATGGCCTTTCGAAGAAAATGGCGCATTTACGTTTAATAATTCCGCGAAAGTCAAGGCAAATACAGACCTAATGCGAAATTGAAAAGAAAATCCGAATATCAGAAACAGAACCCAGAACCAATATGCTCAGCAGTTGCTTTGTAGCCAATAAACTCAACTAGAAATTGCTTATCTTTTATGTAACGCCATAAAACGTAATACCGATAACAGACTAAGCACACATATGTAAATTACCTGCTAAA >TRINITY_DN90_c0_g1_i1 len=1240 path=[1970:0-527 753:528-1239] [-1, 1970, 753, -2] GTCGATACTAGACAACGAATAATTGTGTCTATTTTTAAAAATAATTCCTTTTGTAAGCAGATTTTTTTTTTCATGCATGTTTCGAGTAAATTGGATTACGCATTCCACGTAACATCGTAAATGTAACCACATTGTTGTAACATACGGTATTTTTTCTGACAACGGACTCGATTGTAAGCAACTTTGTAACATTATAATCCTATGAGTATGACATTCTTAATAATAGCAACAGGGATAAAAATAAAACTACATTGTTTCATTCAACTCGTAAGTGTTTATTTAAAATTATTATTAAACACTATTGTAATAAAGTTTATATTCCTTTGTCAGTGGTAGACACATAAACAGTTTTCGAGTTCACTGTCG >TRINITY_DN84_c0_g1_i1 len=301 path=[1:0-220 358:221-300] [-1, 1, 358, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCACTTTTAAATCTTATAAACATGTGATCCGTCTGCTCATTTGGACGTTACTGCCCAAAGTTGGTACATGTTTCGTACTCACG >TRINITY_DN84_c0_g1_i2 len=301 path=[1:0-220 199:221-300] [-1, 1, 199, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCAGCTAACCAAAGATAAGTGTCTTGGCTTGGTATCTACAGATCTCTTTTCGTAATTTCGTGAGTACGAAACATGTACCAACT >TRINITY_DN72_c0_g1_i1 len=434 path=[412:0-247 847:248-271 661:272-433] [-1, 412, 847, 661, -2] GTTAATTTAGTGGGAAGTATGTGTTAAAATTAGTAAATTAGGTGTTGGTGTGTTTTTAATATGAATCCGGAAGTGTTTTGTTAGGTTACAAGGGTACGGAATTGTAATAATAGAAATCGGTATCCTTGAGACCAATGTTATCGCATTCGATGCAAGAATAGATTGGGAAATAGTCCGGTTATCAATTACTTAAAGATTTCTATCTTGAAAACTATTTCTAATTGGTAAAAAAACTTATTTAGAATCACCCATAGTTGGAAGTTTAAGATTTGAGACATCTTAAATTTTTGGTAGGTAATTTTAAGATTCTATCGTAGTTAGTACCTTTCGTTCTTCTTATTTTATTTGTAAAATATATTACATTTAGTACGAGTATTGTATTTCCAATATTCAGTCTAATTAGAATTGCAAAATTACTGAACACTCAATCATAA >TRINITY_DN75_c0_g1_i1 len=478 path=[456:0-477] [-1, 456, -2] CGAGCACATCAGGCCAGGGTTCCCCAAGTGCTCGAGTTTCGTAACCAAACAACCATCTTCTGGTCCGACCACCAGTCACATGATCAGCTGTGGCGCTCAGTATACGAGCACAGATTGCAACAGCCACCAAATGAGAGAGGAAAGTCATCCACATTGCCATGAAATCTGCGAAAGAGCGTAAATTGCGAGTAGCATGACCGCAGGTACGGCGCAGTAGCTGGAGTTGGCAGCGGCTAGGGGTGCCAGGAGGAGTGCTCCAAGGGTCCATCGTGCTCCACATGCCTCCCCGCCGCTGAACGCGCTCAGAGCCTTGCTCATCTTGCTACGCTCGCTCCGTTCAGTCATCTTCGTGTCTCATCGTCGCAGCGCGTAGTATTTACG ``` There are close to 400,000 sequences in this file. I have another file ids.txt in the following format: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 >TRINITY_DN15434_c5_g3_i1 >TRINITY_DN9323_c8_g3_i5 >TRINITY_DN11957_c1_g7_i1 >TRINITY_DN15373_c1_g1_i1 >TRINITY_DN22913_c0_g1_i1 >TRINITY_DN13029_c4_g5_i1 ``` I have 100 sequence ids in this file. When I match these ids to the source file I want an output that gives me the match for each of these ids with the entire sequence. For example, for an id: ``` >TRINITY_DN80_c0_g1_i1 ``` I want my output to be: ``` >TRINITY_DN80_c0_g1_i1 CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` I want all hundred sequences in this format. I used this code: ``` while read p; do echo ''$p >> out.fasta grep -A 400000 -w $p source.fasta | sed -n -e '1,/>/ {/>/ !{'p''}} >> out.fasta done < ids.txt ``` But my output is different in that only the last id has a sequence and the rest dont have any sequence associated: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 .... >TRINITY_DN10309_c6_g3_i1 >TRINITY_DN6990_c0_g1_i1 TTTTTTTTTTTTTGTGGAAAAACATTGATTTTATTGAATTGTAAACTTAAAATTAGATTGGCTGCACATCTTAGATTTTGTTGAAAGCAGCAATATCAACAGACTGGACGAAGTCTTCGAATTCCTGGATTTTTTCAGTCAAGAGATCAACAGACACTTTGTCGTCTTCAATGACACACATGATCTGCAGTTTGTTGATACCATATCCAACAGGTACAAGTTTGGAAGCTCCCCAGAGGAGACCATCCATTTCGATGGTGCGGACCTGGTTTTCCATTTCTTTCATGTCTGTTTCATCATCCCATGGCTTGACGTCAAGGATTATAGATGATTTAGCAATGAGAGCAGGTTTCTTCGATTTTTTGTCAGCATAAGCTTTCAGACGTTCTTCACGAATTCTGGCGGCCTCTGCATCCTCTTCCTCGTCGCCAGATCCGAATAGGTCGACGTCATCATCGTCGTCATCCTTAGCAGCGGGTGCAGGTGCTGTGGTGGTCTTTCCGCCAGCGGTCAGAGGGCTAGCTCCAGCCGCCCAGGATTTGCGCTCCTCGGCATTGTAGGAGGCAATCTGGTTGTACCACCGGAGAGCGTGGGGCAAGCTTGCGCTCGGGGCCTTGCCGACTTGTTGGAACACTTGGAAATCGGCTTGAGTTGGTGTGTAACCTGACACATAACTCTTATCAGCTAAGAAATTGTTAAGCTCATTAAGGCCTTGTGCGGTTTTAACGTCTCCTACTGCCATTTTTATTTAAAAAAGTAGTTTTTTTCGAGTAATAGCCACACGCCCCGGCACAATGTGAGCAAGAAGGAATGAAAAAGAAATCTGACATTGACATTGCCATGAAATTGACTTTCAAAGAACGAATGAATTGAACTAATTTGAACGG ``` I am only getting the desired output for the 100th id from my ids.txt. Could someone help me on where my script is wrong. I would like to get all 100 sequences when i run the script. Thank you I have added google drive links to the files i am working with: [ids.txt](https://drive.google.com/open?id=1t1dv5GlbwD-qfN2EYVRSVYxo2XPxGHWx) [Source.fasta](https://drive.google.com/open?id=1gMjwOjUAgmr04EFpZDKpkEHMcC3YlzlR)
2019/02/18
[ "https://Stackoverflow.com/questions/54740667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296702/" ]
the best way to do this is using either python or perl. I was able to make a script for extracting the ids using python as follows. ``` #script to extract sequences from a source file based on ids in another file #the source is a fasta file with a header and a sequence that follows in one line #the ids file contains one id per line #both the id and source file should contain the character '>' at the beginning that siginifies an id def main(): #asks the user for the ids file file1 = raw_input('ids file: '); #opens the ids file into the memory ids_file = open(file1, 'r'); #asks the user for the fasta file file2 = raw_input('fasta file: '); #opens the fasta file into memory; you need your memory to be larger than the filesize, or python will hard crash fasta_file = open(file2, 'r'); #ask the user for the file name of output file file3 = raw_input('enter the output filename: '); #opens output file with append option; append is must as you dont want to override the existing data output_file = open(file3, 'w'); #split the ids into an array ids_lines = ids_file.read().splitlines() #split the fasta file into an array, the first element will be the id followed by the sequence fasta_lines = fasta_file.read().splitlines() #initializing loop counters i = 0; j = 0; #while loop to iterate over the length of the ids file as this is the limiter for the program while j<len(fasta_lines) and i<len(ids_lines): #if statement to match ids from both files and bring matching sequences if ids_lines[i] == fasta_lines[j]: #output statements including newline characters output_file.write(fasta_lines[j]) output_file.write('\n') output_file.write(fasta_lines[j+1]) output_file.write('\n') #increment i so that we go for the next id i=i+1; #deprecate j so we start all over for the new id j=0; else: #when there is no match check the id, we are skipping the sequence in the middle which is j+1 j=j+2; ids_file.close() fasta_file.close() output_file.close() main()` ``` The code is not perfect but works for any number of ids. I have tested for my samples which contained 5000 ids in one of them and the program worked fine. If there are improvements to the code please do so, I am a relatively newbie at programming so the code is a bit crude.
First group all id's as one expression separated by | like this ``` cat ids.txt | tr '\n' '|' | awk "{print "\"" $0 "\""}' ``` Remove the last | symbol from the expression. Now you can grep using the output you got from previous command like this ``` egrep -E ">TRINITY_DN14840_c10_g1_i1|>TRINITY_DN8506_c0_g1_i1|>TRINITY_DN12276_c0_g2_i1|>TRINITY_DN15434_c5_g3_i1|>TRINITY_DN9323_c8_g3_i5|>TRINITY_DN11957_c1_g7_i1|>TRINITY_DN15373_c1_g1_i1|>TRINITY_DN22913_c0_g1_i1|>TRINITY_DN13029_c4_g5_i1" source.fasta ``` This will print only the matching lines Editing as per tripleee comments Using the following is printing the output properly Assuming the ID and sequence are in different lined ``` tr '\n' '|' <ids.txt | sed 's/|$//' | grep -A 1 -E -f - source.fasta ```
54,740,667
I have a "source.fasta" file that contains information in the following format: ``` >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG >TRINITY_DN83_c0_g1_i1 len=371 path=[1:0-173 152:174-370] [-1, 1, 152, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTATCGAGTAAGTTTACAGTCGTAAATAAAGAATCTGCCTTGAACAAACCTTATTCCTTTTTATTCTAAAAGAGGCCTTTGCGTAGTAGTAACATAGTACAAATTGGTTTATTTAACGATTTATAAACGATATCCTTCCTACAGTCGGGTGAAAAGAAAGTATTCGAAATTAGAATGGTTCCTCATATTACACGTTGCTG >TRINITY_DN83_c0_g1_i2 len=218 path=[1:0-173 741:174-217] [-1, 1, 741, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTACCGAGTAAGTTTCCAGTCGTAAATAAAGAATCTGCCAGATCGGA >TRINITY_DN99_c0_g1_i1 len=326 path=[1:0-242 221:243-243 652:244-267 246:268-325] [-1, 1, 221, 652, 246, -2] ATCGGTACTATCATGTCATATATCTAGAAATAATACCTACGAATGTTATAAGAATTTCATAACATGATATAACGATCATACATCATGGCCTTTCGAAGAAAATGGCGCATTTACGTTTAATAATTCCGCGAAAGTCAAGGCAAATACAGACCTAATGCGAAATTGAAAAGAAAATCCGAATATCAGAAACAGAACCCAGAACCAATATGCTCAGCAGTTGCTTTGTAGCCAATAAACTCAACTAGAAATTGCTTATCTTTTATGTAACGCCATAAAACGTAATACCGATAACAGACTAAGCACACATATGTAAATTACCTGCTAAA >TRINITY_DN90_c0_g1_i1 len=1240 path=[1970:0-527 753:528-1239] [-1, 1970, 753, -2] GTCGATACTAGACAACGAATAATTGTGTCTATTTTTAAAAATAATTCCTTTTGTAAGCAGATTTTTTTTTTCATGCATGTTTCGAGTAAATTGGATTACGCATTCCACGTAACATCGTAAATGTAACCACATTGTTGTAACATACGGTATTTTTTCTGACAACGGACTCGATTGTAAGCAACTTTGTAACATTATAATCCTATGAGTATGACATTCTTAATAATAGCAACAGGGATAAAAATAAAACTACATTGTTTCATTCAACTCGTAAGTGTTTATTTAAAATTATTATTAAACACTATTGTAATAAAGTTTATATTCCTTTGTCAGTGGTAGACACATAAACAGTTTTCGAGTTCACTGTCG >TRINITY_DN84_c0_g1_i1 len=301 path=[1:0-220 358:221-300] [-1, 1, 358, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCACTTTTAAATCTTATAAACATGTGATCCGTCTGCTCATTTGGACGTTACTGCCCAAAGTTGGTACATGTTTCGTACTCACG >TRINITY_DN84_c0_g1_i2 len=301 path=[1:0-220 199:221-300] [-1, 1, 199, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCAGCTAACCAAAGATAAGTGTCTTGGCTTGGTATCTACAGATCTCTTTTCGTAATTTCGTGAGTACGAAACATGTACCAACT >TRINITY_DN72_c0_g1_i1 len=434 path=[412:0-247 847:248-271 661:272-433] [-1, 412, 847, 661, -2] GTTAATTTAGTGGGAAGTATGTGTTAAAATTAGTAAATTAGGTGTTGGTGTGTTTTTAATATGAATCCGGAAGTGTTTTGTTAGGTTACAAGGGTACGGAATTGTAATAATAGAAATCGGTATCCTTGAGACCAATGTTATCGCATTCGATGCAAGAATAGATTGGGAAATAGTCCGGTTATCAATTACTTAAAGATTTCTATCTTGAAAACTATTTCTAATTGGTAAAAAAACTTATTTAGAATCACCCATAGTTGGAAGTTTAAGATTTGAGACATCTTAAATTTTTGGTAGGTAATTTTAAGATTCTATCGTAGTTAGTACCTTTCGTTCTTCTTATTTTATTTGTAAAATATATTACATTTAGTACGAGTATTGTATTTCCAATATTCAGTCTAATTAGAATTGCAAAATTACTGAACACTCAATCATAA >TRINITY_DN75_c0_g1_i1 len=478 path=[456:0-477] [-1, 456, -2] CGAGCACATCAGGCCAGGGTTCCCCAAGTGCTCGAGTTTCGTAACCAAACAACCATCTTCTGGTCCGACCACCAGTCACATGATCAGCTGTGGCGCTCAGTATACGAGCACAGATTGCAACAGCCACCAAATGAGAGAGGAAAGTCATCCACATTGCCATGAAATCTGCGAAAGAGCGTAAATTGCGAGTAGCATGACCGCAGGTACGGCGCAGTAGCTGGAGTTGGCAGCGGCTAGGGGTGCCAGGAGGAGTGCTCCAAGGGTCCATCGTGCTCCACATGCCTCCCCGCCGCTGAACGCGCTCAGAGCCTTGCTCATCTTGCTACGCTCGCTCCGTTCAGTCATCTTCGTGTCTCATCGTCGCAGCGCGTAGTATTTACG ``` There are close to 400,000 sequences in this file. I have another file ids.txt in the following format: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 >TRINITY_DN15434_c5_g3_i1 >TRINITY_DN9323_c8_g3_i5 >TRINITY_DN11957_c1_g7_i1 >TRINITY_DN15373_c1_g1_i1 >TRINITY_DN22913_c0_g1_i1 >TRINITY_DN13029_c4_g5_i1 ``` I have 100 sequence ids in this file. When I match these ids to the source file I want an output that gives me the match for each of these ids with the entire sequence. For example, for an id: ``` >TRINITY_DN80_c0_g1_i1 ``` I want my output to be: ``` >TRINITY_DN80_c0_g1_i1 CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` I want all hundred sequences in this format. I used this code: ``` while read p; do echo ''$p >> out.fasta grep -A 400000 -w $p source.fasta | sed -n -e '1,/>/ {/>/ !{'p''}} >> out.fasta done < ids.txt ``` But my output is different in that only the last id has a sequence and the rest dont have any sequence associated: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 .... >TRINITY_DN10309_c6_g3_i1 >TRINITY_DN6990_c0_g1_i1 TTTTTTTTTTTTTGTGGAAAAACATTGATTTTATTGAATTGTAAACTTAAAATTAGATTGGCTGCACATCTTAGATTTTGTTGAAAGCAGCAATATCAACAGACTGGACGAAGTCTTCGAATTCCTGGATTTTTTCAGTCAAGAGATCAACAGACACTTTGTCGTCTTCAATGACACACATGATCTGCAGTTTGTTGATACCATATCCAACAGGTACAAGTTTGGAAGCTCCCCAGAGGAGACCATCCATTTCGATGGTGCGGACCTGGTTTTCCATTTCTTTCATGTCTGTTTCATCATCCCATGGCTTGACGTCAAGGATTATAGATGATTTAGCAATGAGAGCAGGTTTCTTCGATTTTTTGTCAGCATAAGCTTTCAGACGTTCTTCACGAATTCTGGCGGCCTCTGCATCCTCTTCCTCGTCGCCAGATCCGAATAGGTCGACGTCATCATCGTCGTCATCCTTAGCAGCGGGTGCAGGTGCTGTGGTGGTCTTTCCGCCAGCGGTCAGAGGGCTAGCTCCAGCCGCCCAGGATTTGCGCTCCTCGGCATTGTAGGAGGCAATCTGGTTGTACCACCGGAGAGCGTGGGGCAAGCTTGCGCTCGGGGCCTTGCCGACTTGTTGGAACACTTGGAAATCGGCTTGAGTTGGTGTGTAACCTGACACATAACTCTTATCAGCTAAGAAATTGTTAAGCTCATTAAGGCCTTGTGCGGTTTTAACGTCTCCTACTGCCATTTTTATTTAAAAAAGTAGTTTTTTTCGAGTAATAGCCACACGCCCCGGCACAATGTGAGCAAGAAGGAATGAAAAAGAAATCTGACATTGACATTGCCATGAAATTGACTTTCAAAGAACGAATGAATTGAACTAATTTGAACGG ``` I am only getting the desired output for the 100th id from my ids.txt. Could someone help me on where my script is wrong. I would like to get all 100 sequences when i run the script. Thank you I have added google drive links to the files i am working with: [ids.txt](https://drive.google.com/open?id=1t1dv5GlbwD-qfN2EYVRSVYxo2XPxGHWx) [Source.fasta](https://drive.google.com/open?id=1gMjwOjUAgmr04EFpZDKpkEHMcC3YlzlR)
2019/02/18
[ "https://Stackoverflow.com/questions/54740667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296702/" ]
Repeatedly looping over a large file is inefficient; you really want to avoid running `grep` (or `sed` or `awk`) more than once if you can avoid it. Generally speaking, `sed` and Awk will often easily allow you to specify actions for individual lines in a file, and then you run the script on the file just once. For this particular problem, the standard Awk idiom with `NR==FNR` comes in handy. This is a mechanism which lets you read a number of keys into memory (concretely, when `NR==FNR` it means that you are processing the first input file, because the overall input line number is equal to the line number within this file) and then check if they are present in subsequent input files. Recall that Awk reads one line at a time and performs all the actions whose conditions match. The conditions are a simple boolean, and the actions are a set of Awk commands within a pair of braces. ``` awk 'NR == FNR { s[$0]; next } # If we fall through to here, we have finished processing the first file. # If we see a wedge and p is 1, reset it -- this is a new sequence /^>/ && p { p = 0 } # If the prefix of this line is in s, we have found a sequence we want. ($1$2 in s) || ($1 in s) || ((substr($1, 1, 1) " " substr($1, 2)) in s) { if ($1 ~ /^>./) { print $1 } else { print $1 $2 }; p = 1; next } # If p is true, we want to print this line p' ids.txt source.fasta >out.fasta ``` So when we are reading `ids.txt`, the condition `NR==FNR` is true, and so we simply store each line in the array `s`. The `next` causes the rest of the Awk script to be skipped for this line. On subsequent reads, when `NR!=FNR`, we use the variable `p` to control what to print. When we see a new sequence, we set `p` to 0 (in case it was 1 from a previous iteration). Then when we see a new sequence, we check if it is in `s`, and if so, we set `p` to one. The last line simply prints the line if `p` is not empty or zero. (An empty action is a shorthand for the action `{ print }`.) The slightly complex condition to check if `$1` is in `s` might be too complicated -- I put in some normalizations to make sure that a space between the `>` and the sequence identifier is tolerated, regardless of there was one in `ids.txt` or not. This can probably be simplified if your files are consistently formatted.
the best way to do this is using either python or perl. I was able to make a script for extracting the ids using python as follows. ``` #script to extract sequences from a source file based on ids in another file #the source is a fasta file with a header and a sequence that follows in one line #the ids file contains one id per line #both the id and source file should contain the character '>' at the beginning that siginifies an id def main(): #asks the user for the ids file file1 = raw_input('ids file: '); #opens the ids file into the memory ids_file = open(file1, 'r'); #asks the user for the fasta file file2 = raw_input('fasta file: '); #opens the fasta file into memory; you need your memory to be larger than the filesize, or python will hard crash fasta_file = open(file2, 'r'); #ask the user for the file name of output file file3 = raw_input('enter the output filename: '); #opens output file with append option; append is must as you dont want to override the existing data output_file = open(file3, 'w'); #split the ids into an array ids_lines = ids_file.read().splitlines() #split the fasta file into an array, the first element will be the id followed by the sequence fasta_lines = fasta_file.read().splitlines() #initializing loop counters i = 0; j = 0; #while loop to iterate over the length of the ids file as this is the limiter for the program while j<len(fasta_lines) and i<len(ids_lines): #if statement to match ids from both files and bring matching sequences if ids_lines[i] == fasta_lines[j]: #output statements including newline characters output_file.write(fasta_lines[j]) output_file.write('\n') output_file.write(fasta_lines[j+1]) output_file.write('\n') #increment i so that we go for the next id i=i+1; #deprecate j so we start all over for the new id j=0; else: #when there is no match check the id, we are skipping the sequence in the middle which is j+1 j=j+2; ids_file.close() fasta_file.close() output_file.close() main()` ``` The code is not perfect but works for any number of ids. I have tested for my samples which contained 5000 ids in one of them and the program worked fine. If there are improvements to the code please do so, I am a relatively newbie at programming so the code is a bit crude.
54,740,667
I have a "source.fasta" file that contains information in the following format: ``` >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG >TRINITY_DN83_c0_g1_i1 len=371 path=[1:0-173 152:174-370] [-1, 1, 152, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTATCGAGTAAGTTTACAGTCGTAAATAAAGAATCTGCCTTGAACAAACCTTATTCCTTTTTATTCTAAAAGAGGCCTTTGCGTAGTAGTAACATAGTACAAATTGGTTTATTTAACGATTTATAAACGATATCCTTCCTACAGTCGGGTGAAAAGAAAGTATTCGAAATTAGAATGGTTCCTCATATTACACGTTGCTG >TRINITY_DN83_c0_g1_i2 len=218 path=[1:0-173 741:174-217] [-1, 1, 741, -2] GTTGTAAACTTGTATACAATTGGGTTCATTAAAGTGTGCACATTATTTCATAGTTGATTTGATTATTCCGAGTGACCTATTTCGTCACTCGATGTTTAAAGAAATTGCTAGTGTGACCCCAATTGCGTCAGACCAAAGATTGAATCTAGACATTAATTTCCTTTTGTATTTGTACCGAGTAAGTTTCCAGTCGTAAATAAAGAATCTGCCAGATCGGA >TRINITY_DN99_c0_g1_i1 len=326 path=[1:0-242 221:243-243 652:244-267 246:268-325] [-1, 1, 221, 652, 246, -2] ATCGGTACTATCATGTCATATATCTAGAAATAATACCTACGAATGTTATAAGAATTTCATAACATGATATAACGATCATACATCATGGCCTTTCGAAGAAAATGGCGCATTTACGTTTAATAATTCCGCGAAAGTCAAGGCAAATACAGACCTAATGCGAAATTGAAAAGAAAATCCGAATATCAGAAACAGAACCCAGAACCAATATGCTCAGCAGTTGCTTTGTAGCCAATAAACTCAACTAGAAATTGCTTATCTTTTATGTAACGCCATAAAACGTAATACCGATAACAGACTAAGCACACATATGTAAATTACCTGCTAAA >TRINITY_DN90_c0_g1_i1 len=1240 path=[1970:0-527 753:528-1239] [-1, 1970, 753, -2] GTCGATACTAGACAACGAATAATTGTGTCTATTTTTAAAAATAATTCCTTTTGTAAGCAGATTTTTTTTTTCATGCATGTTTCGAGTAAATTGGATTACGCATTCCACGTAACATCGTAAATGTAACCACATTGTTGTAACATACGGTATTTTTTCTGACAACGGACTCGATTGTAAGCAACTTTGTAACATTATAATCCTATGAGTATGACATTCTTAATAATAGCAACAGGGATAAAAATAAAACTACATTGTTTCATTCAACTCGTAAGTGTTTATTTAAAATTATTATTAAACACTATTGTAATAAAGTTTATATTCCTTTGTCAGTGGTAGACACATAAACAGTTTTCGAGTTCACTGTCG >TRINITY_DN84_c0_g1_i1 len=301 path=[1:0-220 358:221-300] [-1, 1, 358, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCACTTTTAAATCTTATAAACATGTGATCCGTCTGCTCATTTGGACGTTACTGCCCAAAGTTGGTACATGTTTCGTACTCACG >TRINITY_DN84_c0_g1_i2 len=301 path=[1:0-220 199:221-300] [-1, 1, 199, -2] ACTATTATGTAGTACCTACATTAGAAACAACTGACCCAAGACAGGAGAAGTCATTGGATGATTTTCCCCATTAAAAAAAGACAACCTTTTAAGTAAGCATACTCCAAATTAAGGTTTAATTAGCTAAGTGAGCGCGAAAAATGATCAAATATACCGACGTCCATTTGGGGCCTATCCTTTTTAGTGTTCCTAATTGAAATCCTCACGTATACAGCTAGTCAGCTAACCAAAGATAAGTGTCTTGGCTTGGTATCTACAGATCTCTTTTCGTAATTTCGTGAGTACGAAACATGTACCAACT >TRINITY_DN72_c0_g1_i1 len=434 path=[412:0-247 847:248-271 661:272-433] [-1, 412, 847, 661, -2] GTTAATTTAGTGGGAAGTATGTGTTAAAATTAGTAAATTAGGTGTTGGTGTGTTTTTAATATGAATCCGGAAGTGTTTTGTTAGGTTACAAGGGTACGGAATTGTAATAATAGAAATCGGTATCCTTGAGACCAATGTTATCGCATTCGATGCAAGAATAGATTGGGAAATAGTCCGGTTATCAATTACTTAAAGATTTCTATCTTGAAAACTATTTCTAATTGGTAAAAAAACTTATTTAGAATCACCCATAGTTGGAAGTTTAAGATTTGAGACATCTTAAATTTTTGGTAGGTAATTTTAAGATTCTATCGTAGTTAGTACCTTTCGTTCTTCTTATTTTATTTGTAAAATATATTACATTTAGTACGAGTATTGTATTTCCAATATTCAGTCTAATTAGAATTGCAAAATTACTGAACACTCAATCATAA >TRINITY_DN75_c0_g1_i1 len=478 path=[456:0-477] [-1, 456, -2] CGAGCACATCAGGCCAGGGTTCCCCAAGTGCTCGAGTTTCGTAACCAAACAACCATCTTCTGGTCCGACCACCAGTCACATGATCAGCTGTGGCGCTCAGTATACGAGCACAGATTGCAACAGCCACCAAATGAGAGAGGAAAGTCATCCACATTGCCATGAAATCTGCGAAAGAGCGTAAATTGCGAGTAGCATGACCGCAGGTACGGCGCAGTAGCTGGAGTTGGCAGCGGCTAGGGGTGCCAGGAGGAGTGCTCCAAGGGTCCATCGTGCTCCACATGCCTCCCCGCCGCTGAACGCGCTCAGAGCCTTGCTCATCTTGCTACGCTCGCTCCGTTCAGTCATCTTCGTGTCTCATCGTCGCAGCGCGTAGTATTTACG ``` There are close to 400,000 sequences in this file. I have another file ids.txt in the following format: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 >TRINITY_DN15434_c5_g3_i1 >TRINITY_DN9323_c8_g3_i5 >TRINITY_DN11957_c1_g7_i1 >TRINITY_DN15373_c1_g1_i1 >TRINITY_DN22913_c0_g1_i1 >TRINITY_DN13029_c4_g5_i1 ``` I have 100 sequence ids in this file. When I match these ids to the source file I want an output that gives me the match for each of these ids with the entire sequence. For example, for an id: ``` >TRINITY_DN80_c0_g1_i1 ``` I want my output to be: ``` >TRINITY_DN80_c0_g1_i1 CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` I want all hundred sequences in this format. I used this code: ``` while read p; do echo ''$p >> out.fasta grep -A 400000 -w $p source.fasta | sed -n -e '1,/>/ {/>/ !{'p''}} >> out.fasta done < ids.txt ``` But my output is different in that only the last id has a sequence and the rest dont have any sequence associated: ``` >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN8506_c0_g1_i1 >TRINITY_DN12276_c0_g2_i1 .... >TRINITY_DN10309_c6_g3_i1 >TRINITY_DN6990_c0_g1_i1 TTTTTTTTTTTTTGTGGAAAAACATTGATTTTATTGAATTGTAAACTTAAAATTAGATTGGCTGCACATCTTAGATTTTGTTGAAAGCAGCAATATCAACAGACTGGACGAAGTCTTCGAATTCCTGGATTTTTTCAGTCAAGAGATCAACAGACACTTTGTCGTCTTCAATGACACACATGATCTGCAGTTTGTTGATACCATATCCAACAGGTACAAGTTTGGAAGCTCCCCAGAGGAGACCATCCATTTCGATGGTGCGGACCTGGTTTTCCATTTCTTTCATGTCTGTTTCATCATCCCATGGCTTGACGTCAAGGATTATAGATGATTTAGCAATGAGAGCAGGTTTCTTCGATTTTTTGTCAGCATAAGCTTTCAGACGTTCTTCACGAATTCTGGCGGCCTCTGCATCCTCTTCCTCGTCGCCAGATCCGAATAGGTCGACGTCATCATCGTCGTCATCCTTAGCAGCGGGTGCAGGTGCTGTGGTGGTCTTTCCGCCAGCGGTCAGAGGGCTAGCTCCAGCCGCCCAGGATTTGCGCTCCTCGGCATTGTAGGAGGCAATCTGGTTGTACCACCGGAGAGCGTGGGGCAAGCTTGCGCTCGGGGCCTTGCCGACTTGTTGGAACACTTGGAAATCGGCTTGAGTTGGTGTGTAACCTGACACATAACTCTTATCAGCTAAGAAATTGTTAAGCTCATTAAGGCCTTGTGCGGTTTTAACGTCTCCTACTGCCATTTTTATTTAAAAAAGTAGTTTTTTTCGAGTAATAGCCACACGCCCCGGCACAATGTGAGCAAGAAGGAATGAAAAAGAAATCTGACATTGACATTGCCATGAAATTGACTTTCAAAGAACGAATGAATTGAACTAATTTGAACGG ``` I am only getting the desired output for the 100th id from my ids.txt. Could someone help me on where my script is wrong. I would like to get all 100 sequences when i run the script. Thank you I have added google drive links to the files i am working with: [ids.txt](https://drive.google.com/open?id=1t1dv5GlbwD-qfN2EYVRSVYxo2XPxGHWx) [Source.fasta](https://drive.google.com/open?id=1gMjwOjUAgmr04EFpZDKpkEHMcC3YlzlR)
2019/02/18
[ "https://Stackoverflow.com/questions/54740667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296702/" ]
``` $ awk 'NR==FNR{a[$1];next} $1 in a{c=2} c&&c--' ids.txt source.fasta >TRINITY_DN80_c0_g1_i1 len=723 path=[700:0-350 1417:351-368 1045:369-722] [-1, 700, 1417, 1045, -2] CGTGGATAACACATAAGTCACTGTAATTTAAAAACTGTAGGACTTAGATCTCCTTTCTATATTTTTCTGATAACATATGGAACCCTGCCGATCATCCGATTTGTAATATACTTAACTGCTGGATAACTAGCCAAAAGTCATCAGGTTATTATATTCAATAAAATGTAACTTGCCGTAAGTAACAGAGGTCATATGTTCCTGTTCGTCACTCTGTAGTTACAAATTATGACACGTGTGCGCTG ``` The above was run using your posted source.fasta and this ids.txt: ``` $ cat ids.txt >TRINITY_DN14840_c10_g1_i1 >TRINITY_DN80_c0_g1_i1 ```
This might work for you (GNU sed): ``` sed 's#.*#/^&/{s/ .*//;N;p}#' idFile | sed -nf - fastafile ``` Convert the idFile into a sed script and run it against the fastaFile.
47,717,708
I have 3 tables STUDENT, SUBJECT and GRADE. STUDENT ``` +------------+------------+------------+ | student_id | first_name | last_name | +------------+------------+------------+ | 0 | Arthur | Pain | | 1 | Richard | Gordon | | 2 | Jennifer | Adelaide | +------------+------------+------------+ ``` SUBJECT ``` +------------+--------------+ | subject_id | subject_name | +------------+--------------+ | 001 | Math | | 002 | Science | | 003 | English | +------------+--------------+ ``` GRADE ``` +-------------+-------------+--------+ | student_id | subject_id | grade | +-------------+-------------+--------+ | 0 | 001 | A | | 0 | 002 | B | | 0 | 003 | A | | 1 | 001 | B | | 1 | 002 | A | | 1 | 003 | F | | 2 | 001 | A | | 2 | 002 | B | | 2 | 003 | B | +-------------+-------------+--------+ ``` I have tried the query below. ``` SELECT * FROM student st WHERE EXISTS (SELECT 1 FROM grade g WHERE st.student_id = g.student_id AND g.grade IN ('A','B'); ``` I want to select the students with grades only 'A' OR 'B'.
2017/12/08
[ "https://Stackoverflow.com/questions/47717708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7671013/" ]
The errors are right there. You don't have enough space on your host; and the `entrypoint.sh` file is being denied. Ensure your host has enough disk space (Shell in and `df -h` to check and expand the volume or just bring up a new instance with more space) and for the `entrypoint.sh` ensure that when building your image it is executable `chmod +x` and also is readable by the user the container is running as. Test your containers locally first; the second error should have been caught in development instantly.
If it's too many tasks running and they have consumed the space then you will need to shell in to the host and do the following. Don't use `-f` on the `docker rm` as that will remove the running ECS agent container ``` docker rm $(docker ps -aq) ```
47,717,708
I have 3 tables STUDENT, SUBJECT and GRADE. STUDENT ``` +------------+------------+------------+ | student_id | first_name | last_name | +------------+------------+------------+ | 0 | Arthur | Pain | | 1 | Richard | Gordon | | 2 | Jennifer | Adelaide | +------------+------------+------------+ ``` SUBJECT ``` +------------+--------------+ | subject_id | subject_name | +------------+--------------+ | 001 | Math | | 002 | Science | | 003 | English | +------------+--------------+ ``` GRADE ``` +-------------+-------------+--------+ | student_id | subject_id | grade | +-------------+-------------+--------+ | 0 | 001 | A | | 0 | 002 | B | | 0 | 003 | A | | 1 | 001 | B | | 1 | 002 | A | | 1 | 003 | F | | 2 | 001 | A | | 2 | 002 | B | | 2 | 003 | B | +-------------+-------------+--------+ ``` I have tried the query below. ``` SELECT * FROM student st WHERE EXISTS (SELECT 1 FROM grade g WHERE st.student_id = g.student_id AND g.grade IN ('A','B'); ``` I want to select the students with grades only 'A' OR 'B'.
2017/12/08
[ "https://Stackoverflow.com/questions/47717708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7671013/" ]
The errors are right there. You don't have enough space on your host; and the `entrypoint.sh` file is being denied. Ensure your host has enough disk space (Shell in and `df -h` to check and expand the volume or just bring up a new instance with more space) and for the `entrypoint.sh` ensure that when building your image it is executable `chmod +x` and also is readable by the user the container is running as. Test your containers locally first; the second error should have been caught in development instantly.
Do docker ps -a Which results in all the stopped containers which are excited, these also consumes disk space.use below command to remove those zoombie docker rm $(docker ps -a | grep Exited | awk '{print $1}') And also remove older images or unused images these takes more DiskStation size than containers docker rmi -f image\_name
47,717,708
I have 3 tables STUDENT, SUBJECT and GRADE. STUDENT ``` +------------+------------+------------+ | student_id | first_name | last_name | +------------+------------+------------+ | 0 | Arthur | Pain | | 1 | Richard | Gordon | | 2 | Jennifer | Adelaide | +------------+------------+------------+ ``` SUBJECT ``` +------------+--------------+ | subject_id | subject_name | +------------+--------------+ | 001 | Math | | 002 | Science | | 003 | English | +------------+--------------+ ``` GRADE ``` +-------------+-------------+--------+ | student_id | subject_id | grade | +-------------+-------------+--------+ | 0 | 001 | A | | 0 | 002 | B | | 0 | 003 | A | | 1 | 001 | B | | 1 | 002 | A | | 1 | 003 | F | | 2 | 001 | A | | 2 | 002 | B | | 2 | 003 | B | +-------------+-------------+--------+ ``` I have tried the query below. ``` SELECT * FROM student st WHERE EXISTS (SELECT 1 FROM grade g WHERE st.student_id = g.student_id AND g.grade IN ('A','B'); ``` I want to select the students with grades only 'A' OR 'B'.
2017/12/08
[ "https://Stackoverflow.com/questions/47717708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7671013/" ]
The errors are right there. You don't have enough space on your host; and the `entrypoint.sh` file is being denied. Ensure your host has enough disk space (Shell in and `df -h` to check and expand the volume or just bring up a new instance with more space) and for the `entrypoint.sh` ensure that when building your image it is executable `chmod +x` and also is readable by the user the container is running as. Test your containers locally first; the second error should have been caught in development instantly.
I realize this answer isn't 100% relevant to the question asked, but some googling brought me here due to the title and I figure my solution might help someone later down the line. I also had this issue, but the reason why my containers kept restarting wasn't a lack of space or other resources, it was because I had enabled dynamic host port mapping and forgotten to update my security group as needed. What happened then is that the health checks my load balancer sent to my containers inevitably failed and ECS restarted the containers (whoops). Dynamic Port Mapping in AWS Documentation: * <https://aws.amazon.com/premiumsupport/knowledge-center/dynamic-port-mapping-ecs/> * <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PortMapping.html> Contents --> hostPort tl;dr - Make sure your load balancer can health check ports 32768 - 65535.
47,717,708
I have 3 tables STUDENT, SUBJECT and GRADE. STUDENT ``` +------------+------------+------------+ | student_id | first_name | last_name | +------------+------------+------------+ | 0 | Arthur | Pain | | 1 | Richard | Gordon | | 2 | Jennifer | Adelaide | +------------+------------+------------+ ``` SUBJECT ``` +------------+--------------+ | subject_id | subject_name | +------------+--------------+ | 001 | Math | | 002 | Science | | 003 | English | +------------+--------------+ ``` GRADE ``` +-------------+-------------+--------+ | student_id | subject_id | grade | +-------------+-------------+--------+ | 0 | 001 | A | | 0 | 002 | B | | 0 | 003 | A | | 1 | 001 | B | | 1 | 002 | A | | 1 | 003 | F | | 2 | 001 | A | | 2 | 002 | B | | 2 | 003 | B | +-------------+-------------+--------+ ``` I have tried the query below. ``` SELECT * FROM student st WHERE EXISTS (SELECT 1 FROM grade g WHERE st.student_id = g.student_id AND g.grade IN ('A','B'); ``` I want to select the students with grades only 'A' OR 'B'.
2017/12/08
[ "https://Stackoverflow.com/questions/47717708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7671013/" ]
I realize this answer isn't 100% relevant to the question asked, but some googling brought me here due to the title and I figure my solution might help someone later down the line. I also had this issue, but the reason why my containers kept restarting wasn't a lack of space or other resources, it was because I had enabled dynamic host port mapping and forgotten to update my security group as needed. What happened then is that the health checks my load balancer sent to my containers inevitably failed and ECS restarted the containers (whoops). Dynamic Port Mapping in AWS Documentation: * <https://aws.amazon.com/premiumsupport/knowledge-center/dynamic-port-mapping-ecs/> * <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PortMapping.html> Contents --> hostPort tl;dr - Make sure your load balancer can health check ports 32768 - 65535.
If it's too many tasks running and they have consumed the space then you will need to shell in to the host and do the following. Don't use `-f` on the `docker rm` as that will remove the running ECS agent container ``` docker rm $(docker ps -aq) ```
47,717,708
I have 3 tables STUDENT, SUBJECT and GRADE. STUDENT ``` +------------+------------+------------+ | student_id | first_name | last_name | +------------+------------+------------+ | 0 | Arthur | Pain | | 1 | Richard | Gordon | | 2 | Jennifer | Adelaide | +------------+------------+------------+ ``` SUBJECT ``` +------------+--------------+ | subject_id | subject_name | +------------+--------------+ | 001 | Math | | 002 | Science | | 003 | English | +------------+--------------+ ``` GRADE ``` +-------------+-------------+--------+ | student_id | subject_id | grade | +-------------+-------------+--------+ | 0 | 001 | A | | 0 | 002 | B | | 0 | 003 | A | | 1 | 001 | B | | 1 | 002 | A | | 1 | 003 | F | | 2 | 001 | A | | 2 | 002 | B | | 2 | 003 | B | +-------------+-------------+--------+ ``` I have tried the query below. ``` SELECT * FROM student st WHERE EXISTS (SELECT 1 FROM grade g WHERE st.student_id = g.student_id AND g.grade IN ('A','B'); ``` I want to select the students with grades only 'A' OR 'B'.
2017/12/08
[ "https://Stackoverflow.com/questions/47717708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7671013/" ]
I realize this answer isn't 100% relevant to the question asked, but some googling brought me here due to the title and I figure my solution might help someone later down the line. I also had this issue, but the reason why my containers kept restarting wasn't a lack of space or other resources, it was because I had enabled dynamic host port mapping and forgotten to update my security group as needed. What happened then is that the health checks my load balancer sent to my containers inevitably failed and ECS restarted the containers (whoops). Dynamic Port Mapping in AWS Documentation: * <https://aws.amazon.com/premiumsupport/knowledge-center/dynamic-port-mapping-ecs/> * <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PortMapping.html> Contents --> hostPort tl;dr - Make sure your load balancer can health check ports 32768 - 65535.
Do docker ps -a Which results in all the stopped containers which are excited, these also consumes disk space.use below command to remove those zoombie docker rm $(docker ps -a | grep Exited | awk '{print $1}') And also remove older images or unused images these takes more DiskStation size than containers docker rmi -f image\_name
6,806,037
Is it possible that I can view the line number and file name (for my program running with ltrace/strace) along with the library call/system call information. Eg: ``` code section :: ptr = malloc(sizeof(int)*5); (file:code.c, line:21) ``` ltrace or any other tool: `malloc(20) :: code.c::21` I have tried all the options of ltrace/strace but cannot figure out a way to get this info. If not possible through ltrace/strace, do we have any parallel tool option for GNU/Linux?
2011/07/24
[ "https://Stackoverflow.com/questions/6806037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720094/" ]
You may be able to use the `-i` option (to output the instruction pointer at the time of the call) in `strace` and `ltrace`, combined with `addr2line` to resolve the calls to lines of code.
No It's not possible. Why don't you use gdb for this purpose? When you are compiling application with gcc use -ggdb flags to get debugger info into your program and then run your program with gdb or equivalent frontend (ddd or similar) Here is quick gdb manual to help you out a bit. <http://www.cs.cmu.edu/~gilpin/tutorial/>
6,806,037
Is it possible that I can view the line number and file name (for my program running with ltrace/strace) along with the library call/system call information. Eg: ``` code section :: ptr = malloc(sizeof(int)*5); (file:code.c, line:21) ``` ltrace or any other tool: `malloc(20) :: code.c::21` I have tried all the options of ltrace/strace but cannot figure out a way to get this info. If not possible through ltrace/strace, do we have any parallel tool option for GNU/Linux?
2011/07/24
[ "https://Stackoverflow.com/questions/6806037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720094/" ]
No It's not possible. Why don't you use gdb for this purpose? When you are compiling application with gcc use -ggdb flags to get debugger info into your program and then run your program with gdb or equivalent frontend (ddd or similar) Here is quick gdb manual to help you out a bit. <http://www.cs.cmu.edu/~gilpin/tutorial/>
You can use strace-plus that can collects stack traces associated with each system call. <http://code.google.com/p/strace-plus/>
6,806,037
Is it possible that I can view the line number and file name (for my program running with ltrace/strace) along with the library call/system call information. Eg: ``` code section :: ptr = malloc(sizeof(int)*5); (file:code.c, line:21) ``` ltrace or any other tool: `malloc(20) :: code.c::21` I have tried all the options of ltrace/strace but cannot figure out a way to get this info. If not possible through ltrace/strace, do we have any parallel tool option for GNU/Linux?
2011/07/24
[ "https://Stackoverflow.com/questions/6806037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720094/" ]
No It's not possible. Why don't you use gdb for this purpose? When you are compiling application with gcc use -ggdb flags to get debugger info into your program and then run your program with gdb or equivalent frontend (ddd or similar) Here is quick gdb manual to help you out a bit. <http://www.cs.cmu.edu/~gilpin/tutorial/>
Pretty old question, but I found a way to accomplish what OP wanted: First use strace with `-k` option, which will generate a stack trace like this: ``` openat(AT_FDCWD, NULL, O_RDONLY) = -1 EFAULT (Bad address) > /usr/lib/libc-2.33.so(__open64+0x5b) [0xefeab] > /usr/lib/libc-2.33.so(_IO_file_open+0x26) [0x816f6] > /usr/lib/libc-2.33.so(_IO_file_fopen+0x10a) [0x818ca] > /usr/lib/libc-2.33.so(__fopen_internal+0x7d) [0x7527d] > /mnt/r/build/tests/main(main+0x90) [**0x1330**] > /usr/lib/libc-2.33.so(__libc_start_main+0xd5) [0x27b25] > /mnt/r/build/tests/main(_start+0x2e) [0x114e] ``` The address of each function call are displayed at the end of each line, and you can paste it to `addr2line` to retrieve the file and line. For example, we want to locate the call in `main()` (fifth line of the stack trace). ```bash addr2line -e tests/main 0x1330 ``` It will show something like this: ``` /mnt/r/main.c:55 ```
6,806,037
Is it possible that I can view the line number and file name (for my program running with ltrace/strace) along with the library call/system call information. Eg: ``` code section :: ptr = malloc(sizeof(int)*5); (file:code.c, line:21) ``` ltrace or any other tool: `malloc(20) :: code.c::21` I have tried all the options of ltrace/strace but cannot figure out a way to get this info. If not possible through ltrace/strace, do we have any parallel tool option for GNU/Linux?
2011/07/24
[ "https://Stackoverflow.com/questions/6806037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720094/" ]
You may be able to use the `-i` option (to output the instruction pointer at the time of the call) in `strace` and `ltrace`, combined with `addr2line` to resolve the calls to lines of code.
You can use strace-plus that can collects stack traces associated with each system call. <http://code.google.com/p/strace-plus/>
6,806,037
Is it possible that I can view the line number and file name (for my program running with ltrace/strace) along with the library call/system call information. Eg: ``` code section :: ptr = malloc(sizeof(int)*5); (file:code.c, line:21) ``` ltrace or any other tool: `malloc(20) :: code.c::21` I have tried all the options of ltrace/strace but cannot figure out a way to get this info. If not possible through ltrace/strace, do we have any parallel tool option for GNU/Linux?
2011/07/24
[ "https://Stackoverflow.com/questions/6806037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720094/" ]
You may be able to use the `-i` option (to output the instruction pointer at the time of the call) in `strace` and `ltrace`, combined with `addr2line` to resolve the calls to lines of code.
Pretty old question, but I found a way to accomplish what OP wanted: First use strace with `-k` option, which will generate a stack trace like this: ``` openat(AT_FDCWD, NULL, O_RDONLY) = -1 EFAULT (Bad address) > /usr/lib/libc-2.33.so(__open64+0x5b) [0xefeab] > /usr/lib/libc-2.33.so(_IO_file_open+0x26) [0x816f6] > /usr/lib/libc-2.33.so(_IO_file_fopen+0x10a) [0x818ca] > /usr/lib/libc-2.33.so(__fopen_internal+0x7d) [0x7527d] > /mnt/r/build/tests/main(main+0x90) [**0x1330**] > /usr/lib/libc-2.33.so(__libc_start_main+0xd5) [0x27b25] > /mnt/r/build/tests/main(_start+0x2e) [0x114e] ``` The address of each function call are displayed at the end of each line, and you can paste it to `addr2line` to retrieve the file and line. For example, we want to locate the call in `main()` (fifth line of the stack trace). ```bash addr2line -e tests/main 0x1330 ``` It will show something like this: ``` /mnt/r/main.c:55 ```
36,368,711
I am keep on getting the following error when I build, > > use of undeclared identifier 'make\_unique' > m\_planet = make\_unique(); > > > My Header File which gives out the error, ``` #include "planet.h" #include <memory> using namespace std; class PlanetBuilder { public: PlanetBuilder(); virtual ~PlanetBuilder(); void createNewPlanetProduct() { m_planet = make_unique<Planet>(); } protected: unique_ptr<Planet> m_planet; }; #endif // PLANETBUILDER_H ``` I am running QtCreator 3.6.0 , tried on both Mac and Windows platforms and the error is consistent.. where am I going wrong?
2016/04/02
[ "https://Stackoverflow.com/questions/36368711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5077684/" ]
make\_unique requires `#include <memory>` But since you have done that, I would think you are not using C++14 or above. Try adding following flag on your make file. ``` -std=c++14 ```
For current QT which is 5.7 I'm using a #include . By following a link bellow you find out more. [QScopedPointer link](http://doc.qt.io/qt-5/qscopedpointer.html)
7,322,878
I,m creating a quiz to Android, and my questions and answers are stored in the SQLite DB. Now I realized that maybe users can browse the db and see all questions and answers from the device if they have the apropriate tools, am I right? How can I prevent them from users from seeing my data? Is it possible to use a password to access data, or something like that? Thanks in advance, João
2011/09/06
[ "https://Stackoverflow.com/questions/7322878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/931090/" ]
Consider using the [`javax.crypto`](http://developer.android.com/reference/javax/crypto/package-summary.html) api. Store your answers in the database as encrypted strings, and then use the encryption key in your app's code to decrypt the data after it's read from the database. Remember that a determined user *will* find a way to break your encryption (typically by coercing the encryption key out of your app's source code), and there is no such thing as 100% secure when dealing with untrusted parties (i.e. users).
Yes, it's definitely possible! You can [encode and decode the data with a key](http://practicalcryptography.com/ciphers/caesar-cipher/). At least, it will be not directly readable. Each time you write data in your DB, you encode it. Each time you read it, you decode it.
10,251,328
I have a task scheduled as such: ``` <task:scheduler id="notification.scheduler" pool-size="15" /> <task:scheduled-tasks scheduler="notification.scheduler"> <task:scheduled ref="notificationProcessor" method="sendNextQueueEvent" fixed-rate="500" /> <task:scheduled ref="notificationProcessor" method="deleteNextCompletedEvent" fixed-rate="60000" /> </task:scheduled-tasks> ``` I think I have a misunderstanding of how the scheduled tasks work with the pool size. Despite the pool-size being 15, it seems only one thread is being used. For example, if I have fifteen events in the queue, I would think there would be fifteen threads checking every minute to remove an event from the queue. Obviously, this is wrong. How can I make it so that there's fifteen threads calling this method for the time interval using Spring's scheduler abstraction? Edit: What I want to accomplish is this: Every half second, I want to check to see if there are queued events to send. When this is done, I want to send a maximum of 15 (if 15 exist). How would I accomplish this using the spring abstractions for the java thread stuff?
2012/04/20
[ "https://Stackoverflow.com/questions/10251328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366447/" ]
First of all `<task:scheduler/>` is a wrapper around `ScheduledThreadPoolExecutor` extending `ThreadPoolExecutor`. JavaDoc for the latter says: > > even core threads are initially created and started only when new tasks arrive > > > Secondly you must understand that scheduled tasks (this is a Java feature, not Spring's) do not run concurrently, even if they take longer time than repeat interval. They simply wait. So you don't have 15 events waiting in the queue, you have 15 executions that are late and wait for that single thread. No need to create another one because next execution has to wait for the previous one to finish. Again, this is how Java scheduling framework works. Of course if you have several different tasks scheduled, more threads will be created.
Spring's [`task:scheduler`](http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/scheduling.html#threadPoolTaskExecutor) is by default a bean properties wrapper for [`java.util.concurrent.ThreadPoolExecutor`](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html): > > corePoolSize - the number of threads to keep in the pool, even if they > are idle. > > > This does not guarantee that the `pools-size` property is equivalent to having that number of *active* threads. On the other hand, you should note that at *any given point in time* there can be only a maximum number of threads equal to processing cores on the machine that you're using; i.e. all other threads will be waiting to switch to `RUNNING` mode and continue execution. Also, in Spring's documentation, it mentions that if this is not what you need, you can also take advantage of `ConcurrentTaskExecutor`.
51,871,706
I have an automation project and it's working fine with java-client 5.0.4, while updating it to java-client: 6.1.0 in `pom.xml` file, then it's showing below error on IDE `java.lang.NoClassDefFoundError: org/openqa/selenium/remote/internal/OkHttpClient$Factory` above error showing within a second, seems like no interaction with Appium server and as a result there is no error log on Appium server Project: Maven Appium server: 1.8.1
2018/08/16
[ "https://Stackoverflow.com/questions/51871706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6333173/" ]
You can use pattern: ``` [!,.:;-](?= |$) ``` To match any characters `!`,`,`,`.`,`:`,`;` and `-` that are followed by whitespace or end of string. --- In Python: ``` import re text = "Hi! We are looking for smart, young and hard-working c++ developer. Our perfect candidate should know: - c++, c#, .NET in expert level;" print (re.sub(r'[!,.:;-](?= |$)',r'',text)) ``` Prints: ``` Hi We are looking for smart young and hard-working c++ developer Our perfect candidate should know c++ c# .NET in expert level ```
My solution ``` def clean(s: str, keep=None, remove=None): """ delete punctuation from "s" except special words """ if keep is None: keep = [] if remove is None: remove = [] protected = [False for _ in s] # True if you keep # compute protected chars for w in keep: # for every special word for i in range(len(s)-len(w)): same = True for j in range(len(w)): if w[j] != s[i + j]: same = False if same: for j in range(len(w)): protected[i + j] = True # delete unwanted chars out = '' for i in range(len(s)): if protected[i]: out += s[i] else: if s[i] not in remove: out += s[i] return out if __name__ == "__main__": test = "Hi! We are looking for smart, young and hard-working c++ developer. Our perfect candidate should know:" \ " - c++, c# in expert level;" Remove = ['.', ',', ':', ';', '+', '-', '!', '?', '#'] Keep = ['c++', 'c#'] print(clean(test, keep=Keep, remove=Remove)) ```
3,019
The thing I dislike most about MPI is dealing with datatypes (i.e. data maps/masks) because they don't fit that nicely with object oriented C++. `boost::mpi` only supports MPI 1.1, however, from their website: > > boost::mpi is a C++ friendly interface to the standard Message Passing Interface… Boost.MPI can build MPI data types for user-defined types using the Boost.Serialization library > > > Has anyone had any experience with `boost::mpi` for serious scientific computing? Would you recommend it? Did you had any issues (scaling problems, compiler problems, errors, not implemented features, the need for some mpi 2.2 features)? Can you comment on using `boost::mpi` instead of using the MPI C implementation from C++? Can you combine both (use boost::mpi when you can, C-MPI elsewhere)? Do you know of any large scientific code using `boost::mpi` ?
2012/08/08
[ "https://scicomp.stackexchange.com/questions/3019", "https://scicomp.stackexchange.com", "https://scicomp.stackexchange.com/users/1831/" ]
I have always thought that we should use it in our own project, deal.II, because it is higher level than pure MPI and can save a few lines of code here and there. That said, what I learned over the years is that most high-level code doesn't actually have that much MPI code to begin with -- the 600,000 lines of code in deal.II have only ~50 calls to MPI. That's certainly much much less than a package such as PETSc, but I think it's nevertheless true that most codes have fewer MPI calls than one would expect at first and that, consequently, the benefit of using something that's higher level is not as great as one may think at first glance. What this then boils down to is for you to consider what the trade-offs are. How much MPI will you need to use, and how does that compare to the additional effort required to build and link with an external library.
As far as I know, `boost::mpi` is just a `c++` wrapper around the `C` API. As such, you should be able to use `boost::mpi` and switch to the `C` API whenever some functionality is not implemented. Indeed, from their webpage: > > The thin abstractions in Boost.MPI allow one to easily combine it with calls to the underlying C MPI library. > > > I have not used it myself, and do not know of a major library that does, but I'd expect it to be just a lightweight wrapper and as such one should not worry about the performance compared to `C` API.
8,770,425
I am retrieving data from database depending upon the texboxes input and storing in a datatable , after then from datatable im sending data into dynamic table and displaying table in a panel,in the table all the data of the first column are of linkbuttons, i wrote event handler for dynamic link buttons , but the event handler is not triggering, and i want to store the linkbutton text in a string in the event handler, but the event handler is not triggering. Code: ``` protected void Button1_Click(object sender, EventArgs e) { // GridView1. DataTable dt = new DataTable(); OleDbConnection con = new OleDbConnection(str); con.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = con; cmd.CommandText = "select ID,title,desc from [SO] where ID='" + TextBox1.Text.ToString() + "'or title='" + TextBox2.Text.ToString() + "'"; OleDbDataAdapter db = new OleDbDataAdapter(cmd); db.Fill(dt); Table tb = new Table(); tb.BorderColor = Color.Black; tb.BorderWidth = 2; DataRow dr; for (int i = 0; i < dt.Rows.Count; i++) { TableRow tr = new TableRow(); tr.BorderColor = Color.Black; tr.BorderWidth = 2; tr.ID = "tr" + i; TableCell tc = new TableCell(); tc.BorderColor = Color.Black; tc.BorderWidth = 2; tc.ID = "tc" + i; TableCell tc1 = new TableCell(); tc1.BorderColor = Color.Black; tc1.BorderWidth = 2; tc1.ID = "tc1" + i; TableCell tc2 = new TableCell(); tc2.BorderColor = Color.Black; tc2.BorderWidth = 2; tc2.ID = "tc2" + i; LinkButton t = new LinkButton(); t.BorderColor = Color.Black; t.BorderWidth = 2; t.ID = "t" + i; t.Click += new EventHandler(t_edit); TextBox t1 = new TextBox(); t1.BorderColor = Color.Black; t1.BorderWidth = 2; t1.ID = "t1" + i; TextBox t2 = new TextBox(); t2.BorderColor = Color.Black; t2.BorderWidth = 2; t2.ID = "t2" + i; dr = dt.Rows[i]; t.Text = Convert.ToString(dr["ID"]); t1.Text = Convert.ToString(dr["title"]); t2.Text = Convert.ToString(dr["desc"]); tc.Controls.Add(t); tc1.Controls.Add(t1); tc2.Controls.Add(t2); tr.Cells.Add(tc); tr.Cells.Add(tc1); tr.Cells.Add(tc2); tb.Rows.Add(tr); } Panel1.Controls.Add(tb); } protected void t_edit(object sender, EventArgs e) { } ``` --- k but by using the sessions concept im retrieving the total table so that the linkbuttons are also retrieving , and i want to add the linkbttons on a button click , here the problem is the eventhandler is not assiging to the linkbutton, and im adding linkbuttons on button click,not on page load.
2012/01/07
[ "https://Stackoverflow.com/questions/8770425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1135997/" ]
You must have to use `Page_Init` or `Page_Load` event handler to write code that create controls dynamically. Please read MSDN pages on [How to add controls dynamically](http://msdn.microsoft.com/en-us/library/kyt0fzt1.aspx) and ASP.NET Page life cycle articles.
You can add event handlers to the `Page_Load` event but the important think to remember is that they must be added on every page load. It is common to do setup type tasks such as this in a !`Page.IsPostBack` clause. When wiring up event handlers that's not the case otherwise they will seem to disappear ``` if(!Page.PostBack) { control.EventRaised += new EventHandler(EventResponse) } ``` is wrong and will result in the handler disappearing on postback
61,248,748
I'm pretty new to java streams and am trying to determine how to find the max from each list, in a list of lists, and end with a single list that contains the max from each sublist. I can accomplish this by using a `for` loop and `stream` like so: ``` // databaseRecordsLists is a List<List<DatabaseRecord>> List<DatabaseRecord> mostRecentRecords = new ArrayList<>(); for (List<DatabaseRecord> databaseRecords : databaseRecordsLists) { mostRecentRecords.add(databaseRecords.stream() .max(Comparator.comparing(DatabaseRecord::getTimestamp)) .orElseThrow(NoSuchElementException::new)); } ``` I've looked into the `flatMap` api, but then I'll only end up with a single map of all `DatabaseRecord` objects, where I need a max from each individual list. Any ideas on a cleaner way to accomplish this?
2020/04/16
[ "https://Stackoverflow.com/questions/61248748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4954435/" ]
You don't need `flatMap`. Create a `Stream<List<DatabaseRecord>>`, and map each `List<DatabaseRecord>` of the `Stream` to the max element. Then collect all the max elements into the output `List`. ``` List<DatabaseRecord> mostRecentRecords = databaseRecordsLists.stream() .map(list -> list.stream() .max(Comparator.comparing(DatabaseRecord::getTimestamp)) .orElseThrow(NoSuchElementException::new)) .collect(Collectors.toList()); ```
Based on the comments, I suggested to rather ignore the empty collection, otherwise, no result would be returned and `NoSuchElementException` thrown even the empty collection *might* (?) be a valid state. If so, you can improve the current solution: ``` databaseRecordsLists.stream() .filter(list -> !list.isEmpty()) // Only non-empty ones .map(list -> list.stream() .max(Comparator.comparing(DatabaseRecord::getTimestamp)) // Get these with max .orElseThrow(NoSuchElementException::new)) // Never happens .collect(Collectors.toList()); // To List ``` If you use a version higher than Java 8: * As of Java 10, `orElseThrow(NoSuchElementException::new)` can be subsituted with [`orElseThrow()`](https://docs.oracle.com/javase/10/docs/api/java/util/Optional.html#orElseThrow()). * As of Java 11, you can use [`Predicate.not(..)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/function/Predicate.html#not(java.util.function.Predicate)), therefore the filter part would look like: `.filter(Predicate.not(List::isEmpty))`.
2,658,106
``` int arr[ 5 ] = { 0 }; int i = 8; // out of bounds arr[ i ] = 8; ``` I know that I can just check i like this if( i < 0 || i > 5 ) .... I also know about SEH in Visual Studio, but it looks like not working solution. ``` __try { /* code */ } __except(GetExceptionCode() == EXCEPTION_ARRAY_BOUNDS_EXCEEDED) ``` This is not working. As I see SEH working in situations like divide to 0, access protected pages ... How can I protect my program from crashes?
2010/04/17
[ "https://Stackoverflow.com/questions/2658106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/181797/" ]
There is no guarantee that SEH will catch this - it depends on your hardware detecting the access , which does not happen for all invalid array accesses. If you want to be sure of catching it, use the standard C++ `std::vector` container instead of an array, and access it via its `at()` member function, rather than the `[]` operator - this will raise a standard C++ exception if the access is invalid.
Use proper containers like std::vector and catch the exceptions?
2,658,106
``` int arr[ 5 ] = { 0 }; int i = 8; // out of bounds arr[ i ] = 8; ``` I know that I can just check i like this if( i < 0 || i > 5 ) .... I also know about SEH in Visual Studio, but it looks like not working solution. ``` __try { /* code */ } __except(GetExceptionCode() == EXCEPTION_ARRAY_BOUNDS_EXCEEDED) ``` This is not working. As I see SEH working in situations like divide to 0, access protected pages ... How can I protect my program from crashes?
2010/04/17
[ "https://Stackoverflow.com/questions/2658106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/181797/" ]
You cannot protect yourself from this. If you want, you have to use another language that checks for you. C and C++ demand that you check yourself that you write safe code. An alternative may be to wrap the array into a struct... ``` template<typename E, std::size_t s> struct array { E &operator[](std::ptrdiff_t i) { assert(i < s && "out of range!"); return d[i]; } E const &operator[](std::ptrdiff_t i) const { assert(i < s && "out of range!"); return d[i]; } typedef E underlying_array[s]; underlying_array &raw() { return d; } underlying_array const &raw() const { return d; } E d[s]; }; array<int, 5> arr = { 0 }; arr[8] = 8; /* assert will ring */ foo(arr.raw()); /* pass as an int[5] */ ``` That class is provided by `boost` and C++0x too (however, without a `raw` function), but error checking is not required for them.
Use proper containers like std::vector and catch the exceptions?
2,658,106
``` int arr[ 5 ] = { 0 }; int i = 8; // out of bounds arr[ i ] = 8; ``` I know that I can just check i like this if( i < 0 || i > 5 ) .... I also know about SEH in Visual Studio, but it looks like not working solution. ``` __try { /* code */ } __except(GetExceptionCode() == EXCEPTION_ARRAY_BOUNDS_EXCEEDED) ``` This is not working. As I see SEH working in situations like divide to 0, access protected pages ... How can I protect my program from crashes?
2010/04/17
[ "https://Stackoverflow.com/questions/2658106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/181797/" ]
Use proper containers like std::vector and catch the exceptions?
You have a couple of options: * don't use raw arrays (use std::vector or boost::array instead) * don't use C++ the only other option is to write code that **does not contain any out-of-bounds errors** There is absolutely no way to reliably detect out-of-bounds errors on raw arrays in C++. You could just catch the access violation that *sometimes* occurs, but that won't give you a correct program. You'll still go out of bounds in many other cases, overwriting previously allocated memory and corrupting other parts of your program.
2,658,106
``` int arr[ 5 ] = { 0 }; int i = 8; // out of bounds arr[ i ] = 8; ``` I know that I can just check i like this if( i < 0 || i > 5 ) .... I also know about SEH in Visual Studio, but it looks like not working solution. ``` __try { /* code */ } __except(GetExceptionCode() == EXCEPTION_ARRAY_BOUNDS_EXCEEDED) ``` This is not working. As I see SEH working in situations like divide to 0, access protected pages ... How can I protect my program from crashes?
2010/04/17
[ "https://Stackoverflow.com/questions/2658106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/181797/" ]
There is no guarantee that SEH will catch this - it depends on your hardware detecting the access , which does not happen for all invalid array accesses. If you want to be sure of catching it, use the standard C++ `std::vector` container instead of an array, and access it via its `at()` member function, rather than the `[]` operator - this will raise a standard C++ exception if the access is invalid.
You cannot protect yourself from this. If you want, you have to use another language that checks for you. C and C++ demand that you check yourself that you write safe code. An alternative may be to wrap the array into a struct... ``` template<typename E, std::size_t s> struct array { E &operator[](std::ptrdiff_t i) { assert(i < s && "out of range!"); return d[i]; } E const &operator[](std::ptrdiff_t i) const { assert(i < s && "out of range!"); return d[i]; } typedef E underlying_array[s]; underlying_array &raw() { return d; } underlying_array const &raw() const { return d; } E d[s]; }; array<int, 5> arr = { 0 }; arr[8] = 8; /* assert will ring */ foo(arr.raw()); /* pass as an int[5] */ ``` That class is provided by `boost` and C++0x too (however, without a `raw` function), but error checking is not required for them.
2,658,106
``` int arr[ 5 ] = { 0 }; int i = 8; // out of bounds arr[ i ] = 8; ``` I know that I can just check i like this if( i < 0 || i > 5 ) .... I also know about SEH in Visual Studio, but it looks like not working solution. ``` __try { /* code */ } __except(GetExceptionCode() == EXCEPTION_ARRAY_BOUNDS_EXCEEDED) ``` This is not working. As I see SEH working in situations like divide to 0, access protected pages ... How can I protect my program from crashes?
2010/04/17
[ "https://Stackoverflow.com/questions/2658106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/181797/" ]
There is no guarantee that SEH will catch this - it depends on your hardware detecting the access , which does not happen for all invalid array accesses. If you want to be sure of catching it, use the standard C++ `std::vector` container instead of an array, and access it via its `at()` member function, rather than the `[]` operator - this will raise a standard C++ exception if the access is invalid.
You have a couple of options: * don't use raw arrays (use std::vector or boost::array instead) * don't use C++ the only other option is to write code that **does not contain any out-of-bounds errors** There is absolutely no way to reliably detect out-of-bounds errors on raw arrays in C++. You could just catch the access violation that *sometimes* occurs, but that won't give you a correct program. You'll still go out of bounds in many other cases, overwriting previously allocated memory and corrupting other parts of your program.
2,658,106
``` int arr[ 5 ] = { 0 }; int i = 8; // out of bounds arr[ i ] = 8; ``` I know that I can just check i like this if( i < 0 || i > 5 ) .... I also know about SEH in Visual Studio, but it looks like not working solution. ``` __try { /* code */ } __except(GetExceptionCode() == EXCEPTION_ARRAY_BOUNDS_EXCEEDED) ``` This is not working. As I see SEH working in situations like divide to 0, access protected pages ... How can I protect my program from crashes?
2010/04/17
[ "https://Stackoverflow.com/questions/2658106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/181797/" ]
You cannot protect yourself from this. If you want, you have to use another language that checks for you. C and C++ demand that you check yourself that you write safe code. An alternative may be to wrap the array into a struct... ``` template<typename E, std::size_t s> struct array { E &operator[](std::ptrdiff_t i) { assert(i < s && "out of range!"); return d[i]; } E const &operator[](std::ptrdiff_t i) const { assert(i < s && "out of range!"); return d[i]; } typedef E underlying_array[s]; underlying_array &raw() { return d; } underlying_array const &raw() const { return d; } E d[s]; }; array<int, 5> arr = { 0 }; arr[8] = 8; /* assert will ring */ foo(arr.raw()); /* pass as an int[5] */ ``` That class is provided by `boost` and C++0x too (however, without a `raw` function), but error checking is not required for them.
You have a couple of options: * don't use raw arrays (use std::vector or boost::array instead) * don't use C++ the only other option is to write code that **does not contain any out-of-bounds errors** There is absolutely no way to reliably detect out-of-bounds errors on raw arrays in C++. You could just catch the access violation that *sometimes* occurs, but that won't give you a correct program. You'll still go out of bounds in many other cases, overwriting previously allocated memory and corrupting other parts of your program.
23,711,272
How Do I achieve this result ? What I need is calculate total cost of a Product when a product is made up of components. New for me, I should add a 100$ to total cost if customer chooses for a service called Delivery. This is what I have tried so far. ``` Select Sum(Component.Cost*ProductComponent.Quantity) as TotCost from ProductComponent Left Join Component on ProductComponent.ComponentId = Component.ComponentId ``` I Guess this will get me total cost of a product. Now There is another table Service which has a many to many relationship with Order. Order has a many to many relationship with Service. What I need is I need to add another 100$ in total cost if there is 'deliverly' used in service. I have attached an ER diagram of my database structure. I hope my question is clear. ![enter image description here](https://i.stack.imgur.com/ttlBC.jpg)
2014/05/17
[ "https://Stackoverflow.com/questions/23711272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2380004/" ]
The problem is that you've got a `Content-Length` header claiming that you're going to send the server `5142` bytes in the `POST` body but you're not sending any body content at all. As a consequence, the server hangs waiting for the body; it will probably fail with a time out in a few minutes. To fix this, ensure that the `Content-Length` header matches the length of the body in bytes.
Please try `print(res.status)` Otherwise what I'm using is: <http://docs.python-requests.org/en/latest/>
33,325,383
Guys when I attended a C quiz online, I came across a statement `while(s++,6);` where *s* is initialized to zero. I don't know what the *while* loop will exactly do when there is a comma operator in between. When I ran it on my gcc compiler it ran with no output. But when I changed the *while* condition as `while(1,s++)` it returned *s* value as 1. Can anyone tell me what is happening at that *while*.
2015/10/25
[ "https://Stackoverflow.com/questions/33325383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5484867/" ]
The comma operator evaluates the left side and then throws away the result. The while condition keeps looping for any value other than zero. The first will be an infinite loop; the second will increment s and then stop. I suspect in this case the comma was a typo and they meant to type a less-than.
From C11 standard §6.5.17: > > The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value. > > > This means that `1,s++` evaluates `1` (so nothing happens), then it evaluates `s++` and returns the result of that expression only. So that's expression is equivalent to `while (s++)`. If the left-hand side of a comma expression doesn't have any side effects, like in your situation, then you can remove it.
36,329,164
While working on a program, I made some of my fields static i.e. a `JTextField` for a `E-Number`. But now this field behaves not as expected, on some of my pages it appears, on some others it disappears. Since I am not very experienced working with a lot of statics, there might be a concept I am not understanding. I have created a very simplified but working example of my program ([MCVE](https://stackoverflow.com/help/mcve)) if you want to test it. It shows my overview page at first - the `E-Number JTextField` is missing. If you click on the search button, it shows the tracking page - with the `E-Number JTextField` present. Both pages contain **the same** `workNumberPanel` and I cant find a difference, that would explain the behaviour. So why is the `E-Number JTextField` present on the overview page and missing on the tracking page? Any help / explanation is appreciated! [![Static JTextField disappears](https://i.stack.imgur.com/BGqx9.gif)](https://i.stack.imgur.com/BGqx9.gif) **MainProgram.java** ``` import java.awt.CardLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import net.miginfocom.swing.MigLayout; public class MainProgram extends JFrame { private static final long serialVersionUID = 1L; public static JPanel centerPanel = new JPanel(); public static CardLayout contentCardsLayout = new CardLayout(); OverviewPage overviewPage = new OverviewPage(); TrackingPage trackingPage = new TrackingPage(); public void initialize() { createCenterPanel(); } private void createCenterPanel() { centerPanel.setLayout(contentCardsLayout); overviewPage.setName("overviewPage"); trackingPage.setName("trackingPage"); centerPanel.add(overviewPage, "overviewPage"); centerPanel.add(trackingPage, "trackingPage"); add(centerPanel, "growx, wrap"); } public MainProgram() { setBounds(300, 50, 1200, 900); setLayout(new MigLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); MainProgram window = new MainProgram(); window.setVisible(true); window.initialize(); } catch (Exception e) { e.printStackTrace(); } } }); } } ``` **OverviewPage.java** ``` import javax.swing.JPanel; import net.miginfocom.swing.MigLayout; public class OverviewPage extends JPanel { WorkNumberPanel workNumberPanel = new WorkNumberPanel(); private static final long serialVersionUID = 1L; public OverviewPage() { setLayout(new MigLayout()); add(workNumberPanel, "wrap, growx"); } } ``` **TrackingPage.java** ``` import javax.swing.JPanel; import net.miginfocom.swing.MigLayout; public class TrackingPage extends JPanel { private static final long serialVersionUID = 1L; WorkNumberPanel equipmentNumberPanel = new WorkNumberPanel(); public TrackingPage(){ setLayout(new MigLayout("", "grow, fill")); add(equipmentNumberPanel, "wrap, growx"); } } ``` **WorkNumberPanel.java** ``` import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import net.miginfocom.swing.MigLayout; public class WorkNumberPanel extends JPanel { private static final long serialVersionUID = 1L; private static final Integer TEXTFIELD_LENGTH = 20; JPanel mainWorkNumberPanel = new JPanel(); JLabel lblWorkNumber = new JLabel("E-Nr: "); JLabel lblN_Number = new JLabel("N-Nr.: "); JLabel lblSNumber = new JLabel("W-Nr.: "); public static JTextField txtWorkNumber = new JTextField(TEXTFIELD_LENGTH); JTextField txtNNumber = new JTextField(TEXTFIELD_LENGTH); JTextField txtSNumber = new JTextField(TEXTFIELD_LENGTH); JButton btnSearchEntry = new JButton("Search"); public WorkNumberPanel() { createEquipmentNumberPanel(); btnSearchEntry.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainProgram.contentCardsLayout.show(MainProgram.centerPanel, "trackingPage"); } }); } private void createEquipmentNumberPanel() { setLayout(new MigLayout()); mainWorkNumberPanel.setLayout(new MigLayout("", "[][grow, fill][][grow, fill][][grow, fill][]")); mainWorkNumberPanel.add(lblWorkNumber); mainWorkNumberPanel.add(txtWorkNumber); mainWorkNumberPanel.add(lblN_Number); mainWorkNumberPanel.add(txtNNumber); mainWorkNumberPanel.add(lblSNumber); mainWorkNumberPanel.add(txtSNumber); mainWorkNumberPanel.add(btnSearchEntry); add(mainWorkNumberPanel, "push, span, growx"); } } ```
2016/03/31
[ "https://Stackoverflow.com/questions/36329164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368690/" ]
Probably because when you create your "pages" with this code ``` OverviewPage overviewPage = new OverviewPage(); TrackingPage trackingPage = new TrackingPage(); ``` the `TrackingPage` will be the last one to execute the following line ``` mainWorkNumberPanel.add(txtWorkNumber); ``` in `private void createEquipmentNumberPanel()`, and hence that Panel will "own" the JTextField. It only makes sense that a UI component can only be at one place at any given time, otherwise things would get very strange :) Your statement > > Both pages contain the same workNumberPanel and I cant find a difference, that would explain the behaviour. > > > is simply not true. You are creating a new instance of `WorkNumberPanel` in both `OverViewPage` and `TrackingPage` when you execute the following line ``` WorkNumberPanel equipmentNumberPanel = new WorkNumberPanel(); ``` So my recommendation is that you find another way of implementing what you want without using a static JTextField (or any other UI component for that matter).
Here you instantiate a `OverviewPage`, then a `TrackingPage` . ``` OverviewPage overviewPage = new OverviewPage(); TrackingPage trackingPage = new TrackingPage(); ``` Both of these classes instantiate a `WorkNumberPanel` . `WorkNumberPanel` add the static `JTextField` (txtWorkNumber) to their display panel (*mainWorkNumberPanel*). A single `Component` can't be added to several `Container` objects. This is what happens to your textfield, since it is `static` and not an instance variable. The last addition will win, so the textfield will appear in `TrackingPage` only, and not in `OverviewPage` anymore . Just don't make it `static`.
36,329,164
While working on a program, I made some of my fields static i.e. a `JTextField` for a `E-Number`. But now this field behaves not as expected, on some of my pages it appears, on some others it disappears. Since I am not very experienced working with a lot of statics, there might be a concept I am not understanding. I have created a very simplified but working example of my program ([MCVE](https://stackoverflow.com/help/mcve)) if you want to test it. It shows my overview page at first - the `E-Number JTextField` is missing. If you click on the search button, it shows the tracking page - with the `E-Number JTextField` present. Both pages contain **the same** `workNumberPanel` and I cant find a difference, that would explain the behaviour. So why is the `E-Number JTextField` present on the overview page and missing on the tracking page? Any help / explanation is appreciated! [![Static JTextField disappears](https://i.stack.imgur.com/BGqx9.gif)](https://i.stack.imgur.com/BGqx9.gif) **MainProgram.java** ``` import java.awt.CardLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import net.miginfocom.swing.MigLayout; public class MainProgram extends JFrame { private static final long serialVersionUID = 1L; public static JPanel centerPanel = new JPanel(); public static CardLayout contentCardsLayout = new CardLayout(); OverviewPage overviewPage = new OverviewPage(); TrackingPage trackingPage = new TrackingPage(); public void initialize() { createCenterPanel(); } private void createCenterPanel() { centerPanel.setLayout(contentCardsLayout); overviewPage.setName("overviewPage"); trackingPage.setName("trackingPage"); centerPanel.add(overviewPage, "overviewPage"); centerPanel.add(trackingPage, "trackingPage"); add(centerPanel, "growx, wrap"); } public MainProgram() { setBounds(300, 50, 1200, 900); setLayout(new MigLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); MainProgram window = new MainProgram(); window.setVisible(true); window.initialize(); } catch (Exception e) { e.printStackTrace(); } } }); } } ``` **OverviewPage.java** ``` import javax.swing.JPanel; import net.miginfocom.swing.MigLayout; public class OverviewPage extends JPanel { WorkNumberPanel workNumberPanel = new WorkNumberPanel(); private static final long serialVersionUID = 1L; public OverviewPage() { setLayout(new MigLayout()); add(workNumberPanel, "wrap, growx"); } } ``` **TrackingPage.java** ``` import javax.swing.JPanel; import net.miginfocom.swing.MigLayout; public class TrackingPage extends JPanel { private static final long serialVersionUID = 1L; WorkNumberPanel equipmentNumberPanel = new WorkNumberPanel(); public TrackingPage(){ setLayout(new MigLayout("", "grow, fill")); add(equipmentNumberPanel, "wrap, growx"); } } ``` **WorkNumberPanel.java** ``` import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import net.miginfocom.swing.MigLayout; public class WorkNumberPanel extends JPanel { private static final long serialVersionUID = 1L; private static final Integer TEXTFIELD_LENGTH = 20; JPanel mainWorkNumberPanel = new JPanel(); JLabel lblWorkNumber = new JLabel("E-Nr: "); JLabel lblN_Number = new JLabel("N-Nr.: "); JLabel lblSNumber = new JLabel("W-Nr.: "); public static JTextField txtWorkNumber = new JTextField(TEXTFIELD_LENGTH); JTextField txtNNumber = new JTextField(TEXTFIELD_LENGTH); JTextField txtSNumber = new JTextField(TEXTFIELD_LENGTH); JButton btnSearchEntry = new JButton("Search"); public WorkNumberPanel() { createEquipmentNumberPanel(); btnSearchEntry.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainProgram.contentCardsLayout.show(MainProgram.centerPanel, "trackingPage"); } }); } private void createEquipmentNumberPanel() { setLayout(new MigLayout()); mainWorkNumberPanel.setLayout(new MigLayout("", "[][grow, fill][][grow, fill][][grow, fill][]")); mainWorkNumberPanel.add(lblWorkNumber); mainWorkNumberPanel.add(txtWorkNumber); mainWorkNumberPanel.add(lblN_Number); mainWorkNumberPanel.add(txtNNumber); mainWorkNumberPanel.add(lblSNumber); mainWorkNumberPanel.add(txtSNumber); mainWorkNumberPanel.add(btnSearchEntry); add(mainWorkNumberPanel, "push, span, growx"); } } ```
2016/03/31
[ "https://Stackoverflow.com/questions/36329164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368690/" ]
Probably because when you create your "pages" with this code ``` OverviewPage overviewPage = new OverviewPage(); TrackingPage trackingPage = new TrackingPage(); ``` the `TrackingPage` will be the last one to execute the following line ``` mainWorkNumberPanel.add(txtWorkNumber); ``` in `private void createEquipmentNumberPanel()`, and hence that Panel will "own" the JTextField. It only makes sense that a UI component can only be at one place at any given time, otherwise things would get very strange :) Your statement > > Both pages contain the same workNumberPanel and I cant find a difference, that would explain the behaviour. > > > is simply not true. You are creating a new instance of `WorkNumberPanel` in both `OverViewPage` and `TrackingPage` when you execute the following line ``` WorkNumberPanel equipmentNumberPanel = new WorkNumberPanel(); ``` So my recommendation is that you find another way of implementing what you want without using a static JTextField (or any other UI component for that matter).
First off you need to understand what a static field is. A static field is not related to a particular instance of an object. The field is related to the class itself. There's quite a good explanation [here](https://stackoverflow.com/questions/797964/what-is-the-exact-meaning-of-static-fields-in-java) and [here](https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class). --- Now with regards to your case. A `JComponent` can only be added to one panel at a time. Adding it to another will remove it from the first. In your code you are creating multiple instances of 'WorkingNumberPanel'. When you do this you add the text fields to the panel, **including** the `static` text field `txtWorkNumber`. Since the field `txtWorkNumber` is static you are adding **the same object** to multiple components, which as I mentioned above will remove it from anywhere it was previously added. One possible way of solving this would be to store the value from `txtWorkNumber` in a static variable and create a new instance (non-static) text field to add to the panel.
36,329,164
While working on a program, I made some of my fields static i.e. a `JTextField` for a `E-Number`. But now this field behaves not as expected, on some of my pages it appears, on some others it disappears. Since I am not very experienced working with a lot of statics, there might be a concept I am not understanding. I have created a very simplified but working example of my program ([MCVE](https://stackoverflow.com/help/mcve)) if you want to test it. It shows my overview page at first - the `E-Number JTextField` is missing. If you click on the search button, it shows the tracking page - with the `E-Number JTextField` present. Both pages contain **the same** `workNumberPanel` and I cant find a difference, that would explain the behaviour. So why is the `E-Number JTextField` present on the overview page and missing on the tracking page? Any help / explanation is appreciated! [![Static JTextField disappears](https://i.stack.imgur.com/BGqx9.gif)](https://i.stack.imgur.com/BGqx9.gif) **MainProgram.java** ``` import java.awt.CardLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import net.miginfocom.swing.MigLayout; public class MainProgram extends JFrame { private static final long serialVersionUID = 1L; public static JPanel centerPanel = new JPanel(); public static CardLayout contentCardsLayout = new CardLayout(); OverviewPage overviewPage = new OverviewPage(); TrackingPage trackingPage = new TrackingPage(); public void initialize() { createCenterPanel(); } private void createCenterPanel() { centerPanel.setLayout(contentCardsLayout); overviewPage.setName("overviewPage"); trackingPage.setName("trackingPage"); centerPanel.add(overviewPage, "overviewPage"); centerPanel.add(trackingPage, "trackingPage"); add(centerPanel, "growx, wrap"); } public MainProgram() { setBounds(300, 50, 1200, 900); setLayout(new MigLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); MainProgram window = new MainProgram(); window.setVisible(true); window.initialize(); } catch (Exception e) { e.printStackTrace(); } } }); } } ``` **OverviewPage.java** ``` import javax.swing.JPanel; import net.miginfocom.swing.MigLayout; public class OverviewPage extends JPanel { WorkNumberPanel workNumberPanel = new WorkNumberPanel(); private static final long serialVersionUID = 1L; public OverviewPage() { setLayout(new MigLayout()); add(workNumberPanel, "wrap, growx"); } } ``` **TrackingPage.java** ``` import javax.swing.JPanel; import net.miginfocom.swing.MigLayout; public class TrackingPage extends JPanel { private static final long serialVersionUID = 1L; WorkNumberPanel equipmentNumberPanel = new WorkNumberPanel(); public TrackingPage(){ setLayout(new MigLayout("", "grow, fill")); add(equipmentNumberPanel, "wrap, growx"); } } ``` **WorkNumberPanel.java** ``` import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import net.miginfocom.swing.MigLayout; public class WorkNumberPanel extends JPanel { private static final long serialVersionUID = 1L; private static final Integer TEXTFIELD_LENGTH = 20; JPanel mainWorkNumberPanel = new JPanel(); JLabel lblWorkNumber = new JLabel("E-Nr: "); JLabel lblN_Number = new JLabel("N-Nr.: "); JLabel lblSNumber = new JLabel("W-Nr.: "); public static JTextField txtWorkNumber = new JTextField(TEXTFIELD_LENGTH); JTextField txtNNumber = new JTextField(TEXTFIELD_LENGTH); JTextField txtSNumber = new JTextField(TEXTFIELD_LENGTH); JButton btnSearchEntry = new JButton("Search"); public WorkNumberPanel() { createEquipmentNumberPanel(); btnSearchEntry.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainProgram.contentCardsLayout.show(MainProgram.centerPanel, "trackingPage"); } }); } private void createEquipmentNumberPanel() { setLayout(new MigLayout()); mainWorkNumberPanel.setLayout(new MigLayout("", "[][grow, fill][][grow, fill][][grow, fill][]")); mainWorkNumberPanel.add(lblWorkNumber); mainWorkNumberPanel.add(txtWorkNumber); mainWorkNumberPanel.add(lblN_Number); mainWorkNumberPanel.add(txtNNumber); mainWorkNumberPanel.add(lblSNumber); mainWorkNumberPanel.add(txtSNumber); mainWorkNumberPanel.add(btnSearchEntry); add(mainWorkNumberPanel, "push, span, growx"); } } ```
2016/03/31
[ "https://Stackoverflow.com/questions/36329164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368690/" ]
Here you instantiate a `OverviewPage`, then a `TrackingPage` . ``` OverviewPage overviewPage = new OverviewPage(); TrackingPage trackingPage = new TrackingPage(); ``` Both of these classes instantiate a `WorkNumberPanel` . `WorkNumberPanel` add the static `JTextField` (txtWorkNumber) to their display panel (*mainWorkNumberPanel*). A single `Component` can't be added to several `Container` objects. This is what happens to your textfield, since it is `static` and not an instance variable. The last addition will win, so the textfield will appear in `TrackingPage` only, and not in `OverviewPage` anymore . Just don't make it `static`.
First off you need to understand what a static field is. A static field is not related to a particular instance of an object. The field is related to the class itself. There's quite a good explanation [here](https://stackoverflow.com/questions/797964/what-is-the-exact-meaning-of-static-fields-in-java) and [here](https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class). --- Now with regards to your case. A `JComponent` can only be added to one panel at a time. Adding it to another will remove it from the first. In your code you are creating multiple instances of 'WorkingNumberPanel'. When you do this you add the text fields to the panel, **including** the `static` text field `txtWorkNumber`. Since the field `txtWorkNumber` is static you are adding **the same object** to multiple components, which as I mentioned above will remove it from anywhere it was previously added. One possible way of solving this would be to store the value from `txtWorkNumber` in a static variable and create a new instance (non-static) text field to add to the panel.
65,143,408
I have an Arraylist with the values: was - 2 it - 2 the - 2 times - 2 of - 2 best - 1 worst - 1 This list has just been sorted by the count value at the end of the string(using selection sort), but now I want to sort the words that have the same count alphabetically and I have no idea how to do this. So the expected output should be ``` [it - 2, of - 2, the - 2, times - 2, was - 2, best - 1, worst - 1] ```
2020/12/04
[ "https://Stackoverflow.com/questions/65143408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Overview -------- For sorting there are always two approaches: 1. Make the class `Comparable` 2. Use a `Comparator` I'll assume your values are some sort of class like ``` public class Entry { private final String text; private final int count; // getters, constructor, toString, ... } ``` --- Comparable ---------- For the first option, simply let your class implement `Comparable` with a logic that first uses the `count` and then, if it is equal, considers the `text`. ``` public class Entry implements Comparable<? extends Entry> { private final String text; private final int count; // getters, constructor, toString, ... @Override public int compareTo(Entry other) { int countResult = -1 * Integer.compare(count, other.count); return countResult != 0 ? countResult : text.compareTo(other.text); } } ``` Then simply sort your collection: ``` Collections.sort(entries); ``` The `-1 *` is to get the *sorting-by-count* descending instead of the default, ascending. --- Comparator ---------- You can do the very same using a `Comparator`. Fortunately, we got some nice helper methods since Java 8 that make this even simpler, here is the code: ``` Comparator<Entry> comparator = Comparator.comparingInt(Foo::getValue()) .reversed() .thenComparing(Foo::getText()); ``` And then you just give that to the sorter: ``` entries.sort(comparator); ```
``` 1:- With Use Comparator Collections.sort(creatorIdList, (Object o1,Object o2)->{ //return 0; }); ```
65,143,408
I have an Arraylist with the values: was - 2 it - 2 the - 2 times - 2 of - 2 best - 1 worst - 1 This list has just been sorted by the count value at the end of the string(using selection sort), but now I want to sort the words that have the same count alphabetically and I have no idea how to do this. So the expected output should be ``` [it - 2, of - 2, the - 2, times - 2, was - 2, best - 1, worst - 1] ```
2020/12/04
[ "https://Stackoverflow.com/questions/65143408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Split the strings on `\s+-\s+` which means one or more whitespace characters (i.e. `\s+`) followed by `-` which in turn is followed by one or more whitespace characters. Perform the first level of comparison for the descending order of the numeric (second) parts and then perform the second level of comparison for the ascending order of the first parts. ``` import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Main { public static void main(String args[]) { List<String> list = new ArrayList<>( List.of("was - 2", "it - 2", "the - 2", "times - 2", "of - 2", "best - 1", "worst - 1")); list.sort(new Comparator<String>() { @Override public int compare(String s1, String s2) { String[] s1Parts = s1.split("\\s+-\\s+"); String[] s2Parts = s2.split("\\s+-\\s+"); int i = Integer.compare(Integer.parseInt(s2Parts[1]), Integer.parseInt(s1Parts[1])); if (i != 0) { return i; } return s1Parts[0].compareTo(s2Parts[0]); } }); System.out.println(list); } } ``` **Output:** ``` [it - 2, of - 2, the - 2, times - 2, was - 2, best - 1, worst - 1] ``` **Note:** if the two parts of each string are always separated by `-`, you can split as `s1.split(" - ");`.
``` 1:- With Use Comparator Collections.sort(creatorIdList, (Object o1,Object o2)->{ //return 0; }); ```
65,143,408
I have an Arraylist with the values: was - 2 it - 2 the - 2 times - 2 of - 2 best - 1 worst - 1 This list has just been sorted by the count value at the end of the string(using selection sort), but now I want to sort the words that have the same count alphabetically and I have no idea how to do this. So the expected output should be ``` [it - 2, of - 2, the - 2, times - 2, was - 2, best - 1, worst - 1] ```
2020/12/04
[ "https://Stackoverflow.com/questions/65143408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Split the strings on `\s+-\s+` which means one or more whitespace characters (i.e. `\s+`) followed by `-` which in turn is followed by one or more whitespace characters. Perform the first level of comparison for the descending order of the numeric (second) parts and then perform the second level of comparison for the ascending order of the first parts. ``` import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Main { public static void main(String args[]) { List<String> list = new ArrayList<>( List.of("was - 2", "it - 2", "the - 2", "times - 2", "of - 2", "best - 1", "worst - 1")); list.sort(new Comparator<String>() { @Override public int compare(String s1, String s2) { String[] s1Parts = s1.split("\\s+-\\s+"); String[] s2Parts = s2.split("\\s+-\\s+"); int i = Integer.compare(Integer.parseInt(s2Parts[1]), Integer.parseInt(s1Parts[1])); if (i != 0) { return i; } return s1Parts[0].compareTo(s2Parts[0]); } }); System.out.println(list); } } ``` **Output:** ``` [it - 2, of - 2, the - 2, times - 2, was - 2, best - 1, worst - 1] ``` **Note:** if the two parts of each string are always separated by `-`, you can split as `s1.split(" - ");`.
Overview -------- For sorting there are always two approaches: 1. Make the class `Comparable` 2. Use a `Comparator` I'll assume your values are some sort of class like ``` public class Entry { private final String text; private final int count; // getters, constructor, toString, ... } ``` --- Comparable ---------- For the first option, simply let your class implement `Comparable` with a logic that first uses the `count` and then, if it is equal, considers the `text`. ``` public class Entry implements Comparable<? extends Entry> { private final String text; private final int count; // getters, constructor, toString, ... @Override public int compareTo(Entry other) { int countResult = -1 * Integer.compare(count, other.count); return countResult != 0 ? countResult : text.compareTo(other.text); } } ``` Then simply sort your collection: ``` Collections.sort(entries); ``` The `-1 *` is to get the *sorting-by-count* descending instead of the default, ascending. --- Comparator ---------- You can do the very same using a `Comparator`. Fortunately, we got some nice helper methods since Java 8 that make this even simpler, here is the code: ``` Comparator<Entry> comparator = Comparator.comparingInt(Foo::getValue()) .reversed() .thenComparing(Foo::getText()); ``` And then you just give that to the sorter: ``` entries.sort(comparator); ```
10,797,773
I am trying to create a screen recording app in Android. For this, i am using FFmpeg. I have created the libffmpeg.so file. Now i would like to use the same in Android project for calling it's native function. How can i do that..?
2012/05/29
[ "https://Stackoverflow.com/questions/10797773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/776284/" ]
This tutorial provides a detail explanation about this topic. [How to Build Android Applications Based on FFmpeg by An Example](http://www.roman10.net/how-to-build-android-applications-based-on-ffmpeg-by-an-example/)
You can find the example [How to load another .so file in your android project?](https://stackoverflow.com/questions/20063397/how-to-load-another-so-file-in-your-android-project/20063480#20063480) That is the good way to show you how to load \*.so file. > > 1 - Add folder jni/libs/\*.so > > > 2 - Use "Right-click mouse" -> Android Tools -> Add native support -> Set name of file \*.cpp > > > 3 - Two files : \*.cpp and Android.mk appeared. > > > 4 - Use Cygwin to build & compile \*.so into the project. > > > Thanks,
20,835,534
I was trying to declare a function pointer that points to any function that returns the same type. I omitted the arguments types in the pointer declaration to see what error will be generated. But the program was compiled successfully and executed without any issue. Is this a correct declaration? Shouldn't we specify the arguments types? ``` #include <stdio.h> #include <stdlib.h> void add(int a, int b) { printf("a + b = %d", a + b); } void (*pointer)() = &add; int main() { add(5, 5); return 0; } ``` Output: ``` a + b = 10 ```
2013/12/30
[ "https://Stackoverflow.com/questions/20835534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2727656/" ]
Empty parentheses within a type name means unspecified arguments. Note that this is an obsolescent feature. > > ### C11(ISO/IEC 9899:201x) §6.11.6 Function declarators > > > The use of function declarators with empty parentheses (not prototype-format parameter > type declarators) is an obsolescent feature. > > >
`void (*pointer)()` explains function pointed have unspecified number of argument. It is not similar to `void (*pointer)(void)`. So later when you used two arguments that fits successfully according to definition.
20,835,534
I was trying to declare a function pointer that points to any function that returns the same type. I omitted the arguments types in the pointer declaration to see what error will be generated. But the program was compiled successfully and executed without any issue. Is this a correct declaration? Shouldn't we specify the arguments types? ``` #include <stdio.h> #include <stdlib.h> void add(int a, int b) { printf("a + b = %d", a + b); } void (*pointer)() = &add; int main() { add(5, 5); return 0; } ``` Output: ``` a + b = 10 ```
2013/12/30
[ "https://Stackoverflow.com/questions/20835534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2727656/" ]
`void (*pointer)()` explains function pointed have unspecified number of argument. It is not similar to `void (*pointer)(void)`. So later when you used two arguments that fits successfully according to definition.
There are couple of things you should know here... **Function declaration:** ``` int myFunction(); ``` **Function prototype:** ``` int myFunction(int a, float b); ``` * A `prototype` is a special kind of declaration that describes the number and the types of function parameters. * A `non-prototype` function declaration doesn't say anything about its parameter. Example: ``` int myFunction(); ``` This `non-prototype` function declaration does not mean that `myFunction` takes no arguments. It means that `myFunction` take an unspecified number of arguments. The compiler simply turns off argument type checking, number of arguments checking and conversion for `myFunction`. So you can do, ``` int myFunction(); // The non-prototype signature will match a definition for // myFunction with any parameter list. // This is the function definition... int myFunction(int x, float b, double d) { ... } ```
20,835,534
I was trying to declare a function pointer that points to any function that returns the same type. I omitted the arguments types in the pointer declaration to see what error will be generated. But the program was compiled successfully and executed without any issue. Is this a correct declaration? Shouldn't we specify the arguments types? ``` #include <stdio.h> #include <stdlib.h> void add(int a, int b) { printf("a + b = %d", a + b); } void (*pointer)() = &add; int main() { add(5, 5); return 0; } ``` Output: ``` a + b = 10 ```
2013/12/30
[ "https://Stackoverflow.com/questions/20835534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2727656/" ]
Empty parentheses within a type name means unspecified arguments. Note that this is an obsolescent feature. > > ### C11(ISO/IEC 9899:201x) §6.11.6 Function declarators > > > The use of function declarators with empty parentheses (not prototype-format parameter > type declarators) is an obsolescent feature. > > >
There are couple of things you should know here... **Function declaration:** ``` int myFunction(); ``` **Function prototype:** ``` int myFunction(int a, float b); ``` * A `prototype` is a special kind of declaration that describes the number and the types of function parameters. * A `non-prototype` function declaration doesn't say anything about its parameter. Example: ``` int myFunction(); ``` This `non-prototype` function declaration does not mean that `myFunction` takes no arguments. It means that `myFunction` take an unspecified number of arguments. The compiler simply turns off argument type checking, number of arguments checking and conversion for `myFunction`. So you can do, ``` int myFunction(); // The non-prototype signature will match a definition for // myFunction with any parameter list. // This is the function definition... int myFunction(int x, float b, double d) { ... } ```
35,673,172
I have a simple script that is trying to register a click on a button. However, I keep getting the error `*element*.addEventListener` is not a function. Can anyone explain what I'm doing wrong? **HTML** ``` <div id="game"> <canvas id="gameScreen" width="550" height="500"></canvas> <div id="output"><p></p></div> <div id="controls"> <button id="north">North</button> <button id="east">East</button> <button id="west">West</button> <button id="south">South</button> </div> </div> ``` **JS** ``` window.addEventListener("load", function(){ var canvas = document.getElementById("gameScreen"); var ctx = canvas.getContext("2d"); var output = document.getElementById("output"); var outputText = output.querySelector("p"); var controls = document.getElementById("controls"); var directionButtons = controls.getElementsByTagName("button"); directionButtons.addEventListener("click", function(){ console.log(this); }) }) ``` **Error** > > TypeError: directionButtons.addEventListener is not a function > > >
2016/02/27
[ "https://Stackoverflow.com/questions/35673172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The **[getElementsByTagName()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName)** method will return a list of nodes and you should loop through them and attach listener to every one : ``` function my_click(){ alert(this.id); } var directionButtons = controls.getElementsByTagName("button"); for(i=0; i<directionButtons.length; i++) { directionButtons[i].addEventListener("click", my_click, false); } ``` Hope this helps. --- ```js function my_click(){ alert(this.id); } var directionButtons = document.getElementsByTagName("button"); for(i=0; i<directionButtons.length; i++) { directionButtons[i].addEventListener("click", my_click, false); } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id='1'>Button 1</button> <button id='2'>Button 2</button> <button id='3'>Button 3</button> <button id='4'>Button 4</button> ```
Variable `directionButtons` is an array of multiple elements. You'll need to use loop here in order to add listeners. ```js window.addEventListener("load", function() { var canvas = document.getElementById("gameScreen"); var ctx = canvas.getContext("2d"); var output = document.getElementById("output"); var outputText = output.querySelector("p"); var controls = document.getElementById("controls"); var directionButtons = controls.getElementsByTagName("button"); for (i = 0; i < directionButtons.length; i++) { directionButtons[i].addEventListener("click", function() { console.log(this); }); } }) ``` ```html <div id="game"> <canvas id="gameScreen" width="550" height="500"></canvas> <div id="output"> <p></p> </div> <div id="controls"> <button id="north">North</button> <button id="east">East</button> <button id="west">West</button> <button id="south">South</button> </div> </div> ```
52,028,664
While coding for competitions in codechef, I face this problem with python, to read > > > ``` > 3 # number of required input > 1 4 2 # inputs > > ``` > > to read input i used: ``` data=list(map(int,input().split())) ``` but it will read any number of inputs and will store as list. How to restrict size of input or size of list? while writing input it should accept only input with spaces
2018/08/26
[ "https://Stackoverflow.com/questions/52028664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8901248/" ]
`System.out.println(fun(20)+" "+fun(21l));` is passed a `String` that is the result of concatenating the values returned by `fun(20)` and `fun(21l)`. Therefore, these two methods are executed before this `println` statement, each of them printing its own `String`. * first `fun(20)` prints "float called " and returns 20.0 * then `fun(21l)` prints "long called " and returns 21 * finally `System.out.println(fun(20)+" "+fun(21l));` prints "20.0 21"
This is an example of method overloading. The example shows that an class can have several methods with the same name. Some more examples are listed here: <https://beginnersbook.com/2013/05/method-overloading/>
8,767,201
I'd like to create a motion blur effect by rendering and additively blending moving objects at multiple points in their trajectory over the course of a frame. I was thinking that the calculation for determining the draw location could be performed in a vertex shader. It seems to me, though, that I might need to employ the use of a geometry shader if I want to avoid passing in the geometry for each render. What is my best course of action? I am deciding between: 1. Assembling the vertex data for each sub-frame manually and passing it to the GPU each time (I wouldn't need to have a vertex program if I do this) 2. Send the geometry along with velocity values. I can calculate the intermediate position in a vertex shader, though I'm not certain about how to specify that a certain velocity value is assigned to certain groups of primitives. I will need to send in the same vertices once for each sub-frame render because the vertex shader cannot create new vertices. 3. Use a geometry shader to produce all geometry for all sub-frames. I should be able to get all of the sub-frames without passing any data back and forth during the entire rendering process. The balance I want to strike here is I want a minimum of redundant data-passing while supporting as much hardware as reasonably possible. It seems like I should be able to use a Vertex Buffer Object to store my geometry data, and just pass a few uniforms to send velocity data to the vertex shader on each render. Does that work? Also a VBO buffer is persistent, so for best performance I should be stepping in and modifying geometry data on an as-needed basis, correct? Another potential problem I don't know how to deal with is that I want to draw my intermediate positions accurately by interpolating the translation and rotation that rigid objects traverse over a frame, rather than just interpolating the resultant vertex positions alone. The difference here is be that a spinning object will leave a curved streak. Is there some way I can prevent having to issue a call for each separate dynamic rigid object? Maybe I could use a generic vertex attribute to send in my velocity? It would be somewhat redundant because I could have an object with 100 vertices with the same velocity data, but at least then my shader can get a stream of this data this way. It seems to me that there might not be too much to gain by performing the vertex transformations on the GPU: I would have to pass in a velocity vector, an angular velocity scalar, and a center of mass vector as vertex attributes. It seems like a big waste of bandwidth. However, I can use that data for a potentially large number of "samples" (sub-frame renders). I've gotten by for a very long time using the OpenGL Immediate Mode but I want to do things right this time around. UPDATE: See extended comment discussion for the direction this has taken. I'm now fairly certain that multiple samples will not produce a good result because of the "strobe light effect": At some velocities I'll need to use blur for performance reasons. In that case I need to accumulate blurred sub-frames; rendering sub-frames and then blurring it will still leave artifacts.
2012/01/07
[ "https://Stackoverflow.com/questions/8767201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340947/" ]
> > I'd like to create a motion blur effect by rendering and additively blending moving objects at multiple points in their trajectory over the course of a frame. > > > That's certainly one way to do implement motion blur. But these days motion blur is implementy by a vector blur postprocessing filter in the fragment shader. See <http://www.blender.org/development/release-logs/blender-242/vector-blur/> for an explanation how it works. For realtime the process must be reproduced with post processing shaders.
1. Software render the sub-frames - Consider this the "baseline" case. 2. Vertex shader - You could do this, but don't try to send geometry velocity, just send the vertex velocity: Render the frame to a VBO, calling glVertexAttrib to include the current velocity and acceleration of each vertex. Render the VBO repeatedly, specifying the time offset for each sub-frame with a uniform value. The vertex shader would then need to apply the offests based on the uniform time value. 3. Geometry shader - If you went with this, you could implement it much like #2, except the "loop and vary" would be implemented in the shader instead - helping to offload more work to the GPU. You also mention: * Render everything with a VBO - If you used VBOs/display lists like this you would basically be doing option #1 with more hardware acceleration. * Interpolation problems - It's probably not worth your effort to get an exact interpolation. Unless the objects are moving very fast *and* curving, linear interpolation of speed (first order) is probably fine. You can improve on it by also including acceleration (second order), but additional orders or a more accurate physics model likely to be worth the effort or cost. * Might not be worth it - This is really the crux of the problem. Depending on your application, hardware, and other details, any one of these possible solutions could outperform another. If performance is important, you should probably try a prototype implementation of each and run benchmarks on your target devices to see what fits best. (The sad reality it that you can't easily perform benchmarks until you've already done all the work.)
14,530,887
Is there a workaround to get D3.js to parse datetimes that have milliseconds included? I can't get this to work: ``` var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S").parse parseDate("2011-01-01T12:14:35") //that works parseDate("2011-01-01T12:14:35.3456") //returns null ```
2013/01/25
[ "https://Stackoverflow.com/questions/14530887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1443118/" ]
If your dateTime strings are already in that format, you don't need d3 to parse it into an actual date object. For example: ``` new Date("2011-01-01T12:14:35") # Sat Jan 01 2011 04:14:35 GMT-0800 (PST) ``` results in a correct date object.
Try looking at the `d3.time.format.iso` formatting function, shown on the wiki page: [d3.time.format.iso](https://github.com/mbostock/d3/wiki/Time-Formatting#wiki-format_iso).
14,530,887
Is there a workaround to get D3.js to parse datetimes that have milliseconds included? I can't get this to work: ``` var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S").parse parseDate("2011-01-01T12:14:35") //that works parseDate("2011-01-01T12:14:35.3456") //returns null ```
2013/01/25
[ "https://Stackoverflow.com/questions/14530887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1443118/" ]
Include format to parse the miliseconds which uses %L [source](https://github.com/mbostock/d3/wiki/Time-Formatting). For your case: ``` var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S").parse parseDate("2011-01-01T12:14:35") //that works var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%L").parse parseDate("2011-01-01T12:14:35.345") // works ``` Note that you provided 4 digits as milliseconds, which I think is not true if you are dealing with milliseconds. If you really have 4 digits or 6 digits (microseconds) and you are only interested in milliseconds, you can filter off the last few digits. For example: ``` var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%L000").parse parseDate("2011-01-01T12:14:35.345000") //that works ```
Try looking at the `d3.time.format.iso` formatting function, shown on the wiki page: [d3.time.format.iso](https://github.com/mbostock/d3/wiki/Time-Formatting#wiki-format_iso).
233,471
Whats wrong with this statement? why it gives below error message **Error Message:** > > SELECT failed because the following SET options have incorrect > settings: 'QUOTED\_IDENTIFIER'. Verify that SET options are correct for > use with indexed views and/or indexes on computed columns and/or > filtered indexes and/or query notifications and/or XML data type > methods and/or spatial index operations. > > > **Statement** ``` SELECT ISNULL(STUFF((SELECT ', ' + u.TITLE + ' ' + u.FirstNAME + ' ' + LastNAME [text()] FROM table1 c INNER JOIN table2 u ON c.user = u.user AND c.Task = @task AND c.Type = 'Assign' FOR XML PATH(''), TYPE) .value('.','NVARCHAR(MAX)'),1,2,' ') ,'') UNAMESLIST ```
2019/03/29
[ "https://dba.stackexchange.com/questions/233471", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/164767/" ]
As documented in [SET QUOTED\_IDENTIFIER (Transact-SQL)](https://learn.microsoft.com/en-us/sql/t-sql/statements/set-quoted-identifier-transact-sql?view=sql-server-2017) > > SET QUOTED\_IDENTIFIER must be ON when you invoke XML data type > methods. > > > A simple test ``` set quoted_identifier off DECLARE @xmlRecords XML SET @xmlRecords = '<records><record orderId="1" refCode="1234"></record></records>' SELECT records.record.value('(@orderId)[1]', 'INT') AS orderId FROM @xmlRecords.nodes('/records/record') records(record) ``` > > Msg 1934, Level 16, State 1, Line 8 SELECT failed because the > following SET options have incorrect settings: 'QUOTED\_IDENTIFIER'. > Verify that SET options are correct for use with indexed views and/or > indexes on computed columns and/or query notifications and/or xml data > type methods. > > > You are using `FOR XML PATH` ``` SET QUOTED_IDENTIFIER off DECLARE @T TABLE (id VARCHAR(5),col1 XML) INSERT INTO @t (id,col1) VALUES ('1','<node1>one</node1>') SELECT ISNULL(STUFF(( SELECT ', ' + id FROM @t FOR XML PATH('') ,TYPE ).value('.', 'NVARCHAR(MAX)'), 1, 2, ' '), '') UNAMESLIST ``` > > Msg 1934, Level 16, State 1, Line 8 SELECT failed because the > following SET options have incorrect settings: 'QUOTED\_IDENTIFIER'. > Verify that SET options are correct for use with indexed views and/or > indexes on computed columns and/or query notifications and/or xml data > type methods. > > >
Check results from command: ``` DBCC useroptions ``` There are other very important settings to observe here too: ``` language us_english dateformat mdy datefirst 7 ``` Here in Australia am using settings as per: ``` language British dateformat dmy datefirst 1 ``` Strangely, my process worked on a dev level DB but not SIT level DB, I resolved this issue by adding this line to my stored proc that performs the XML import: ``` SET QUOTED_IDENTIFIER ON ``` I also found that this has to be added above the CREATE PROCEDURE statement ! i.e. as per this example: ``` SET ANSI_WARNINGS ON GO SET ANSI_PADDING ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE dbo.P427007ImportAHSAHospitalDetails @Path VARCHAR(255), @FileName VARCHAR(255), @OperatorID VARCHAR(10), @BranchID VARCHAR(10), @TillID VARCHAR(10) AS BEGIN SET ANSI_WARNINGS ON SET ANSI_PADDING ON SET QUOTED_IDENTIFIER ON DECLARE @DebugModeFlag CHAR SELECT @DebugModeFlag = 'N' ---------------------------------------------------------------------------------------- -- Empty the [ImportAHSAHospitalDetails] table IF @DebugModeFlag = 'Y' PRINT 'Empty the [ImportAHSAHospitalDetails] table'; ---------------------------------------------------------------------------------------- DELETE FROM [ImportAHSAHospitalDetails]; DBCC CHECKIDENT ('ImportAHSAHospitalDetails', RESEED, 0); DELETE FROM dbo.ImportProviderWarnings WHERE ImportType = 'Z' DECLARE @ProcessID INT, @EffDateText VARCHAR(10), @EffDate DATETIME, @FileVersion VARCHAR(10), @InsertCount INT, @UpdateCount INT, @InvalidCount INT, @ProcessStartTime DATETIME, @ProcessEndTime DATETIME, @ProcessDuration INT DECLARE @HOSDetailsRaw TABLE (HOSDetailsData XML) DECLARE @HOSDetailsXML XML SELECT @ProcessStartTime=GETDATE() ---------------------------------------------------------------------------------------- -- Importing Raw Data File IF @DebugModeFlag = 'Y' PRINT 'Importing Raw Data File'; ---------------------------------------------------------------------------------------- INSERT INTO @HOSDetailsRaw EXEC ('SELECT * FROM OPENROWSET ( BULK ''' + @Path + @FileName + ''', SINGLE_CLOB) AS xmlData') SELECT @HOSDetailsXML = HOSDetailsData FROM @HOSDetailsRaw; ---------------------------------------------------------------------------------------- -- Get the Effective Date IF @DebugModeFlag = 'Y' PRINT 'Get the Effective Date'; ---------------------------------------------------------------------------------------- WITH XMLNAMESPACES( 'http://www.ahsa.com.au/schema/hospitaldetails' AS ns) SELECT @EffDateText = @HOSDetailsxml.value('(/ns:HospitalDetails/@effectiveDate)[1]', 'VARCHAR(10)' ); SELECT @EffDate = DATEFROMPARTS (SUBSTRING(@EffDateText, 1, 4), SUBSTRING(@EffDateText, 6, 2), SUBSTRING(@EffDateText, 9, 2)); ---------------------------------------------------------------------------------------- -- Get the File Version IF @DebugModeFlag = 'Y' PRINT 'Get the File Version'; ---------------------------------------------------------------------------------------- WITH XMLNAMESPACES( 'http://www.ahsa.com.au/schema/hospitaldetails' AS ns) SELECT @FileVersion = @HOSDetailsxml.value('(/ns:HospitalDetails/@fileVersion)[1]', 'VARCHAR(10)' ); ```
7,418,490
I have a string of text like this: ``` This is a[WAIT] test. ``` What I want to do is search the string for a substring that starts with [ and ends with ] Each one I find I want to add it to an ArrayList and replace substring in original string with a ^ Here is my regex: ``` String regex_script = "/^\\[\\]$/"; //Match a string which starts with the character [ ending in the character ] ``` Here is what I have so far: ``` StringBuffer sb = new StringBuffer(); Pattern p = Pattern.compile(regex_script); // Create a pattern to match Matcher m = p.matcher(line); // Create a matcher with an input string boolean result = m.find(); while(result) { m.appendReplacement(sb, "^"); result = m.find(); } m.appendTail(sb); // Add the last segment of input to the new String ``` how would I got about doing this? Thanks
2011/09/14
[ "https://Stackoverflow.com/questions/7418490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/917009/" ]
you can do: ``` String regex_script = "\\[([^\\]]*)\\]"; String line = "This is a[WAIT] testThis is a[WAIT] test"; StringBuffer sb = new StringBuffer(); List<String> list = new ArrayList<String>(); //use to record Pattern p = Pattern.compile(regex_script); // Create a pattern to match Matcher m = p.matcher(line); // Create a matcher with an input string while (m.find()) { list.add(m.group(1)); m.appendReplacement(sb, "[^]"); } m.appendTail(sb); // Add the last segment of input to the new String System.out.println(sb.toString()); ```
If you are searching a substring, don't use ^ and $. Those are for beginning and at end at a string (not a word) Try: ``` String regex_script = "/\[.*\]/"; ```
29,130
We are virtualizing our license servers and have to start using network USB hubs for the authentication keys. The ones I've found will be messy in a rack. Has anyone ever seen a rackmountable version? If that's not an option, are there any rackmountable normals hubs? Or maybe some setup I haven't come up with?
2009/06/20
[ "https://serverfault.com/questions/29130", "https://serverfault.com", "https://serverfault.com/users/1565/" ]
You mean something like this: [**Metal 7-Port USB 2.0 Powered Slim Hub for PC-MAC with Power Adapter**](http://www.qualitycables.com/productdetails1.cfm?sku=USBG-7U2ML&cats=&catid=104%2C653%2C210%2C212) ![alt text](https://www.coolgear.com/images/USBG-7U2ML.jpg) > > Industrial USB Hub with 7 Ports > feature a rugged metal enclosure. > > > Or this one with 12 ports: **[Industrial 12-Port USB 2.0 Powered Hub for PC-MAC DIN-RAIL Mount](http://www.usbgear.com/computer_cable_details.cfm?sku=USBG-12U2ML&cats=104&catid=104%2C653%2C210%2C212)** ![Image of an Industrial 12-Port USB 2.0 Powered Hub](https://www.coolgear.com/images/USBG-12U2ML.jpg) > > Industrial USB Hub with 12 Ports > feature a rugged metal enclosure. > > >
Well even at 1U having splattnes suggested devices occupy a rack space seems a bit of a waste - these devices seem easy enough to mount inside a rack cabinet but outside of the actual 19" mount-space. Mounting them to a rack shelf first if you really need them inside that space should also be easy and cheap. Actual rack-mountable equipment is hard to come by when we're talking about smaller stuff - the options are usually limited to large-scale bays to fit a lot (=more than a couple) of specific devices, like old school modems and whatnot, or *very* expensive custom frames to hold (usually very expensive) small hardware like the simpler cisco aironet controllers. I'd say (sadly) you're looking at finding a decent generic shelf to house these things in that satisfies your need for order - or just pin them somewhere to the walls or the rails of the rack.
29,130
We are virtualizing our license servers and have to start using network USB hubs for the authentication keys. The ones I've found will be messy in a rack. Has anyone ever seen a rackmountable version? If that's not an option, are there any rackmountable normals hubs? Or maybe some setup I haven't come up with?
2009/06/20
[ "https://serverfault.com/questions/29130", "https://serverfault.com", "https://serverfault.com/users/1565/" ]
You mean something like this: [**Metal 7-Port USB 2.0 Powered Slim Hub for PC-MAC with Power Adapter**](http://www.qualitycables.com/productdetails1.cfm?sku=USBG-7U2ML&cats=&catid=104%2C653%2C210%2C212) ![alt text](https://www.coolgear.com/images/USBG-7U2ML.jpg) > > Industrial USB Hub with 7 Ports > feature a rugged metal enclosure. > > > Or this one with 12 ports: **[Industrial 12-Port USB 2.0 Powered Hub for PC-MAC DIN-RAIL Mount](http://www.usbgear.com/computer_cable_details.cfm?sku=USBG-12U2ML&cats=104&catid=104%2C653%2C210%2C212)** ![Image of an Industrial 12-Port USB 2.0 Powered Hub](https://www.coolgear.com/images/USBG-12U2ML.jpg) > > Industrial USB Hub with 12 Ports > feature a rugged metal enclosure. > > >
What i've discovered on gearslutz.com: <http://www.gearslutz.com/board/so-much-gear-so-little-time/71862-rackmount-usb-hub-16-ports-2.html>
29,130
We are virtualizing our license servers and have to start using network USB hubs for the authentication keys. The ones I've found will be messy in a rack. Has anyone ever seen a rackmountable version? If that's not an option, are there any rackmountable normals hubs? Or maybe some setup I haven't come up with?
2009/06/20
[ "https://serverfault.com/questions/29130", "https://serverfault.com", "https://serverfault.com/users/1565/" ]
You mean something like this: [**Metal 7-Port USB 2.0 Powered Slim Hub for PC-MAC with Power Adapter**](http://www.qualitycables.com/productdetails1.cfm?sku=USBG-7U2ML&cats=&catid=104%2C653%2C210%2C212) ![alt text](https://www.coolgear.com/images/USBG-7U2ML.jpg) > > Industrial USB Hub with 7 Ports > feature a rugged metal enclosure. > > > Or this one with 12 ports: **[Industrial 12-Port USB 2.0 Powered Hub for PC-MAC DIN-RAIL Mount](http://www.usbgear.com/computer_cable_details.cfm?sku=USBG-12U2ML&cats=104&catid=104%2C653%2C210%2C212)** ![Image of an Industrial 12-Port USB 2.0 Powered Hub](https://www.coolgear.com/images/USBG-12U2ML.jpg) > > Industrial USB Hub with 12 Ports > feature a rugged metal enclosure. > > >
I know this is an old thread, but thought I'd make an updated answer. USBGear/Coolgear now has several direct rack-mount models: [Industrial 16-Port USB 2.0 Rack Mount Hub with Built-in Power Supply](http://usbgear.com/CG-1600i-RM.html) [Industrial 16-Port USB 3.0 Din-Rail/WallMount Hub with output up to 1.5A Charging per port](http://usbgear.com/USB3-16U1.html) Fair disclosure: I work for the company and found this thread in our logs.
37,076,966
Trying to enroll IOS device (IPhone 6s, ios 9.3) in WSO2 but unfortunately failing. I am using registered csr file and Apple MDM certificate. Followed instructions mentioned in document. Failing at step 2 on IOS device after entering Domain, username and password. On UI, below is the error > > "An unexpected error occured. Please try again." > > > In Logs I see below errors: > > [2016-05-06 11:54:22,746] ERROR {org.wso2.carbon.device.mgt.ios.util.OAuthUtils} - Error occurred while sending 'Post' request due to failure of server connection > javax.net.ssl.SSLException: hostname in certificate didn't match: <10.XXX.XXX.XXX> != > > > [2016-05-06 11:54:22,770] ERROR {org.apache.catalina.core.StandardWrapperValve} - Servlet.service() for servlet [JAXServlet] in context with path [/ios-enrollment] threw exception > java.lang.RuntimeException: org.apache.cxf.interceptor.Fault > at org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:116) > > > Not sure what's going wrong. Any thoughts? Note: my IP is masked above replacing my original IP on which WSO2 is running.
2016/05/06
[ "https://Stackoverflow.com/questions/37076966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6301187/" ]
Make sure you have configured the all the config files where the local IP address is used you need to check that and reconfigure all the files to utilize the IP mask or domain you are using.
1. You need to follow the steps given [here](https://docs.wso2.com/display/EMM200/General+iOS+Server+Configurations) in order to configure IOS in WSO2 EMM. 2. You need to obtain a singed CSR from WSO2 by following steps provided [here](https://docs.wso2.com/display/EMM200/Obtaining+the+Signed+CSR+File) 3. If the server has domain with a SSL certificate from a know CA, all the root and intermediate certificates must be included to the following keystores. * wso2carbon.jks * client-truststore.jks NOTE: > > Make sure to Generate the SSL certificate based on your domain/IP address of the WSO2 EMM server runs on. > > >
37,076,966
Trying to enroll IOS device (IPhone 6s, ios 9.3) in WSO2 but unfortunately failing. I am using registered csr file and Apple MDM certificate. Followed instructions mentioned in document. Failing at step 2 on IOS device after entering Domain, username and password. On UI, below is the error > > "An unexpected error occured. Please try again." > > > In Logs I see below errors: > > [2016-05-06 11:54:22,746] ERROR {org.wso2.carbon.device.mgt.ios.util.OAuthUtils} - Error occurred while sending 'Post' request due to failure of server connection > javax.net.ssl.SSLException: hostname in certificate didn't match: <10.XXX.XXX.XXX> != > > > [2016-05-06 11:54:22,770] ERROR {org.apache.catalina.core.StandardWrapperValve} - Servlet.service() for servlet [JAXServlet] in context with path [/ios-enrollment] threw exception > java.lang.RuntimeException: org.apache.cxf.interceptor.Fault > at org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:116) > > > Not sure what's going wrong. Any thoughts? Note: my IP is masked above replacing my original IP on which WSO2 is running.
2016/05/06
[ "https://Stackoverflow.com/questions/37076966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6301187/" ]
Make sure you have configured the all the config files where the local IP address is used you need to check that and reconfigure all the files to utilize the IP mask or domain you are using.
Adding to Kachiecx's answer, I assume you are using a self-signed SSL certificate. When creating a SSL certificate, make sure you provide the common name of the certificate to match your IP/hostname. This is mentioned in the doc [1] under step 6. Also make sure, you follow the step given in step 3 of general server configurations[2] [1]. <https://docs.wso2.com/display/EMM201/General+iOS+Server+Configurations> [2]. <https://docs.wso2.com/display/EMM200/General+Server+Configurations#GeneralServerConfigurations-Generalserverconfigurations>
30,452,561
So, I have following html. ``` <div id="a" class="a_button"> <a class="a_link" href="#"> <div class="icon_container"> <img class="icon_image" src="#"> </div> <div class="title_container"> <span class="title_inactive"> Title </span> </div> </a> </div> ``` I am including an image to describe the situation better. ![enter image description here](https://i.stack.imgur.com/KT3uN.png) So, as you can see, this button is consisted of two `divs`: `icon_container` and `title_container`. On mouse hover, the background color changes as planned. Now, the color of `title` on `not-hover` is black and it should turn `white` when mouse is hovered. And when mouse is hovered over the `title_container` div, the color changes from black and white (good). However, when the mouse is hovered over the `icon_container`, the color of text does not change to white, even though the background color changes. How can I make it so that when the mouse is hovered over the `icon_container`, it will cause the `title` color to be changed? Here is what I have so far: <https://jsfiddle.net/8wfhnupk/5/> Thanks!
2015/05/26
[ "https://Stackoverflow.com/questions/30452561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4456697/" ]
add this to CSS: ``` .title_container > .title_inactive:hover{color:white} ```
``` <div class="title_container" style="color:red"> <span class="title inactive"> Title </span> </div> ``` by applying inline style as shown above the text color will change.
30,452,561
So, I have following html. ``` <div id="a" class="a_button"> <a class="a_link" href="#"> <div class="icon_container"> <img class="icon_image" src="#"> </div> <div class="title_container"> <span class="title_inactive"> Title </span> </div> </a> </div> ``` I am including an image to describe the situation better. ![enter image description here](https://i.stack.imgur.com/KT3uN.png) So, as you can see, this button is consisted of two `divs`: `icon_container` and `title_container`. On mouse hover, the background color changes as planned. Now, the color of `title` on `not-hover` is black and it should turn `white` when mouse is hovered. And when mouse is hovered over the `title_container` div, the color changes from black and white (good). However, when the mouse is hovered over the `icon_container`, the color of text does not change to white, even though the background color changes. How can I make it so that when the mouse is hovered over the `icon_container`, it will cause the `title` color to be changed? Here is what I have so far: <https://jsfiddle.net/8wfhnupk/5/> Thanks!
2015/05/26
[ "https://Stackoverflow.com/questions/30452561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4456697/" ]
As you hover the `a` tag you need to change the color of the span in the title\_container class. Add this to your css : ``` a:hover .title_container span{ color:#fff; } ``` or for the [jsfiddle](https://jsfiddle.net/8wfhnupk/4/) ``` .royal_button a:hover .royal_menu_title{ color:#fff; } ```
add this to CSS: ``` .title_container > .title_inactive:hover{color:white} ```
30,452,561
So, I have following html. ``` <div id="a" class="a_button"> <a class="a_link" href="#"> <div class="icon_container"> <img class="icon_image" src="#"> </div> <div class="title_container"> <span class="title_inactive"> Title </span> </div> </a> </div> ``` I am including an image to describe the situation better. ![enter image description here](https://i.stack.imgur.com/KT3uN.png) So, as you can see, this button is consisted of two `divs`: `icon_container` and `title_container`. On mouse hover, the background color changes as planned. Now, the color of `title` on `not-hover` is black and it should turn `white` when mouse is hovered. And when mouse is hovered over the `title_container` div, the color changes from black and white (good). However, when the mouse is hovered over the `icon_container`, the color of text does not change to white, even though the background color changes. How can I make it so that when the mouse is hovered over the `icon_container`, it will cause the `title` color to be changed? Here is what I have so far: <https://jsfiddle.net/8wfhnupk/5/> Thanks!
2015/05/26
[ "https://Stackoverflow.com/questions/30452561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4456697/" ]
add this to CSS: ``` .title_container > .title_inactive:hover{color:white} ```
This would be the solution: ``` .royal_button:hover div { color:#fff; } ``` [**JSFiddle**](https://jsfiddle.net/8wfhnupk/6/)
30,452,561
So, I have following html. ``` <div id="a" class="a_button"> <a class="a_link" href="#"> <div class="icon_container"> <img class="icon_image" src="#"> </div> <div class="title_container"> <span class="title_inactive"> Title </span> </div> </a> </div> ``` I am including an image to describe the situation better. ![enter image description here](https://i.stack.imgur.com/KT3uN.png) So, as you can see, this button is consisted of two `divs`: `icon_container` and `title_container`. On mouse hover, the background color changes as planned. Now, the color of `title` on `not-hover` is black and it should turn `white` when mouse is hovered. And when mouse is hovered over the `title_container` div, the color changes from black and white (good). However, when the mouse is hovered over the `icon_container`, the color of text does not change to white, even though the background color changes. How can I make it so that when the mouse is hovered over the `icon_container`, it will cause the `title` color to be changed? Here is what I have so far: <https://jsfiddle.net/8wfhnupk/5/> Thanks!
2015/05/26
[ "https://Stackoverflow.com/questions/30452561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4456697/" ]
As you hover the `a` tag you need to change the color of the span in the title\_container class. Add this to your css : ``` a:hover .title_container span{ color:#fff; } ``` or for the [jsfiddle](https://jsfiddle.net/8wfhnupk/4/) ``` .royal_button a:hover .royal_menu_title{ color:#fff; } ```
``` <div class="title_container" style="color:red"> <span class="title inactive"> Title </span> </div> ``` by applying inline style as shown above the text color will change.
30,452,561
So, I have following html. ``` <div id="a" class="a_button"> <a class="a_link" href="#"> <div class="icon_container"> <img class="icon_image" src="#"> </div> <div class="title_container"> <span class="title_inactive"> Title </span> </div> </a> </div> ``` I am including an image to describe the situation better. ![enter image description here](https://i.stack.imgur.com/KT3uN.png) So, as you can see, this button is consisted of two `divs`: `icon_container` and `title_container`. On mouse hover, the background color changes as planned. Now, the color of `title` on `not-hover` is black and it should turn `white` when mouse is hovered. And when mouse is hovered over the `title_container` div, the color changes from black and white (good). However, when the mouse is hovered over the `icon_container`, the color of text does not change to white, even though the background color changes. How can I make it so that when the mouse is hovered over the `icon_container`, it will cause the `title` color to be changed? Here is what I have so far: <https://jsfiddle.net/8wfhnupk/5/> Thanks!
2015/05/26
[ "https://Stackoverflow.com/questions/30452561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4456697/" ]
This would be the solution: ``` .royal_button:hover div { color:#fff; } ``` [**JSFiddle**](https://jsfiddle.net/8wfhnupk/6/)
``` <div class="title_container" style="color:red"> <span class="title inactive"> Title </span> </div> ``` by applying inline style as shown above the text color will change.
30,452,561
So, I have following html. ``` <div id="a" class="a_button"> <a class="a_link" href="#"> <div class="icon_container"> <img class="icon_image" src="#"> </div> <div class="title_container"> <span class="title_inactive"> Title </span> </div> </a> </div> ``` I am including an image to describe the situation better. ![enter image description here](https://i.stack.imgur.com/KT3uN.png) So, as you can see, this button is consisted of two `divs`: `icon_container` and `title_container`. On mouse hover, the background color changes as planned. Now, the color of `title` on `not-hover` is black and it should turn `white` when mouse is hovered. And when mouse is hovered over the `title_container` div, the color changes from black and white (good). However, when the mouse is hovered over the `icon_container`, the color of text does not change to white, even though the background color changes. How can I make it so that when the mouse is hovered over the `icon_container`, it will cause the `title` color to be changed? Here is what I have so far: <https://jsfiddle.net/8wfhnupk/5/> Thanks!
2015/05/26
[ "https://Stackoverflow.com/questions/30452561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4456697/" ]
alternatively you can use this, ``` <style> .icon_container:hover{ color:#000; background-color:#fff; } .title_container:hover{ color:#FFF; background-color:green; } </style> ```
``` <div class="title_container" style="color:red"> <span class="title inactive"> Title </span> </div> ``` by applying inline style as shown above the text color will change.
30,452,561
So, I have following html. ``` <div id="a" class="a_button"> <a class="a_link" href="#"> <div class="icon_container"> <img class="icon_image" src="#"> </div> <div class="title_container"> <span class="title_inactive"> Title </span> </div> </a> </div> ``` I am including an image to describe the situation better. ![enter image description here](https://i.stack.imgur.com/KT3uN.png) So, as you can see, this button is consisted of two `divs`: `icon_container` and `title_container`. On mouse hover, the background color changes as planned. Now, the color of `title` on `not-hover` is black and it should turn `white` when mouse is hovered. And when mouse is hovered over the `title_container` div, the color changes from black and white (good). However, when the mouse is hovered over the `icon_container`, the color of text does not change to white, even though the background color changes. How can I make it so that when the mouse is hovered over the `icon_container`, it will cause the `title` color to be changed? Here is what I have so far: <https://jsfiddle.net/8wfhnupk/5/> Thanks!
2015/05/26
[ "https://Stackoverflow.com/questions/30452561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4456697/" ]
As you hover the `a` tag you need to change the color of the span in the title\_container class. Add this to your css : ``` a:hover .title_container span{ color:#fff; } ``` or for the [jsfiddle](https://jsfiddle.net/8wfhnupk/4/) ``` .royal_button a:hover .royal_menu_title{ color:#fff; } ```
This would be the solution: ``` .royal_button:hover div { color:#fff; } ``` [**JSFiddle**](https://jsfiddle.net/8wfhnupk/6/)
30,452,561
So, I have following html. ``` <div id="a" class="a_button"> <a class="a_link" href="#"> <div class="icon_container"> <img class="icon_image" src="#"> </div> <div class="title_container"> <span class="title_inactive"> Title </span> </div> </a> </div> ``` I am including an image to describe the situation better. ![enter image description here](https://i.stack.imgur.com/KT3uN.png) So, as you can see, this button is consisted of two `divs`: `icon_container` and `title_container`. On mouse hover, the background color changes as planned. Now, the color of `title` on `not-hover` is black and it should turn `white` when mouse is hovered. And when mouse is hovered over the `title_container` div, the color changes from black and white (good). However, when the mouse is hovered over the `icon_container`, the color of text does not change to white, even though the background color changes. How can I make it so that when the mouse is hovered over the `icon_container`, it will cause the `title` color to be changed? Here is what I have so far: <https://jsfiddle.net/8wfhnupk/5/> Thanks!
2015/05/26
[ "https://Stackoverflow.com/questions/30452561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4456697/" ]
As you hover the `a` tag you need to change the color of the span in the title\_container class. Add this to your css : ``` a:hover .title_container span{ color:#fff; } ``` or for the [jsfiddle](https://jsfiddle.net/8wfhnupk/4/) ``` .royal_button a:hover .royal_menu_title{ color:#fff; } ```
alternatively you can use this, ``` <style> .icon_container:hover{ color:#000; background-color:#fff; } .title_container:hover{ color:#FFF; background-color:green; } </style> ```
30,452,561
So, I have following html. ``` <div id="a" class="a_button"> <a class="a_link" href="#"> <div class="icon_container"> <img class="icon_image" src="#"> </div> <div class="title_container"> <span class="title_inactive"> Title </span> </div> </a> </div> ``` I am including an image to describe the situation better. ![enter image description here](https://i.stack.imgur.com/KT3uN.png) So, as you can see, this button is consisted of two `divs`: `icon_container` and `title_container`. On mouse hover, the background color changes as planned. Now, the color of `title` on `not-hover` is black and it should turn `white` when mouse is hovered. And when mouse is hovered over the `title_container` div, the color changes from black and white (good). However, when the mouse is hovered over the `icon_container`, the color of text does not change to white, even though the background color changes. How can I make it so that when the mouse is hovered over the `icon_container`, it will cause the `title` color to be changed? Here is what I have so far: <https://jsfiddle.net/8wfhnupk/5/> Thanks!
2015/05/26
[ "https://Stackoverflow.com/questions/30452561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4456697/" ]
alternatively you can use this, ``` <style> .icon_container:hover{ color:#000; background-color:#fff; } .title_container:hover{ color:#FFF; background-color:green; } </style> ```
This would be the solution: ``` .royal_button:hover div { color:#fff; } ``` [**JSFiddle**](https://jsfiddle.net/8wfhnupk/6/)
53,481,818
I'm trying to write an test function for mbedtls which randomly generates a key for AES encryption. I use the original tutorial Code from mbedtls. My Programm always stops when executing "mbedtls\_ctr\_drbg\_seed()". About my environmet: Basic Sourcefiles from STM\_CUBEmx, Board: ST32F767 Nucleo, Compiling based on Makefile from STM\_Cube ``` mbedtls_ctr_drbg_context ctr_drbg; mbedtls_entropy_context entropy; char *pers="anything"; int ret; //Start mbedtls_entropy_init(&entropy); debugPrintln("Init entropy done"); mbedtls_ctr_drbg_init(&ctr_drbg); debugPrintln("Init ctr_drbg done"); if((ret=mbedtls_ctr_drbg_seed(&ctr_drbg,mbedtls_entropy_func,&entropy,(unsigned char *) pers,strlen(pers)))!=0){ //Error info debugPrintln("ERROR ctr_drbg_seed "); return -1; } debugPrintln("Init ctr_drbg_seed done"); if((ret=mbedtls_ctr_drbg_random(&ctr_drbg,key,32))!=0){ return -1; } ``` Thank you in advance
2018/11/26
[ "https://Stackoverflow.com/questions/53481818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8378096/" ]
I combined [this answer **(1)**](https://codereview.stackexchange.com/a/158929/185595) and [this answer **(2)**](https://codereview.stackexchange.com/a/158928/185595) to speed up the function. The two key ideas are: When testing primality of a candidate ... * ... do not divide by every number (2, 3, 4, 5, 6, ...) but only by the preceding prime numbers (2, 3, 5, ...). Every non-prime number > 2 is has to have some prime factor. * ... divide only by numbers that are ≤ sqrt(candidate). ``` import math def nth_prime(n): prime_list = [2] candidate = 3 while len(prime_list) < n: max_factor = math.sqrt(candidate) is_prime = True for p in prime_list: if p > max_factor: break elif candidate % p == 0: is_prime = False break if is_prime: prime_list.append(candidate) candidate += 2 return prime_list[-1] ``` Benchmark of different solutions: ================================= ``` n=9000 n=15000 n=25000 n=75000 your solution 1m38.455s - - - linked answer (1) 0m 2.954s 8.291s 22.482s - linked answer (2) 0m 0.352s 0.776s 1.685s 9.567s this answer 0m 0.120s 0.228s 0.410s 1.857s Brij's answer 0m 0.315s 0.340s 0.317s 0.318s ``` For every `n` the programs where started from scratch. As we can see, Brij's Sieve Of Eratosthenes takes a fairly low constant amount of time. If you want to find big prime numbers below a fixed limit then that's the best solution (here n < 78499, as the 78499-*th* prime number is 1 000 003 which is bigger than the sieve list). If you also want to find a lot of smaller or medium sized prime numbers or cannot accept a fixed limit then go with this solution.
``` def SieveOfEratosthenes(): n = 1000000 prime = [True for i in range(n+1)] p = 2 count = 0 while (p * p <= n): if (prime[p] == True): count = count + 1 for i in range(p * p, n+1, p): prime[i] = False p += 1 seive = [] for p in range(2, n): if prime[p]: seive.append(p) return seive def primes_function(n , seive): return seive[n - 1] #main seive = SieveOfEratosthenes() while True: n = input() if n == 'END': break elif n > '0': n = int(n) value = primes_function(n,seive) print(value) ``` Full working : <https://ide.geeksforgeeks.org/QTSGQfhFV3> I have precomputed the primes below 10^6 and made a list of primes and accessed the nth prime number by the index.
30,559,608
I'm new to Beanstalk. I've created a Rails application and set the database production configuration to use the environment variables hopefully provided by AWS. I'm using Mysql (mysql2 gem), and want to use RDS and Passenger (I have no preference there). On my development environment I can run the rails application with my local Mysql (it is just a basic application I've created for experimentation). I have added the passenger gem to Gemfile and bundled, but I'm using WEBBrick in development still. The only thing I did not do by the book is that I did not use 'eb' but rather tried from the console. My application/environment failed to run as while "rake db:migrate" it still thinks I wanted it to connect to the local Mysql (I guess from the logs that it is not aware of RACK\_ENV and hence uses 'development'). Any tip? I can of course try next the 'eb', yet would prefer to work with the console. Regards, Oren
2015/05/31
[ "https://Stackoverflow.com/questions/30559608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1614089/" ]
In Elastic Beanstalk (both the web console and the cli), you can pass environnement variables. If you pass the `RAKE_ENV` variable, you will change your environnement. After that you still need to pass your database parameters (db password, name, ...) which should not be hardcoded into the code.
Have you tried to run ``` bin/rake db:migrate RAILS_ENV=development ``` ? I got the same issue and that worked for me.
30,559,608
I'm new to Beanstalk. I've created a Rails application and set the database production configuration to use the environment variables hopefully provided by AWS. I'm using Mysql (mysql2 gem), and want to use RDS and Passenger (I have no preference there). On my development environment I can run the rails application with my local Mysql (it is just a basic application I've created for experimentation). I have added the passenger gem to Gemfile and bundled, but I'm using WEBBrick in development still. The only thing I did not do by the book is that I did not use 'eb' but rather tried from the console. My application/environment failed to run as while "rake db:migrate" it still thinks I wanted it to connect to the local Mysql (I guess from the logs that it is not aware of RACK\_ENV and hence uses 'development'). Any tip? I can of course try next the 'eb', yet would prefer to work with the console. Regards, Oren
2015/05/31
[ "https://Stackoverflow.com/questions/30559608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1614089/" ]
In Elastic Beanstalk (both the web console and the cli), you can pass environnement variables. If you pass the `RAKE_ENV` variable, you will change your environnement. After that you still need to pass your database parameters (db password, name, ...) which should not be hardcoded into the code.
I recommend you enter to EC2 instance through this command "**eb ssh**" (The first time you need specified you **.pem** file, if you have not one you can create in **IAM services**) and check your logs for more information about yours error. If you have problems when you are uploading your code (eb deploy) you have the log in this file: "**/var/log/eb-activity.log**" (Remember this file is in your EC2 instance) If you have a problems with your app, you can read the logs in this files: "**/var/app/support/logs/production.log**" or "**/var/app/support/logs/passenger.log**" Other recommedations is install **EB CLI** version 3. for manage your eb instance <http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html>
30,559,608
I'm new to Beanstalk. I've created a Rails application and set the database production configuration to use the environment variables hopefully provided by AWS. I'm using Mysql (mysql2 gem), and want to use RDS and Passenger (I have no preference there). On my development environment I can run the rails application with my local Mysql (it is just a basic application I've created for experimentation). I have added the passenger gem to Gemfile and bundled, but I'm using WEBBrick in development still. The only thing I did not do by the book is that I did not use 'eb' but rather tried from the console. My application/environment failed to run as while "rake db:migrate" it still thinks I wanted it to connect to the local Mysql (I guess from the logs that it is not aware of RACK\_ENV and hence uses 'development'). Any tip? I can of course try next the 'eb', yet would prefer to work with the console. Regards, Oren
2015/05/31
[ "https://Stackoverflow.com/questions/30559608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1614089/" ]
In Elastic Beanstalk (both the web console and the cli), you can pass environnement variables. If you pass the `RAKE_ENV` variable, you will change your environnement. After that you still need to pass your database parameters (db password, name, ...) which should not be hardcoded into the code.
I believed that Elastic Beanstalk will run 'rake db:migrate' by itself. Indeed it seems to try, but that is failing. I gave my bounty to 'Yahs Hef', even though I will only try this evening (UK). My disorientation with AWS caused me to forget this easy solution, of running the migration by myself. If this does not work by itself, I'll simplify the database configuration as possibile.
30,559,608
I'm new to Beanstalk. I've created a Rails application and set the database production configuration to use the environment variables hopefully provided by AWS. I'm using Mysql (mysql2 gem), and want to use RDS and Passenger (I have no preference there). On my development environment I can run the rails application with my local Mysql (it is just a basic application I've created for experimentation). I have added the passenger gem to Gemfile and bundled, but I'm using WEBBrick in development still. The only thing I did not do by the book is that I did not use 'eb' but rather tried from the console. My application/environment failed to run as while "rake db:migrate" it still thinks I wanted it to connect to the local Mysql (I guess from the logs that it is not aware of RACK\_ENV and hence uses 'development'). Any tip? I can of course try next the 'eb', yet would prefer to work with the console. Regards, Oren
2015/05/31
[ "https://Stackoverflow.com/questions/30559608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1614089/" ]
Have you tried to run ``` bin/rake db:migrate RAILS_ENV=development ``` ? I got the same issue and that worked for me.
I believed that Elastic Beanstalk will run 'rake db:migrate' by itself. Indeed it seems to try, but that is failing. I gave my bounty to 'Yahs Hef', even though I will only try this evening (UK). My disorientation with AWS caused me to forget this easy solution, of running the migration by myself. If this does not work by itself, I'll simplify the database configuration as possibile.
30,559,608
I'm new to Beanstalk. I've created a Rails application and set the database production configuration to use the environment variables hopefully provided by AWS. I'm using Mysql (mysql2 gem), and want to use RDS and Passenger (I have no preference there). On my development environment I can run the rails application with my local Mysql (it is just a basic application I've created for experimentation). I have added the passenger gem to Gemfile and bundled, but I'm using WEBBrick in development still. The only thing I did not do by the book is that I did not use 'eb' but rather tried from the console. My application/environment failed to run as while "rake db:migrate" it still thinks I wanted it to connect to the local Mysql (I guess from the logs that it is not aware of RACK\_ENV and hence uses 'development'). Any tip? I can of course try next the 'eb', yet would prefer to work with the console. Regards, Oren
2015/05/31
[ "https://Stackoverflow.com/questions/30559608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1614089/" ]
I recommend you enter to EC2 instance through this command "**eb ssh**" (The first time you need specified you **.pem** file, if you have not one you can create in **IAM services**) and check your logs for more information about yours error. If you have problems when you are uploading your code (eb deploy) you have the log in this file: "**/var/log/eb-activity.log**" (Remember this file is in your EC2 instance) If you have a problems with your app, you can read the logs in this files: "**/var/app/support/logs/production.log**" or "**/var/app/support/logs/passenger.log**" Other recommedations is install **EB CLI** version 3. for manage your eb instance <http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html>
I believed that Elastic Beanstalk will run 'rake db:migrate' by itself. Indeed it seems to try, but that is failing. I gave my bounty to 'Yahs Hef', even though I will only try this evening (UK). My disorientation with AWS caused me to forget this easy solution, of running the migration by myself. If this does not work by itself, I'll simplify the database configuration as possibile.
18,433,856
I want to get my location if phone is connected to Wifi or mobile network. However if phone is on mobile network things dont run as wanted. Nothing is happening until if i enable GPS. Can i get location without enabling GPS or i have to do that ? And if GPS is must, how could i warn user to enable GPS ? ``` private void setUpMap() { // TODO Auto-generated method stub mMap.setMyLocationEnabled(true); LocationManager manager = (LocationManager)getActivity().getSystemService(FragmentActivity.LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = manager.getBestProvider(criteria, true); myLocation = manager.getLastKnownLocation(provider); latitude = myLocation.getLatitude(); longitude = myLocation.getLongitude(); LatLng latlng = new LatLng(latitude, longitude); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 14)); } ```
2013/08/25
[ "https://Stackoverflow.com/questions/18433856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1889451/" ]
Please refer this [Demo](http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/). You have to create one **GPSTracker** Services which is track your last location. I think 100% solve your issue if you concentrate on demo. If work like charm then accept answer.
You have a very loaded question. ``` Can i get location without enabling GPS or i have to do that ? ``` Of course you can. Location comes from Location Providers. Examples includes Network, Wifi and GPS. You do not need all 3. Just any one will do. ``` And if GPS is must, how could i warn user to enable GPS ? ``` You can use the method isProviderEnabled (String provider) under [LocationManager](http://developer.android.com/reference/android/location/LocationManager.html#isProviderEnabled%28java.lang.String%29) Class to check if the GPS Provider is enabled. If you u can show some message and a link to enable it. To learn how to make your app location aware, I suggest you follow the official notes [here](https://developer.android.com/training/location/retrieve-current.html). Thats how I learnt it as well.
17,279,726
I want to create a generic super class called **Vista** that extends android Activity, and then create all my activities extending my class Vista (thus to inherit all my common methods in all my activities). But in the project I have some FragmentActivity classes and I can't extend these from the class Vista. Any solution? Can i change my FragmentActivity in a simile Activity and use android.app.fragment with TabHost inside, instead of android.support.v4.fragment because I am develop for android 4+ ? ![enter image description here](https://i.stack.imgur.com/2rODL.png)
2013/06/24
[ "https://Stackoverflow.com/questions/17279726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1241276/" ]
You need to make the *Vista* class a standalone helper class. Then create an *ActivityVista* class that extends *Activity* and includes an instance of the *Vista* helper class as a private member. And also create a *FragmentActivityVista* class that extends *FragmentActivity* and includes an instance of the *Vista* helper class. The *ActivityVista* and *FragmentActivityVista* classes will have to have a bunch of forwarding functions that call through to the *Vista* helper class, but they at least won't have to duplicate the full functionality.
You have 2 ways : 1. Add VistaFragmentActivity and extend it for Fragments 2. Make yout Vista to extend FragmentActivity Best wishes.
71,726,164
Basically what I am trying to achieve is to enforce function to return a correct type based on the key passed to the function. So if the key is `service1` the correct return type should be `Payloads['service1']`. How can I achieve this? ```js interface Payloads { service1: { a: boolean; }; service2: { b: string; }; service3: { c: number; }; }; const createPayload = <S extends keyof Payloads>(key: S): Payloads[S] => { switch (key) { case 'service1': return { a: true } case 'service2': return { b: 'e' } case 'service3': return { c: 3 } default: throw new Error('undefined service') } } ``` Error I get: [![error](https://i.stack.imgur.com/ge5Tn.png)](https://i.stack.imgur.com/ge5Tn.png) [TypeScript playground link](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgApwJ4BsD2cAmAzsgN4BQylyh0AbsEgIwBcpFVHcrARjjlhDggA3O0oBfURxpR6SAEytyHDt1aEwUUAHMpVSWOp0GEAMxLDHBKxABXALbdoeiaINkEOEBuQIogyHRsPHxkAF5kAB4AZWQIAA9IECJkAGsIDBwYNExcAkIAPgAKdIxWaIBKViC8ogBtaIBdcIK2aQB3YDAEAAtkEoyKtpVKBDgaZAByGTkIRknWfzBbKBBSZC5kTVsUcUsqMYnp4wUF5CWVtZJkNSmISeQ9kdHxlGPZE1Mzi9X162RTI99pR8BB4LYsGBWGAelAcO1kCAIAiAKJQOFQIqTWzJMGgCChGYmSYVQx7PZAA)
2022/04/03
[ "https://Stackoverflow.com/questions/71726164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13269713/" ]
The type `Payloads[S]` is an [indexed access type](https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html) that depends on an as-yet unspecified [generic](https://www.typescriptlang.org/docs/handbook/2/generics.html) type parameter `S`. In your implementation, the compiler is unable to use [control flow analysis](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#control-flow-analysis) to narrow the type parameter `S` in the `switch`/`case` statement. It sees that `key` can be narrowed to, for example, `"service1"`, but it does not narrow the type parameter `S`. And therefore it doesn't know that `{ a: true }` will be assignable to `Payloads[S]` in that circumstance. The compiler is essentially being too cautious here; the only thing it would be happy returning is a value which is assignable to `Payloads[S]` no matter what `S` is, which turns out to be the [intersection](https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types) of all the value types, equivalent to `{a: boolean; b: string; c: number}`. Since you never return a value like this, the compiler complains. There are several open issues in GitHub asking for some improvement here. See [microsoft/TypeScript#33014](https://github.com/microsoft/TypeScript/issues/33014) for example. For now, though (as of TS4.6), if you must write code that works this way, then the compiler won't help you verify type safety. You will need to take over the responsibility by using something like [type assertions](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions) ``` const createPayloadAssert = <S extends keyof Payloads>(key: S): Payloads[S] => { switch (key) { case 'service1': return { a: true } as Payloads[S] case 'service2': return { b: 'e' } as Payloads[S] case 'service3': return { c: 3 } as Payloads[S] default: throw new Error('undefined service') } } ``` or a single-call-signature [overload](https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads) ``` function createPayloadOverload<S extends keyof Payloads>(key: S): Payloads[S]; function createPayloadOverload(key: keyof Payloads) { switch (key) { case 'service1': return { a: true }; case 'service2': return { b: 'e' }; case 'service3': return { c: 3 }; default: throw new Error('undefined service') } } ``` to loosen things enough to prevent the error. This necessarily allows you to make mistakes where you accidentally switch around the return values. But for now that's the best you can do with `switch`/`case`. --- If you are willing to refactor your implementation to a form where the compiler can actually verify the safety of your code, you can do it by indexing into an object: ``` const createPayload = <S extends keyof Payloads>(key: S): Payloads[S] => ({ service1: { a: true }, service2: { b: 'e' }, service3: { c: 3 } }[key]); const createPayloadBad = <S extends keyof Payloads>(key: S): Payloads[S] => ({ service1: { a: true }, service2: { a: true }, // <-- error! service3: { c: 3 } }[key]); ``` This works because, among other things, indexed access types were [introduced to TypeScript](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types) (called "lookup types" in that link) in order to represent *at the type level* what happens when you index into an object with a key *at the value level*. That is, if you have an object-like value `t` of type `T`, and a key-like value `k` of type `K`, then when indexing into `t` with `k` like `t[k]`, the property you read will be of type `T[K]`. So if you want the compiler to know that you have a value of type `Payloads[S]`, you can do so by indexing into a value of type `Payloads` with a key of type `S`, as shown above. [Playground link to code](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgApwJ4BsD2cAmAzsgN4BQylyh0AbsEgIwBcpFVHcrARjjlhDggA3O0oBfURxpR6SAEytyHDt1aEwUUAHMpVSWOp0GEAMxLDHBKxABXALbdoeiaINkyCHCA3IEUQUh0bDx8AEFCGTBkAF5kAB4AZWQIAA9IECJkAGsIDBwYNExcAkIAPgAKXIxWRIBKVmCSogBtRIBdWLK2aQB3YDAEAAtkKry6npVKBDgaZAByGTkIRnnWALBbKBBSZC5kTVsUcT3iJtDCNvbLKhm5xeMFNeQNrZ2SZDUFiHnkE9miiFSlcbtNZigHrITKZnq9trtrMhTH9ToDmpcOqDkPgIPBbFgwKwwEMoDhesgQBByQBRKCkqAVea2TK40AQfBGKFIeZ1QziMj8sgwZkIMDAbx+AJwILFUIAeVo0GaSRS6QgmWI1QKaIulWqtQaOuBHVEwpAovFO38gQg5wICqVoTGNRyeW1dqIE2UVEI-UGI2dXqxdwhSxMq3WEE28I++0OxxcKhDCzDT0j0fen1Y8x+f0TVnBKceZlhUbeCNYyIMU0oOLxBKJJLJFKpyFp9MZzLrbI5qZ+vI4-MFnm8vmt0ttsoIsQSyTSGSyWsKHvKzoNjSnrQ6XVG3sofZYuzjUCOfwANIY+4pdl8c79xBfpMXzBWkX8BS1qu06qIRz5ouOMpAvgABC05xCq87qoubrLpuq76sg9QbsBGKdDE3QVHunLLIesZEiexyPj6xbXvhByEeeyAAPTUQkAC09EpHSOBQAAhJez5KH4lbvuIn55N+ohAA)
TypeScript doesn't know the type of `S` in the body of the function, so it expects you to pass *all* properties to make sure `Payloads[S]` is fulfilled. But you can trick TypeScript! By changing the return type to `Payloads[keyof Payloads]` it means *one of the options*, and you don't get any error. Now this has changed the public method signature, but we don't want that. To make this work we have to use `function` declarations, because they allow *overloads*. We are going to add *one* overload to the function, which is the old signature: ``` function createPayload<S extends keyof Payloads>(key: S): Payloads[S]; function createPayload<S extends keyof Payloads>(key: S): Payloads[keyof Payloads] { // code here... } ``` This exposes `Payloads[S]` to the caller, but internally we expect `Payloads[keyof Payloads]`. A full working example [here](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgApwJ4BsD2cAmAzsgN4BQylyh0AbsEgIwBcpFVHcrARjjlhDggA3O0oBfURxpR6SAEytyHDt1aEwUUAHMpVSWOp0GEAMxLDHBKxABXALbdoeiaINkYtkAjDAcIZAQoQUh0bDx8AB4AZWQIAA9IECJkAGsIDBwYNExcAkIAPgAKdIxWaIBKVjC8ogBtaIBdUU9vX39A4LhQ3IiYuMSIZOJSrJzw-OLS8qrx2sI60eyaiMJGtmkAd2AwBAALZBKMio2VSgQ4GmQAchk5CEZr1mCwWygAkmQuZE1bFHFLFQLldbsYFE9kC83h9kGobhBrsgAWdzpcUKDZCZTBCoe9SIFWKYkYDKPgIPBbFgwKwwHsoDhNsgQBBGQBRKD0qBFa5eMkwUAQfBGTFIa4VQwAgFAA).
48,841,854
I'm having a problem presenting data in the required way. My dataframe is formatted and then sorted by 'Site ID'. I need to present the data by Site ID with all date instances grouped alongside. I'm 90% there in terms of how I want it to look using pivot\_table ``` df_pivot = pd.pivot_table(df, index=['Site Ref','Site Name', 'Date']) ``` however the date column is not sorted. (The tiny example output appears sorted however the \*\*\*\*Thu Jan 11 2018 10:43:20 entry\*\*\*\* illustrates my issue on large data sets) I cannot figure out how to present it like below but also with the dates sorted per site ID Any help is gratefully accepted ``` df = pd.DataFrame.from_dict([{'Site Ref': '1234567', 'Site Name': 'Building A', 'Date': 'Mon Jan 08 2018 10:43:20', 'Duration': 120}, {'Site Ref': '1245678', 'Site Name':'Building B', 'Date': 'Mon Jan 08 2018 10:43:20', 'Duration': 120}, {'Site Ref': '1245678', 'Site Name':'Building B', 'Date': 'Tue Jan 09 2018 10:43:20', 'Duration': 70}, {'Site Ref': '1245678', 'Site Name':'Building B', 'Date': 'Wed Jan 10 2018 10:43:20', 'Duration': 120}, {'Site Ref': '1212345', 'Site Name':'Building C', 'Date': 'Fri Jan 12 2018 10:43:20', 'Duration': 100}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Thu Jan 11 2018 10:43:20', 'Duration': 80}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Fri Jan 12 2018 12:22:20', 'Duration': 80}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Mon Jan 15 2018 11:43:20', 'Duration': 90}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Wed Jan 17 2018 10:43:20', 'Duration': 220}]) df = DataFrame(df, columns=['Site Ref', 'Site Name', 'Date', 'Duration']) df = df.sort_values(by=['Site Ref']) df Site Ref Site Name Date Duration 5 1123456 Building D Thu Jan 11 2018 10:43:20 80 6 1123456 Building D Fri Jan 12 2018 12:22:20 80 7 1123456 Building D Mon Jan 15 2018 11:43:20 90 8 1123456 Building D Wed Jan 17 2018 10:43:20 220 4 1212345 Building C Fri Jan 12 2018 10:43:20 100 0 1234567 Building A Mon Jan 08 2018 10:43:20 120 1 1245678 Building B Mon Jan 08 2018 10:43:20 120 2 1245678 Building B Tue Jan 09 2018 10:43:20 70 3 1245678 Building B Wed Jan 10 2018 10:43:20 120 df_pivot = pd.pivot_table(df, index=['Site Ref','Site Name', 'Date']) df_pivot Site Ref Site Name Date 1123456 Building D Fri Jan 12 2018 12:22:20 80 Mon Jan 15 2018 11:43:20 90 ****Thu Jan 11 2018 10:43:20 80**** Wed Jan 17 2018 10:43:20 220 1212345 Building C Fri Jan 12 2018 10:43:20 100 1234567 Building A Mon Jan 08 2018 10:43:20 120 1245678 Building B Mon Jan 08 2018 10:43:20 120 Tue Jan 09 2018 10:43:20 70 Wed Jan 10 2018 10:43:20 120 ```
2018/02/17
[ "https://Stackoverflow.com/questions/48841854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9373483/" ]
It's sorted [lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order), because `Date` has object (string) dtype Workaround - add a new column of `datetime` dtype, use it before `Date` in the `pivot_table` and drop it afterwards: ``` In [74]: (df.assign(x=pd.to_datetime(df['Date'])) .pivot_table(df, index=['Site Ref','Site Name', 'x', 'Date']) .reset_index(level='x', drop=True)) Out[74]: Duration Site Ref Site Name Date 1123456 Building D Thu Jan 11 2018 10:43:20 80 Fri Jan 12 2018 12:22:20 80 Mon Jan 15 2018 11:43:20 90 Wed Jan 17 2018 10:43:20 220 1212345 Building C Fri Jan 12 2018 10:43:20 100 1234567 Building A Mon Jan 08 2018 10:43:20 120 1245678 Building B Mon Jan 08 2018 10:43:20 120 Tue Jan 09 2018 10:43:20 70 Wed Jan 10 2018 10:43:20 120 ```
You need to convert your dates to datetime values rather than strings. Something like the following would work on your current pivot table: ``` df_pivot.reset_index(inplace=True) df_pivot['Date'] = pd.to_datetime(df_pivot['Date']) df_pivot.sort_values(by=['Site Ref', 'Date'], inplace=True) ```
48,841,854
I'm having a problem presenting data in the required way. My dataframe is formatted and then sorted by 'Site ID'. I need to present the data by Site ID with all date instances grouped alongside. I'm 90% there in terms of how I want it to look using pivot\_table ``` df_pivot = pd.pivot_table(df, index=['Site Ref','Site Name', 'Date']) ``` however the date column is not sorted. (The tiny example output appears sorted however the \*\*\*\*Thu Jan 11 2018 10:43:20 entry\*\*\*\* illustrates my issue on large data sets) I cannot figure out how to present it like below but also with the dates sorted per site ID Any help is gratefully accepted ``` df = pd.DataFrame.from_dict([{'Site Ref': '1234567', 'Site Name': 'Building A', 'Date': 'Mon Jan 08 2018 10:43:20', 'Duration': 120}, {'Site Ref': '1245678', 'Site Name':'Building B', 'Date': 'Mon Jan 08 2018 10:43:20', 'Duration': 120}, {'Site Ref': '1245678', 'Site Name':'Building B', 'Date': 'Tue Jan 09 2018 10:43:20', 'Duration': 70}, {'Site Ref': '1245678', 'Site Name':'Building B', 'Date': 'Wed Jan 10 2018 10:43:20', 'Duration': 120}, {'Site Ref': '1212345', 'Site Name':'Building C', 'Date': 'Fri Jan 12 2018 10:43:20', 'Duration': 100}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Thu Jan 11 2018 10:43:20', 'Duration': 80}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Fri Jan 12 2018 12:22:20', 'Duration': 80}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Mon Jan 15 2018 11:43:20', 'Duration': 90}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Wed Jan 17 2018 10:43:20', 'Duration': 220}]) df = DataFrame(df, columns=['Site Ref', 'Site Name', 'Date', 'Duration']) df = df.sort_values(by=['Site Ref']) df Site Ref Site Name Date Duration 5 1123456 Building D Thu Jan 11 2018 10:43:20 80 6 1123456 Building D Fri Jan 12 2018 12:22:20 80 7 1123456 Building D Mon Jan 15 2018 11:43:20 90 8 1123456 Building D Wed Jan 17 2018 10:43:20 220 4 1212345 Building C Fri Jan 12 2018 10:43:20 100 0 1234567 Building A Mon Jan 08 2018 10:43:20 120 1 1245678 Building B Mon Jan 08 2018 10:43:20 120 2 1245678 Building B Tue Jan 09 2018 10:43:20 70 3 1245678 Building B Wed Jan 10 2018 10:43:20 120 df_pivot = pd.pivot_table(df, index=['Site Ref','Site Name', 'Date']) df_pivot Site Ref Site Name Date 1123456 Building D Fri Jan 12 2018 12:22:20 80 Mon Jan 15 2018 11:43:20 90 ****Thu Jan 11 2018 10:43:20 80**** Wed Jan 17 2018 10:43:20 220 1212345 Building C Fri Jan 12 2018 10:43:20 100 1234567 Building A Mon Jan 08 2018 10:43:20 120 1245678 Building B Mon Jan 08 2018 10:43:20 120 Tue Jan 09 2018 10:43:20 70 Wed Jan 10 2018 10:43:20 120 ```
2018/02/17
[ "https://Stackoverflow.com/questions/48841854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9373483/" ]
It's sorted [lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order), because `Date` has object (string) dtype Workaround - add a new column of `datetime` dtype, use it before `Date` in the `pivot_table` and drop it afterwards: ``` In [74]: (df.assign(x=pd.to_datetime(df['Date'])) .pivot_table(df, index=['Site Ref','Site Name', 'x', 'Date']) .reset_index(level='x', drop=True)) Out[74]: Duration Site Ref Site Name Date 1123456 Building D Thu Jan 11 2018 10:43:20 80 Fri Jan 12 2018 12:22:20 80 Mon Jan 15 2018 11:43:20 90 Wed Jan 17 2018 10:43:20 220 1212345 Building C Fri Jan 12 2018 10:43:20 100 1234567 Building A Mon Jan 08 2018 10:43:20 120 1245678 Building B Mon Jan 08 2018 10:43:20 120 Tue Jan 09 2018 10:43:20 70 Wed Jan 10 2018 10:43:20 120 ```
Sort the values by Site Ref, groupby mean using `sort = False` i.e ``` df.sort_values('Site Ref').groupby(['Site Ref','Site Name','Date'],sort=False).mean() Duration Site Ref Site Name Date 1123456 Building D Thu Jan 11 2018 10:43:20 80 Fri Jan 12 2018 12:22:20 80 Mon Jan 15 2018 11:43:20 90 Wed Jan 17 2018 10:43:20 220 1212345 Building C Fri Jan 12 2018 10:43:20 100 1234567 Building A Mon Jan 08 2018 10:43:20 120 1245678 Building B Mon Jan 08 2018 10:43:20 120 Tue Jan 09 2018 10:43:20 70 Wed Jan 10 2018 10:43:20 120 ```
13,077,227
What will be the context for CONNECTIVITY\_SERVICE in a Fragment? I have checked getActivity also but it is giving an error. ``` public boolean isOnline() { ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); try { if (connectionManager.getActiveNetworkInfo().isConnected()) { Log.d("ConStatus", "Data Connection On"); return true; } else { Log.d("ConStatus", "Data Connection off"); return false; } } catch (NullPointerException e) { Log.i("ConStatus", "No Active Connection"); return false; } } ```
2012/10/25
[ "https://Stackoverflow.com/questions/13077227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1744952/" ]
`getSystemService()` is a method on `Context`. A `Fragment` would call it using `getActivity()`: ``` getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); ```
I faced a similar problem when trying to implement a Google map offline tile provider within a fragment (based on 0ne\_Up's answer [here](https://stackoverflow.com/questions/48938723/google-maps-offline-mode-on-android-application?rq=1)). I solved it by using the following: ``` private ConnectivityManager connectivityManager; ... connectivityManager = (ConnectivityManager) getActivity(). getSystemService( getActivity().CONNECTIVITY_SERVICE ); ```
265,569
i've come across a lot of questions recently that ask you whether or not there exist certain kinds of ideal, say; does there exist an ideal$ J $of $\mathbb{Z}[i]$ for which $\mathbb{Z}[i] /J$ is a field of 8 elements? or for $R ={\{a + bi\sqrt3: a,b \in Z}\} $show there is an ideal $I$ of $R$ so that $R/I$ is isomorphic to $\mathbb{Z}\_7,$ but no ideal so that $R/J$ is isomorphic to $\mathbb{Z}\_5$? i am struggling to find examples in such questions, and also in proving them impossible. Is there any intuition to know if such things exist? and any standard approach to answering these questions with ideals? An approach to begin with?
2012/12/26
[ "https://math.stackexchange.com/questions/265569", "https://math.stackexchange.com", "https://math.stackexchange.com/users/36016/" ]
For the case of $\, \Bbb Z[i]\,$: try to prove the nice **Claim:** For any $\,a+bi\in\Bbb Z[i]\,\,,\,\,\gcd(a,b)=1\,$ , we have that $$\Bbb Z[i]/\langle a+bi\rangle\,\cong\Bbb Z/(a^2+b^2)\Bbb Z=:\Bbb Z\_{a^2+b^2}$$ Assuming the above, the question is now whether we can write $\,8=a^2+b^2\,,\,a,b\in\Bbb Z\,,\,(a,b)=1$ , which we can't... Could you do something similar with $\,\Bbb Z[\sqrt{-3}]\,$ ?
The ring $\Bbb{Z}[i]$ is the ring of integers of $\Bbb{Q}(i)$. Hence finding an ideal such that the quotient is a field of 8 elements is impossible. This is because such an ideal must be prime, lies over $2\Bbb{Z}$ and is of inertia degree 3 but this is impossible because it violates the formula $\sum e\_if\_i = n$. We have $e\_i$ being the ramification indices of the primes lying over $2\Bbb{Z}$, $f\_i$ the inertia degrees and $n = 2$ in this case.
42,875,328
I want to add onblur function to html code inside in my javascript code and below my code is not working. can anyone advice me on this please ``` <script type="text/javascript"> $(document).ready(function() { var max_fields = 15; //maximum input boxes allowed var wrapper = $(".input_fields_wrap"); var add_button = $(".add_field_button"); var fname_lname = ' <div class="form-group"><label for="inputRegNo" class="col-lg-3 col-md-3 col-sm-3 col-xs-3 control-label" style="text-align: left;"></label><input class="special-block" type="text" name="fname[]" placeholder="Name" onblur="document.getElementById('refa5').innerHTML+='<br/>'+ this.value" />&nbsp;&nbsp;<input class="special-block" type="text" name="lname[]" placeholder="Designation" /><button href="#" class="remove_field">-</button></div>' var x = 1; $(add_button).click(function(e){ e.preventDefault(); if(x < max_fields){ x++; //text box increment $(wrapper).append(fname_lname); } }); $(wrapper).on("click",".remove_field", function(e){ e.preventDefault(); $(this).parent('div').remove(); x--; }) }); ```
2017/03/18
[ "https://Stackoverflow.com/questions/42875328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7366435/" ]
With this bit of information, you can generate queries flexibly. ``` In [2]: User.email Out[2]: <sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7f42cd4b7410> In [3]: User.email == '' Out[3]: <sqlalchemy.sql.elements.BinaryExpression object at 0x7f42ca640550> In [4]: User.email.in_([]) ...warning Out[4]: <sqlalchemy.sql.elements.BinaryExpression object at 0x7f42c9e07710> ``` You can do ``` user_attribute = getattr(User, 'email') # get attribute if equals_filter: user_filter = user_attribute == equals_value # compute expression else: user_filter = user_attribute.in_(in_list) users = session.query(User).filter(user_filter) # filter using expression ```
You can use. `declarative_base` and `filter_by`. ``` from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String engine = create_engine('sqlite:///test.db', convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db_session.query_property() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50), unique=True) def __init__(self, name=None): self.name = name def __repr__(self): return '<User %r>' % (self.name) Base.metadata.create_all(bind=engine) db_session.add(User('name1')) db_session.commit() User.query.filter_by(name='name1').first() # => <User u'name1'> ```
1,094
How can I create hindrances to radio waves?
2010/11/19
[ "https://physics.stackexchange.com/questions/1094", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/547/" ]
Any conductive material will block any EM radiation, including radio waves. However, the thickness of material required to fully block the radiation depends on the wavelength of the radiation and the properties of the material. With a perfect conductor, the radiation is stopped completely by any thickness of the material, but in any real material (except for a superconductor) the radiation is attenuated as it travels through the material. The strength of the radiation will fall off with an exponential decay, and it will do so more quickly in a better conductor. The important number here is called "skin depth" which is given by: $$\delta = \frac{c}{\sqrt{2\pi\sigma\mu\omega}} $$ Where $\sigma$ is the conductivity of the material, $\mu$ is the magnetic permeability of the material, and $\omega$ is the frequency of the radiation. The skin depth is the distance into the material at which the radiation will have fallen to a fraction of $1/e \approx 0.37$ relative to its original intensity. As you can see, the skin depth will be smaller for a better conductor or higher frequency radiation. For example, for Aluminum, radiation at 60Hz will have a skin depth of over 8 millimeters, while optical radiation around 600 THz will have a skin depth around 3 nanometers! This is why metal blocks visible light so well, yet radio waves easily penetrate into your house. Sources: 1. "Lectures on Electromagnetism" page 280. Ashok Das; Hindustan Book Agency, New Delhi, 2004. 2. <http://en.wikipedia.org/wiki/Skin_effect>
A large sheet or volume of matter that contains plenty of freely moveable charge carriers. Examples: metal, which contains electrons not assigned to particular atoms, but free to move; plasmas which consist of electrons and positive ions free to move in space; or a cloud of charged dust particles. If you just want to slow it down not stop the radio waves, any dielectric material will do, the the index of refraction can vary greatly with frequency. Have enough of this material to block the line of sight between all points of the emitter and all points of the sensor/observer, and more beyond that to reduce radiation sneaking around due to diffraction. To say much more, the question needs to be more specific.
1,094
How can I create hindrances to radio waves?
2010/11/19
[ "https://physics.stackexchange.com/questions/1094", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/547/" ]
A large sheet or volume of matter that contains plenty of freely moveable charge carriers. Examples: metal, which contains electrons not assigned to particular atoms, but free to move; plasmas which consist of electrons and positive ions free to move in space; or a cloud of charged dust particles. If you just want to slow it down not stop the radio waves, any dielectric material will do, the the index of refraction can vary greatly with frequency. Have enough of this material to block the line of sight between all points of the emitter and all points of the sensor/observer, and more beyond that to reduce radiation sneaking around due to diffraction. To say much more, the question needs to be more specific.
Let's go for a somewhat more unconventional answer. Consider this: if you have a radio wave of certain frequency and wavelength, you can *"cancel out"* its effect by emitting another wave of same frequency, wavelength and amplitude, just offset by half of its period. Something like this: (forgive the crude drawing) [![Two waves in sync like described](https://i.stack.imgur.com/pRRms.png)](https://i.stack.imgur.com/pRRms.png) The two waves would neutralize each other–so to an observer there would be effectively no radiation.
1,094
How can I create hindrances to radio waves?
2010/11/19
[ "https://physics.stackexchange.com/questions/1094", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/547/" ]
Any conductive material will block any EM radiation, including radio waves. However, the thickness of material required to fully block the radiation depends on the wavelength of the radiation and the properties of the material. With a perfect conductor, the radiation is stopped completely by any thickness of the material, but in any real material (except for a superconductor) the radiation is attenuated as it travels through the material. The strength of the radiation will fall off with an exponential decay, and it will do so more quickly in a better conductor. The important number here is called "skin depth" which is given by: $$\delta = \frac{c}{\sqrt{2\pi\sigma\mu\omega}} $$ Where $\sigma$ is the conductivity of the material, $\mu$ is the magnetic permeability of the material, and $\omega$ is the frequency of the radiation. The skin depth is the distance into the material at which the radiation will have fallen to a fraction of $1/e \approx 0.37$ relative to its original intensity. As you can see, the skin depth will be smaller for a better conductor or higher frequency radiation. For example, for Aluminum, radiation at 60Hz will have a skin depth of over 8 millimeters, while optical radiation around 600 THz will have a skin depth around 3 nanometers! This is why metal blocks visible light so well, yet radio waves easily penetrate into your house. Sources: 1. "Lectures on Electromagnetism" page 280. Ashok Das; Hindustan Book Agency, New Delhi, 2004. 2. <http://en.wikipedia.org/wiki/Skin_effect>
In short, just build a [Faraday Cage](http://en.wikipedia.org/wiki/Faraday_cage) out of conducting material with a mesh size much smaller than the wavelength of the electromagnetic wave you want to block.
1,094
How can I create hindrances to radio waves?
2010/11/19
[ "https://physics.stackexchange.com/questions/1094", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/547/" ]
Any conductive material will block any EM radiation, including radio waves. However, the thickness of material required to fully block the radiation depends on the wavelength of the radiation and the properties of the material. With a perfect conductor, the radiation is stopped completely by any thickness of the material, but in any real material (except for a superconductor) the radiation is attenuated as it travels through the material. The strength of the radiation will fall off with an exponential decay, and it will do so more quickly in a better conductor. The important number here is called "skin depth" which is given by: $$\delta = \frac{c}{\sqrt{2\pi\sigma\mu\omega}} $$ Where $\sigma$ is the conductivity of the material, $\mu$ is the magnetic permeability of the material, and $\omega$ is the frequency of the radiation. The skin depth is the distance into the material at which the radiation will have fallen to a fraction of $1/e \approx 0.37$ relative to its original intensity. As you can see, the skin depth will be smaller for a better conductor or higher frequency radiation. For example, for Aluminum, radiation at 60Hz will have a skin depth of over 8 millimeters, while optical radiation around 600 THz will have a skin depth around 3 nanometers! This is why metal blocks visible light so well, yet radio waves easily penetrate into your house. Sources: 1. "Lectures on Electromagnetism" page 280. Ashok Das; Hindustan Book Agency, New Delhi, 2004. 2. <http://en.wikipedia.org/wiki/Skin_effect>
Let's go for a somewhat more unconventional answer. Consider this: if you have a radio wave of certain frequency and wavelength, you can *"cancel out"* its effect by emitting another wave of same frequency, wavelength and amplitude, just offset by half of its period. Something like this: (forgive the crude drawing) [![Two waves in sync like described](https://i.stack.imgur.com/pRRms.png)](https://i.stack.imgur.com/pRRms.png) The two waves would neutralize each other–so to an observer there would be effectively no radiation.
1,094
How can I create hindrances to radio waves?
2010/11/19
[ "https://physics.stackexchange.com/questions/1094", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/547/" ]
In short, just build a [Faraday Cage](http://en.wikipedia.org/wiki/Faraday_cage) out of conducting material with a mesh size much smaller than the wavelength of the electromagnetic wave you want to block.
Let's go for a somewhat more unconventional answer. Consider this: if you have a radio wave of certain frequency and wavelength, you can *"cancel out"* its effect by emitting another wave of same frequency, wavelength and amplitude, just offset by half of its period. Something like this: (forgive the crude drawing) [![Two waves in sync like described](https://i.stack.imgur.com/pRRms.png)](https://i.stack.imgur.com/pRRms.png) The two waves would neutralize each other–so to an observer there would be effectively no radiation.
45,788,700
I have a textfield in the `MyCustomCell`, and set the textfield delegate in the `cellForRowIndexPath` tableview delegate. When user changes the textfield value and it calls `textFieldShouldEndEditing`. All it works. However, I wonder how to know which textfield (indexPath) is changed? ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"Cell"; MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { // use this if you created your cell with IB cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil] objectAtIndex:0]; // otherwise use this cell = [[[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; // now set the view controller as the text field delegate cell.textField.delegate = self; } // configure cell... return cell; } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { [textField resignFirstResponder]; return YES; } ```
2017/08/21
[ "https://Stackoverflow.com/questions/45788700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1669996/" ]
Set `UITextField` tag in your `cellForRowAtIndexPath` method. If there is only one section in your tableview you can set the row as tag. Like this. ``` cell.textField.delegate = self; cell.textField.tag = indexPath.row; ``` And in your `textFieldShouldEndEditing` method you can check the tag. ``` - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { int row = textField.tag; [textField resignFirstResponder]; return YES; } ```
You Can Try this: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"Cell"; MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { // use this if you created your cell with IB cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil] objectAtIndex:0]; // otherwise use this cell = [[[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; // now set the view controller as the text field delegate cell.textField.delegate = self; textField.tag = indexPath.Row; } // configure cell... return cell; } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { NSLog("Selected Cell is:%@",textField.tag); [textField resignFirstResponder]; return YES; } ```
45,788,700
I have a textfield in the `MyCustomCell`, and set the textfield delegate in the `cellForRowIndexPath` tableview delegate. When user changes the textfield value and it calls `textFieldShouldEndEditing`. All it works. However, I wonder how to know which textfield (indexPath) is changed? ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"Cell"; MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { // use this if you created your cell with IB cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil] objectAtIndex:0]; // otherwise use this cell = [[[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; // now set the view controller as the text field delegate cell.textField.delegate = self; } // configure cell... return cell; } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { [textField resignFirstResponder]; return YES; } ```
2017/08/21
[ "https://Stackoverflow.com/questions/45788700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1669996/" ]
Set `UITextField` tag in your `cellForRowAtIndexPath` method. If there is only one section in your tableview you can set the row as tag. Like this. ``` cell.textField.delegate = self; cell.textField.tag = indexPath.row; ``` And in your `textFieldShouldEndEditing` method you can check the tag. ``` - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { int row = textField.tag; [textField resignFirstResponder]; return YES; } ```
`- (BOOL)textFieldShouldEndEditing:(UITextField *)textField { if ([[[textField superview] superview] isKindOfClass:[MyCustomCell class]]) { MyCustomCell *cell = (MyCustomCell *)[[textField superview] superview]; NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; // this is what you want. } return YES; }`
45,788,700
I have a textfield in the `MyCustomCell`, and set the textfield delegate in the `cellForRowIndexPath` tableview delegate. When user changes the textfield value and it calls `textFieldShouldEndEditing`. All it works. However, I wonder how to know which textfield (indexPath) is changed? ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"Cell"; MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { // use this if you created your cell with IB cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil] objectAtIndex:0]; // otherwise use this cell = [[[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; // now set the view controller as the text field delegate cell.textField.delegate = self; } // configure cell... return cell; } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { [textField resignFirstResponder]; return YES; } ```
2017/08/21
[ "https://Stackoverflow.com/questions/45788700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1669996/" ]
`- (BOOL)textFieldShouldEndEditing:(UITextField *)textField { if ([[[textField superview] superview] isKindOfClass:[MyCustomCell class]]) { MyCustomCell *cell = (MyCustomCell *)[[textField superview] superview]; NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; // this is what you want. } return YES; }`
You Can Try this: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"Cell"; MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { // use this if you created your cell with IB cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil] objectAtIndex:0]; // otherwise use this cell = [[[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; // now set the view controller as the text field delegate cell.textField.delegate = self; textField.tag = indexPath.Row; } // configure cell... return cell; } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { NSLog("Selected Cell is:%@",textField.tag); [textField resignFirstResponder]; return YES; } ```
17,576,135
I have a textfield, which I want to have a 'dynamic' placeholder text (definied and managed in the view), but I also want it to have an action defined for it. I tried the two following lines: ``` {{ input id="test" placeholder=view.text action expand target="view"}} <input type="text" id="test" placeholder="{{view.text}}" {{action expand target="view"}} /> ``` Both are not working. So my question is, is there a way to achieve what I want or would it be easier to have a focus handler in the view, which just filters for the id (and then calls the expand function)?
2013/07/10
[ "https://Stackoverflow.com/questions/17576135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085007/" ]
If you want to stick to input helpers, you can do something like this: ``` {{input placeholder=view.text action="expand" targetObject=view}} ``` Notice that targetObject should **not** be a string.
You could try to do it like this: ``` <input type="text" id="test" {{bindAttr placeholder=view.text}} {{action expand target="view"}} /> ``` See [here](http://jsbin.com/axihur/7/edit) for a working example. Hope it helps
70,097,154
I recently started working on a project and I'm trying NextJS for the first time for this project. In the past I have already coded a website with plain ReactJS and used mongoose to connect to my mongodb. Now for NextJS I can only find explanations and tutorials where the are not using "mongoose" but "mongodb". I find it quite complicated since you don't have "schemas" like you do in mongoose. (Or am I just missing something) Is there a way to implement the "mongoose.schema"-Way for the mongodb-module? Or which of these both ways is the "best-practice" way? Thanks in advice.
2021/11/24
[ "https://Stackoverflow.com/questions/70097154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13575279/" ]
<https://docs.nestjs.com/techniques/mongodb> They Reference it as mongodb... But they natively use mongoose to facilitate it -> and right down to the schemas... I know what you mean, the documentation is lacking all the parts that make it work... however after watching this video. I was able to see how he made it work . <https://youtu.be/wqhNoDE6pb4> Around 30-35 he starts setting up the mongoose connection. At 43 he starts working on the schema. Might be best to just watch the entire flow as you get to see everything that works , then you can try and play with the various features you want to implement once you have something that works bare bones.
1. You create schema ``` import mongoose from 'mongoose'; var Schema = mongoose.Schema; var user = new Schema({ name: {type: String, required: true}, email: {type: String, required: true}, password: {type: String, required: true}, }); mongoose.models = {}; var User = mongoose.model('User', user); export default User; ``` 2. You add your shema to `/api/yourRequest` ``` var user = new User({ name, email, password: password, }); var usercreated = await user.save(); ``` 3. If something wrong, you check [docs](https://mongoosejs.com/docs/guide.html) *I find it quite complicated since you don't have "schemas" like you do in mongoose.* - a lot of projects for a test doesn't use mongoose schemas because of complex "pre-thinking". This means you need to "define" all possible params and fields before the real coding. Also problems with nested Schemas and special types. So, it's possible to use mongoose schemas with no problems if you have defined "project requirements and data structures before" P.S. imagine you started to develop and fill DB with next mongoose schema: ``` var user = new Schema({ name: {type: String, required: true}, email: {type: String, required: true}, password: {type: String, required: true}, test: {type: String, required: false} }); ``` and then you notice that `test` must be required as `true`. In this case you will need to rework all data in your DB where test is `null` otherwise you might have errors with data. This is a simple case of "erroring" but imagine you have other model schema instead of test - this is where your headache begins.
10,721,951
I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this? ``` $('.poshytip-trigger').each(function (index) { var $this = $(this); var data = $this.data(); var options = {}; if (data['class-name']) { options.className = data['class-name']; } if (data['align-x']) { options.alignX = data['align-x']; } if (data['align-y']) { options.alignY = data['align-y']; } if (data['offset-y']) { options.offsetY = data['offset-y']; } if (data['offset-x']) { options.offsetX = data['offset-x']; } $this.poshytip(options); }); ```
2012/05/23
[ "https://Stackoverflow.com/questions/10721951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52360/" ]
Something like this - **It does convert `offset-x` to `offsetX`:** <http://jsfiddle.net/8C4rZ/1/> HTML: ``` <p data-test="sdsd" data-test2="4434"></p>​ ``` JavaScript: ``` $(document).ready(function() { var options = {}; for (var key in $("p").data()) { options[key] = $("p").data(key); } console.log(options); });​ ``` But I think Daniel's approach is better, since he explicitly controls which attributes gets set. This will take *all* `data-` attributes.
Try using a for in loop. ``` var array = ['class-name', 'align-x', 'align-y', 'offset-y', 'offset-x']; for (x in array) { if(data[array[x]]) { options[array[x]] = data[array[x]]; } } ``` **Update:** In response to the OP's clarification, he could write something like this: ``` var Pair = function(hyphenated, camcelCased) { this.hyphenated = hyphenated; this.camelCased = camelCased; } var array = [ new Pair('class-name', 'ClassName'), new Pair('align-x', 'alignX'), new Pair('align-y', 'alignY'), new Pair('offset-x', 'offsetX'), new Pair('offset-y', 'offsetY')]; var i, optionNameHyphenated, optionNameCamelCased; for(i = 0; i < array.length; i++) { optionNameHyphenated = array[i]['hyphenated']; optionNameCamelCased = array[i]['camelCased']; if (data[optionNameHyphenated]); options[optionNameCamelCased] = data[optionNameHyphenated]; } ```
10,721,951
I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this? ``` $('.poshytip-trigger').each(function (index) { var $this = $(this); var data = $this.data(); var options = {}; if (data['class-name']) { options.className = data['class-name']; } if (data['align-x']) { options.alignX = data['align-x']; } if (data['align-y']) { options.alignY = data['align-y']; } if (data['offset-y']) { options.offsetY = data['offset-y']; } if (data['offset-x']) { options.offsetX = data['offset-x']; } $this.poshytip(options); }); ```
2012/05/23
[ "https://Stackoverflow.com/questions/10721951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52360/" ]
I would use a for..in loop to read the data-\* tags.. Also you don't need to camelcase as jQuery converts it to camelCase internally... [Source code reference](https://github.com/jquery/jquery/blob/master/src/data.js#L102). ``` $('.poshytip-trigger').each(function (index) { var $this = $(this); var data = $this.data(); var options = {}; for (var keys in data) { options[keys] = data[keys]; } // For older versions of jQuery you can use $.camelCase function for (var keys in data) { options[$.camelCase(keys)] = data[keys]; } }); ``` [**DEMO**](http://jsfiddle.net/3eeqV/) for jQuery 1.4.4, ``` $('.poshytip-trigger').each(function(index) { var $this = $(this); var data = $this.data(); var options = {}; for (var keys in data) { options[camelCase(keys)] = data[keys]; } }); //copied from http://james.padolsey.com/jquery/#v=git&fn=jQuery.camelCase function camelCase(str) { return str.replace(/^-ms-/, "ms-").replace(/-([a-z]|[0-9])/ig, function(all, letter) { return (letter + "").toUpperCase(); }); } ``` [**DEMO for 1.4.4**](http://jsfiddle.net/3eeqV/3/)
Try using a for in loop. ``` var array = ['class-name', 'align-x', 'align-y', 'offset-y', 'offset-x']; for (x in array) { if(data[array[x]]) { options[array[x]] = data[array[x]]; } } ``` **Update:** In response to the OP's clarification, he could write something like this: ``` var Pair = function(hyphenated, camcelCased) { this.hyphenated = hyphenated; this.camelCased = camelCased; } var array = [ new Pair('class-name', 'ClassName'), new Pair('align-x', 'alignX'), new Pair('align-y', 'alignY'), new Pair('offset-x', 'offsetX'), new Pair('offset-y', 'offsetY')]; var i, optionNameHyphenated, optionNameCamelCased; for(i = 0; i < array.length; i++) { optionNameHyphenated = array[i]['hyphenated']; optionNameCamelCased = array[i]['camelCased']; if (data[optionNameHyphenated]); options[optionNameCamelCased] = data[optionNameHyphenated]; } ```
10,721,951
I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this? ``` $('.poshytip-trigger').each(function (index) { var $this = $(this); var data = $this.data(); var options = {}; if (data['class-name']) { options.className = data['class-name']; } if (data['align-x']) { options.alignX = data['align-x']; } if (data['align-y']) { options.alignY = data['align-y']; } if (data['offset-y']) { options.offsetY = data['offset-y']; } if (data['offset-x']) { options.offsetX = data['offset-x']; } $this.poshytip(options); }); ```
2012/05/23
[ "https://Stackoverflow.com/questions/10721951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52360/" ]
I would use a for..in loop to read the data-\* tags.. Also you don't need to camelcase as jQuery converts it to camelCase internally... [Source code reference](https://github.com/jquery/jquery/blob/master/src/data.js#L102). ``` $('.poshytip-trigger').each(function (index) { var $this = $(this); var data = $this.data(); var options = {}; for (var keys in data) { options[keys] = data[keys]; } // For older versions of jQuery you can use $.camelCase function for (var keys in data) { options[$.camelCase(keys)] = data[keys]; } }); ``` [**DEMO**](http://jsfiddle.net/3eeqV/) for jQuery 1.4.4, ``` $('.poshytip-trigger').each(function(index) { var $this = $(this); var data = $this.data(); var options = {}; for (var keys in data) { options[camelCase(keys)] = data[keys]; } }); //copied from http://james.padolsey.com/jquery/#v=git&fn=jQuery.camelCase function camelCase(str) { return str.replace(/^-ms-/, "ms-").replace(/-([a-z]|[0-9])/ig, function(all, letter) { return (letter + "").toUpperCase(); }); } ``` [**DEMO for 1.4.4**](http://jsfiddle.net/3eeqV/3/)
Something like this - **It does convert `offset-x` to `offsetX`:** <http://jsfiddle.net/8C4rZ/1/> HTML: ``` <p data-test="sdsd" data-test2="4434"></p>​ ``` JavaScript: ``` $(document).ready(function() { var options = {}; for (var key in $("p").data()) { options[key] = $("p").data(key); } console.log(options); });​ ``` But I think Daniel's approach is better, since he explicitly controls which attributes gets set. This will take *all* `data-` attributes.
10,721,951
I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this? ``` $('.poshytip-trigger').each(function (index) { var $this = $(this); var data = $this.data(); var options = {}; if (data['class-name']) { options.className = data['class-name']; } if (data['align-x']) { options.alignX = data['align-x']; } if (data['align-y']) { options.alignY = data['align-y']; } if (data['offset-y']) { options.offsetY = data['offset-y']; } if (data['offset-x']) { options.offsetX = data['offset-x']; } $this.poshytip(options); }); ```
2012/05/23
[ "https://Stackoverflow.com/questions/10721951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52360/" ]
Something like this - **It does convert `offset-x` to `offsetX`:** <http://jsfiddle.net/8C4rZ/1/> HTML: ``` <p data-test="sdsd" data-test2="4434"></p>​ ``` JavaScript: ``` $(document).ready(function() { var options = {}; for (var key in $("p").data()) { options[key] = $("p").data(key); } console.log(options); });​ ``` But I think Daniel's approach is better, since he explicitly controls which attributes gets set. This will take *all* `data-` attributes.
``` var names = ["className", "alignY", ...]; $(names).each(function(ind, name){ var dataName = name.replace(/[A-Z]/, function(letter){ return letter.toLowerCase(); }); if(data[dataName]){ options[name] = data[dataName]; } }); ``` Does this work? Unlike the other answers, this piece of code both convert only explicitly set attributes and keeps the options-object attribute name camelCase.
10,721,951
I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this? ``` $('.poshytip-trigger').each(function (index) { var $this = $(this); var data = $this.data(); var options = {}; if (data['class-name']) { options.className = data['class-name']; } if (data['align-x']) { options.alignX = data['align-x']; } if (data['align-y']) { options.alignY = data['align-y']; } if (data['offset-y']) { options.offsetY = data['offset-y']; } if (data['offset-x']) { options.offsetX = data['offset-x']; } $this.poshytip(options); }); ```
2012/05/23
[ "https://Stackoverflow.com/questions/10721951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52360/" ]
I would use a for..in loop to read the data-\* tags.. Also you don't need to camelcase as jQuery converts it to camelCase internally... [Source code reference](https://github.com/jquery/jquery/blob/master/src/data.js#L102). ``` $('.poshytip-trigger').each(function (index) { var $this = $(this); var data = $this.data(); var options = {}; for (var keys in data) { options[keys] = data[keys]; } // For older versions of jQuery you can use $.camelCase function for (var keys in data) { options[$.camelCase(keys)] = data[keys]; } }); ``` [**DEMO**](http://jsfiddle.net/3eeqV/) for jQuery 1.4.4, ``` $('.poshytip-trigger').each(function(index) { var $this = $(this); var data = $this.data(); var options = {}; for (var keys in data) { options[camelCase(keys)] = data[keys]; } }); //copied from http://james.padolsey.com/jquery/#v=git&fn=jQuery.camelCase function camelCase(str) { return str.replace(/^-ms-/, "ms-").replace(/-([a-z]|[0-9])/ig, function(all, letter) { return (letter + "").toUpperCase(); }); } ``` [**DEMO for 1.4.4**](http://jsfiddle.net/3eeqV/3/)
``` var names = ["className", "alignY", ...]; $(names).each(function(ind, name){ var dataName = name.replace(/[A-Z]/, function(letter){ return letter.toLowerCase(); }); if(data[dataName]){ options[name] = data[dataName]; } }); ``` Does this work? Unlike the other answers, this piece of code both convert only explicitly set attributes and keeps the options-object attribute name camelCase.
68,961,129
I have some multithreaded code that involves using a nested loop, where the inner one is run in parallel. "Shared" across each thread is a `Sender` that will return results. Notably `Sender` implements `Send` so there should be no problem cloning it and sending it using Rayon's `for_each_with()`. However, compiling this code: ```rust use std::sync::mpsc::channel; use rayon::prelude::*; fn main(){ let (sender, receiver) = channel(); (0..5).for_each(|i|{ (0..5).into_par_iter().for_each_with(&sender, |sender, j|{ sender.send(i + j).unwrap(); }); }); } ``` Gives me: ``` 8 | (0..5).into_par_iter().for_each_with(&sender, |sender, j|{ | ^^^^^^^ `Sender<_>` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `Sender<_>` = note: required because of the requirements on the impl of `Send` for `&Sender<_>` ``` ([Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=672cca8549c65d2b17e2e8236bbe6261)) Now I was thinking this might be because I'm trying to clone a reference, but if I move the actual `sender` into `for_each_with()` (ie `for_each_with(sender, ...)`), it will be consumed by the first iteration of the outer loop: ``` error[E0507]: cannot move out of `sender`, a captured variable in an `FnMut` closure ``` ([Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3d27dfdaf41f1cd4bcd54a5648374424)). How can I implement this pattern in a way that satisfies the Rust compiler?
2021/08/28
[ "https://Stackoverflow.com/questions/68961129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148718/" ]
AFAIK, Rayon use a threadpool, this mean that rayon require the item to implement `Send` cause it will send it to a thread. rayon doesn't clone for each item but for each thread: ```rust fn for_each_with<OP, T>(self, init: T, op: OP) where OP: Fn(&mut T, Self::Item) + Sync + Send, T: Send + Clone, ``` We can see the `OP` take a `&mut T` not a `T`. This mean [`for_each_with()`](https://docs.rs/rayon/1.5.1/rayon/iter/trait.ParallelIterator.html#method.for_each_with) clone for each number of thread used not for the number of item produce. [Reference need to implement `Sync` to implement `Send`](https://doc.rust-lang.org/nightly/std/marker/trait.Send.html#impl-Send-8). [`Sender` is define to not implement `Sync`](https://doc.rust-lang.org/nightly/std/sync/mpsc/struct.Sender.html#impl-Sync). I don't know the detail of this choice anyway this mean `&Sender` can't be share between thread. I don't think there is solution to remove this constrain. But if you want you could use [crossbeam-channel](https://crates.io/crates/crossbeam-channel) that implement `Sync`: ```rust use crossbeam_channel::unbounded; // 0.5.1 use rayon::prelude::*; // 1.5.1 fn main() { let (sender, _receiver) = unbounded(); for i in 0..5 { (0..5).into_par_iter().for_each_with(&sender, |sender, j| { sender.send(i + j).unwrap(); }); } } ``` would compile fine. Bonus is that crossbeam-channel claim to be faster. That said, cloning is totally fine for the std `Sender`: ```rust use rayon::prelude::*; use std::sync::mpsc::channel; fn main() { let (sender, _receiver) = channel(); for i in 0..5 { let sender = sender.clone(); (0..5).into_par_iter().for_each_with(sender, |sender, j| { sender.send(i + j).unwrap(); }); } } ``` That would indeed clone `O(n)` time more but `Sender` from std is mean to be clone a lot. (Actually it's probably just add one clone cause you choice to make a nested loop, the code probably doesn't clone the last one but just give it the last thread and so you just clone one too much as we can [test](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4d8169f7b5d587eb1581098f91978c5a)) Anyway, all your problems come from a strange situation, one should flatten the iteration like: ```rust use rayon::prelude::*; use std::sync::mpsc::channel; fn main() { let (sender, _recever) = channel(); (0..5) .into_par_iter() .flat_map_iter(|i| (0..5).map(move |j| (i, j))) .for_each_with(sender, |sender, (i, j)| { sender.send(i + j).unwrap(); }); } ``` You could also consider not using `Sender` rayon is probably mean to be use with `collect()` and instead of sending the item you could just collect them at the end.
`Sender` is made to be cloned, its literally [in the docs](https://doc.rust-lang.org/std/sync/mpsc/fn.channel.html). Each child thread has to have its own sender.
68,694,853
When I tried to implement an express get service call with a mongoose find method it is giving me '*Product.find*' is not a function error. FYI-'Product' is the mongoose model which I imported . ROUTES FILE ----------- ``` const express = require('express'); const routes = express.Router(); const Product = require('../models/product'); routes.get('/',(req,res)=>{ const list= Product.find(); res.send(list); }) ``` MODEL FILE ---------- ``` const mongoose = require('mongoose'); const productSchema = mongoose.Schema({ name:String, subject:String }) exports.Product = mongoose.model('Product',productSchema); ``` ERROR ----- ``` TypeError:Product.find is not a function. ```
2021/08/07
[ "https://Stackoverflow.com/questions/68694853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7697231/" ]
When you are exporting the model like `exports.Product`,you need to import the model in routes file as an object. ``` const {Product} = require('../models/product'); ``` OR we can use `module.exports` instead of `exports.Product` without making any changes in the import of routes file.
Because you are not importing your model in route file. Better if you can use `module.exports` instead of exports.Product.