source
stringclasses 1
value | task_type
stringclasses 1
value | in_source_id
stringlengths 1
8
| prompt
stringlengths 209
40.4k
| gold_standard_solution
stringlengths 0
56.7k
| verification_info
stringclasses 1
value | metadata
stringlengths 138
225
| problem_id
stringlengths 9
10
|
---|---|---|---|---|---|---|---|
stackexchange | llm_judgeable_groundtruth_similarity | 19804089 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I'm listening for an event with socket.io, once that fires I'm trying to update a record to a new value. socket.on('contentEdited', function (newContent) {collection.update( { '_id' : ObjectId("5279262e74d92da751eb2b8e") }, { $set: { 'content': newContent } } ), function (err, result) { if (err) throw err; console.log(result) };}); The syntax works in the shell, but throws the following error in node when the event fires: Error: Cannot use a writeConcern without a provided callback I tried adding an function at the end afterwards for basic error checking, but I'm not sure how to provide a callback in the way mongo expects. Still kinda new to this, thanks
Now provide the response and nothing else.
| I think your problem is that the callback function needs to be inside the update function call instead of outside it. The format for the nodejs MongoDB driver can be found here: http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#update So it should look like this: collection.update( { '_id' : ObjectId("5279262e74d92da751eb2b8e") }, { $set: { 'content': newContent } }, function (err, result) { if (err) throw err; console.log(result); }) Note that the parentheses has moved after the callback function. You could also set the write concern to "unacknowledged" instead of "acknowledged." The MongoDB concept of "Write Concerns" determines how certain you want to be that MongoDB successfully wrote to the DB. The lowest level of write concern, "Unacknowledged" just writes data to the server and doesn't wait to response. This used to be the default, but now the default is to wait for MongoDB to acknowledge the write. You can learn more about write concerns here: http://docs.mongodb.org/manual/core/write-concern/ To set the write concern to unacknowledged, add the option {w: 0} : collection.update( { '_id' : ObjectId("5279262e74d92da751eb2b8e") }, { $set: { 'content': newContent } }, { w : 0 }); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19804089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2318064/']} | jdg_72041 |
stackexchange | llm_judgeable_groundtruth_similarity | 77834 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a quick and dirty way to generate a list of numbers from 1 to some arbitrary large number in order such that the digits of each number are only 0's, 1's, and 2's? I tried doing n = {0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2};v = Sort @ Rest @ DeleteDuplicates[ FromDigits /@ (Cases[ Permutations /@ Rest @ DeleteDuplicates @ Subsets[n], {x__?(Head[#] =!= List &)} :> {x}, -1])]; but it slows down pretty fast, so I don't think I can add any more entries to n . (Also, still not sure how to copy-paste Mathematica code in here so it looks exactly like it does in Mathematica )
Now provide the response and nothing else.
| A possibly more general function to be aware of is Tuples : FromDigits /@ Tuples[{0, 1, 2}, 4] {0, 1, 2, 10, 11, 12, 20, 21, 22, 100, 101, 102, 110, 111, 112, 120, 121, 122, 200, 201, 202, 210, 211, 212, 220, 221, 222, 1000, 1001, 1002, 1010, 1011, 1012, 1020, 1021, 1022, 1100, 1101, 1102, 1110, 1111, 1112, 1120, 1121, 1122, 1200, 1201, 1202, 1210, 1211, 1212, 1220, 1221, 1222, 2000, 2001, 2002, 2010, 2011, 2012, 2020, 2021, 2022, 2100, 2101, 2102, 2110, 2111, 2112, 2120, 2121, 2122, 2200, 2201, 2202, 2210, 2211, 2212, 2220, 2221, 2222} This is a bit faster than using IntegerDigits : FromDigits /@ Tuples[{0, 1, 2}, 12] // Length // TimingFromDigits /@ IntegerDigits[Range[0, 531440], 3] // Length // Timing {0.312002, 531441}{0.530403, 531441} | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/77834', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/24634/']} | jdg_72042 |
stackexchange | llm_judgeable_groundtruth_similarity | 58923065 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When styling a React Native app with Styled Components 5.x I'm getting the warning... Expected style "borderWidth: 2" to contain units. This didn't happen with previous versions. What does the warning mean?
Now provide the response and nothing else.
| After some research and questions on github I tracked this one down... Styled Components uses the package css-to-react-native for it's React Native conversions. css-to-react-native recently released version 3 which now requires units to be present for all measurements. Details here . You should use px for React Native as it is density independent . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58923065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/25197/']} | jdg_72043 |
stackexchange | llm_judgeable_groundtruth_similarity | 42395034 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am receiving a bindata from the Nodejs server and now from that I need to display an image. How can I achieve this? Is there any method to convert bindata to JPEG or any other format? Or is it possible to convert that in server and then send that image to react? Here's how I'm trying to display the binary data ( item.Image.data.data ) with an image tag: <img src={item.Image.data.data} /> This is my detailed react code snippet: componentDidMount(){ let self = this; axios.get('http://localhost:8080/list') .then(function(data) { console.log(data); self.setState({post:data.data}); });}<ul className="w3-ul w3-card-4 w3-light-grey"> { this.state.post.map((item, index) => { return ( <Link to="/displaylist" style={{ textDecoration: 'none' }} key={index}> <li className=" w3-hover-green w3-padding-16" onClick={this.handleClick(item.Id)}> <img src={item.Image.data.data} className="w3-left w3-circle w3-margin-right" width="60px" height="40px" /> <span>{item.Firstname}</span><br/><br/> </li> </Link> )} )}</ul> This is my nodejs code snippet: server.get('/list', function(req, res) { databaseInterface.listStudent(function(err, students) { var myJSON = students; res.json(myJSON); // You should see the newly saved student here });});
Now provide the response and nothing else.
| If the binary data is represented as a base64 string : // Base64 string dataconst data = 'iVBORw0KGgoAAAANSUhEUgAAAFgAAABSCAYAAADQDhNSAAAABHNCSVQICAgIfAhkiAAAFN5JREFUeJztnHl0FFW+xz/VS3rLTkJ2EkICIWEzgICIw8Ao6KCo4zDKuM04bqjPJyLqoAj6VBREHcVtBnXUcUMU3BVUhFFQQJEQkwhJyJ6Qfe10ernzRzVFd9JJukOKd857+Z6Tc6qr7vKrb27d+t3f73tLSk1NFQxBNWj+tw34v44hglXGEMEqY4hglTFEsMoYIlhlDBGsMoYIVhlDBKuMIYJVhu6UdxgaTsSkGZjiRoBGg62umtZfDtFRcliV/szJaYSMHo8hKhZcLqxVpTQe2I2jpUmV/rrjlBGsMZpJ/fPtxJ27CI0+qMd1a3U5NdvepfLDN7A3N5xUX/rwSOJ/exkxZ1+MKTaxx3WXvYuqT96m6MXHcHV2nFRf/UE6FcEeXXAoEx95heBRY/st6+y0UrHlFUrfeg6nNbCb15rMjPjDDSRceCVao6nf8m2Fefx011U4WpsD6icQnBKCx61+jmHTfg2AEIKW3P005exFOJ2YEpKJmDidoMhorzq2ump+eeo+Gr7b4VcfkdNmM/qW1fJU4IYQAntjHY0/7cFaUYKk1RI+fiphWZNBkgCo/24Hh+67fnBu1AdUJzhy6q8Y/8ALAAiXk/x1d3Hsy/e7WaEhcsoskhZdR/j4KcppIQRVH79F4fMP4eqy+Wxfozcw6oa/EnfeH5DcpAkhaD60n7K3X6Bh3y4QLq86w+dcQMayNUgaLQA5K6+j4fuvB+uWvaCNiIhYpUrLbqQtuRdTfDIIQfm7L1O++UUfpQTWyhJqtr1LW2EeoZmnobOEIEkSIaPHETnlLBr27cTZ0eZVyxAdx4SHXiRq+hwkSUIIga22ioLH7qL4xXVYK0uAnuOnvbgArclCWGY2APqQ8J7/9EGCqm6a1hxM+KQZALicTsre+Ue/dep3f8G+6xdQ/fm7IGRyQtKzyH5yE8Hp45RywenjyH5yEyHpWYA8amu2vce+6xdQv/uLfvspe2cjLocDgPBJM9CagwO+P3+gKsGhYyag0cmOSkv+AexN9X7Vc1rbKVh/N/nr71amhqDIaCY9+grhp51B+GlnMOnRV5R529llo2D93RSsvxuntd2vPuxN9bTkHwBAo9MROmZCoLfnF1R108wjRinHbYdzA65fs+09OsqKGbfqGYLCh6E1WRi/+jkANEEGALqa6sldtUQhKxC0HT5E+Lgpiq2NP34bcBv9QdURHBQ5XDnuPFY5oDZa8w9wYOlldFaXAzKxx8ntrC7nwNLLBkSubFOVT1sHE+rOwSazctz9BRUIrJUlFL20vsf5opfWu19kA4OnTZ62DibUjUW43SZAeWENBObkdEbfsqrH+dG3rMKcnD7gdr1s8rR1EKEqwZ6+q9Y4sBESFBHF+AdeQBccCoCtoRZbQy0grxDHP/AC+oioAbXtOWp787NPFqoS7LkE1YdFBFxf0geRtXIDxuHxcnvtbeSs+As5K/6Co11+vI3D4xm3cgOSj/hGf9CHnrBJreWyqgTb6muUY0N0bB8lfSP9ppWEjp0EgHA6+PnBW2kvzqe9OJ+fH7wV4ZT92NCxk0i/6b6A2/e0ydPWwYSqBB9/8wPyai4AxM67hLj5vwfkRUTh82to/OHfyvXGH/5N4QtrlN9x8y8hdt4lAfVhik9R2ve0dTChKsEdZYXKsTnF/5eROSWdtCX3Au4V2vYtVLz/ao9yFVtfpXrbe8rvtCX3BthPmk9bBxOqLjTsTQ3YGmoxREajDw7DGJtEZ3VZr+X1YZEYomLIuGMtWoNRPuly4WhvYdT1f0XS6ZE08pgQLhfCYcfR3opwOpG0WrQGI5l3PU7+2juw1dX0GVc2xiahDw4DoKuxDnvTycWge4PqAffWX3IwTJ8DyHNl57EKzEmjCB41FktKOuakUZgSkjHGJKA19IzhSlotiRde5Xd/lpR0Jm/YAoDTZqWzpgJrRQkdZYW0Hz1MW2EeHWWFytx+3Ea1oHq4MmnRtaT+eRkgu1g6k0U1p95fOK0dOKztGNyxjKKN6yjb9HdV+lKFYI3RxLDpc4ieeQ4Rk89E10+kSgihxHKPo6Ugh5bc/TjaW3F2duDqsuGyd52I7UoaNPogNEEGtEYzOksIoVmTCR0zvs92fcHR0Ubj/n9T+83n1O/5ElenNfCb7gWDSnDI6PHEL7iM6Fnz0ZosPsscf2O3HcmlrSifjtIjdJQfJeH8xcQvWAyAvbmRvdedF3BuTh8WydQXPlZ87soP36Dig39hTkzBPCKd4NQxBKdlYYxN7JV4p7Wd2l2fUvnhG4MydQwKwRHZM0levISwcVN6XBNC4LJ1Kjmyo6/8jZLXN3iVsaRmMPmpzUhaHUII8tcuH3AAfPicCxi7fK3ct9PB/lt+R3tRvleZ5MU3kXLlfwFyDlBrMPpcKjcf2kfJ68/Q+MM3A7IFTjKjYUpMJfOux0i5/BZltQUyqW2FeVS8+xKHn15N6+EcomfNB0BjMFL96SavdrLufQpjTAIAjft2UfziuoGaRHtxAaFjJmJKSEbSaLCMHEP1Z5u9yqRecweGqFj5n7luOUUvPkZXXTW60AhlXgZ5lRgzdyFhmZNpKcjB0dIYsD0DHsGJF1/NyKuXKqFDAKetk5ovtlL54eteo0ZrsjDjzW/RGowIIfj+T2cr7prniHPaOtl3/W9P2uk3xiYy5fmPFFcv79E7lCfCGJvE6S9tQ5IknLZOdl96hleQ3pKaQfyCxcTMXXjCVUSOVRS/vJ7yd18OyJaAR7Ck0zN2+VqSfncNklb28lz2Liref5Wf/+dWar/+CHtjnVcd4bDLbllyGpIk4WhtpjnnezQGI+PuewadJRghBKVvPkf9t9t9G2qyEDVjLtGz5hE+4XSCwodhq61COOw9yjraWpC0OsInTgMgdPQEKj9+E+F0kLDwSiLc5+t3b+8xFdkb62j47iuqPn0HSaslOC0TSatF0uqInDwLc+JI6vd8BS5Xj3592h0QwRoNWfc8pTzucvZ2Hzn3XMuxrz7sU8ThsncxfPYCAAwxCVRsfZWk319L1Bm/AeQ0fd7DS5X4gicSLrqKcaueJWbuQsInTiN84jSizzqX+PMX47J30eoj4N5acJCYuReis4SgswTj6rLRnLufMUsfRh8cihCC4pfWYy0v9m1vZ4fsWez8BEtqhjKFWVJGYxk5htpdn/gVgg2I4JQrbyX+3EWATG7Zpr+Tv+5Ov+amzqoy4s5dhNZkQR8cirXiKCOvvg1NkAEhBEc23E/bkZ5ppfSbV5G8eInXVHQcmiADkVNmERQeRcP3O7yuCacDe3MD0TPPAeTEqe1YFXHz5XiFvbGOw0+v7pHS7w5HaxM1X2xBow8iNDMbSZIwJ6UiabQ0/bSn3/v2m2BT4kgy73oMSaNBCMHRV56k5NW/+R9IFy70oeGKpzHs9F8pC472onyOPHN/jyrDZy8g9c+399t0yOjxWMuP0n70F6/z7Ud/IWrGXIIio9EEGRh2+q+Uaa1i62s0/uindyAETT/uRricREyaDkBY5mkc2/lJvxo3v4M9CQuvUIxr3LeL0jee9beqgsqP30I4nXLH7hEphKD4n4/7/EclL17id9s+ywpB8cuPKz+VPp1OKj9+MxDTASh941nq98oCFUmrI2HhFf3W8ZvgiOyZsnFCUPLGMwEbB2CrqaBuj7dmoTX/J5+qGmNskldWuj+YR4zC6EPo17D3a1ryvOfouj1fYBtgEtZzYB3npC/4TbAxOk45bi0Y+Aqn8oPXvX6XbfItRjEMj/N5vi8YPHzxvvrobkMgaC3IQbifNmO07/484TfBTvf6XJIkdCFhAzQPgtMyvX6HZEz0Wc5l6wyoXXnF6DuG0L2PkLSsgNr2hC4kTFlmO/2QvvpNcFtRnnJ83N0KGBotCRd4z1sJ5y9GHxbZo2h7yeGAEpHC3kV7yZEe5/VhkSScv9jrXPwFl4Nb+Bcohs/+rXLsyUlv8JvgY19+oBwn//EmjDE957v+EDVjDsZuj77WZCFp0XU9yro6rRz7+iO/2z729Uc+o2BJi67rEXgyDo8jasYcv9tW6sUkkvzHmwH5ifHkpDf4TXDNF1tod8v89SFhTHhoY69zXm+IO+9S5bjxwG7lOOH8xT7bKn5pPV3dVoW+0NVYR7EPYYohOk4ZvUIIrz49bfEHhuHxTHhoI3r39NhReoSaL7b0W89vgoXTSd6a2xXVuSkhhewnN/n1JgV59RZx2hkAuBx28h9ZRtPB72UjggyMvPq2HnW6Gmo5uOIaOmurelwDd+iztoqDK66hy62V8IRnrKQ5Zy/5jyzD5V5aR5x2Bgb36qw/RGTPJPvJTZgSUgA5YJ+3ZpnicvaFgFZy9qZ6Wn45SPSZ89Do9GhNZobPuQBjbCKtBT/1KflPWHgFEW4pa/2eL6n+7B06SguJnf97JEnCkpJOw75ddHVLn9sb66j+7B1cXTb04cPQh4aBEHSUFlH5wb/IX3unT5crZMwE0m5coeiG8x6+DWt5MSFpmZiTRiFJEvbWJppz9vZqc1BkNGlLVpJ67Z3o3NOMs9PKofuX0Jrnnx5uQNG04PQssu592itE6ey0Uvnxm1S8909sPkbc1L9/gjkpFSEEufffpGh4M+5cR8yvzwegpeAgP/73or5XhxqNfL2vMpLEaU+8rUhSa776gPxH5LTVsBlzGXef7Md3lBWx99pze1Q3RMeRcNFVxJ93qRLHPi7uzn3g5oCUogNK27cdzmX/jQup3vae4hNqjSaSLv4T017eTtbKDQybPhdJpwfAMnIM5qRUQI50NezdqbRVvHGd4u6EjplA3PxFfXfucvW7PI+bv0gh19nZQfHGE/Hlhr07sbtVPOakVCwjxwBylHDY9LlkrdzAtJe3k3Txn7zIrdm+hf03LgxYhnvSGY3QrMmkXrNMkeN7wt7WQsN3X6EJMigRuOrPN1Ow/q9e5UZcej0jr14q12ltltNFfrzcfEEfESWnjULC5JjJy49T+tbzXmXGLH2I2HN+B0Dtrk9xddmInPZr9G7923EIIWjJ+5Gijetoyd0/IHtOeo+GrbaK6s8203xoP/rQCExxIxRHXBtkIDg1A0vyCYFHV2O9PC+6nPJIEoKW/INEnTmPoLBItAYjxthEand+MiB7MpatUbYVdJQVkb/uTnnUa7SYR4wicsosQjOzFaWRJTmN4NQMtB7ROuFy0bB3J4efXsXRfz7hc8rzF4OeVTbGJBLzmwsZPnsB5qSRfZZ1dXXRUVGMtbwYXXCo4mUA5D92N3XffC5nG/qL2EmSHJCfeTYZt5+QUzX++C2OthZMiSMxJ4xEE9S7QFAIgbW8mGM7PqJm+3t01lT4d8P9QFVdhDklneRLb/Ra/QQK4XLhsllxdtkQdjvCJbtGkkaLpNejDTKgMZgUxc9AcGzHR5S8+SwdRwd/O6+qyp6Oo4ext56Il1Z9uglrZSkh6VkEj8qU0+f9ECNpNGhNll5lAP5AuL2Ozupy2gp/pvVwLqb4EYq40N7apAq5cAqkU6EZbvmp+03cfGifck1jMGFOTMGUkIIxJhHD8DgMUbEMO302klar1OsPnhoH4XRS//0ObHXV2I5V0VlTjrXiKB3lR72CQWHjpigEH7dRDahKsKTTYUkZLf9wuWjt5uK4bFbaCvNoK/QOmiRffgspl9+s1MtZeT0t+QfQ6PUguUe8cOGy2wkdO4nxq59H0mrdsepnKXntqX5taz2cq4gGLSmjkXQ6hKNnPvBkoap81ZQwUiYFeSNLb+HE7ih5fYOyjJa0WjKWrUFnsmBvasDeWCf/NTWgM1nIuH2NMtqbc/b2ELX0BpfNqmyg0ej1mBL6fiEPFCoTfEJ03VFW5H9Fl4u8NUuV+EJQRBRZ921A46FT0BiMZN23gSD3/oyuhlry1iz1O50O0FF+wiZPWwcTqhLsmQXprAlMTNLVUEvug7cqwZmQ9HFkLF8rS5wkiYw71hLi3lrrctjJffBWnwGfvtBZdcImT1sHE6oSrA8fphwHevMALbn7OfL0/YofHD3zHNJuWEHaDSuIPlNOxx9P+Q9kpdXVeMImT1sHE6q+5HTmE66Vo611QG1Uffo2psQUki65BsArkyuEoHzzi1R98vaA2na0n7BJax64G9gX1N2IqD3x/3M5e0qc/EXRxrUc2/Gh1zkhBLVff0zRxrUDbtdTdiVp1RlrqhIs7CduwNd3evxvSNDRTeIkSZL8kjqJHaSee+uEvWvA7fQFdTfBeEiqgsIGOMdJEqOuu4vEi67ucSnl8lvQWULk7VwDINrTJrtKX6FSlWDPgMnxeHAg0BjNZNzxiKIvE0LQuG8XAJFTzwIg8aKrMQxPIH/t8oC/IOVp02AFd7pD1Smi7cjPynHY+KmA/xuuzUmjyH7ibS9ya3d8xKHVSzi0eonXnBw982yyn3gbc5L/SiAkyW2TWzDuYetgQt2NiKVHsNVVA2CIiiFi8pn9V5I0JCy8guynNmNxbyoUQlD61vPkPboM4bAjHHbyHllGyZvPKbEKS0o62U9tlr0Mqf/bisg+E0NUDABd9TV0lPbUVAwGVP8oki40QvmqSHB6JjXbt/oUTQOET5xO5ooniJt3CRp3usnR0U7BuuVUbu2507PpwB46ygqJmDxL3nGk0xM59SyGTZuNtbK018WN1mQh854nCXILXiref42mA/1LUQcC1ffJ6cMiOX3jZ8rnCNoK8yj8xyM05+xDuJyYYpOIyJ5JzNkXeX03RwhBa8FB8h+9o9+Pbpjik8lYvpbQbhKploKD1Gx7j8YfvsFaXYak0RI2fiqj/rJc+Uieo62F76+Zd9JfG+wNp+TDdNGz5jP27se9Yr/HY7S+4sGO9laOvvY0FVtf8T+2oNGQsPBKUi6/GZ0lpMdl4XKBJHmHNl0u8h6+jdpdnwZ+U35C9SkC5LnYWl1O5OQzlUdf6n6zQuC0tlOx9VXyHr6NpgO7A3O9hKA1/wDVn70DkoQlZbSX7929P2enlYIn7qF2h//yrIHglIzg4zBEx5Fw4VVETj1L/vqqJNFVX0PrLznUf7eDum8+C/h7lb1BazITNXMew6bNJmT0eIKGxYAQWKtKadi7k4otvvUbg41TSvD/Rwx9oFllDBGsMoYIVhlDBKuMIYJVxhDBKmOIYJXxH4r7WLwgFoGBAAAAAElFTkSuQmCC'const Example = ({ data }) => <img src={`data:image/jpeg;base64,${data}`} />ReactDOM.render(<Example data={data} />, document.getElementById('container')) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="container"></div> If you just have an image URL, you can simply do : const imageURL = 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/1280px-React-icon.svg.png'const Example = ({ imageURL }) => <img src={imageURL} width={100} />ReactDOM.render(<Example imageURL={imageURL} />, document.getElementById('container')) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="container"></div> | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/42395034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7413709/']} | jdg_72044 |
stackexchange | llm_judgeable_groundtruth_similarity | 69504 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have seen many proofs about a prime element is irreducible, but up to now I am thinking whether this result is true for any ring. Recently, I got this proof: Suppose that $a$ is prime, and that $a = bc$. Then certainly $a\mid bc$, so by definition of prime, $a\mid b$ or $a\mid c$, say $a \mid b$.If $b = ad$ then $b = bcd$, so $cd = 1$ and therefore $c$ is a unit. (Note that $b$ cannot be $0$,forif so, $a = bc = 0$, which is not possible since $a$ is prime.) Similarly, if $a\mid c$ with $c = ad$ then $c = bcd$, so $bd = 1$ and $b$ is a unit. Therefore $a$ is irreducible. I think with the above proof we do not need the ring to be an integral domain. If this is the case then I will stop doubting, else, I am still in it. Can somebody help me out?
Now provide the response and nothing else.
| Notice that your proof assumes that $\rm\: b\ne 0\ \Rightarrow\ b\:$ is cancellable, so it fails if $\rm\:b\:$ is a zero-divisor. Factorization theory is more complicated in non-domains. Basic notions such as associate and irreducible bifurcate into a few inequivalent notions. See for example When are Associates Unit Multiples? D.D. Anderson, M. Axtell, S.J. Forman, and Joe Stickles. Rocky Mountain J. Math. Volume 34, Number 3 (2004), 811-828. Factorization in Commutative Rings with Zero-divisors. D.D. Anderson, Silvia Valdes-Leon. Rocky Mountain J. Math. Volume 28, Number 2 (1996), 439-480 | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/69504', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16942/']} | jdg_72045 |
stackexchange | llm_judgeable_groundtruth_similarity | 30300279 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Golang, we can specify open source libraries on GitHub as dependencies. For example: import "github.com/RichardKnop/somelibrary" This will try to look for a branch based on your Go version and default to master if I understand correctly. So there is no way to import a specific release of a dependency, e.g.: import "github.com/RichardKnop/somelibrary#v1.4.8" What is the best practise to manage dependencies in Go then? I can see two approaches. I. Version Modules Is it to create new modules for major versions with breaking changes? For example, my Go library could define modules v1 and v2 so then you could do: import "github.com/RichardKnop/somelibrary/v1" Or: import "github.com/RichardKnop/somelibrary/v2" Based on what you need. Any changes made to v1 or v2 would be required not to break any APIs or working functionality. II. Forking This would give you a complete control over a version of external dependency your Go code requires. For example, you could fork github.com/RichardKnop/somelibrary into your own GitHub account and then in your code do: import "github.com/ForkingUser/somelibrary" Then you would have to fork all external dependencies which seems a bit overkill. However it would give you total control over versions. You could keep your forks at a version you know is working with your code and only update forks once you have checked that new releases of dependencies do not break anything. Thoughts?
Now provide the response and nothing else.
| Note: June 2015, the first support for vendoring appears in Go 1.5! See c/10923/ : When GO15VENDOREXPERIMENT=1 is in the environment, this CL changes the resolution of import paths according to the Go 1.5 vendor proposal: If there is a source directory d/vendor , then, when compiling a source file within the subtree rooted at d , import "p" is interpreted as import "d/vendor/p" if that exists. When there are multiple possible resolutions, the most specific (longest) path wins. The short form must always be used: no import path can contain “ /vendor/ ” explicitly. Import comments are ignored in vendored packages. Update January 2016: Go 1.6 will make vendoring the default. And as detailed in the article "MOST GO TOOLS NOW WORK WITH GO15VENDOREXPERIMENT" : 1.6 brings support for /vendor/ to most tools (like the oracle) out of the box; use the Beta to rebuild them. issue 12278 has been resolved. there still is an issue with goimports , and there is a CL that can be cherry-picked . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30300279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95944/']} | jdg_72046 |
stackexchange | llm_judgeable_groundtruth_similarity | 2676755 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I get really frustrated that all these real analysis books and online webpages say $S(n) = n + 1$ but then say addition is defined in terms off the relationships $a + 0 = a$ and $a + S(b) = S(a+b)$. I feel like this is a bit of a circular definition because we haven't really defined $S(n)$ and I don't like labeling it "$S(n) = n + 1$" because that feels like a cheap way of appealing to intuition when the whole point of analysis is to rigorously define the very things we normally take for granted and find obvious so that we more accurately understand what we are and are not permitted to do with these numbers. Can we just treat it as a mapping to some other distinct element? If I look at it this way then I would end up defining axioms like this: Zero is a number. If $a$ is a number, then the successor of $a$, denoted $S(a)$, is a number. $a$ and $S(a)$ are considered distinct numbers. If two numbers have the same successors, then they themselves are equal numbers. Zero is not the successor of any other number. So I am envisioning a sort of linked-list relationship: $$0 \rightarrow \alpha \rightarrow \beta \rightarrow \gamma \rightarrow \delta \rightarrow \epsilon \rightarrow \zeta \rightarrow \eta...$$ The labels are arbitrary but I am seeing natural numbers as just nodes linked together where successor just means "whatever this node points to". So you wouldn't see something like $\alpha$ (or anything else) point to two different nodes, or anything pointing to $0$, or anything pointing to itself. And then if we want to compute $\beta + \gamma$ using our definition of addition we see that: $$\beta + \gamma = \beta + S(\beta) = S(\beta + \beta)$$ $$\beta + \beta = \beta + S(\alpha) = S(\beta + \alpha)$$ $$\beta + \alpha = \beta + S(0) = S(\beta + 0)$$ $$\beta + 0 = \beta$$ Combining: $$\beta + \gamma = S(S(S(\beta)))$$ Which makes sense intuitively, taking the third successor to $\beta$. And if we want to define $\beta$ relative to $0$ or its eventual node in the list we could replace it with successors and then show that $$\beta + \gamma = S(S(S(S(\alpha)))) = S(S(S(S(S(0))))) = \epsilon$$ I mean is this the right way to think of it? Am I right to find $S(n) = n + 1$ problematic or am I missing some point as to why it's always defined this way?
Now provide the response and nothing else.
| Yep, that works as a successor function! You do need to make sure the number concept is the minimal concept, otherwise you might have a set that has more than the nodes in the linked-list. Otherwise, the way your doing it is actually pretty swell, and you're right to find the "naive successor function definition" problematic and cyclic. A successor function $S:\mathbb{N}\to \mathbb{N}$ is any function from which follows the following properties: For all $x\in \mathbb{N}, S(x) \neq x$ $S$ is one-to-one. There is some element $e\in\mathbb{N}$ such that, for all $x\in \mathbb{N}, S(x) \neq e$ Also, $\mathbb{N}$ is the minimal set on which you can define such an $S$. Any such function and any such set can be one type of successor function. Note, the only things needed for that definition is logic, sets, and functions. I never use addition or zero or any sembalence of numbers. Also, the successor function needn't be unique; multiple different implementations can fit this "successor interface." You can check out a video by PBS on defining the successor function here . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2676755', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/537069/']} | jdg_72047 |
stackexchange | llm_judgeable_groundtruth_similarity | 9186395 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to read an object method's local value from a decorator that wraps it. I've got access to the function and func_code from within the decorator but it seems all I can get out of it is the names of the local vars, but not their values. Is it possible?
Now provide the response and nothing else.
| See https://stackoverflow.com/a/4249347/224295 , http://code.activestate.com/recipes/577283-decorator-to-expose-local-variables-of-a-function-/ Working example: import sysclass persistent_locals(object): def __init__(self, func): self._locals = {} self.func = func def __call__(self, *args, **kwargs): def tracer(frame, event, arg): if event=='return': self._locals = frame.f_locals.copy() # tracer is activated on next call, return or exception sys.setprofile(tracer) try: # trace the function call res = self.func(*args, **kwargs) finally: # disable tracer and replace with old one sys.setprofile(None) return res def clear_locals(self): self._locals = {} @property def locals(self): return self._locals@persistent_localsdef func(): local1 = 1 local2 = 2func()print func.locals | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9186395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/159241/']} | jdg_72048 |
stackexchange | llm_judgeable_groundtruth_similarity | 25068032 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While trying to know how long a line of C code used to execute, I noticed this weird thing : int main (char argc, char * argv[]) { time_t begin, end; uint64_t i; double total_time, free_time; int A = 1; int B = 1; begin = clock(); for (i = 0; i<(1<<31)-1; i++); end = clock(); free_time = (double)(end-begin)/CLOCKS_PER_SEC; printf("%f\n", free_time); begin = clock(); for (i = 0; i<(1<<31)-1; i++) { A += B%2; } end = clock(); free_time = (double)(end-begin)/CLOCKS_PER_SEC; printf("%f\n", free_time); return(0);} Which when executed displays : 5.8734254.826874 Why does the empty loop use more time than the second which has an instruction within ? Of course I've tried many variants but everytime, an empty loop takes more time than one with one single instruction within. Note that I have tried swapping loops order and adding some warmup code and it didn't change my problem at all. I'm using codeblocks as IDE with GNU gcc compiler, linux ubuntu 14.04 and have a quadcore intel i5 at 2.3GHz (I've tried running the programm on a single core, this doesn't change the result).
Now provide the response and nothing else.
| The fact is that modern processors are complicated. All the instructions executed will interact with each other in complicated and interesting ways. Thanks for "that other guy" for posting the code. Both OP and "that other guy" apparently found that the short loop takes 11 cycles, while the long one takes 9 cycles. For the long loop, 9 cycles is plenty of time even though there are lot of operations. For the short loop, there must be some stall caused by it being so short, and just adding a nop makes the loop long enough to avoid the stall. One thing that happens if we look at the code: 0x00000000004005af <+50>: addq $0x1,-0x20(%rbp)0x00000000004005b4 <+55>: cmpq $0x7fffffff,-0x20(%rbp)0x00000000004005bc <+63>: jb 0x4005af <main+50> We read i and write it back ( addq ). We read it immediately again, and compare it ( cmpq ). And then we loop. But the loop uses branch prediction. So at the time when the addq is executed, the processor isn't really sure it is allowed to write to i (because branch prediction could be wrong). Then we compare to i . The processor will try to avoid reading i from memory, because reading it takes a long time. Instead some bit of hardware will remember that we just wrote to i by adding to it, and instead of reading i , the cmpq instruction gets the data from the store instruction. Unfortunately, we are not sure at this point if the write to i actually happened or not! So that could introduce a stall here. The problem here is that the conditional jump, the addq which leads to a conditional store, and the cmpq which isn't sure where to get the data from, are all very very close together. They are unusually close together. It could be that they are so close together, the processor cannot figure out at this time whether to take i from the store instruction or to read it from memory. And reads it from memory, which is slower because it has to wait for the store to finish. And adding just one nop gives the processor enough time. Usually you think that there is RAM, and there is cache. On a modern Intel processor, reading memory can read from (slowest to fastest): Memory (RAM) L3 cache (optional) L2 cache L1 cache Previous store instruction that hasn't written to L1 cache yet. So what the processor does internally in the short, slow loop: Read i from L1 cache Add 1 to i Write i to L1 cache Wait until i is written to L1 cache Read i from L1 cache Compare i with INT_MAX Branch to (1) if it is less. In the long, fast, loop the processor does: Lots of stuff Read i from L1 cache Add 1 to i Do a "store" instruction that will write i to L1 cache Read i directly from the "store" instruction without touching L1 cache Compare i with INT_MAX Branch to (1) if it is less. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25068032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3882647/']} | jdg_72049 |
stackexchange | llm_judgeable_groundtruth_similarity | 6538 |
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm aware that this is basically a duplicate question, but I don't have any rep in this community so I can't comment on it, and I don't think I should "answer" that question with my own question: No-cloning theorem and distinguishing between two non-orthogonal quantum states Exercise 1.2: Explain how a device which, upon input of one of two non-orthogonal quantum states $|ψ⟩$ or $|ϕ⟩$ correctly identified the state, could be used to build a device which cloned the states $|ψ⟩$ and $|ϕ⟩$ , in violation of the no-cloning theorem. Conversely, explain how a device for cloning could be used to distinguish non-orthogonal quantum states. The first part isn't quite trivial to me. Since the device can distinguish both $|\psi\rangle$ and $|\phi\rangle$ with certainty, they are effectively orthogonal states, and thus can be cloned when the device measures in the "basis" $\{|\psi\rangle,|\phi\rangle\}$ . Is this correct?
Now provide the response and nothing else.
| The Hadamard gate is: $$\frac{1}{\sqrt 2} \left(|0\rangle \langle 0 | + |0\rangle\langle 1| + |1\rangle \langle 0| - |1\rangle \langle 1|\right)$$ And since $|+\rangle$ is $\frac{1}{\sqrt 2}\left(|0\rangle + |1\rangle \right)$ , you can work out that $H(|+\rangle) = |0\rangle$ So, $$CNOT(H|+\rangle \otimes |+\rangle)$$ $$= CNOT(|0\rangle \otimes |+\rangle)$$ $$= |0\rangle \otimes |+\rangle$$ You can also check that $H^2 = I$ or that the Hadamard gate is both Unitary and Hermitian. $$H = H^\dagger$$ $$H^\dagger = H^{-1}$$ So, $H = H^{-1}$ , the Hadamard gate is its own inverse. What you have done is not projection of $|00\rangle$ to get the state $|\phi^+\rangle$ , but you just applied the unitary that takes the computational basis to the Bell basis. As you said in the comments, true, if you measure a state in a basis, you will get one of the basis vectors as outcomes with different probabilities. To see that, express the state in hand in the measurement basis. For ex: $$|00\rangle = \frac{1}{\sqrt 2} (|\phi^+\rangle + |\phi^-\rangle)$$ so you will get $|\phi^+\rangle$ with 50% probability and $|\phi^-\rangle$ with 50% probability. Similarly, on expressing $|++\rangle$ in the Bell basis as: $$\frac{1}{\sqrt 2}(|\phi^+\rangle + |\psi^+\rangle)$$ you get each of those states with 50% probability on measuring. | {} | {'log_upvote_score': 4, 'links': ['https://quantumcomputing.stackexchange.com/questions/6538', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/7816/']} | jdg_72050 |
stackexchange | llm_judgeable_groundtruth_similarity | 21140021 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Be warned I am new to C++. When I compile my program I notice that there is an .obj created for every class that I have. When I looked at other programs in my program files, I realized that these programs barely had any .obj's so I guess that I am doing something wrong. Also if I deleted the obj files from the release directory and tried to run the exe again and it still worked exactly as before, I know these files can't be pointless but... What is their use? Should it make them for every class file? - if not how do I resolve this? How do I put them in one directory like a folder called obj when I compile?
Now provide the response and nothing else.
| .obj files ( .o files on Linux/Unix) are compiled source files, there will indeed be one for each .cpp file, or more formally "compilation unit". They are produced by the compilation phase of building a project. These .obj files are then combined by linker either to an application, usually .exe file on Windows, or a library file, which on windows can be a .dll for dynamic library, or .lib for static library (which is basically a collection of .obj files in one packed into one file, see below). On Unix-like platform application usually has no extension, and dynamic library has .so extension, and static library has .a extension. You do not see .obj files or static .lib files with programs, because they are not needed at runtime, they are used only by linker. When you run the linking phase of building a project, linker combines all the needed .obj files into .exe and .dll files (or equivalent), which are used at runtime. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21140021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3198492/']} | jdg_72051 |
stackexchange | llm_judgeable_groundtruth_similarity | 3597682 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to iterate the installed fonts using javascript?
Now provide the response and nothing else.
| To start off, you might want to check what fonts are installed on the client. Read up on https://www.lalit.org/wordpress/wp-content/uploads/2008/05/fontdetect.js?ver=0.3 You need to have your own list of fonts to check, then you have an array of installed fonts by checking each of the list to see which one is installed. The difference in widths will tell you the availability of the fonts installed on the client's computers because the browser will fall back to its default font. So you probably need to do some invisible testing for text widths to determine if a font is installed. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3597682', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/397524/']} | jdg_72052 |
stackexchange | llm_judgeable_groundtruth_similarity | 1598294 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
For the variable Triangle $\Delta ABC$ with fixed vertex at $C(1,2)$ and $A,\,B$ having co-ordinates $(\cos t, \sin t)$, $(\sin t, -\cos t)$, find the locus of its centroid.
Now provide the response and nothing else.
| The parametric equation of the locus curve for centroid is $$\begin{align}\vec G &= \frac{1}{3} (\vec A + \vec B + \vec C)\\&= \frac{1}{3}[(1+\cos t+\sin t){\bf{i}}+(2+\sin t -\cos t){\bf{j}}] \\&\equiv x_G {\bf{i}} + y_G {\bf{j}}\end{align}$$ In fact, this locus is a circle and the details of it is given in the answer by marwalix. It's Cartesian equation is $$(x_G-{1\over 3})^2+(y_G-{2\over 3})^2={2\over 9}$$ So it is a circle centered at $(\frac{1}{3},\frac{2}{3})$ with the radius $R=\frac{\sqrt{2}}{3}$. This animation helps to visualize the locus better. As you can see, if one of the points $A$ or $B$ lies at the intersection of the two circles then all the points lie on a line and the centroid is $A$ or $B$ itself! | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1598294', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/301391/']} | jdg_72053 |
stackexchange | llm_judgeable_groundtruth_similarity | 11722749 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know we can have 'parents' and 'children' when we are talking about processes. But is it possible to get parent Thread name? I did my research, but I have found answer only for .Net Edit: I tried setting names: public class Main { public static void main(String[] args) { Thread r = new ThreadA(); r.start(); }}public class ThreadA extends Thread { public void run() { Thread.currentThread().setName("Thread A"); System.out.println("Here " + Thread.currentThread().getName()); Thread r = new ThreadB(); r.setName(Thread.currentThread().getName()); r.start(); }}public class ThreadB extends Thread { public void run() { Thread.currentThread().setName("Thread B"); System.out.println("Here " + Thread.currentThread().getName()); Thread r = new ThreadC(); r.setName(Thread.currentThread().getName()); r.start(); }}public class ThreadC extends Thread { public void run() { Thread.currentThread().setName("Thread C"); System.out.println("Here " + Thread.currentThread().getName()); }}
Now provide the response and nothing else.
| I know we can have 'parents' and 'children' when we are talking about processes. But is it possible to get parent Thread name? A thread does not have a reference to the parent thread so there is no way for you to get the name of the parent from a particular thread. In looking at the code, the parent thread is used to get daemon status, priority, and other information but the name is not stored in the new Thread object. You mentioned that you need to have the name of the threads so you can group those that "go together in a control flow". I would look into ThreadGroup s. They aren't used too often but you might want to in this case: ThreadGroup threadGroup = new ThreadGroup("mythreadgroup");Thread thread = new Thread(threadGroup, new Runnable() {...});...// then you can do such methods asthreadGroup.enumerate(...); With thread-groups you can tie multiple threads together. You can, of course, do this with a collection as well yourself. Edit: You mentioned that the real issue is how can you measure the "time spent" in each component of a distributed system – in this case the RMI handlers. I'm afraid there is no easy answer here. For wall clock, you are going to have to compare the System.currentTimeMillis() at the start of each RMI method call with the time from the end. You can also use the following code to test the CPU time used by the thread. ThreadInfo threadInfo = ManagementFactory.getThreadMXBean().getThreadCpuTime(thread.getId()); To get the "user" time you use getThreadUserTime(...) . I'm not sure thread-ids are reused so maybe all you need to do is record all of the thread-ids in your RMI calls in a collection and then note their CPU and user times in a monitoring thread. I suspect the RMI threads have a particular name so your monitoring thread could find the threads in the thread list to do this but you are not going to be able to determine which thread is handling which RMI request. Lastly, one thing to consider is to take time stamps at a number of points in the process and to pass this long[] around between calls. This would add some small percentage of data overhead but then you would be able to get a good feeling about the performance of the various different parts of your distributed system. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11722749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1527394/']} | jdg_72054 |
stackexchange | llm_judgeable_groundtruth_similarity | 28105905 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
is it possible to reverse the order of a tableView. I have searched a lot for a solution but all the results have not quite been a solution to what I am trying to achieve. They all suggest scrolling to the last position of a table with scrollToRowAtIndexPath and populating the data in reverse. But this doesn't work if the table content is dynamic and in some instances not all the cells have data. For example in a normal tableView the order is: label 1 label 2 label 3 empty empty scroll direction v V the desired result would be: scroll direction ^ ^ empty empty empty label 3 label 2 label 1 in this example if I used the suggested method of scrollToRowAtIndexPath and use the length of the array of objects, I would only get the third cell from the top. And end up with something like this: unwanted outcome: label 3 label 2 label 1 empty empty scroll direction v V any help would be great thank you.
Now provide the response and nothing else.
| To populate UITableView from the bottom : - (void)updateTableContentInset { NSInteger numRows = [self.tableView numberOfRowsInSection:0]; CGFloat contentInsetTop = self.tableView.bounds.size.height; for (NSInteger i = 0; i < numRows; i++) { contentInsetTop -= [self tableView:self.tableView heightForRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]]; if (contentInsetTop <= 0) { contentInsetTop = 0; break; } } self.tableView.contentInset = UIEdgeInsetsMake(contentInsetTop, 0, 0, 0);} To reverse the order of elements: dataSourceArray = dataSourceArray.reverseObjectEnumerator.allObjects; Swift 4.2/5 version: func updateTableContentInset() { let numRows = self.tableView.numberOfRows(inSection: 0) var contentInsetTop = self.tableView.bounds.size.height for i in 0..<numRows { let rowRect = self.tableView.rectForRow(at: IndexPath(item: i, section: 0)) contentInsetTop -= rowRect.size.height if contentInsetTop <= 0 { contentInsetTop = 0 break } } self.tableView.contentInset = UIEdgeInsets(top: contentInsetTop,left: 0,bottom: 0,right: 0)} Swift 3/4.0 version: self.tableView.contentInset = UIEdgeInsetsMake(contentInsetTop, 0, 0, 0) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28105905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/508761/']} | jdg_72055 |
stackexchange | llm_judgeable_groundtruth_similarity | 8740859 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My application uses native shared library (.so), I am loading it by calling System.loadLibrary("xxx") . It loads fine and I can call the native methods. I wonder if there is any possibility to detect which shared libraries application uses. I tried to list loaded libraries by PackageManager: PackageManager pm = getPackageManager();String applicationPackage = this.getApplicationInfo().packageName;ApplicationInfo ai = pm.getApplicationInfo(applicationPackage, PackageManager.GET_SHARED_LIBRARY_FILES);String[] soFiles = ai.sharedLibraryFiles; but it returns an empty list. It works only if my application uses some .jar libraries like com.google.android.maps which I specify by uses-library in the application tag of the manifest. How can I list .so libraries?
Now provide the response and nothing else.
| The solution is simple, many thanks to @ praetorian-droid try { Set<String> libs = new HashSet<String>(); String mapsFile = "/proc/" + android.os.Process.myPid() + "/maps"; BufferedReader reader = new BufferedReader(new FileReader(mapsFile)); String line; while ((line = reader.readLine()) != null) { if (line.endsWith(".so")) { int n = line.lastIndexOf(" "); libs.add(line.substring(n + 1)); } } Log.d("Ldd", libs.size() + " libraries:"); for (String lib : libs) { Log.d("Ldd", lib); } } catch (FileNotFoundException e) { // Do some error handling... } catch (IOException e) { // Do some error handling... } | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8740859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941518/']} | jdg_72056 |
stackexchange | llm_judgeable_groundtruth_similarity | 3001805 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In a lot of C++ API'S (COM-based ones spring to mind) that make something for you, the pointer to the object that is constructed is usually required as a ** pointer (and the function will construct and init it for you) You usually see signatures like: HRESULT createAnObject( int howbig, Object **objectYouWantMeToInitialize ) ; -- but you seldom see the new object being passed as a return value. Besides people wanting to see error codes, what is the reason for this? Is it better to use the ** pattern rather than a returned pointer for simpler operations such as: wchar_t* getUnicode( const char* src ) ; Or would this better be written as: void getUnicode( const char* src, wchar_t** dst ) ; The most important thing I can think of is to remember to free it, and the ** way, for some reason, tends to remind me that I have to deallocate it as well.
Now provide the response and nothing else.
| "Besides wanting error codes"? What makes you think there is a besides. Error codes are pretty much the one and only reason. The function needs some way to indicate failure. C doesn't have exceptions, so it has to do that through either a pointer parameter, or the return value, and the return value is idiomatic, and easier to check when calling the function. (By the way, there's no universal rule that ** means you have to free the object. That's not always the case, and it's probably a bad idea to use something that arbitrary to remind you of which objects to clean up.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3001805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111307/']} | jdg_72057 |
stackexchange | llm_judgeable_groundtruth_similarity | 18359599 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to set the jquery datepicker date format but it is not working, I have read few posts and answer already but none of them worked for me. Below is the code I am using please check and tell me where I am doing wrong. I am getting the datetime from Database as 2012-03-06 00:00:00 UTC <script> $(document).ready(function() { $(".datepicker").datepicker({ dateFormat:'MM-DD-YYYY' }).val(); }); </script> Also I tried <script> $(document).ready(function() { var dateTypeVar = $('.datepicker').datepicker('getDate'); $.datepicker.formatDate('dd-mm-yy', dateTypeVar); }); </script>
Now provide the response and nothing else.
| This 2012-03-06 00:00:00 UTC is not a valid JavaScript date, so the datepicker can't accept the value assigned. Date object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date setDate method: http://api.jqueryui.com/datepicker/#method-setDate Get the date in a compliant format, and then set the datepicker in this way. Code: $(document).ready(function () { var dbDate = "2012-03-06"; var date2 = new Date(dbDate); $(".datepicker").datepicker({ dateFormat: 'mm-dd-yy' }).datepicker('setDate', date2)}); Demo: http://jsfiddle.net/IrvinDominin/7ck7D/ | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18359599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2634485/']} | jdg_72058 |
stackexchange | llm_judgeable_groundtruth_similarity | 22848017 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a table that appears as follows: Time Name Cust_ID Num_Calls Num_Orders12.00 ABC 100 20 1012.25 PQR 102 23 1212.30 ABC 100 26 1501.00 ABC 100 26 1802.00 PQR 102 23 1404.00 PQR 102 25 20 How do I delete the earlier records for each "Name & Cust_ID" and keep the most recent one. The other fields in the record may change as I run them through my Access Database, but Name and ID remains the same. My output at the End of the Day should be: Time Name Cust_ID Num_Calls Num_Orders01.00 ABC 100 26 1804.00 PQR 102 25 20
Now provide the response and nothing else.
| You can use the existing Java methods to create a date: // takes the date encoded as milliseconds since midnight, January 1, 1970 UTCdef mydate = new Date(System.currentTimeMillis())// create from an existing Calendar objectdef mydate = new GregorianCalendar(2014, Calendar.APRIL, 3, 1, 23, 45).time Groovy also provides some streamlined extensions for creating Dates. Date.parse() and Date.parseToStringDate() parse it from a String. The Date.copyWith() method builds a date from a map. You can use them like this: // uses the format strings from Java's SimpleDateFormatdef mydate = Date.parse("yyyy-MM-dd hh:mm:ss", "2014-04-03 1:23:45")// uses a format equivalent to EEE MMM dd HH:mm:ss zzz yyyydef mydate = Date.parseToStringDate("Thu Apr 03 01:23:45 UTC 2014")def mydate = new Date().copyWith( year: 2014, month: Calendar.APRIL, dayOfMonth: 3, hourOfDay: 1, minute: 23, second: 45) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22848017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3495451/']} | jdg_72059 |
stackexchange | llm_judgeable_groundtruth_similarity | 182011 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a function G[x,y,z,r,s,t] in the code below. Quite simply, I want to generate a list of all possible tuples $(x,y,z,r,s,t)$ such that all six entries are taken from the set $\{0,1,2,...,N-1\}$ where $N$ will be an integer parameter of the problem. I then want to evaluate $G$ on each of these tuples and as efficiently as I can, count the number of the tuples which evaluate to 0 modulo $N$ . I at least have the following: G[x_, y_, z_, r_, s_, t_] := x*y*z*(r^3 + s^3 + t^3) - r*s*t*(x^3 + y^3 + z^3);F[N_] := Range[0, N - 1];Tup[N_] := Tuples[F[N], 6]; So Tup[N] is a list of all my tuples of interest. I was about to do a "for loop" ranging over the number of tuples and evaluate something like G[Tup[2][[4]][[1]], Tup[2][[4]][[2]], Tup[2][[4]][[3]], Tup[2][[4]][[4]], Tup[2][[4]][[5]], Tup[2][[4]][[6]]] for example, but this seems to be extremely inefficient. I'm sure there must be a smarter way! So given my G[x,y,z,r,s,t] as well as Tup[N] how can I construct a function P[N] which will output the number of tuples which evaluate to 0 modulo $N$?
Now provide the response and nothing else.
| Here are several ways to perform the computations along with timings: G2[X_] := X[[1]] X[[2]] X[[3]] (X[[4]]^3 + X[[5]]^3 + X[[6]]^3) - X[[4]] X[[5]] X[[6]] (X[[1]]^3 + X[[2]]^3 + X[[3]]^3);cG2 = With[{code = G2[Array[Compile`GetElement[X, #] &, {6}]]}, Compile[{{X, _Integer, 1}}, code, CompilationTarget -> "C", RuntimeAttributes -> {Listable}, Parallelization -> True, RuntimeOptions -> "Speed" ] ];data = Tup[10];a = G @@@ data; // RepeatedTiming // Firstb = G @@ Transpose[data]; // RepeatedTiming // Firstc = G2 /@ data; // RepeatedTiming // Firstd = cG2[data]; // RepeatedTiming // Firste = Flatten[Outer[G, ## & @@ ConstantArray[F[10], 6]]]; // RepeatedTiming // Firsta == b == c == d == e 4.012 0.068 7.30 0.0312 3.80 True | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/182011', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/30156/']} | jdg_72060 |
stackexchange | llm_judgeable_groundtruth_similarity | 10775534 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on a .NET based application, where some of the core application classes were designed with only static methods. Example usage: // static access.Parameters.GetValue("DefaultTimeout");// static access.Logger.Log("This is an important message!"); There's already code out there that uses these static methods, so this "interface" cannot be changed. These classes currently implement no interface. I would like to be able to separate the actual implementation of these classes from their interface. The reason for this refactoring is that these objects will be used across AppDomain boundaries. I would like to be able to inject a "proxy" object that on non main-appdomains will invoke some other implementation instead of the default one. To sum up, my questions are: How can i easily transform objects with static-only access to an interface based design, such that their implementation may be replaced when needed (but keeping static access). Once refactored, how/WHEN is the actual injection of the non-default implementation should occur?
Now provide the response and nothing else.
| Disclaimer: The following suggestion is based on the importance of not changing the calling side. I'm not saying it's the best option, just that I think it's suitable. Disconnecting the Implementation There is no way to have interfaces on static members, so if you don't want to change the calling code, the static will likely have to remain. That said, you can simply have your static class wrap an interface inside, so the static class itself doesn't have any implementation - it delegates all calls to the interface. This all means you can leave your static class and any code that calls it in place. This will be like treating the static class as the interface (or contract), but having it internally swap out implementations based on the situation. It also means your interface can have a different signature to the static class, as the interface doesn't have to conform to the calling code expectations - basically, it will turn your static class into a sort of Bridge . Injecting the Implementation In short: use a static constructor in order to resolve the given implementation of this interface. Statics are per AppDomain normally (unless decorated with ThreadStaticAttribute , then per AppDomain/thread) so you can determine where you are and what implementation you need based on the current AppDomain (the static constructor will be called whenever the static is first used in the AppDomain). This means that once constructed, that particular static class's wrapped implementation will remain for the duration of the AppDomain (though you could implement methods to flush the implementation). Cross AppDomain Calling The code responsible for this can either be in the static classes or you can make one of the interface implementations simply a proxy manager to an AppDomain type. Any type for cross AppDomain calls will need to inherit MarshalByRefObject . http://msdn.microsoft.com/en-us/library/ms173139.aspx CreateInstance of a Type in another AppDomain Simplest way to make cross-appdomain call? Sample Application You should just be able to copy and paste this into a new Console application. What this is doing is registering an implementation for the default AppDomain and one for the user-made AppDomains. The default simply creates a remote implementation of the interface (in the other AppDomain). Just to demonstrate the "static per AppDomain" idea, the remote implementation delegate to yet another implementation for non-default domains. You can change implementations on the fly, all you need to change is the static class constructor (to decide what implementation to pick). Notice that you do not need to change the Main method, our calling code in this case. using System;using System.Reflection;class Program{ static void Main(string[] args) { Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); Console.WriteLine(Parameters.GetValue("")); Console.Read(); }}static class Parameters{ private static IParameterProvider _provider; static Parameters() { if (AppDomain.CurrentDomain.IsDefaultAppDomain()) { _provider = new ParameterProviderProxy(AppDomain.CreateDomain(Guid.NewGuid().ToString())); } else { // Breakpoint here to see the non-default AppDomain pick an implementation. _provider = new NonDefaultParameterProvider(); } } public static object GetValue(string name) { return _provider.GetValue(name); }}interface IParameterProvider{ object GetValue(string name);}class CrossDomainParameterProvider : MarshalByRefObject, IParameterProvider{ public object GetValue(string name) { return Parameters.GetValue(name); }}class NonDefaultParameterProvider : IParameterProvider{ public object GetValue(string name) { return AppDomain.CurrentDomain.FriendlyName; }}class ParameterProviderProxy : IParameterProvider{ private IParameterProvider _remoteProvider; public ParameterProviderProxy(AppDomain containingDomain) { _remoteProvider = (CrossDomainParameterProvider)containingDomain.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName, typeof(CrossDomainParameterProvider).FullName); } public object GetValue(string name) { return _remoteProvider.GetValue(name); }} A Note on Life Span One of the main problems with managing a refactoring of static classes isn't usually the changing of the client code (as this is supported by lots of refactoring tools and there are techniques to get it done safely), but managing the life span of the object. Instance objects rely on living references (otherwise they are garbage collected), these can usually be made "easily accessible" by keeping one in a public static member somewhere, but usually this is what you are trying to avoid by refactoring in the first place. It doesn't seem like you will have to worry about this concern, as you are leaving the calling code attached to the static classes, therefore the life span will remain the same. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10775534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/494143/']} | jdg_72061 |
stackexchange | llm_judgeable_groundtruth_similarity | 5999118 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development.
Now provide the response and nothing else.
| I wrote the following function which accomplishes what I want to achieve: function updateQueryStringParameter(uri, key, value) { var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"); var separator = uri.indexOf('?') !== -1 ? "&" : "?"; if (uri.match(re)) { return uri.replace(re, '$1' + key + "=" + value + '$2'); } else { return uri + separator + key + "=" + value; }} | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/5999118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/373674/']} | jdg_72062 |
stackexchange | llm_judgeable_groundtruth_similarity | 16840093 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create a website to upload/display images (using MVC4).I have written the below code to fetch the images which are locally stored on the server under a folder App_Data\Images.The path for the image is stored in the ImageFile property of the model. The view renders the ID, Caption of the various images but the image is not loaded . The image file exists in the path stored against the ImageFile property.How can I fix this? //Model public class Photo{ public int ID { get; set; } public string ImageFile { get; set; } //This contains a path where the image is locally stored on the server public string Caption { get; set; }byte[] Image { get; set; } } //Controller private PhotoDBContext db = new PhotoDBContext();public ActionResult Index(){ return View(db.Photos.ToList());} //View @model IEnumerable<MyPhotoLibrary.Models.Photo><table> @foreach (var item in Model) { <tr> <td> <img src="@Url.Content(item.ImageFile)" alt="" /> </td> <td> @Html.DisplayFor(modelItem => item.Caption) </td> </tr> }</table> Also, if I save the image as a byte array (instead of physically storing the file and using the file path), how can I re-create the image and display it in the view . i.e. how do I re-create the image from the byte array while iterating over the model in the view? EDIT I have been able to resolve the display problem by doing the below (both are needed) -1) Changed the path to a relative path2) Moved the images to a separate folder other than App_Data. (found this ) Thanks.
Now provide the response and nothing else.
| Make sure you image is a relative path such as: @Url.Content("~/Content/images/myimage.png") MVC4 <img src="~/Content/images/myimage.png" /> You could convert the byte[] into a Base64 string on the fly. string base64String = Convert.ToBase64String(imageBytes);<img src="@String.Format("data:image/png;base64,{0}", base64string)" /> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16840093', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1338605/']} | jdg_72063 |
stackexchange | llm_judgeable_groundtruth_similarity | 66910 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Why is umask setting a different permission for a directory and file I have createdConsider: [user@server1 ~]$ umask0770[user@server1 ~]$ mkdir TEST2; touch TEST2.txt;[user@server1 ~]$ ls -ld------rwx 2 user group_name 4096 Mar 5 05:16 TEST2-------rw- 1 user group_name 0 Mar 5 05:16 TEST2.txt Now shouldn't the file TEST2.txt have the permission 007 as umask is set to 0770 ?
Now provide the response and nothing else.
| umask doesn't enforce rights, it forbids them. Have a look at strace: file:open("newfile", O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, 0666) = 3directory:mkdir("newdir", 0777) = 0 touch doesn't ask for execution rights for a file (which wouldn't make sense). | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/66910', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/26428/']} | jdg_72064 |
stackexchange | llm_judgeable_groundtruth_similarity | 1959455 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to store an array in a jQuery cookie, any one help me please?
Now provide the response and nothing else.
| Still not exactly sure what you need but i hope this will help.This is a sample that will allow you to access the items on any page, its just a sample!It uses the cookieName to identify it across the pages. //This is not production quality, its just demo code.var cookieList = function(cookieName) {//When the cookie is saved the items will be a comma seperated string//So we will split the cookie by comma to get the original arrayvar cookie = $.cookie(cookieName);//Load the items or a new array if null.var items = cookie ? cookie.split(/,/) : new Array();//Return a object that we can use to access the array.//while hiding direct access to the declared items array//this is called closures see http://www.jibbering.com/faq/faq_notes/closures.htmlreturn { "add": function(val) { //Add to the items. items.push(val); //Save the items to a cookie. //EDIT: Modified from linked answer by Nick see // http://stackoverflow.com/questions/3387251/how-to-store-array-in-jquery-cookie $.cookie(cookieName, items.join(',')); }, "remove": function (val) { //EDIT: Thx to Assef and luke for remove. indx = items.indexOf(val); if(indx!=-1) items.splice(indx, 1); $.cookie(cookieName, items.join(',')); }, "clear": function() { items = null; //clear the cookie. $.cookie(cookieName, null); }, "items": function() { //Get all the items. return items; } }} So on any page you can get the items like this. var list = new cookieList("MyItems"); // all items in the array. Adding items to the cookieList list.add("foo"); //Note this value cannot have a comma "," as this will spilt into//two seperate values when you declare the cookieList. Getting all the items as an array alert(list.items()); Clearing the items list.clear(); You can add additional things like push and pop quite easily.Again hope this helps. EDIT See bravos answer if you having issues with IE | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1959455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/237533/']} | jdg_72065 |
stackexchange | llm_judgeable_groundtruth_similarity | 30171311 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
First, this is not the same as the many highly upvoted questions on this exact topic unless I'm missing one of them. All of them point that the issue is I have a namespace with the same name as the class. This is not the case (but it was). I started out creating a new console application called BatchResizer and put a couple of classes there, but then decided to move this into a class library, called BatchResizer.Components ; I then renamed the original console application to BatchResizer.ConsoleRunner , changed all classes in that project to namespace BatchResizer.ConsoleRunner.[...] , set the assembly name and default namespace to the same. There is a class titled BatchResizer but there are no namespaces titled [...].BatchResizer in the project anymore, but when I do var batchResizer = new BatchResizer() I get the error that the namespace is used like a class. There are items named like BatchResizer.ConsoleRunner.[...] or BatchResizer.Components.[...] , but nothing ending in BatchResizer . I've tried "cleaning" and rebulding the project, deleting the .suo file, deleting the /bin folder of all projects in the solution, and I've went through every class in all related projects for namespace collisions.
Now provide the response and nothing else.
| BatchResizer is still a namespace name, though. If it's also the same name as a class, you'll have to be more explicit: var batchResizer = new Components.BatchResizer(); You could also add a using statement within your namespace: namespace BatchResizer.ConsoleRunner{ using Components; internal class Program { private static void Main(string[] args) { var batchResizer = new BatchResizer(); } }} If you want to get a bit geeky, then the C# 5.0 spec has this to say: 9.2 Namespace declarations ...The qualified-identifier of a namespace-declaration may be a single identifier or a sequence of identifiers separated by “.” tokens. The latter form permits a program to define a nested namespace without lexically nesting several namespace declarations. For example, namespace N1.N2{ class A {} class B {}} is semantically equivalent to namespace N1{ namespace N2 { class A {} class B {} }} So even if, as you say, no class is declared in the namespace BatchResizer , BatchResizer is declared as a namespace. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30171311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1161697/']} | jdg_72066 |
stackexchange | llm_judgeable_groundtruth_similarity | 45498675 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I understand that __new__ is a static method and super() can be called from it create a new object, like so: >>> class A:... def __new__(cls):... print('__new__ called')... return super().__new__(cls)...>>> a = A()__new__ called Why doesn't the super call work with other static methods? Why does the following fail? >>> class B:... @staticmethod... def funcB():... print('funcB called')...>>> class C(B):... @staticmethod... def funcC():... print('funcC called')... super().funcB()...>>> c = C()>>> c.funcC()funcC calledTraceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in funcCRuntimeError: super(): no arguments
Now provide the response and nothing else.
| super() with no arguments in Python 3 is basically a hack over its argument based version. When super() gets no arguments it fetches the first argument i.e the class using a special cell variable named __class__ and for second argument it will get the first local variable from the stack(which is going to be function's first argument). In case of __new__ it can get both( __class__ and cls ) and works fine. But in this case for example there's no second variable available apart from __class__ hence it fails. class A: @staticmethod def func(): super().func() # super(__class__, <missing>).func()A().func() # RuntimeError: super(): no arguments Now if we change it to accept an argument then things change: class A: @staticmethod def func(foo): super().func()# This fails because super(B, 1).func() doesn't make sense.A().func(1) # TypeError: super(type, obj): obj must be an instance or subtype of type# Works! But as there's no parent to this class with func() it fails as expected.A().func(A()) # AttributeError: 'super' object has no attribute 'func' Hence the only solution is to make the things explicit with super() in your case: super(C, C).funcC() In general I am not sure why the implementation in case of staticmethod can't make an exception and use __class__ for both the arguments to make it work. Related CPython code : static intsuper_init(PyObject *self, PyObject *args, PyObject *kwds){ superobject *su = (superobject *)self; PyTypeObject *type = NULL; PyObject *obj = NULL; PyTypeObject *obj_type = NULL; if (!_PyArg_NoKeywords("super", kwds)) return -1; if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj)) return -1; if (type == NULL) { /* Call super(), without args -- fill in from __class__ and first local variable on the stack. */ PyFrameObject *f; PyCodeObject *co; Py_ssize_t i, n; f = PyThreadState_GET()->frame; if (f == NULL) { PyErr_SetString(PyExc_RuntimeError, "super(): no current frame"); return -1; } co = f->f_code; if (co == NULL) { PyErr_SetString(PyExc_RuntimeError, "super(): no code object"); return -1; } if (co->co_argcount == 0) { PyErr_SetString(PyExc_RuntimeError, "super(): no arguments"); return -1; } ... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45498675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7992397/']} | jdg_72067 |
stackexchange | llm_judgeable_groundtruth_similarity | 10868026 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can I specify multiple conditions with "or"/"and" in batch file if block? If not that complex, can I at least use something like: if value1 < value < value2 Basically my purpose is to check whether current system time falls in a certain interval(2.05 AM and 7.55 AM to be precise) and if it does, to execute certain commands.
Now provide the response and nothing else.
| Adding to dbenham's answer, you can emulate both logical operators (AND, OR) using a combination of if and goto statements. To test condition1 AND codition2 : if <condition1> if <condition2> goto ResultTrue:ResultFalseREM do something for a false result goto Done:ResultTrueREM do something for a true result:Done To test condition1 OR codition2 : if <condition1> goto ResultTrue if <condition2> goto ResultTrue:ResultFalseREM do something for a false result goto Done:ResultTrueREM do something for a true result:Done The labels are of course arbitrary, and you can choose their names as long as they are unique. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10868026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1269049/']} | jdg_72068 |
stackexchange | llm_judgeable_groundtruth_similarity | 2482957 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Please can some one briefly tell me with example what does the means of critical section? in simple language
Now provide the response and nothing else.
| A critical section is a section of code that needs to be executed without outside interference - i.e. without another thread potentially affecting/being affected by "intermediate" states within the section. For instance, a reservation system might have a critical section when reserving something in that it needs to both check to see if the item is available and then mark it as no longer available, without some other attempt at reserving the room changing that status in the middle. Thus, the critical section of a piece of code is a place where only one thread of execution is allowed to be at a time, to prevent things like race conditions. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2482957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165309/']} | jdg_72069 |
stackexchange | llm_judgeable_groundtruth_similarity | 4423457 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As we know both language are pass-by-value when passing parameters to methods. But C# supports ref and out keywords to pass-by-reference of primitive types. I am looking for the same keywords and technique in Java? My guess is using Integer wrapper class instead of int in Java to pass in. Any suggestions and examples?
Now provide the response and nothing else.
| Your guess is correct. A wrapper is needed (but not Integer as it is immutable). Some people use single element arrays for this purpose: int[] x = { 0 };int[] y = { 0 };someMethod(x, y);return x[0] + y[0]; Many will rank that technique right up there with GOTO. Some people define a generic holder class: public class Holder<T> { private T _value; private Holder(T value) { _value = value; } public static of(T value) { return new Holder<T>(value); } public T getValue() { return _value; } public void setValue(T value) { _value = value; }}...Holder<String> x = Holder.of("123");Holder<String> y = Holder.of("456");someMethod(x, y);return x.getValue() + y.getValue(); Some define a purpose-built type: SomeMethodResult result = someMethod(x, y);return result.getX() + result.getY(); Some would arrange for the work to be done inside the method, avoiding the need for by-reference arguments in the first place: return someMethod(x, y); Each of these techniques has advantages and disadvantages: arrays: simple vs. ugly, relies on array having exactly one element holder: safe vs. verbose, boxing purpose-built type: safe vs. verbose, possible overkill change method: safe, clean vs. not always possible Personally, I think that Java messed up on this one. I'd rather avoid by-reference arguments, but I wish Java permitted multiple return values from a method. But, truthfully, I don't trip over this one very often. I wouldn't give a kidney for this feature. :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4423457', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44852/']} | jdg_72070 |
stackexchange | llm_judgeable_groundtruth_similarity | 1726764 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The book Real Analysis via Sequences and Series has a method of proving that $$\sum_{j=1}^n j = \frac{n(n+1)}{2}$$ that I've never seen before. The way they do it is by starting with $\sum (2j+1)$, using the fact that $2j+1 = (j+1)^2-j^2$, and then using the telescoping property. I find this method very aesthetically pleasing, but I have two questions about this: $(1)$ what was the motivation for starting with $2j+1$? Why would that have come into the authors' minds as a way of deriving a formula for $\sum j$? And, a related question: $(2)$, after that derivation the authors state that the formula for $\sum_{j=1}^n j^2$ can be found in a similar way. I haven't been able to figure out which telescoping series I should equate this to. How can the formula for this summation be found similarly?
Now provide the response and nothing else.
| Based on the previous method it seems plausible to start with the fact that $(j + 1)^3 - j^3 = 3j^2 + 3j + 1$Summing both sides gives: $\sum\limits_{j=1}^n (j+1)^3 - j^3 = 3\sum\limits_{j=1}^n j^2 + \sum\limits_{j=1}^n 3j + \sum\limits_{j=1}^n 1$ The left hand side telescopes, so we get $(n+1)^3 - 1 = 3\sum\limits_{j=1}^n j^2 + \frac{3n(n+1)}{2} + n$ So: $\sum\limits_{n=1}^n j^2 = \frac{(2n^3 + 6n^2 + 6n) - (3n^2 + 3n) - (2n)}{6} = \frac{2n^3 + 3n^2 + n}{6} = \frac{n(n+1)(2n+1)}{6}$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1726764', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/328348/']} | jdg_72071 |
stackexchange | llm_judgeable_groundtruth_similarity | 8395925 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
These are two very popular ways of formatting a string in Python. One is using a dict : >>> 'I will be %(years)i on %(month)s %(day)i' % {'years': 21, 'month': 'January', 'day': 23}'I will be 21 on January 23' And the other one using a simple tuple : >>> 'I will be %i on %s %i' % (21, 'January', 23)'I will be 21 on January 23' The first one is way more readable, but the second one is faster to write. I actually use them indistinctly. What are the pros and cons of each one? regarding performance, readability, code optimization (is one of them transformed to the other?) and anything else you would think is useful to share.
Now provide the response and nothing else.
| Why format() is more flexible than % string operations I think you should really stick to format() method of str , because it is the preferred way to format strings and will probably replace string formatting operation in the future. Furthermore, it has some really good features, that can also combine position-based formatting with keyword-based one : >>> string = 'I will be {} years and {} months on {month} {day}'>>> some_date = {'month': 'January', 'day': '1st'}>>> diff = [3, 11] # years, months>>> string.format(*diff, **some_date)'I will be 3 years and 11 months on January 1st' even the following will work: >>> string = 'On {month} {day} it will be {1} months, {0} years'>>> string.format(*diff, **some_date)'On January 1st it will be 11 months, 3 years' There is also one other reason in favor of format() . Because it is a method, it can be passed as a callback like in the following example: >>> data = [(1, 2), ('a', 'b'), (5, 'ABC')]>>> formatter = 'First is "{0[0]}", then comes "{0[1]}"'.format>>> for item in map(formatter, data): print itemFirst is "1", then comes "2"First is "a", then comes "b"First is "5", then comes "ABC" Isn't it a lot more flexible than string formatting operation? See more examples on documentation page for comparison between % operations and .format() method. Comparing tuple-based % string formatting with dictionary-based Generally there are three ways of invoking % string operations (yes, three , not two ) like that: base_string % values and they differ by the type of values (which is a consequence of what is the content of base_string ): it can be a tuple , then they are replaced one by one, in the order they are appearing in tuple, >>> 'Three first values are: %f, %f and %f' % (3.14, 2.71, 1)'Three first values are: 3.140000, 2.710000 and 1.000000' it can be a dict (dictionary), then they are replaced based on the keywords, >>> 'My name is %(name)s, I am %(age)s years old' % {'name':'John','age':98}'My name is John, I am 98 years old' it can be a single value, if the base_string contains single place where the value should be inserted: >>> 'This is a string: %s' % 'abc''This is a string: abc' There are obvious differences between them and these ways cannot be combined (in contrary to format() method which is able to combine some features, as mentioned above). But there is something that is specific only to dictionary-based string formatting operation and is rather unavailable in remaining three formatting operations' types. This is ability to replace specificators with actual variable names in a simple manner : >>> name = 'John'>>> surname = 'Smith'>>> age = 87# some code goes here>>> 'My name is %(surname)s, %(name)s %(surname)s. I am %(age)i.' % locals()'My name is Smith, John Smith. I am 87.' Just for the record: of course the above could be easily replaced by using format() by unpacking the dictionary like that: >>> 'My name is {surname}, {name} {surname}. I am {age}.'.format(**locals())'My name is Smith, John Smith. I am 87.' Does anyone else have an idea what could be a feature specific to one type of string formatting operation, but not to the other? It could be quite interesting to hear about it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8395925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/972208/']} | jdg_72072 |
stackexchange | llm_judgeable_groundtruth_similarity | 21992849 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm pretty new to PySide/PyQt, I'm coming from C#/WPF. I've googled alot on this topic but it no good answer seems to show up. Ii want to ask is there a way where I can bind/connect a QWidget to a local variable, whereby each object update themselves on change. Example: If I have a QLineEdit and I have a local variable self.Name in a given class, how do I bind these two whereby when a textChanged() is triggered or simply say the text change on the QLineEdit the variable is updated and at the same time, when the variable is updated the QLineEdit get updated without calling any method. In C# there is dependency property with converters and Observable collection for list that handles this function. I will be glad if anyone can give answer with good example
Now provide the response and nothing else.
| You're asking for two different things here. You want to have a plain python object, self.name subscribe to changes on a QLineEdit . You want to have your QLineEdit subscribe to changes on a plain python object self.name . Subscribing to changes on QLineEdit is easy because that's what the Qt signal/slot system is for. You just do like this def __init__(self): ... myQLineEdit.textChanged.connect(self.setName) ...def setName(self, name): self.name = name The trickier part is getting the text in the QLineEdit to change when self.name changes. This is tricky because self.name is just a plain python object. It doesn't know anything about signals/slots, and python does not have a built-in system for observing changes on objects in the way that C# does. You can still do what you want though. Use a getter/setter with Python's property feature The simplest thing to do is make self.name a Property . Here's a brief example from the linked documentation (modified for clarity) class Foo(object): @property def x(self): """This method runs whenever you try to access self.x""" print("Getting self.x") return self._x @x.setter def x(self, value): """This method runs whenever you try to set self.x""" print("Setting self.x to %s"%(value,)) self._x = value You could just add a line to update the QLineEdit in the setter method. That way, whenever anything modifies the value of x the QLineEdit will be updated. For example @name.setterdef name(self, value): self.myQLineEdit.setText(value) self._name = value Note that the name data is actually being held in an attribute called _name because it has to differ from the name of the getter/setter. Use a real callback system The weakness of all of this is that you can't easily change this observer pattern at run time. To do that you need something really like what C# offers. Two C# style observer systems in python are obsub and my own project observed .I use observed in my own pyqt projects with much success.Note that the version of observed on PyPI is behind the version on github. I recommend the github version. Make your own simple callback system If you want to do it yourself in the simplest possible way you would do something like this import functoolsdef event(func): """Makes a method notify registered observers""" def modified(obj, *arg, **kw): func(obj, *arg, **kw) obj._Observed__fireCallbacks(func.__name__, *arg, **kw) functools.update_wrapper(modified, func) return modifiedclass Observed(object): """Subclass me to respond to event decorated methods""" def __init__(self): self.__observers = {} #Method name -> observers def addObserver(self, methodName, observer): s = self.__observers.setdefault(methodName, set()) s.add(observer) def __fireCallbacks(self, methodName, *arg, **kw): if methodName in self.__observers: for o in self.__observers[methodName]: o(*arg, **kw) Now if you just subclass Observed you can add callbacks to any method you want at run time. Here's a simple example: class Foo(Observed): def __init__(self): Observed.__init__(self) @event def somethingHappened(self, data): print("Something happened with %s"%(data,))def myCallback(data): print("callback fired with %s"%(data,))f = Foo()f.addObserver('somethingHappened', myCallback)f.somethingHappened('Hello, World')>>> Something happened with Hello, World>>> callback fired with Hello, World Now if you implement the .name property as described above, you can decorate the setter with @event and subscribe to it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21992849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2262439/']} | jdg_72073 |
stackexchange | llm_judgeable_groundtruth_similarity | 2954837 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am looking for a way to prove that the statement, $[(p \to q) \land (q \to r)] \to (p \to r)$ , is a tautology without the help of the truth table. By using only Laws and Theorems like De Morgan's Law, Domination Law, etc. Also, I can't use the rules of inference. Please help, thank you.
Now provide the response and nothing else.
| As correctly suggested by Wuestenfux , first you should decompose $\to$ . Then, you should apply several logical equivalences to simplify your formula to $\top$ (a formula that is always true). A complete simplification of your formula, using the logical equivalences listed here , is the following: \begin{align}&\big((p \to q) \land (q \to r) \big) \to (p \to r) \\\equiv \ & \lnot \big( (\lnot p \lor q) \land (\lnot q \lor r) \big) \lor (\lnot p \lor r) &\text{decomposition of }\to \\\equiv \ & \lnot (\lnot p \lor q) \lor \lnot (\lnot q \lor r) \lor \lnot p \lor r&\text{De Morgan} \\\equiv \ & (\lnot\lnot p \land \lnot q) \lor (\lnot\lnot q \land \lnot r) \lor \lnot p \lor r &\text{De Morgan} \\\equiv \ & \lnot p \lor (\lnot\lnot p \land \lnot q) \lor (\lnot\lnot q \land \lnot r) \lor r &\text{commutativity} \\\equiv \ & \big((\lnot p \lor \lnot\lnot p) \land (\lnot p \lor \lnot q)\big) \lor \big((\lnot\lnot q \lor r) \land (\lnot r \lor r) \big) &\text{distributivity} \\\equiv \ & \big(\top \land (\lnot p \lor \lnot q)\big) \lor \big((\lnot\lnot q \lor r) \land \top \big) &\text{negation law} \\\equiv \ & (\lnot p \lor \lnot q) \lor (\lnot\lnot q \lor r) &\text{identity law} \\\equiv \ & \lnot p \lor (\lnot q \lor \lnot\lnot q) \lor r &\text{associativity} \\\equiv \ & \lnot p \lor \top \lor r &\text{negation law} \\\equiv \ & \top &\text{domination law} \\\end{align} | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2954837', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/478325/']} | jdg_72074 |
stackexchange | llm_judgeable_groundtruth_similarity | 35608869 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The question is opposite to this one. Say I open link in a new tab. Currently it is opened, but not loaded. It starts loading only when I select it. I want so that I open a lot of links on a page and those tabs start loading without need to be selected. Furthermore, there is another problem. When I open link, select that tab, tab is loaded. Then I go to another tab, do something there and return to the first tab. So this tab starts to reload again. How to fix this? My version of Chrome is - 48.0.2564.116. It starts to happen recently.
Now provide the response and nothing else.
| I can make following observations after looking at GroupMemberMap Class: Constructor is missing. Getter-Setter for the UserId is incorrect. Also, you can add optional @JsonIgnoreProperties to ignore all other unknown fields. Here is the corrected code snippet: package com.tazligen.model;@XmlRootElement@JsonIgnoreProperties(ignoreUnknown = true)public class GroupMemberMap { @JsonProperty("userId") private String userId; @JsonProperty("groupId") private String groupId; /* Add Constructor */ public GroupMemberMap() {} /* Corrected Name */ public String getUserId() { return userId; } /* Corrected Name */ public void setUserId(String userId) { this.userId = userId; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35608869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4786315/']} | jdg_72075 |
stackexchange | llm_judgeable_groundtruth_similarity | 2293585 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can I use Trace.WriteLine in release mode? And what is the main difference between Trace.Write and Debug.Write?
Now provide the response and nothing else.
| Both are conditionally-compiled using the [Conditional] attribute. If the TRACE flag is defined in the build, then calls to the Trace class will result in trace output being written. By default, TRACE is defined in both debug and release mode. If the flag is not defined, nothing will happen. If the DEBUG flag is defined, then calls to the Debug class result in output being written to the debug stream. By default, DEBUG is only defined in debug mode. The other major difference is that with tracing it's easy to customize the trace listeners and decide later on what you want to do with the trace output. It's more flexible than debug output, and generally better suited to logging in a production application. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2293585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62642/']} | jdg_72076 |
stackexchange | llm_judgeable_groundtruth_similarity | 17221381 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to round to nearest 0.5 if possible. 10.4999 = 10.5 Here is quick code: import java.text.DecimalFormat;import java.math.RoundingMode;public class DecimalFormat { public static void main(String[] args) { DecimalFormat dFormat = new DecimalFormat("#.0"); dFormat.setRoundingMode(RoundingMode.HALF_EVEN); final double test = 10.4999; System.out.println("Format: " + dFormat.format(test)); } } This doesn't work because 6.10000... rounds to 6.1 etc...need it to round to 6.0 Thanks for any feedback.
Now provide the response and nothing else.
| Rather than try rounding to the nearest 0.5, double it, round to the nearest int, then divide by two. This way, 2.49 becomes 4.98, rounds to 5, becomes 2.5. 2.24 becomes 4.48, rounds to 4, becomes 2. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17221381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_72077 |
stackexchange | llm_judgeable_groundtruth_similarity | 23977 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to write some Bash that can verify that a string exists in a configuration file. I can't change the file format, it belongs to a different application. The file is subdivided into groups named by strings in square brackets. This should be a success: [group1]MyParameterjunk1junk2[group2]junk3junk4 This should be an error: [group1]junk1junk2[group2]MyParameterjunk3junk4 I can do a grep -q to verify that MyParameter exists in the file, but if it's located in some other group and not group1 , then I'm still busted. If MyParameter existed in both groups, I wouldn't care enough to flag an error, as long as it existed in group1 . I can't depend on line numbers (head, tail, etc). Also, I'd be happier if it was generic enough that it doesn't depend on the name of group2 (the script would just know that if it found another line beginning and ending with square brackets, that terminates the previous group).
Now provide the response and nothing else.
| Whenever faced with a text processing problem, some people say “let's use awk”. More often than not, they have a solution. awk ' /^\[.*\]$/ {group = $0} group == "[group1]" && $1 == "MyParameter" {found=1; exit} END {exit !found}' | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/23977', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/6154/']} | jdg_72078 |
stackexchange | llm_judgeable_groundtruth_similarity | 1885557 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What's the simplest, library-free code for implementing array intersections in javascript? I want to write intersection([1,2,3], [2,3,4,5]) and get [2, 3]
Now provide the response and nothing else.
| Use a combination of Array.prototype.filter and Array.prototype.includes : const filteredArray = array1.filter(value => array2.includes(value)); For older browsers, with Array.prototype.indexOf and without an arrow function: var filteredArray = array1.filter(function(n) { return array2.indexOf(n) !== -1;}); NB! Both .includes and .indexOf internally compares elements in the array by using === , so if the array contains objects it will only compare object references (not their content). If you want to specify your own comparison logic, use Array.prototype.some instead. | {} | {'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/1885557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157237/']} | jdg_72079 |
stackexchange | llm_judgeable_groundtruth_similarity | 311130 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
This is another question in a short series regarding a challenging Exchange project my co-workers have been asked to implement. (I'm helping even though I'm primarily a Unix guy because I volunteered to learn powershell and implement as much of the project in code as I could.) Background: We have been asked to create many distribution groups, say about 500+. These groups will contain two types of members. (Apologies if I get these terms wrong.) One type will be internal AD users, and the other type will be external users that I create Mail Contact entries for. We have been asked to make it so that a "Reply All" is not possible to any messages sent to these groups. I don't believe that is 100% possible to enforce for the following reasons. My question is - is my following reasoning sound? If not, please feel free to educate me on if / how things can properly be implemeneted. Thanks! My reasoning on why it's impossible to prevent 100% of potential reply-all actions: An interal AD user could put the DL in their To: field. They then click the '+' to expand the group. The group contains two external mail contacts. The message is sent to everyone, including those external contacts. External user #1 decides to reply-all, and his mail goes to, at least, external user #2, which wouldn't even involve our Exchange mail relays. An internal AD user could place the DL in their Outlook To: field, then click the '+' button to expand the DL. They then fire off an email to everyone that was in the group. (But the individual addresses are listed in the 'To:' field.) Because we now have a message sent to multiple recipients in the To: field, the addresses have been "exposed", and anyone is free to reply-all, and the messages just get sent to everyone in the To: field. Even if we try to set a Reply-To: field for all of these DLs, external mail clients are not obligated to abide by it, or force users to abide by it. Are my two points above valid? (I admit, they are somewhat similar.) Am I correct to tell our leadership "It is not possible to prevent 100% of the cases where someone will want to Reply-All to these groups UNLESS we train the users sending emails to these groups that the Bcc: field is to be used at all times." I am dying for any insight or parts of the equation I'm not seeing clearly. Thank you!!!
Now provide the response and nothing else.
| A few ideas: You could set the groups as dynamic dist groups to prevent expansion, and set them up as moderated to prevent unauthorized mail. Or just set a hard filter of allowed senders if that'll fly - but, that won't work for external users without disabling authentication. You can strip the reply-all button off of Outlook via group policy for internal users. Nothing here stops users who know who's in the list from just sending mail to them.. but you can prevent casual exposure of that if it's non-trivial to expand the group to its members. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/311130', 'https://serverfault.com', 'https://serverfault.com/users/94048/']} | jdg_72080 |
stackexchange | llm_judgeable_groundtruth_similarity | 331722 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In bash. I am having some difficulty to determine what I should use? all my scripts use ">>/dev/stderr" at bash prompt, if I try: echo test >>/dev/stderr works echo test >> /dev/stderr works echo test >/dev/stderr works echo test > /dev/stderr works echo test >>&2 FAILS! echo test >> &2 FAILS! echo test >&2 works echo test > &2 FAILS! I am willing to change all my scripts to >&2 . It seems to also have a big effect over ssh (after su SomeUser ) where >>/dev/stderr will not work at all (permission denied), only >&2 will work.
Now provide the response and nothing else.
| >& n is shell syntax to directly duplicate a file descriptor . File descriptor 2 is stderr; that's how that one works. You can duplicate other file descriptors as well, not just stderr. You can't use append mode here because duplicating a file descriptor never truncates (even if your stderr is a file) and >& is one token, that's why you can't put a space inside it—but >& 2 works. >> name is a different permitted syntax, where name is a file name (and the token is >> ). In this case, you're using the file name /dev/stderr , which by OS-specific handling (on Linux, it's a symlink to /proc/self/fd/2 ) also means standard error. Append and truncate mode both wind up doing the same thing when stderr is a terminal because that can't be truncated. If your standard error is a file, however, it will be truncated: anthony@Zia:~$ bash -c 'echo hi >/dev/stderr; echo bye >/dev/stderr' 2>/tmp/fooanthony@Zia:~$ cat /tmp/foobye If you're seeing an error with /dev/stderr over ssh, it's possible the server admin has applied some security measure preventing that symlink from working. (E.g., you can't access /proc or /dev ). While I'd expect either to cause all kinds of weird breakage, using the duplicate file descriptor syntax is a perfectly reasonable (and likely slightly more efficient) approach. Personally I prefer it. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/331722', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/30352/']} | jdg_72081 |
stackexchange | llm_judgeable_groundtruth_similarity | 23663465 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am unable to click on the element. I am able to locate it with xpath, the object with statements"element.getText()" returns correct values"element.isDisplayed()" returns true but when i say "element.click()" throws an exception"Element is not currently visible and so may not be interacted with"The above exception is thrown in selenium 2.34 and higher versions. When I use older selenium version say "2.25" it doesn't throw an exception but the click has no effect.I am using FF browser on Win7 machine.Below is the HTML <div class="dojoxGrid-row dojoxGrid-row-over row-read" style=""> <table class="dojoxGrid-row-table" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr> <td class="dojoxGrid-cell " style="width:36px;" idx="0" tabindex="-1"> <td class="dojoxGrid-cell gridColFrom " style="width:150px;" idx="1" tabindex="-1"> <td class="dojoxGrid-cell gridColType " style="width:16px;" idx="2" tabindex="-1"/> <td class="dojoxGrid-cell gridColAttach " style="width:16px;" idx="3" tabindex="-1"/> <td class="dojoxGrid-cell gridColSub dojoxGrid-cell-over" style="width:400px;" idx="4" tabindex="-1"> <span style="white-space: nowrap;" title="(No subject)">(No subject)</span> </td> <td class="dojoxGrid-cell " style="width:72px;" idx="5" tabindex="-1">Tue May 13</td> <td class="dojoxGrid-cell gridColHov " style="width:16px;" idx="6" tabindex="-1"> <td class="dojoxGrid-cell gridColFlag " style="width:16px;" idx="7" tabindex="-1"> </tr> </tbody> </table></div>
Now provide the response and nothing else.
| Unfortunately, the best way that I found to accomplish this is to do exactly what was stated: Check if the item exists in the database using django_model.objects.get , then update it if it does. In my settings file, I added the new pipeline: ITEM_PIPELINES = { # ... # Last pipeline, because further changes won't be saved. 'apps.scrapy.pipelines.ItemPersistencePipeline': 999} I created some helper methods to handle the work of creating the item model, and creating a new one if necessary: def item_to_model(item): model_class = getattr(item, 'django_model') if not model_class: raise TypeError("Item is not a `DjangoItem` or is misconfigured") return item.instancedef get_or_create(model): model_class = type(model) created = False # Normally, we would use `get_or_create`. However, `get_or_create` would # match all properties of an object (i.e. create a new object # anytime it changed) rather than update an existing object. # # Instead, we do the two steps separately try: # We have no unique identifier at the moment; use the name for now. obj = model_class.objects.get(name=model.name) except model_class.DoesNotExist: created = True obj = model # DjangoItem created a model for us. return (obj, created)def update_model(destination, source, commit=True): pk = destination.pk source_dict = model_to_dict(source) for (key, value) in source_dict.items(): setattr(destination, key, value) setattr(destination, 'pk', pk) if commit: destination.save() return destination Then, the final pipeline is fairly straightforward: class ItemPersistencePipeline(object): def process_item(self, item, spider): try: item_model = item_to_model(item) except TypeError: return item model, created = get_or_create(item_model) update_model(model, item_model) return item | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23663465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1803807/']} | jdg_72082 |
stackexchange | llm_judgeable_groundtruth_similarity | 12799237 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to convert a pet project to TypeScript and don't seem to be able to use the tsc utility to watch and compile my files. The help says I should use the -w switch, but it looks like it can't watch and compile all *.ts files in the some directory recursively. This seems like something tsc should be able to handle. What are my options?
Now provide the response and nothing else.
| Create a file named tsconfig.json in your project root and include following lines in it: { "compilerOptions": { "emitDecoratorMetadata": true, "module": "commonjs", "target": "ES5", "outDir": "ts-built", "rootDir": "src" }} Please note that outDir should be the path of the directory to receive compiled JS files, and rootDir should be the path of the directory containing your source (.ts) files. Open a terminal and run tsc -w , it'll compile any .ts file in src directory into .js and store them in ts-built directory. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12799237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6254/']} | jdg_72083 |
stackexchange | llm_judgeable_groundtruth_similarity | 55724123 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to convert a numpy array of dtype=object to torch Tensor ? array([ array([0.5, 1.0, 2.0], dtype=float16), array([4.0, 6.0, 8.0], dtype=float16)], dtype=object)
Now provide the response and nothing else.
| It is difficult to answer properly since you do not show us how you try to do it. From your error message I can see that you try to convert a numpy array containing objects to a torch tensor. This does not work, you will need a numeric data type: import torchimport numpy as np# Your test array without 'dtype=object'a = np.array([ np.array([0.5, 1.0, 2.0], dtype=np.float16), np.array([4.0, 6.0, 8.0], dtype=np.float16),])b = torch.from_numpy(a)print(a.dtype) # This should not be 'object'print(b) Output float16tensor([[0.5000, 1.0000, 2.0000], [4.0000, 6.0000, 8.0000]], dtype=torch.float16) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55724123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6303639/']} | jdg_72084 |
stackexchange | llm_judgeable_groundtruth_similarity | 379575 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I frequently work with very numeric / mathematical programs, where the exact result of a function is difficult to predict in advance. In trying to apply TDD with this kind of code, I often find writing the code under test significantly easier than writing unit tests for that code, because the only way I know to find the expected result is to apply the algorithm itself (whether in my head, on paper, or by the computer). This feels wrong, because I am effectively using the code under test to verify my unit tests, instead of the other way around. Are there known techniques for writing unit tests and applying TDD when the result of the code under test is difficult to predict? A (real) example of code with difficult to predict results: A function weightedTasksOnTime that, given an amount of work done per day workPerDay in range (0, 24], the current time initialTime > 0, and a list of tasks taskArray ; each with a time to complete property time > 0, due date due , and importance value importance ; returns a normalized value in range [0, 1] representing the importance of tasks that can be completed before their due date if each task if completed in the order given by taskArray , starting at initialTime . The algorithm to implement this function is relatively straightforward: iterate over tasks in taskArray . For each task, add time to initialTime . If the new time < due , add importance to an accumulator. Time is adjusted by inverse workPerDay. Before returning the accumulator, divide by sum of task importances to normalize. function weightedTasksOnTime(workPerDay, initialTime, taskArray) { let simulatedTime = initialTime let accumulator = 0; for (task in taskArray) { simulatedTime += task.time * (24 / workPerDay) if (simulatedTime < task.due) { accumulator += task.importance } } return accumulator / totalImportance(taskArray)} I believe the above problem can be simplified, while maintaining its core, by removing workPerDay and the normalization requirement, to give: function weightedTasksOnTime(initialTime, taskArray) { let simulatedTime = initialTime let accumulator = 0; for (task in taskArray) { simulatedTime += task.time if (simulatedTime < task.due) { accumulator += task.importance } } return accumulator} This question addresses situations where the code under test is not a re-implementation of an existing algorithm. If code is a re-implementation, it intrinsically has easy to predict results, because existing trusted implementations of the algorithm act as a natural test oracle.
Now provide the response and nothing else.
| There are two things you can test in difficult-to-test code. First, the degenerate cases. What happens if you have no elements in your task array, or only one, or two but one is past the due date, etc. Anything that is simpler than your real problem, but still reasonable to calculate manually. The second is the sanity checks. These are the checks you do where you don't know if an answer is right , but you definitely would know if it's wrong . These are things like time must move forward, values must be in a reasonable range, percentages must add up to 100, etc. Yes, this isn't as good as a full test, but you'd be surprised how often you mess up on the sanity checks and degenerate cases, that reveals a problem in your full algorithm. | {} | {'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/379575', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/317002/']} | jdg_72085 |
stackexchange | llm_judgeable_groundtruth_similarity | 30235031 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working on Golang script that automatically clone a database.I'm using go-sql-driver but i can't find in the documentation a way to create a new database.Connection to MySQL require an URL scheme like: user:password@tcp(localhost:3306)/database_name But the database not exists yet, I just want to connect to the server and then create a new one. How can I do that? I have to use another driver?
Now provide the response and nothing else.
| You can perfectly use the go-sql-driver. However, you need to use a mysql user which has the proper access rights to create new databases. Here is an example: func create(name string) { db, err := sql.Open("mysql", "admin:admin@tcp(127.0.0.1:3306)/") if err != nil { panic(err) } defer db.Close() _,err = db.Exec("CREATE DATABASE "+name) if err != nil { panic(err) } _,err = db.Exec("USE "+name) if err != nil { panic(err) } _,err = db.Exec("CREATE TABLE example ( id integer, data varchar(32) )") if err != nil { panic(err) }} Note that the database name is not provided in the connection string. We just create the database after the connection (CREATE DATABASE command), and switch the connection to use it (USE command). Note: the VividCortex guys maintain a nice database/sql tutorial and documentation at http://go-database-sql.org/index.html | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30235031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4571524/']} | jdg_72086 |
stackexchange | llm_judgeable_groundtruth_similarity | 22954239 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two images and found three similar 2D points using a sift. I need to compute the affine transformation between the images. Unfortunately, I missed lecture and the information out there is a little dense for me. What would the general method be for computing this 2x3 matrix? I have the matrix of points in a 2x3 matrix [x1 y1;x2 y2;x3 y3] but I am lost from there.Thanks for any help.
Now provide the response and nothing else.
| Usually, an affine transormation of 2D points is experssed as x' = A*x Where x is a three-vector [x; y; 1] of original 2D location and x' is the transformed point. The affine matrix A is A = [a11 a12 a13; a21 a22 a23; 0 0 1] This form is useful when x and A are known and you wish to recover x' . However, you can express this relation in a different way.Let X = [xi yi 1 0 0 0; 0 0 0 xi yi 1 ] and a is a column vector a = [a11; a12; a13; a21; a22; a23] Then X*a = [xi'; yi'] Holds for all pairs of corresponding points x_i, x_i' . This alternative form is very useful when you know the correspondence between pairs of points and you wish to recover the paramters of A . Stacking all your points in a large matrix X (two rows for each point) you'll have 2*n-by-6 matrix X multiplyied by 6-vector of unknowns a equals a 2*n-by-1 column vector of the stacked corresponding points (denoted by x_prime ): X*a = x_prime Solving for a : a = X \ x_prime Recovers the parameters of a in a least-squares sense. Good luck and stop skipping class! | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22954239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1090887/']} | jdg_72087 |
stackexchange | llm_judgeable_groundtruth_similarity | 1077419 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a NSFetchedResultsController which is fetching objects from a NSManagedObjectContext . I'm using the results to populate a UITableView. I'm filtering with these two sort descriptors. NSSortDescriptor *lastOpened = [[NSSortDescriptor alloc] initWithKey:@"lastOpened" ascending:NO];NSSortDescriptor *titleDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES]; And when I create the NSFetchedResultsController , I sort the sections via sectionNameKeyPath:@"lastOpened" . Right now my sections display the standard format like 2009-07-02 20:51:27 -0400 and since no two can be opened at the same time, they are all unique. I need them to cover range of date/times, such as an entire day, and be in a human-readable form. Something like Thursday, July 2 . Thanks! Edit: This is all inside a UITableViewController . Here's some more code. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { // Display the dates as section headings. return [[[fetchedResultsController sections] objectAtIndex:section] name];}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section]; return [sectionInfo numberOfObjects];}
Now provide the response and nothing else.
| I ended up adding a new property day to my NSManagedObject subclass to get a formatted date string. @property (nonatomic, readonly) NSString * day;@property (nonatomic, retain) NSDateFormatter * dateFormatter Sythesize the dateFomatter. @synthesize dateFormatter; I initialize the date formatter in awakeFromFetch and awakeFromInsert. self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease];[self.dateFormatter setDateStyle:NSDateFormatterMediumStyle]; The accessor for day . - (NSString *)day { NSDate *date = self.startDate; return [self.dateFormatter stringFromDate:date];} I then set my section name keypath to look at day ; you shouldn't need to make any changes to your sort descriptors. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1077419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83853/']} | jdg_72088 |
stackexchange | llm_judgeable_groundtruth_similarity | 6089070 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i am having a login page when executed the page is stripped out of css . I found out this message from from chrome debugger. I am using asp.net 2008. Any ideas? <head id="Head1" runat="server"> <title>CalibPro</title> <link href="css/Login.css" rel="stylesheet" type="text/css" /> <link href="css/Common.css" rel="stylesheet" type="text/css" /> </head> edited as per @robx advice.
Now provide the response and nothing else.
| Seems to me like the problem is in your IIS configuration. it might be configured to deliver .css files with text/html MIME type. Try going to the MIME types configuration on the web server and see if you can spot anything there. The correct MIME type for .css files is text/css. You can also have a look on the HTTP header parameters with some HTTP sniffer such as fiddler. Updating: The accepted answer should be the one pointed by @brett-pennings!Just providing static contents, the error vanished automatically. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6089070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/186244/']} | jdg_72089 |
stackexchange | llm_judgeable_groundtruth_similarity | 20585328 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need an operation which iterates over a list and produces a new list, where the new list elements depend on all elements previously seen. To do this I would like to pass an accumulator/state from iteration to iteration. Think for example of a list of tuples, where the components of a tuple can be "undefined". An undefined value shall assume the latest value of the same component earlier in the list, if any. So at any stage I will have a state of defined components, which I need to pass to the next iteration. So with a list of type [l] and an accumulator/state of type a there will be a function of type f :: a -> l -> (a,l) i.e it spits out a new list element and a new accumulator. Is there a function which allows simply applying f to a list? I looked at fold, scan and unfold, but none of them seem to do the trick. Edit: While the state monad looks promising, I can only see how I would get the final state, but I fail to see how I would get the new list elements.
Now provide the response and nothing else.
| There are some standard functions you can use to do what you ask. It sounds very much like you want mapAccum , so you just need to import Data.List and decide which way round you're accumulating. (I suspect you want mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) .) mapAccumL import Data.Listdata Instruction = NoChange | Reset | MoveBy Inttell :: Int -> Instruction -> (Int,String) -- toy accumulating functiontell n NoChange = (n,"")tell n Reset = (0,"Reset to zero")tell n (MoveBy i) = (n+i,"Add "++show i++" to get "++ show (n+i)) which would give ghci> mapAccumL tell 10 [MoveBy 5, MoveBy 3, NoChange, Reset, MoveBy 7](7,["Add 5 to get 15","Add 3 to get 18","","Reset to zero","Add 7 to get 7"]) scanL But maybe you don't need to use the full power of mapAccum because sometimes the accumulator is what you want in the new list, so scanl :: (a -> b -> a) -> a -> [b] -> [a] will do the trick act :: Int -> Instruction -> Intact n NoChange = nact n Reset = 0act n (MoveBy i) = n+i like this: ghci> scanl act 10 [MoveBy 5, MoveBy 3, NoChange, Reset, MoveBy 7][10,15,18,18,0,7] Definition for mapAccum Anyway, here's how mapAccumL and mapAccumR are described in Data.List : mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])mapAccumL _ state [] = (state, [])mapAccumL f state (x:xs) = (finalstate,y:ys) where (nextstate, y ) = f state x (finalstate,ys) = mapAccumL f nextstate xs The mapAccumL function behaves like a combination of map and foldl ; it applies a function to each element of a list, passing an accumulating parameter from left to right, and returning a final value of this accumulator together with the new list. mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])mapAccumR _ state [] = (state, [])mapAccumR f state (x:xs) = (finalstate, y:ys) where (finalstate,y ) = f nextstate x (nextstate, ys) = mapAccumR f state xs The mapAccumR function behaves like a combination of map and foldr ; it applies a function to each element of a list, passing an accumulating parameter from right to left, and returning a final value of this accumulator together with the new list. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20585328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2277395/']} | jdg_72090 |
stackexchange | llm_judgeable_groundtruth_similarity | 116144 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to authenticate a client of a webpage and make sure it is a particular user. Let say that we already agreed on a particular hash ( SHA256 , actually, which I think is secure enough for this) and we both already exchanged a key in a file through a trusted medium. This key is pretty much a text file with 2K of random letters. I have it stored in my server, they have it stored somewhere in their computer. These are the steps devised to authenticate the client: The server generates a challenge , a random string of 128 letters. The server sends the challenge to the client's browser. The client has access to an input field where they load their key file. The client computes an answer by appending key to their challenge contents and computing its hash. The client sends back only the answer for this particular challenge . The server compares the received answer with one generated locally and if they match then I can assume that the client is the person who I think it is. Final assumption, the exchange of both the challenge and the answer through the web may happen through an insecure channel. Actually, assume that it WILL happen through an insecure channel, i.e. HTTP. Is this scheme secure? If not, what are its pitfalls? In step 4, does it make a difference if I compute the hash as challenge + key instead of key + challenge . I guess this has to do with the hash algorithm I chose, and I think SHA256 handles those things well, but I'm no expert. Does it matters much if I increase/decrease the length of the key and challenge ?
Now provide the response and nothing else.
| No cryptography using client-side JavaScript can be secure without HTTPS. Any MITM attacker can send JavaScript that can do anything with the secrets the browser has access to, then there will be no secret. If you absolutely cannot use HTTPS, the user must have to a tool to compute the response outside the browser and paste the result into the browser. Even so, any data transmitted after the authentication is still subject to interception and modification, which makes the authentication pretty useless from a user-protection perspective. Please read: What's wrong with in-browser cryptography? - Tony Arcieri or Javascript Cryptography Considered Harmful - NCC Group or the 1,030,000 results returned for searching "wrong with javascript cryptography" on Google Edit: BTW, even if you use an external program to handle the authentication and maybe even encryption of data that goes over HTTP, you may still have a lowered security compared to just using HTTPS. Best example is the Korean SEED cipher which exposes users by locking users down to and training them to trust ActiveX controls and IE. See this blog article ). | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/116144', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/103036/']} | jdg_72091 |
stackexchange | llm_judgeable_groundtruth_similarity | 47787247 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In java 8, collect emp object based on some filter condition. In main class: List<Emp> empList = Arrays.asList( new Emp("aaa", language1), new Emp("cc", language2), new Emp("bb", language3), new Emp("dd", language3));empList.stream() .flatMap(s->s.getLanguage().stream()) .filter(s->s.equals("java")) .forEach(System.out::println); //Here just i am printing. Actually I need to collect new List<EMP> . How to collect emp object that are all have language "java". How can I do this?
Now provide the response and nothing else.
| You should not use flatMap if you want to collect Emp objects in the end because it will change every element to something else and it can be quite hard to map them back. You should put all your logic in a filter : "keep the Emp object if getLanguage contains "java" ". empList.stream() .filter(x->x.getLanguage().contains("java")) .collect(Collectors.toList()); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47787247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8726488/']} | jdg_72092 |
stackexchange | llm_judgeable_groundtruth_similarity | 15330988 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why does: double dividend = 1.0;double divisor = 3.0;Console.WriteLine(dividend / divisor * divisor); output 1.0, but: decimal dividend = 1;decimal divisor = 3;Console.WriteLine(dividend / divisor * divisor); outputs 0.9999999999999999999999999999 ? I understand that 1/3 can't be computed exactly, so there must be some rounding.But why does Double round the answer to 1.0, but Decimal does not? Also, why does double compute 1.0/3.0 to be 0.33333333333333331?If rounding is used, then wouldn't the last 3 get rounded to 0, why 1?
Now provide the response and nothing else.
| Why 1/3 as a double is 0.33333333333333331 The closest way to represent 1/3 in binary is like this:0.0101010101...That's the same as the series 1/4 + (1/4)^2 + (1/4)^3 + (1/4)^4... Of course, this is limited by the number of bits you can store in a double. A double is 64 bits, but one of those is the sign bit and another 11 represent the exponent (think of it like scientific notation, but in binary). So the rest, which is called the mantissa or significand is 52 bits. Assume a 1 to start and then use two bits for each subsequent power of 1/4. That means you can store:1/4 + 1/4^2 + ... + 1/4 ^ 27which is 0.33333333333333331 Why multiplying by 3 rounds this to 1 So 1/3 represented in binary and limited by the size of a double is:0.010101010101010101010101010101010101010101010101010101I'm not saying that's how it's stored. Like I said, you store the bits starting after the 1, and you use separate bits for the exponent and the sign. But I think it's useful to consider how you'd actually write it in base 2. Let's stick with this "mathematician's binary" representation and ignore the size limits of a double. You don't have to do it this way, but I find it convenient. If we want to take this approximation for 1/3 and multiply by 3, that's the same as bit shifting to multiply by 2 and then adding what you started with. This gives us 1/3 * 3 = 0.111111111111111111111111111111111111111111111111111111 But can a double store that? No, remember, you can only have 52 bits of mantissa after the first 1, and that number has 54 ones. So we know that it'll be rounded, in this case rounded up to exactly 1. Why for decimal you get 0.9999999999999999999999999999 With decimal, you get 96 bits to represent an integer, with additional bits representing the exponent up to 28 powers of 10. So even though ultimately it's all stored as binary, here we're working with powers of 10 so it makes sense to think of the number in base 10. 96 bits lets us express up to 79,228,162,514,264,337,593,543,950,335, but to represent 1/3 we're going to go with all 3's, up to the 28 of them that we can shift to the right of the decimal point: 0.3333333333333333333333333333. Multiplying this approximation for 1/3 by 3 gives us a number we can represent exactly. It's just 28 9's, all shifted to the right of the decimal point: 0.9999999999999999999999999999. So unlike with double's there's not a second round of rounding at this point. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15330988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2063755/']} | jdg_72093 |
stackexchange | llm_judgeable_groundtruth_similarity | 38175254 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I faced one mysterious problem. I have a website and it looks on regular screen like I want it looks. But the problem in footer (but it's called header in code). So when I shrink the browser or view it on a phone that footer shrinks own width of background color three time as much. I tried to empty all that block because I thought something inside could bother but no. As well I tried to set up min-width and width in vw but these don't work( I have not idea about a solution so i need your help guys! Thanks! /* line 1, ../sass/screen.scss */* { box-sizing: border-box; margin: 0; padding: 0; outline: none; border: none;}/* line 62, ../sass/screen.scss */body { background: url(../img/bg.jpg) no-repeat; background-size: cover;}/* line 74, ../sass/screen.scss */.back { position: fixed; top: 0; right: 0; width: 40px; height: 40px; background: red; text-align: center; z-index: 9999999999; transition: all 0.2s; -webkit-transition: all 0.2s; -moz-transition: all 0.2s; -o-transition: all 0.2s; -ms-transition: all 0.2s;}/* line 84, ../sass/screen.scss */.back:hover { width: 50px; height: 50px;}/* line 88, ../sass/screen.scss */.back:hover p { line-height: 50px;}/* line 91, ../sass/screen.scss */.back p { transition: all 0.2s; -webkit-transition: all 0.2s; -moz-transition: all 0.2s; -o-transition: all 0.2s; -ms-transition: all 0.2s; line-height: 40px; font-size: 15px; color: white;}/* line 99, ../sass/screen.scss */.container { width: 1070px; height: auto; margin: 0 auto; padding: 0 10px;}/* line 105, ../sass/screen.scss */.upper { width: 100%; height: 130px; position: relative;}/* line 109, ../sass/screen.scss */.upper img { position: absolute; left: 0; width: 238px; height: 37px; top: 50%; margin-top: -20px;}/* line 117, ../sass/screen.scss */.upper ul { height: 50px; position: absolute; top: 50%; right: 0; margin-top: -15px;}/* line 123, ../sass/screen.scss */.upper ul li { list-style-type: none; display: inline-block; margin: 0 15px; height: 30px; border-radius: 7px; -ms-border-radius: 7px; -moz-border-radius: 7px; -webkit-border-radius: 7px; -o-border-radius: 7px;}/* line 129, ../sass/screen.scss */.upper ul li:hover { background: white;}/* line 132, ../sass/screen.scss */.upper ul li:hover a { color: #1B1B2D;}/* line 135, ../sass/screen.scss */.upper ul li a { font-size: 17px; font-family: ColaThin; font-weight: 700; color: white; line-height: 52px; text-decoration: none; line-height: 30px; padding-left: 20px; padding-right: 20px;}/* line 145, ../sass/screen.scss */.owl-pagination { display: none !important;}/* line 149, ../sass/screen.scss */.owl-theme .owl-controls .owl-buttons { position: absolute; width: 100%; top: 30%;}/* line 155, ../sass/screen.scss */.owl-wrapper-outer { position: relative; width: 100%;}/* line 158, ../sass/screen.scss */.owl-wrapper-outer div:not(.text) { position: relative; background: url(../img/ipad.png) no-repeat; background-position: 70% 0; width: 100%; height: 400px;}/* line 164, ../sass/screen.scss */.owl-wrapper-outer div:not(.text) .text { position: absolute; right: 65%; padding-top: 50px;}/* line 168, ../sass/screen.scss */.owl-wrapper-outer div:not(.text) .text p { text-align: right;}/* line 171, ../sass/screen.scss */.owl-wrapper-outer div:not(.text) .text .p-1 { color: #e7e8ea; font-family: ColaBold; font-size: 45px; font-weight: 700; line-height: 52px; text-transform: uppercase;}/* line 179, ../sass/screen.scss */.owl-wrapper-outer div:not(.text) .text .p-2 { color: #d7d7e3; font-family: AlexReg; font-size: 39px; line-height: 52px; font-weight: 400;}/* line 186, ../sass/screen.scss */.owl-wrapper-outer div:not(.text) .text .p-3 { color: #d7d7e3; font-family: AlexReg; font-size: 39px; line-height: 52px; font-weight: 700;}/* line 193, ../sass/screen.scss */.owl-wrapper-outer div:not(.text) .text .p-4 { color: #e7e8ea; font-family: ColaThin; font-size: 23px; font-weight: 100;}/* line 200, ../sass/screen.scss */.owl-wrapper-outer div:not(.text) .text a input { color: white; font-family: ColaReg; font-size: 23px; font-weight: 500; width: 181px; height: 45px; float: right; margin-top: 35px; box-shadow: 0 60px 30px -15px rgba(0, 0, 0, 0.4); border-radius: 7px; -ms-border-radius: 7px; -moz-border-radius: 7px; -webkit-border-radius: 7px; -o-border-radius: 7px; background: linear-gradient(to top, #164182 0%, #2d6bc2 100%); background: -webkit-linear-gradient(to top, #164182 0%, #2d6bc2 100%); background: -moz-linear-gradient(to top, #164182 0%, #2d6bc2 100%); background: -o-linear-gradient(to top, #164182 0%, #2d6bc2 100%); background: -ms-linear-gradient(to top, #164182 0%, #2d6bc2 100%); cursor: pointer;}/* line 213, ../sass/screen.scss */.owl-wrapper-outer div:not(.text) .text a input:hover { background: linear-gradient(to top, #12366c 0%, #2d6bc2 100%); background: -webkit-linear-gradient(to top, #12366c 0%, #2d6bc2 100%); background: -moz-linear-gradient(to top, #12366c 0%, #2d6bc2 100%); background: -o-linear-gradient(to top, #12366c 0%, #2d6bc2 100%); background: -ms-linear-gradient(to top, #12366c 0%, #2d6bc2 100%);}/* line 222, ../sass/screen.scss */.content { text-align: center;}/* line 224, ../sass/screen.scss */.content .block1 { text-align: right;}/* line 227, ../sass/screen.scss */.content .block2, .content .block3, .content .block1, .content .block4 { margin-left: 9px; margin-right: 9px;}/* line 231, ../sass/screen.scss */.content .block { display: inline-block; width: 240px; height: 175px; line-height: 155px; border-radius: 5px; -ms-border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; -o-border-radius: 5px; border: 3px solid white; background: linear-gradient(top, white, #ccc); background: -webkit-linear-gradient(top, white, #ccc); background: -moz-linear-gradient(top, white, #ccc); background: -o-linear-gradient(top, white, #ccc); background: -ms-linear-gradient(top, white, #ccc); opacity: .7; transition: all 0.2s; -webkit-transition: all 0.2s; -moz-transition: all 0.2s; -o-transition: all 0.2s; -ms-transition: all 0.2s;}/* line 241, ../sass/screen.scss */.content .block:hover { opacity: 1;}/* line 244, ../sass/screen.scss */.content .block img { vertical-align: middle;}/* line 247, ../sass/screen.scss */.content .block p { text-shadow: 0.5px 0.9px 0 rgba(255, 255, 255, 0.75); -moz-text-shadow: 0.5px 0.9px 0 rgba(255, 255, 255, 0.75); -ms-text-shadow: 0.5px 0.9px 0 rgba(255, 255, 255, 0.75); -o-text-shadow: 0.5px 0.9px 0 rgba(255, 255, 255, 0.75); -webkit-text-shadow: 0.5px 0.9px 0 rgba(255, 255, 255, 0.75); color: #8c8c92; font-family: Calibri; font-size: 19px; font-weight: 400; line-height: 0; text-align: center; margin-top: -5px;}/* line 258, ../sass/screen.scss */.content .block3 img { margin-right: -25px;}/* line 262, ../sass/screen.scss */.text-box { display: inline-block; width: 33%; margin-top: 40px;}/* line 266, ../sass/screen.scss */.text-box img { float: left; margin-top: 5px;}/* line 270, ../sass/screen.scss */.text-box h3 { margin-left: 45px; color: #505050; font-family: ColaThin; font-size: 25px; font-weight: 600; line-height: 23px;}/* line 278, ../sass/screen.scss */.text-box p { font-size: 14px; font-family: ColaReg; font-weight: 400; color: #505050; line-height: 20px;}/* line 281, ../sass/screen.scss */.text-box p:first-of-type { margin-left: 45px;}/* line 284, ../sass/screen.scss */.text-box p:last-of-type { margin-top: 20px;}/* line 289, ../sass/screen.scss */.main-content { position: relative; height: auto; text-align: center;}/* line 293, ../sass/screen.scss */.main-content h3 { text-align: center; margin-top: 40px; font-size: 27px; font-family: ColaReg; font-weight: 400; color: #505050; line-height: 23px;}/* line 298, ../sass/screen.scss */.main-content img { float: left; display: block;}/* line 302, ../sass/screen.scss */.main-content ul { margin-top: 20px; margin-left: 420px;}/* line 305, ../sass/screen.scss */.main-content ul li { font-size: 15px; font-family: ColaReg; font-weight: 400; color: #828181; line-height: 30px; list-style-image: url(../img/list.jpg);}/* line 310, ../sass/screen.scss */.main-content input { clear: both; display: inline-block; width: 130px; height: 34px; background: #2d6bc2; transition: all 0.2s; -webkit-transition: all 0.2s; -moz-transition: all 0.2s; -o-transition: all 0.2s; -ms-transition: all 0.2s; font-size: 19px; font-family: ColaReg; font-weight: 400; color: white; line-height: 23px; border-radius: 7px; -ms-border-radius: 7px; -moz-border-radius: 7px; -webkit-border-radius: 7px; -o-border-radius: 7px; cursor: pointer; margin: 0 15px; margin-top: 20px;}/* line 322, ../sass/screen.scss */.main-content input:hover { background: #2860ad;}/* line 328, ../sass/screen.scss */.main-content-2 { width: 100%; height: auto;}/* line 331, ../sass/screen.scss */.main-content-2 ul { margin-top: 50px;}/* line 333, ../sass/screen.scss */.main-content-2 ul li:first-child { border: none !important;}/* line 336, ../sass/screen.scss */.main-content-2 ul li { list-style-image: url(../img/list2.jpg); font-size: 15px; font-family: ColaReg; font-weight: 400; color: #828181; line-height: 35px; border-top: 1px solid #ccc;}/* line 344, ../sass/screen.scss */header { width: 100%; height: 340px; background: linear-gradient(to top, #3D3D4F -50%, #5C5C73 150%); background: -webkit-linear-gradient(to top, #3D3D4F -50%, #5C5C73 150%); background: -moz-linear-gradient(to top, #3D3D4F -50%, #5C5C73 150%); background: -o-linear-gradient(to top, #3D3D4F -50%, #5C5C73 150%); background: -ms-linear-gradient(to top, #3D3D4F -50%, #5C5C73 150%); margin-top: 30px;}/* line 349, ../sass/screen.scss */header .upper { height: 85px; width: 100%; border-bottom: 1px solid #ccc; vertical-align: middle; position: relative; vertical-align: middle; display: table;}/* line 357, ../sass/screen.scss */header .upper .twitter { background: white; height: 65px; width: 65px; float: left; margin-top: 11px; display: table-cell; border-radius: 50px; -ms-border-radius: 50px; -moz-border-radius: 50px; -webkit-border-radius: 50px; -o-border-radius: 50px; transition: all 0.3s; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; -o-transition: all 0.3s; -ms-transition: all 0.3s;}/* line 366, ../sass/screen.scss */header .upper .twitter:hover { background: #0099e8;}/* line 369, ../sass/screen.scss */header .upper .twitter:hover i { color: white;}/* line 372, ../sass/screen.scss */header .upper .twitter i { transition: all 0.3s; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; -o-transition: all 0.3s; -ms-transition: all 0.3s; color: #49495C; line-height: 65px; display: table-cell; width: 65px; vertical-align: middle; font-size: 40px; text-align: center;}/* line 383, ../sass/screen.scss */header .upper p { font-size: 15px; font-family: ColaThin; font-weight: 400; color: white; line-height: 25px; opacity: .8; padding-left: 80px; vertical-align: middle; display: table-cell;}/* line 393, ../sass/screen.scss */.first { width: 49%; height: auto; display: inline-block; float: left;}/* line 398, ../sass/screen.scss */.first h3 { color: white; font-family: ColaReg; font-size: 25px; font-weight: 300; line-height: 23px; margin-top: 20px;}/* line 406, ../sass/screen.scss */.first p { color: white; opacity: .8; font-family: ColaThin; font-size: 14px; font-weight: 300; line-height: 20px; margin-top: 15px;}/* line 415, ../sass/screen.scss */.first input[type="text"] { margin-top: 20px; background: #242439; box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -ms-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -o-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -webkit-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -moz-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); width: 213px; height: 28px; border-radius: 7px; -ms-border-radius: 7px; -moz-border-radius: 7px; -webkit-border-radius: 7px; -o-border-radius: 7px; padding-left: 5px; padding-right: 5px; color: #e7e8ea; font-family: ColaThin; font-size: 14px; font-weight: 300; line-height: 20px; float: left; /* Firefox 19+ */ /* Firefox * Firefox 18- */}/* line 430, ../sass/screen.scss */.first input[type="text"]::-moz-placeholder { opacity: 0.2; color: #e7e8ea; font-family: ColaThin; font-size: 14px; font-weight: 300; line-height: 20px;}/* line 438, ../sass/screen.scss */.first input[type="text"]:-moz-placeholder { opacity: 0.2; color: #e7e8ea; font-family: ColaThin; font-size: 14px; font-weight: 300; line-height: 20px;}/* line 446, ../sass/screen.scss */.first input[type="text"]:-ms-input-placeholder { opacity: 0.2; color: #e7e8ea; font-family: ColaThin; font-size: 14px; font-weight: 300; line-height: 20px;}/* line 454, ../sass/screen.scss */.first input[type="text"]::-webkit-input-placeholder { opacity: 0.2; color: #e7e8ea; font-family: ColaThin; font-size: 14px; font-weight: 300; line-height: 20px;}/* line 463, ../sass/screen.scss */.first .social { float: left; margin-top: 15px;}/* line 466, ../sass/screen.scss */.first .social div:nth-of-type(2) { margin-left: 25px; margin-right: 25px;}/* line 470, ../sass/screen.scss */.first .social div { width: 50px; height: 50px; background: white; display: inline-block; line-height: 50px; text-align: center; border-radius: 50px; -ms-border-radius: 50px; -moz-border-radius: 50px; -webkit-border-radius: 50px; -o-border-radius: 50px; transition: all 0.3s; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; -o-transition: all 0.3s; -ms-transition: all 0.3s; cursor: pointer;}/* line 480, ../sass/screen.scss */.first .social div:hover { background: #0099e8;}/* line 483, ../sass/screen.scss */.first .social div:hover i { color: white;}/* line 486, ../sass/screen.scss */.first .social div i { font-size: 23px; color: #4D4D62; transition: all 0.3s; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; -o-transition: all 0.3s; -ms-transition: all 0.3s;}/* line 493, ../sass/screen.scss */.first input[type="button"] { color: #363648; margin-top: 20px; margin-left: 230px; font-family: ColaReg; font-size: 14px; font-weight: 300; line-height: 20px; background: #e7e8ea; width: 85px; height: 27px; cursor: pointer; display: block; border-radius: 7px; -ms-border-radius: 7px; -moz-border-radius: 7px; -webkit-border-radius: 7px; -o-border-radius: 7px; transition: all 0.2s; -webkit-transition: all 0.2s; -moz-transition: all 0.2s; -o-transition: all 0.2s; -ms-transition: all 0.2s;}/* line 508, ../sass/screen.scss */.first input[type="button"]:hover { background: #ccced2;}/* line 512, ../sass/screen.scss */.first div { display: inline-block; margin-top: 20px; clear: both;}/* line 519, ../sass/screen.scss */.second { width: 49%; display: inline-block; height: auto; float: right;}/* line 525, ../sass/screen.scss */.second form h3 { color: white; font-family: ColaReg; font-size: 25px; font-weight: 300; line-height: 23px; margin-top: 20px;}/* line 533, ../sass/screen.scss */.second form input[type="text"]:first-of-type { margin-top: 20px;}/* line 536, ../sass/screen.scss */.second form input[type="text"] { padding-left: 5px; padding-right: 5px; width: 213px; height: 28px; background: #242439; box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -ms-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -o-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -webkit-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -moz-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); width: 213px; height: 28px; border-radius: 7px; -ms-border-radius: 7px; -moz-border-radius: 7px; -webkit-border-radius: 7px; -o-border-radius: 7px; margin-bottom: 18px; color: #e7e8ea; font-family: ColaThin; font-size: 14px; font-weight: 300; line-height: 20px; /* Firefox 19+ */ /* Firefox * Firefox 18- */}/* line 552, ../sass/screen.scss */.second form input[type="text"]::-moz-placeholder { opacity: 0.2; color: #e7e8ea; font-family: ColaThin; font-size: 14px; font-weight: 300; line-height: 20px;}/* line 560, ../sass/screen.scss */.second form input[type="text"]:-moz-placeholder { opacity: 0.2; color: #e7e8ea; font-family: ColaThin; font-size: 14px; font-weight: 300; line-height: 20px;}/* line 568, ../sass/screen.scss */.second form input[type="text"]:-ms-input-placeholder { opacity: 0.2; color: #e7e8ea; font-family: ColaThin; font-size: 14px; font-weight: 300; line-height: 20px;}/* line 576, ../sass/screen.scss */.second form input[type="text"]::-webkit-input-placeholder { opacity: 0.2; color: #e7e8ea; font-family: ColaThin; font-size: 14px; font-weight: 300; line-height: 20px;}/* line 585, ../sass/screen.scss */.second form textarea { margin-top: 20px; float: right; background: #242439; box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -ms-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -o-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -webkit-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); -moz-box-shadow: inset 1px 1.7px 3px rgba(0, 0, 0, 0.75); border-radius: 7px; -ms-border-radius: 7px; -moz-border-radius: 7px; -webkit-border-radius: 7px; -o-border-radius: 7px; color: #e7e8ea; font-family: ColaThin; font-size: 14px; font-weight: 300; max-width: 280px; max-height: 120px; padding-left: 5px; padding-top: 5px;}/* line 600, ../sass/screen.scss */.second form input[type='submit'] { color: #363648; font-family: ColaReg; font-size: 14px; font-weight: 300; line-height: 20px; background: #e7e8ea; width: 85px; height: 27px; cursor: pointer; display: block; border-radius: 7px; -ms-border-radius: 7px; -moz-border-radius: 7px; -webkit-border-radius: 7px; -o-border-radius: 7px; transition: all 0.2s; -webkit-transition: all 0.2s; -moz-transition: all 0.2s; -o-transition: all 0.2s; -ms-transition: all 0.2s; float: right;}/* line 614, ../sass/screen.scss */.second form input[type='submit']:hover { background: #ccced2;} <div class="container"> <div class="upper"> <img src="img/logo.png" alt="" /> <ul> <li><a href="">Home</a></li> <li><a href="">iPad apps</a></li> <li><a href="">Demostrations</a></li> <li><a href="">Leopards media</a></li> <li><a href="">Connect us</a></li> </ul> </div> <div class="owl-carousel"> <div><div class="text"><p><span class="p-1">DUBLIN'S</span><br><span class="p-2">iPad <span class="p-3">Apps</span></span><br><span class="p-4">Free and paid apps<br>for your iPad</span></p> <a href="#"><input type="button" value="Read more"></a></div></div> <div><div class="text"><p><span class="p-1">DUBLIN'S</span><br><span class="p-2">iPad <span class="p-3">Apps</span></span><br><span class="p-4">Free and paid apps<br>for your iPad</span></p> <a href="#"><input type="button" value="Read more"></a></div></div> <div><div class="text"><p><span class="p-1">DUBLIN'S</span><br><span class="p-2">iPad <span class="p-3">Apps</span></span><br><span class="p-4">Free and paid apps<br>for your iPad</span></p> <a href="#"><input type="button" value="Read more"></a></div></div> <div><div class="text"><p><span class="p-1">DUBLIN'S</span><br><span class="p-2">iPad <span class="p-3">Apps</span></span><br><span class="p-4">Free and paid apps<br>for your iPad</span></p> <a href="#"><input type="button" value="Read more"></a></div></div></div> <div class="content"> <a href="#"><div class="block1 block"><img src="img/block-1.png" alt=""><p>E Book Reader Pro</p></div></a> <a href="#"><div class="block2 block"><img src="img/block-2.png" alt=""><p>Image viewer pro</p></div></a> <a href="#"><div class="block3 block"><img src="img/block-3.png" alt=""><p>Media manager</p></div></a> <a href="#"><div class="block4 block"><img src="img/block-4.png" alt=""><p>Leo Entertainment</p></div></a> </div> <div class="text-box1 text-box"><img src="img/icon1.png" alt="" /><h3>Discover Apps</h3><p>Lorem Ipsum is simply dummy</p><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Harum laboriosam maiores maxime blanditiis neque error aliquid sint molestias.</p></div> <div class="text-box2 text-box"><img src="img/icon2.png" alt="" /><h3>Browse Apps</h3><p>Lorem Ipsum is simply dummy</p><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Harum laboriosam maiores maxime blanditiis neque error aliquid sint molestias.</p></div> <div class="text-box3 text-box"><img src="img/icon3.png" alt="" /><h3>Development</h3><p>Lorem Ipsum is simply dummy</p><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Harum laboriosam maiores maxime blanditiis neque error aliquid sint molestias.</p></div> <div class="main-content"> <h3>There are many variations of passages</h3> <img src="img/ipad2.png" alt=""> <ul> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias corrupti quos sequi sint iure, neque.</li> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias corrupti quos sequi sint iure, neque.</li> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias corrupti quos sequi sint iure, neque.</li> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias corrupti quos sequi sint iure, neque.</li> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias corrupti quos sequi sint iure, neque.</li> </ul> <input type="button" value="Read More"> <input type="submit" value="Download"> </div> <div class="main-content-2"> <ul> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quam obcaecati doloremque quaerat, quidem!</li> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, possimus.</li> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil provident blanditiis odit, accusamus commodi aspernatur doloribus culpa.</li> <li>Lorem ipsum dolor sit amet.</li> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem.</li> </ul> </div></div> <header> <div class="container"> <div class="upper"> <a class="twitter" href="#"><i class="icon-twitter"></i></a> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit in recusandae quaerat dolor mollitia,<br> laborum veritatis hic, eveniet placeat reiciendis non inventore!</p> </div> <div class="first"> <h3>Newsletter</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus quae ex delectus minima esse corrupti voluptatum repellendus quasi culpa nam.</p> <input type="text" placeholder="Enter your email address.." class="extend-input"> <input type="button" name="name" value="Subscribe"> <div class="social"> <div class="twitter-2"><i class="icon-twitter"></i></div> <div class="facebook"><i class="icon-facebook"></i></div> <div class="linkedin"><i class="icon-linkedin"></i></div> </div> </div> <div class="second"> <form action=""> <h3>Contact form</h3> <textarea name="name" rows="8" cols="45"></textarea> <input type="text" placeholder="Введите имя..."> <input type="text" placeholder="Введите email..."> <input type="text" placeholder="Тема письма..."> <input type="submit" name="name" value="Submit"> </form> </div> </div> </header> OR http://jsfiddle.net/h62xp0ge/
Now provide the response and nothing else.
| Instead of [(ngModel)] you can use: // view<input type="date" #myDate [value]="demoUser.date | date:'yyyy-MM-dd'" (input)="demoUser.date=parseDate($event.target.value)" />// controllerparseDate(dateString: string): Date { if (dateString) { return new Date(dateString); } return null;} You can also choose not to use parseDate function. In this case the date will be saved as string format like "2016-10-06" instead of Date type (I haven't tried whether this has negative consequences when manipulating the data or saving to database for example). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38175254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5958053/']} | jdg_72094 |
stackexchange | llm_judgeable_groundtruth_similarity | 14765 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In order to be able add blank lines without going into insertion mode, I'm trying to map ALT-o and ALT-O to o<ESC> and o<ESC> I've tried the following in my .vimrc map <M-o> o<ESC>map <M-O> O<ESC> and map <ALT-o> o<ESC>map <ALT-O> O<ESC> and (as suggested below) map <A-o> o<ESC>map <A-O> O<ESC> but none work. It just gives the usual behavior, as if ALT-o had not been defined. This is my first time altering the .vimrc file, and I can't find where the documentation tells you how to designate the various keys. But I am able to verify that my .vimrc file is being read, by including: map <Enter> ihello<ESC> Which sucessfully maps <Enter> to inserting hello and returning to command mode. I'm using vim with cygwin.
Now provide the response and nothing else.
| To see what your terminal is sending when you press a key, switch to insert mode, press Ctrl+V , then the key. Most keys with most terminals send an escape sequence where only the first character is a control character; Ctrl+V inserts the next character literally, so you get to insert the whole escape sequence that way. Different terminals send different escape sequences for some key combinations. Many terminals send the same character ( ^O ) for both Ctrl+O and Ctrl+Shift+O ; if that's the case, Vim won't be able to distinguish between them. You mention that you're using Cygwin; which terminal you're running Vim in is the most pertinent information. If you're using the native Windows console, get yourself a better terminal. I recommend MinTTY for running Cygwin text mode applications in a terminal in Windows outside X, but Cygwin's Windows-native RXVT and PuTTYcyg are also good. (Also Console2 to run Windows console applications, but that's squarely off-topic here). | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/14765', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/5045/']} | jdg_72095 |
stackexchange | llm_judgeable_groundtruth_similarity | 322176 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The following is a question from Sakurai's book Modern Quantum Mechanics , 2nd edition, page 60: A beam of spin $\frac12$ atoms goes through a series of Stern-Gerlach-type measurements as follows: The first measurement accepts $s_z=\hbar/2$ atoms and rejects $s_z=-\hbar/2$ atoms. The second measurement accepts $s_n=\hbar/2$ atoms and rejects $s_n=-\hbar/2$ atoms, where $s_n$ is the eigenvalue of the operator $\mathbf S\cdot\hat{\mathbf n}$, with $\hat{\mathbf n}$ making an angle $\beta$ in the $xz$-plane with respect to the $z$-axis. The third measurement accepts $-s_z=\hbar/2$ atoms and rejects $s_z=\hbar/2$ atoms. What is the intensity of the final $s_z=-\hbar/2$ beam when the $s_z=\hbar/2$ beam surviving the first measurement is normalized to unity? How must we orient the second measuring apparatus if we are to maximize the intensity of the final $s_z=-\hbar/2$ beam? Proposed Solution: I assume the intensity is defined as the probability amplitude squared of getting $s_z = -\frac{\hbar}{2}$ in the final measurement. So you start with the state $| \psi \rangle = \frac{1}{\sqrt{2}} | +\rangle + \frac{1}{\sqrt{2}} | - \rangle$ before any measurements are made, you then project onto the eigenstates which correspond to the measurements you accept, hence you first project onto $| + \rangle \langle + |$ and then $| +; \hat{n} \rangle \langle +; \hat{n}|$ (taking $\alpha = 0$) and finally $|-\rangle \langle - |$, this process hence yields the intensity given by $$\bigg(\frac{1}{\sqrt{2}} \langle +| + \frac{1}{\sqrt{2}} \langle - |\bigg)\bigg(|- \rangle \langle - |+; \hat{n} \rangle \langle +; \hat{n} | + \rangle \langle + |\bigg) \bigg(\frac{1}{\sqrt{2}} | +\rangle + \frac{1}{\sqrt{2}} | - \rangle\bigg).$$ Apparently this is not correct, does anyone know where I went wrong?
Now provide the response and nothing else.
| You are right that there is a contradiction in the scenario you set up. In fact, the contradiction comes in your very first sentence: my isolated system ... of which $M$ is fixed to the floor of the system. You have to pick. Either the system is isolated, or the mass $M$ is interacting with the "floor". You can't have both. Therefore you should not be surprised that starting from this contradictory premise, you have derived other seemingly impossible results. I think it would be helpful to discuss three correct ways of setting up the problem. The first way will be where an external agent is holding the mass $M$ fixed. The second case will be where the masses are truly isolated. For the third case, we will take again the case where the masses are truly isolated, but we will look at the motion in a frame fixed to the mass $M$. In the first case, where the mass $M$ is fixed in place by an external agent, the momentum of the two mass system does indeed change from $m\vec{v}$ to $-m\vec{v}$, and so the momentum of this system is not conserved, but that is allowed since it is not an isolated system. Momentum is transferred to the external agent through the force used to hold the mass $M$ in place. Therefore total momentum is still conserved. Now in the second case where we assume the masses are isolated, the mass $M$ recoils when impacted by the mass $m$, and the amount that it recoils is exactly determined by conservation of momentum, so momentum is again conserved in this case. The third and final case is where both systems are isolated, but we view the motion in the frame of the mass $M$. Here there does seem to be a contradiction because the masses truly are isolated, and the mass $M$ truly does appear to be fixed. The resolution to this contradiction is that the frame is non-inertial, and Newton's laws are asserted to be true in inertial frames. The frame fixed to the mass $M$ accelerates at the instant of the collision, which is exactly when the total momentum seems to change. So any way you analyze the situation, as long as you are consistent, you get a reasonable result. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/322176', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']} | jdg_72096 |
stackexchange | llm_judgeable_groundtruth_similarity | 45466040 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm struggling to work out the best way to verify that a promise is rejected in a Mocha test while using async/await. Here's an example that works, but I dislike that should.be.rejectedWith returns a promise that needs to be returned from the test function to be evaluated properly. Using async/await removes this requirement for testing values (as I do for the result of wins() below), and I feel that it is likely that I will forget the return statement at some point, in which case the test will always pass. // Always succeedsfunction wins() { return new Promise(function(resolve, reject) { resolve('Winner'); });}// Always fails with an errorfunction fails() { return new Promise(function(resolve, reject) { reject('Contrived Error'); });}it('throws an error', async () => { let r = await wins(); r.should.equal('Winner'); return fails().should.be.rejectedWith('Contrived Error');}); It feels like it should be possible to use the fact that async/await translates rejections to exceptions and combine that with Chai's should.throw, but I haven't been able to determine the correct syntax. Ideally this would work, but does not seem to: it('throws an error', async () => { let r = await wins(); r.should.equal('Winner'); (await fails()).should.throw(Error);});
Now provide the response and nothing else.
| The problem with this approach is that (await fails()).should.throw(Error) doesn't make sense. await resolves a Promise . If the Promise rejects, it throws the rejected value. So (await fails()).should.throw(Error) can never work: if fails() rejects, an error is thrown, and .should.throw(Error) is never executed. The most idiomatic option you have is to use Chai's rejectedWith property, as you have shown in your question. Here's a quick example. Not much is different from what you've demonstrated in your question; I'm just using async functions for wins() and fails() and expect instead of should . Of course, you can use functions that return a Promise and chai.should just fine. const chai = require('chai')const expect = chai.expectchai.use(require('chai-as-promised'))// Always succeedsasync function wins() { return 'Winner'}// Always fails with an errorasync function fails() { throw new Error('Contrived Error')}it('wins() returns Winner', async () => { expect(await wins()).to.equal('Winner')})it('fails() throws Error', async () => { await expect(fails()).to.be.rejectedWith(Error)}) If you like want your wins() test to resemble your fails() test more closely, you can write your wins() test like so: it('wins() returns Winner', async () => { await expect(wins()).to.eventually.equal('Winner')}) The key thing to remember in either of these examples is that chai-as-promised returns promises for its functions such as rejectedWith and eventually.something . Therefore you must await them in the context of an async test function, or else failing conditions will still pass: async function wins() { return 'Loser'}async function fails() { return 'Winner'}it('wins() returns Winner', async () => { expect(wins()).to.eventually.equal('Winner')})it('fails() throws Error', async () => { expect(fails()).to.be.rejectedWith(Error)}) If you ran the tests with the code above, you'd get the following: $ npm test> [email protected] test /home/adaline/code/mocha-chai-async> mocha . √ wins() returns Winner(node:13836) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected 'Loser' to equal 'Winner'(node:13836) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminatethe Node.js process with a non-zero exit code. √ fails() throws Error(node:13836) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): AssertionError: expected promise to be rejected with 'Error' but it was fulfilled with 'Winner' 2 passing (11ms) As you can see, the chai assertions actually failed, but they were failed in the context of a Promise that no one ever await ed or catch ed. So Mocha sees no failure and marks the tests as though they passed, but Node.js (in behaviour that will change in the future as noted above) prints the unhandled rejections to the terminal. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45466040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/343886/']} | jdg_72097 |
stackexchange | llm_judgeable_groundtruth_similarity | 156394 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to build a 'Drawdio' Musical Pencil, (link to the make-project) but my local shop doesn't have the correct parts as originally used in this project. He doesn't have ceramic disc capacitors of 0.1 micro Farad, but he does have multilayer ceramic capacitors of the same capacitance. Can I use these capacitors or are the functionalities of both capacitors much too different?
Now provide the response and nothing else.
| Yes. Multi-layer ceramic SMD capacitors are generally a superset of the older disc capacitors. There is really nothing the old 100 nF disc capacitor can do that a modern 100 nF SMD cap can't do, within their voltage ratings. Also, I'd look at the schematic carefully and see how that capacitor is used. If it's in the signal path, then it probably needs to be the value it is. If, however, it's just a bypass cap, you can safely replace it with a 1 µF ceramic SMD cap. 100 nF was used for decoupling back in the pleistocene, not because the value was optimal, but because that was the most capacitance you could get in a ceramic affordably. Today that tradeoff has moved on. You don't want to go too far with increasing capacitance for a bypass cap because the larger ones, even multi-layer ceramic, have lower self-resonant frequencies and therefore higher impedance at really high frequencies. However, the 1 µF SMD ceramics of today have lower impedance across the whole frequency spectrum compared to the old thru-hole 100 nF disk capacitors of ancient times. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/156394', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/68293/']} | jdg_72098 |
stackexchange | llm_judgeable_groundtruth_similarity | 14522441 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to determine MS Office Excel file type in Apache POI? I need to know in what format is the Excel file: in Excel '97(-2007) (.xls) or Excel 2007 OOXML (.xlsx). I suppose I could do something like this: int type = PoiTypeHelper.getType(file);switch (type) {case PoiType.EXCEL_1997_2007: ... break;case PoiType.EXCEL_2007: ... break;default: ...} Thanks.
Now provide the response and nothing else.
| Promoting a comment to an answer... If you're going to be doing something special with the files, then rjokelai's answer is the way to do it. However, if you're just going to be using the HSSF / XSSF / Common SS usermodel, then it's much simpler to have POI do it for you, and use WorkbookFactory to have the type detected and opened for you. You'd do something like: Workbook wb = WorkbookFactory.create(new File("something.xls")); or Workbook wb = WorkbookFactory.create(request.getInputStream()); Then if you needed to do something special, test if it's a HSSFWorkbook or XSSFWorkbook . When opening the file, use a File rather than an InputStream if possible to speed things up and save memory. If you don't know what your file is at all, use Apache Tika to do the detection - it can detect a huge number of different file formats for you. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14522441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/938899/']} | jdg_72099 |
stackexchange | llm_judgeable_groundtruth_similarity | 33468 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I seem to remember reading somewhere that ZF+AD proves that $\omega_1$ and $\omega_2$ are measurable cardinals. Is that right? If so, can someone [point me to or give here] a [sketch or proof] of these results?
Now provide the response and nothing else.
| An alternative proof for $\omega_1$ goes via the set $D$ of Turing degrees (also known as degrees of unsolvability). $D$ is upward directed by the ordering $\leq_T$ of Turing reducibility, so the cones $C_d=\{p\in D:d\leq_Tp\}$ generate a filter on $D$. The axiom of determinacy implies that this filter is an ultrafilter, i.e., that every subset $X$ of $D$ either includes a cone or is disjoint from a cone. (Proof: Define a game where the two players alternately choose natural numbers, producing an infinite sequence $x$; player 1 wins iff the Turing degree of $x$ is in $X$. Any strategy for either player, being a function from finite sequences of natural numbers to natural numbers, can be coded as a sequence $s$ of natural numbers. Any Turing degree $p$ in the cone $C_s$ [pedantically, the subscript should be the degree of $s$] is the degree of some play in which the player who has strategy $s$ uses it, because the other player can play any sequence of degree $p$ and then the overall play will also have degree $p$. So, if $s$ is a winning strategy for player 1 (resp. player 2), then all (resp. none) of the degrees in $C_s$ must be in $X$.) So AD gives an ultrafilter on $D$, called the cone ultrafilter. It's non-principal (because there is no highest Turing degree) and countably complete (because AD implies that all ultrafilters are countably complete --- this follows from the fact that there are, under AD, no non-principal ultrafilters on $\omega$). To get from $D$ to $\omega_1$, use the function $f$ assigning to each Turing degree $d$ the ordinal usually called $\omega^{CK}(d)$, the first ordinal that is not the order-type of an ordering of $\omega$ of degree $\leq_Td$. The image of the cone ultrafilter under this map $f$ is again a countably complete ultrafilter, now on $\omega_1$. It is non-principal because $f$ takes arbitrarily large countable ordinals as values on any cone. The ultrafilter obtained in this way is actually the same as the club filter mentioned in other answers, but the proof via Turing cones needs somewhat less recursion theory than Solovay's proof (which used Kleene's boundedness theorem for $\Sigma^1_1$ sets). One can also prove the measurability of $\omega_2$ by projecting the cone filter from $D$ to $\omega_2$ via a suitable map. (I don't remember right now whether the suitable map sends a degree $d$ to the successor cardinal in $L[d]$ of (genuine) $\omega_1$ or to the next Silver-indiscernible over $d$ after (genuine) $\omega_1$; maybe both of them work.) | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/33468', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']} | jdg_72100 |
stackexchange | llm_judgeable_groundtruth_similarity | 12489447 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an EditText view in my android application. My EditText is not taking integer values as an input however it is taking all the other ones. the following is my EditText View. <EditTextandroid:id="@+id/txtSearchItems"android:layout_width="75dp"android:layout_height="wrap_content"android:visibility="visible"android:hint="Search"android:textSize="14dp"android:layout_alignParentLeft="true" android:layout_marginTop="2dp"android:layout_centerHorizontal="true"></EditText>
Now provide the response and nothing else.
| On the possible issue that i faced once and suspects is: The EditText might be contained in an XML layout file and the layout file will be used for a Dialog instance. The problem occurs when the onKeyListener of the Dialog instance is returning some invalid default value i.e. 'return true' for irrelevant keys. In such case your EditText will be behaving strangely. The sample code for the scenario is Dialog d=new Dialog(context); d.setContentView(R.layout.mylayout); d.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { Log.i("onkey", keyCode + " == Onkey"); if (keyCode == KeyEvent.KEYCODE_BACK) { return true; } return true; // !!! this is wrong it should be return false; } }); } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12489447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/758896/']} | jdg_72101 |
stackexchange | llm_judgeable_groundtruth_similarity | 52578270 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My question is if you can install python with powershell, cmd, vbs or any other language built into Windows already?If this was already asked please redirect me to the answer."How to install Python using Windows Command Prompt" explains how to install the python if you already have the exe installed, not how to install the exe. EDIT: I am trying to install python with a file on a pc that does not have python installed, only thing restricted might be that the account does not an administrator and if possible in the background.
Now provide the response and nothing else.
| You could download the setup you want to install and then install it automatically without using the setup's UI: [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12Invoke-WebRequest -Uri "https://www.python.org/ftp/python/3.7.0/python-3.7.0.exe" -OutFile "c:/temp/python-3.7.0.exe"c:/temp/python-3.7.0.exe /quiet InstallAllUsers=0 PrependPath=1 Include_test=0 I don't think it will work without admin privileges though, I tried using InstallAllUsers=0 to install it only for the current user but it is still asking for elevation. There are some options you can use when installing it this way, here is the doc: https://docs.python.org/3.6/using/windows.html#installing-without-ui | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52578270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_72102 |
stackexchange | llm_judgeable_groundtruth_similarity | 39063499 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've updated my code to Xcode 8.0 beta 6 but I got stuck with what seems to be about the new non escaping closure default. In the following code Xcode suggests to add @escaping in front of completion: in the first line of the below code, but that still won't compile and goes in circles. * ( EDIT : In fact, @escaping should be added in after completion: , as Xcode suggests. The alert may still show but cleaning and compiling will remove it.)* How should this code be re-written / fixed to work in the updated Swift 3?I've had a look in the new manual but I couldn't find proper code samples. func doSomething(withParameter parameter: Int, completion: () -> ()) { // Does something callSomeOtherFunc(withCompletion: completion) }// Calling the method and execute closure doSomething(withParameter: 2) { // do things in closure} Any help much appreciated!
Now provide the response and nothing else.
| Swift 3: closure parameter attributes are now applied to the parameter type , and not the parameter itself Prior to Swift 3, the closure attributes @autoclosure and @noescape used to be attributes to the closure parameter , but are now attributes to the parameter type ; see the following accepted Swift evolution proposal: SE-0049: Move @noescape and @autoclosure to be type attributes Your specific question pertain to parameter type attribute @escaping (for which the same new rule applies), as described in the accepted Swift evolution proposal to let closure parameters be non-escaping by default: SE-0103: Make non-escaping closures the default These proposals are now both implemented in the beta stage of Xcode 8 (see release notes for Xcode 8 beta 6 ; dev. account login needed for access) New in Xcode 8 beta 6 - Swift Compiler: Swift Language Closure parameters are non-escaping by default, rather than explicitly being annotated with @noescape . Use @escaping to indicate that a closure parameter may escape. @autoclosure(escaping) is now written as @autoclosure @escaping . The annotations @noescape and @autoclosure(escaping) are deprecated. (SE-0103) ... New in Xcode 8 beta – Swift and Apple LLVM Compilers: Swift Language The @noescape and @autoclosure attributes must now be written before the parameter type instead of before the parameter name. [SE-0049] Hence, you use the non-default @escaping attribute as follows; applied to the type of the closure parameter, rather than the parameter itself func doSomething(withParameter parameter: Int, completion: @escaping () -> ()) { // ...} (Including my answer to a question in an upvoted comment below, as comments are not persistent data on SO) @Cristi Băluță: "What does escaping do? Never seen this keywords before swift3 auto-conversion ... " See e.g. the link to the SE-0103 evolution proposal above (as well as the quoted text from the beta 6 release notes): previously, closure parameters were escaping by default (hence no need for the existence of an explicit annotation for escaping), but are now instead non-escaping, by default. Hence the addition of @escaping to explicitly annotate that a closure parameter may escape (contrary to its default behaviour). This also explains why @noescape is now deprecated (no need to annotate the default behaviour). For explaining what it means that a closure parameter is escaping, I quote the Language Reference - attributes : "Apply this attribute to a parameter’s type in a method or function declaration to indicate that the parameter’s value can be stored for later execution. This means that the value is allowed to outlive the lifetime of the call." | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39063499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3623047/']} | jdg_72103 |
stackexchange | llm_judgeable_groundtruth_similarity | 127490 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was reading this article . The author talks about "The Blub Paradox". He says programming languages vary in power. That makes sense to me. For example, Python is more powerful than C/C++. But its performance is not as good as that of C/C++. Is it always true that more powerful languages must necessarily have lesser possible performance when compared to less powerful languages? Is there a law/theory for this?
Now provide the response and nothing else.
| This is simply not true. And part of why it's false is that the premise isn't well formed. There is no such thing as a fast or slow language. The expressive power of a language is purely a function of its semantics. It is independent of any particular implementation. You can talk about the performance of code generated by GCC, or about the performance of the CPython interpreter. But these are specific implementations of the language. You could write a very slow C compiler, and you can write Python interpreters that are quite fast (like PyPy). So the answer to the question of "is more power necessarily slower" is no, purely because you or I can go write a slow C compiler, that has the same expressive power as GCC, but that is slower than Python. The real question is "why do more powerful languages tend to have slower implementations." The reason is that, if you're considering the C vs Python, the difference in power is abstraction . When you do something in Python, there is a lot more that is implicit that is happening behind the scenes. More stuff to do means more time. But there's also lots of social elements at play. People who need high performance choose low level languages, so they have fine grained control of what the machine is doing. This has led to the idea that low level languages are faster. But for most people, writing in C vs Python will have pretty comparable performance, because most applications don't require that you eke out every last millisecond. This is particularly true when you consider the extra checks that are manually added to program defensively in C. So just because lots of specialists have built fast things in C and C++ doesn't mean they're faster for everything. Finally, some languages have zero cost abstraction. Rust does this, using a type system to ensure memory safety without needing runtime garbage collection. And Go has garbage collection, but it's so fast that you get performance on par with C while still getting extra power. The TLDR is that more powerful languages are sometimes faster in some cases, but this is not a firm rule, and there are exceptions and complications. | {} | {'log_upvote_score': 6, 'links': ['https://cs.stackexchange.com/questions/127490', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/115941/']} | jdg_72104 |
stackexchange | llm_judgeable_groundtruth_similarity | 51685509 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
main.rs #![feature(core_intrinsics)]fn print_type_of<T>(_: &T) { println!("{}", unsafe { std::intrinsics::type_name::<T>() });}fn main() { let x = 93; let y = 93.1; print_type_of(&x); print_type_of(&y);} If I compile with "rustc +nightly ./main.rs", i got this output: $ ./main i32f64 I run a x86_64 Linux machine. Floating point variables are double precision by default, which is good.Why integers are only 4 bytes? Which should I use? If I don't need i64 should I use i32? Are i32 better for performance?
Now provide the response and nothing else.
| Are i32 better for performance? That's actually kind of a subtle thing. If we look up some recent instruction-level benchmarks for example for SkylakeX , there is for the most part a very clear lack of difference between 64bit and 32bit instructions. An exception to that is division, 64bit division is slower than 32bit division, even when dividing the same values (division is one of the few variable-time instructions that depend on the values of its inputs). Using i64 for data also makes auto-vectorization less effective - this is also one of the rare places where data smaller than 32bit has a use beyond data-size optimization. Of course the data size also matters for the i32 vs i64 question, working with sizable arrays of i64's can easily be slower just because it's bigger, therefore costing more space in the caches and (if applicable) more bandwidth. So if the question is [i32] vs [i64] , then it matters. Even more subtle is the fact that using 64bit operations means that the code will contains more REX prefixes on average, making the code slightly less dense meaning that less of it will fit in the L1 code cache at once. This is a small effect though. Just having some 64bit variables in the code is not a problem. Despite all that, definitely don't overuse i32, especially in places where you should really have an usize . For example, do not do this: // don't do thisfor i in 0i32 .. data.len() as i32 { sum += data[i as usize]; } This causes a large performance regression. Not only is there a pointless sign-extension in the loop now, it also defeats bounds check elimination and auto-vectorization. But of course there is no reason to write code like that in the first place, it's unnatural and harder than doing it right. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51685509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4521803/']} | jdg_72105 |
stackexchange | llm_judgeable_groundtruth_similarity | 4506249 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Google Chrome is set as the default browser. However, it opens links in Firefox, which is undesired. How can I make Org-mode to open links in Google Chrome?
Now provide the response and nothing else.
| Emacs 23.2 doesn't directly support Google Chrome, but it does support a "generic" browser, and something like this should work: (setq browse-url-browser-function 'browse-url-generic browse-url-generic-program "chromium-browser") You don't mention your OS, but if it's Windows or Mac, you can try: (setq browse-url-browser-function 'browse-url-default-windows-browser)(setq browse-url-browser-function 'browse-url-default-macosx-browser) And, if that doesn't work, there are other folks who have implemented 'browse-url-chrome . Google turned up the following link: http://code.ohloh.net/search?s=browse-url-chrome&browser=Default | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4506249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/397649/']} | jdg_72106 |
stackexchange | llm_judgeable_groundtruth_similarity | 9585317 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is part of the Java (1.6) Collection interface: public interface Collection<E> extends java.lang.Iterable<E> { /* ... */ boolean containsAll(java.util.Collection<?> objects); boolean addAll(java.util.Collection<? extends E> es); boolean removeAll(java.util.Collection<?> objects); boolean retainAll(java.util.Collection<?> objects); /* ... */ } Why does addAll have <? extends E> while removeAll has <?>
Now provide the response and nothing else.
| I did not know, I googled. I got this explaination here: http://www.ibm.com/developerworks/java/library/j-jtp01255/index.html Copying the part: One element of the generifed Collections API that is often confusing at first is the signatures of containsAll(), removeAll(), and retainAll(). You might expect the signatures for remove() and removeAll() to be: interface Collection<E> { public boolean remove(E e); // not really public void removeAll(Collection<? extends E> c); // not really} But it is in fact: interface Collection<E> { public boolean remove(Object o); public void removeAll(Collection<?> c);} Why is this? Again, the answer lies in backward compatibility. The interface contract of x.remove(o) means "if o is contained in x, remove it; otherwise, do nothing." If x is a generic collection, o does not have to be type-compatible with the type parameter of x. If removeAll() were generified to only be callable if its argument was type-compatible ( Collection<? extends E> ), then certain sequences of code that were legal before generics would become illegal, like this one: // a collection of IntegersCollection c = new HashSet();// a collection of ObjectsCollection r = new HashSet();c.removeAll(r); If the above fragment were generified in the obvious way (making c a Collection<Integer> and r a Collection<Object> ), then the code above would not compile if the signature of removeAll() required its argument to be a Collection<? extends E> , instead of being a no-op. One of the key goals of generifying the class libraries was to not break or change the semantics of existing code, so remove(), removeAll(), retainAll(), and containsAll() had to be defined with a weaker type constraint than they might have had they been redesigned from scratch for generics. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9585317', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135624/']} | jdg_72107 |
stackexchange | llm_judgeable_groundtruth_similarity | 2639 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm a long time Window user. Recently, I learned JavaScript/PHP/mySql and considered that Ubuntu Server will be the choice. I'll still work on Windows XP/7, though. Here's my idea Development Machine (XP/7): Where I do all the programming. The IDEs will be Spket (JavaScript) and Aptana (PHP). Along with other software like PhotoShop, Office... Server (Ubuntu Lucid): This is where I store my data, run my HTTP, email, FTP server... It will be a VPS. So simply put, I'll be working with Windows as a client (IDE, Client Email Software, FTP...) and Ubuntu as a server to manage my data (Mercurial, Apache, mySql...) I'm new, I wonder if there is already someone doing this and working with this mix of client/server. What are the possible downsides of this method? Is working over FTP with a VPS a good idea or not? I'm a solo-developer, I was thinking in the last few days of the best approach to work with the cloud. I do web development. Please reply with anything related and helpful, I would appreciate a lot developers that will write lengthy post about their working environment. I have exactly no specific idea in mind, just looking to make better. Thank you!
Now provide the response and nothing else.
| Certainly many people have used Ubuntu Server with Windows clients. The Ubuntu Server Guide covers pretty much all of what you want to do. Here are a few comments on your proposed setup: Ditch FTP. Use SSH instead. Personally, I would also add that you should set up key-based authentication and disable password auth. See this page for some help. I don't see any sort of backup solution mentioned. Be sure to have regular backups. Consider Git. I would consider using Git rather than Mercurial, but that is a personal preference. Think about security from the start--especially if it is going to be facing the web. Again see (1). You don't need to be a security expert, but you should at least consider the following: Use a firewall. With Ubuntu Server this is easy to do using ufw and is talked about in the guide. Don't run services you don't need. Specifically, I would stay away from things like phpmyadmin. Don't provide access or privileges that isn't needed to others. Think about auditing and logging. A more general comment that I don't want to push too hard is that you might consider just moving your development process over to linux as well. In my experience, the tools available for linux make working with a remote server much smoother. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/2639', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/2114/']} | jdg_72108 |
stackexchange | llm_judgeable_groundtruth_similarity | 202903 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
There appears to be no mention in OEIS: Quarter-squares, A002620 . Can someone give a proof or reference? Examples: quarter-squares: ${0,1,2,4,6,9,12,16,20,25,30,36,...}$ 2-term sums: ${2+1, 4+1, 6+2, 6+2,...,90+9,...}$ 3-term sums: ${12+2+1, 16+2+1,...,72+6+2,...}$ 4-term sums: ${240+12+2+1,...,6480+72+6+2,...}$
Now provide the response and nothing else.
| The quarter-squares are the numbers of form $k^2$ and $k(k+1)$. Start by expressing $N$ as the sum of four squares. If you used some square four times, i.e. $N=x^2 + x^2 + x^2 + x^2$, then $N=(2x)^2$ is a quarter-square. If you used some square three times but not four times, i.e. $N=x^2 + x^2 + x^2 + y^2$, then $N=(x-1)x + x^2 + x(x+1) + y^2$ is a sum of four distinct quarter-squares. If you used some square twice combined with two other distinct squares, i.e. $N=x^2 + x^2 + y^2 + z^2$, then $N=(x-1)x + x(x+1) + y^2 + z^2$ is a sum of four distinct quarter-squares. If you used two distinct squares twice each, i.e. $N=x^2 + x^2 + y^2 + y^2$, then $N=(x+y)^2 + (x-y)^2$ is a sum of two distinct quarter-squares. Finally, if you used four distinct squares, then $N$ is clearly the sum of four distinct quarter-squares. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/202903', 'https://mathoverflow.net', 'https://mathoverflow.net/users/61426/']} | jdg_72109 |
stackexchange | llm_judgeable_groundtruth_similarity | 71783377 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While implementing a custom tuple ( here) , I found there is a wired swap() function that takes const parameters ( cppreference ): template< class... Types >constexpr void swap( const std::tuple<Types...>& lhs, const std::tuple<Types...>& rhs ) noexcept(/* see below */); and a const-qualified swap() member function ( cppreference ): constexpr void swap( const tuple& other ) noexcept(/* see below */) const; const means the object is read-only, but to swap two objects, it has to modify the objects, which violates the const -ness. So, What's the purpose of const swap() function?
Now provide the response and nothing else.
| This was introduced in the "zip" proposal P2321 originally described in "A Plan for C++23 Ranges" P2214 . P2321 swap for const tuple and const pair. Once tuples of references aremade const-assignable, the default std::swap can be called for consttuples of references. However, that triple-move swap does the wrongthing: int i = 1, j = 2;const auto t1 = std::tie(i), t2 = std::tie(j);// If std::swap(t1, t2); called the default triple-move std::swap then// this would doauto tmp = std::move(t1);t1 = std::move(t2);t2 = std::move(tmp);// i == 2, j == 2 This paper therefore proposes adding overloads of swap for consttuples and pairs to correctly perform element-wise swap. P2214 explains why const assignability is needed for the implementation of zip . It stems from assignment operators not being ref qualified. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/71783377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10953565/']} | jdg_72110 |
stackexchange | llm_judgeable_groundtruth_similarity | 437522 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $T$ be a transformation from $P_2$ to $P_2$ (where $P_2$ is the space of all polynomials with degree less than or equal to $2$) $$T(f(t)) = f''(t)f(t)$$ I'm tempted to say that this is not a linear transformation because $$T(f(t) + g(t)) = (f''(t) + g''(t))(f(t) + g(t))$$ Which does not equal $$T(f(t)) + T(g(t))$$ But I'm not sure if I did that correctly...
Now provide the response and nothing else.
| You are correct, but to complete the job, you should provide a counterexample --that is, specific $f,g\in P_2$. such that $T(f+g)\ne T(f)+T(g)$. Alternately, find a scalar $\alpha$ and an $f\in P_2$ such that $T(\alpha f)\ne\alpha T(f)$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/437522', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/84934/']} | jdg_72111 |
stackexchange | llm_judgeable_groundtruth_similarity | 2953534 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the set $$A = \{-n + 1/n \ : n \in \mathbb{N}\}$$ My attempt I tried to find some limit point in A, but $$\lim_n (-n + 1/n) = -\infty$$ Is there anyone to help?
Now provide the response and nothing else.
| The complement of $A$ is $\bigcup_{n\in\mathbb N}(-n-1+\frac1{n+1},-n+\frac1n)\bigcup(0,+\infty)$ , which is a union of open intervals, thus open. Therefore $A$ , as the complement of an open subset, is closed. Hope this helps. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2953534', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/574517/']} | jdg_72112 |
stackexchange | llm_judgeable_groundtruth_similarity | 40143289 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was going through the Python documentation for asyncio and I'm wondering why most examples use loop.run_until_complete() as opposed to Asyncio.ensure_future() . For example: https://docs.python.org/dev/library/asyncio-task.html It seems ensure_future would be a much better way to demonstrate the advantages of non-blocking functions. run_until_complete on the other hand, blocks the loop like synchronous functions do. This makes me feel like I should be using run_until_complete instead of a combination of ensure_future with loop.run_forever() to run multiple co-routines concurrently.
Now provide the response and nothing else.
| run_until_complete is used to run a future until it's finished. It will block the execution of code following it. It does, however, cause the event loop to run. Any futures that have been scheduled will run until the future passed to run_until_complete is done. Given this example: import asyncioasync def do_io(): print('io start') await asyncio.sleep(5) print('io end')async def do_other_things(): print('doing other things')loop = asyncio.get_event_loop()loop.run_until_complete(do_io())loop.run_until_complete(do_other_things())loop.close() do_io will run. After it's complete, do_other_things will run. Your output will be: io startio enddoing other things If you schedule do_other_things with the event loop before running do_io , control will switch from do_io to do_other_things when the former awaits. loop.create_task(do_other_things())loop.run_until_complete(do_io()) This will get you the output of: doing other thingsio startio end This is because do_other_things was scheduled before do_io . There are a lot of different ways to get the same output, but which one makes sense really depends on what your application actually does. So I'll leave that as an exercise to the reader. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40143289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1462505/']} | jdg_72113 |
stackexchange | llm_judgeable_groundtruth_similarity | 54999775 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I created my first own service in Symfony : // src/Service/PagesGenerator.php namespace App\Service;class PagesGenerator{ public function getPages() { $page = $this->getDoctrine()->getRepository(Pages::class)->findOneBy(['slug'=>$slug]); $messages = [ 'You did it! You updated the system! Amazing!', 'That was one of the coolest updates I\'ve seen all day!', 'Great work! Keep going!', ]; $index = array_rand($messages); return $messages[$index]; }} But I get the error message: Attempted to call an undefined method named "getDoctrine" of class "App\Service\PagesGenerator". I tried then to add in my services.yaml: PagesGenerator: class: %PagesGenerator.class% arguments: - "@doctrine.orm.entity_manager" But then I get the error message: The file "/Users/work/project/config/services.yaml" does not contain valid YAML in /Users/work/project/config/services.yaml (which is loaded in resource "/Users/work/project/config/services.yaml").
Now provide the response and nothing else.
| So, in comments I was saying that is better to let Symfony doing his job and autowiring EntityManager . This is what you should do. Also, can you tell us what Symfony version are you using and if autowiring is enabled (check services.yaml for that)? <?phpnamespace App\Service;use Doctrine\ORM\EntityManagerInterface;class PagesGenerator{ public function __construct(EntityManagerInterface $em) { $this->em = $em; } public function getPages() { $page = $this->em->getRepository(Pages::class)->findOneBy(['slug'=>$slug]); $messages = [ 'You did it! You updated the system! Amazing!', 'That was one of the coolest updates I\'ve seen all day!', 'Great work! Keep going!', ]; $index = array_rand($messages); return $messages[$index]; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54999775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5024157/']} | jdg_72114 |
stackexchange | llm_judgeable_groundtruth_similarity | 15495678 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a simple way to flatten a collection of try's to give either a success of the try values, or just the failure?For example: def map(l:List[Int]) = l map { case 4 => Failure(new Exception("failed")) case i => Success(i)}val l1 = List(1,2,3,4,5,6)val result1 = something(map(l1))result1: Failure(Exception("failed"))val l2 = List(1,2,3,5,6)val result2 = something(map(l2)) result2: Try(List(1,2,3,5,6)) And can how would you handle multiple Failures in the collection?
Now provide the response and nothing else.
| This is pretty close to minimal for fail-first operation: def something[A](xs: Seq[Try[A]]) = Try(xs.map(_.get)) (to the point where you shouldn't bother creating a method; just use Try ). If you want all the failures, a method is reasonable; I'd use an Either : def something[A](xs: Seq[Try[A]]) = Try(Right(xs.map(_.get))). getOrElse(Left(xs.collect{ case Failure(t) => t })) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15495678', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/591032/']} | jdg_72115 |
stackexchange | llm_judgeable_groundtruth_similarity | 4234202 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a Windows Phone 7 application built in Silverlight. This application makes use of the application bar. If the has purchased the application, I want to hide one of the buttons in the application bar. However, I've noticed that the ApplicationIconButton class does not expose a "Visibility" property. At the same time, I did not see a way to dynamically populate the application bar at runtime. Can anybody provide some insight into this? Is this possible? If so, how? Thanks!
Now provide the response and nothing else.
| Application bar buttons work in an index-based way rather than object-based like you would expect. Therefore, you need to specify a button index whenever you want to perform a specific action on it (e.g. disable). For example: ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0];b.IsEnabled = false; This being said, you can create new ApplicationBarIconButton instances and pass them to ApplicationBar: for (int i = 0; i < 2; i++){ ApplicationBarIconButton b = new ApplicationBarIconButton(); b.Text = i.ToString(); b.IconUri = new Uri("/Images/icon1.png", UriKind.Relative); ApplicationBar.Buttons.Add(b);} When removing buttons, you can simply use RemoveAt, given that you know the index of the button to remove: ApplicationBar.Buttons.RemoveAt(0); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4234202', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/208662/']} | jdg_72116 |
stackexchange | llm_judgeable_groundtruth_similarity | 3723846 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do you convert from color HEX code to RGB in pure C using C library only (without C++ or templates)? The RGB struct may be like this: typedef struct RGB { double r; double g; double b;} RGB1; The function I'm looking for should return RGB1.
Now provide the response and nothing else.
| Assuming that your hex value is a 32-bit 'int' type, and that we use the RGB struct described above, then maybe do something like: struct RGB colorConverter(int hexValue){ struct RGB rgbColor; rgbColor.r = ((hexValue >> 16) & 0xFF) / 255.0; // Extract the RR byte rgbColor.g = ((hexValue >> 8) & 0xFF) / 255.0; // Extract the GG byte rgbColor.b = ((hexValue) & 0xFF) / 255.0; // Extract the BB byte return rgbColor; } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3723846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/449125/']} | jdg_72117 |
stackexchange | llm_judgeable_groundtruth_similarity | 13513302 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to Unity 3D and I want to do just little task: to set image on a Texture instance in Unity 3D. I don't know how to do this at runtime, and I also would like to know how I set its transparency low. I don't need Texture2D - I just need Texture. My image is in .png format. I also want set an image from my documents directory on to this texture.
Now provide the response and nothing else.
| First import your image into your project by simply dropping it in your project window. Select the image once it's in the project window and make sure that it is set to a Texture Type of Texture in your inspector. Next, create a new material by right clicking in your project window. Next you want to assign your image to this material and you can go about doing this by dragging and dropping your image (which is in the project window) on to your newly created material. In recent versions of Unity, you will need to drop it on the square to the left of "Albedo". Then click on the new material and in your inspector window it should show you that your image is the active texture and the shader should be set to diffuse by default. To activate transparency you'll want to change the shader type by clicking on the shader drop down menu in the inspector window and selecting Transparent/Diffuse (or any of the transparency options depending on what look you're going for). After this to change it's transparency, simply click on the main color swatch and there should be a new window that opens giving you all kinds of modifiers (with 4 horizontal sliders to adjust Red, Green, Blue & Alpha). Adjust the Alpha slider to affect the transparency of your material. Now, whenever you need to make a call to your material at runtime (e.g if you wanted to change the texture applied to a gameobject), simply do so by using: renderer.material This will affect the material off the gameObject that the script is attached to. So for example, if you wanted to change the texture at runtime from script you could say: // Assign the texture exposed in the inspector the renderer's materialvar texture : Texture;renderer.material.mainTexture = texture; And if you wanted to change the alpha channel: renderer.material.color.a = 0 // For example Hope this helps. Let me know if anything needs clarifying. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13513302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471676/']} | jdg_72118 |
stackexchange | llm_judgeable_groundtruth_similarity | 1814970 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a TableView that builds and draws ok, but then crashes on scrolling the view. I've run through the debugger and it appears that my class level variables are being overwritten somehow so they no longer exist when the titleForHeaderInSection is being called again. The very strange thing is that if I replace the code: -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{NSString *sectionTitle = [favouritesDataSections objectAtIndex:section];return sectionTitle;} with: -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{NSString *sectionTitle = @"Test";return sectionTitle;} It still crashes but this time the debugger lists not an NSString when you hover over the sectionTitle variable. This is the code I used to create the view and set up the class level variables: - (void)loadView {[super loadView];CGRect tableSize = CGRectMake(0,0,320,460);UITableView *favouritesTableView = [[UITableView alloc] initWithFrame:tableSize style:UITableViewStylePlain];favouritesTableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);favouritesTableView.dataSource = self;favouritesTableView.delegate = self;favouritesTableView.rowHeight = 52;[self.view addSubview:favouritesTableView];}- (void)viewDidLoad {[super viewDidLoad];NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = [paths objectAtIndex:0];// Get the full path of the favourites plistNSString *filename = [documentsDirectory stringByAppendingPathComponent:@"Favourites.plist"];// Initialise Dictionary and arrayfavouritesDataAll = [[NSMutableDictionary alloc] init];favouritesDataSections = [[NSArray alloc] init];NSDictionary *dict = [[[NSMutableDictionary alloc] initWithContentsOfFile:filename] retain];favouritesDataAll = dict;[dict release];favouritesDataSections = [favouritesDataAll allKeys]; } I am going absolutely mad trying to track this down - spent 2 days on it so far so would be externally grateful for any help. Best regards Dave
Now provide the response and nothing else.
| OK, fixed it... changed favouritesDataSections = [favouritesDataAll allKeys]; To: favouritesDataSections = [[favouritesDataAll allKeys] retain]; And it all appears to work. From this I would deduce that the array I was using to store the section headings was pointing to data that was autoreleased at some random point, which is why it was barfing at seemingly odd places. I do admit though that I am still at the "trial and error" stage of coding and don't fully understand what I am doing (I am sure you will be cringing reading this). It would be useful to me if you have any thoughts/comments links to further reading or posts about how all this is working (i.e., when and why to use retain, etc) to further my understanding. Thanks again, Dave | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1814970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218394/']} | jdg_72119 |
stackexchange | llm_judgeable_groundtruth_similarity | 9710411 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I have property A on classA and property B on classB and I want classAB to have both properties A and B . I still don't understand how to make this all work with composition . I realize this can be done with inheritance, but I want to learn how to do this with composition . I've looked at examples and I still don't get how it all works.
Now provide the response and nothing else.
| You make a new class, which has instances of classA and classB as member variables. Then you implement the properties by passing through the get/set methods. @interface ClassAB{ ClassA *objectA; ClassB *objectB;}@property (nonatomic,strong) id propertyA;@property (nonatomic,strong) id propertyB;@end@implementation ClassAB- (id)propertyA { return objectA.propertyA; }- (void)setPropertyA:(id)value { objectA.propertyA = value; }- (id)propertyB { return objectB.propertyB; }- (void)setPropertyB:(id)value { objectB.propertyB = value; }@end And that's what composition is. Some languages have special syntax to do this (e.g., in Ruby you can include a set of methods from one class/module in another), but Objective-C doesn't allow this. One thing you can do in Objective-C is catch messages sent to your object which do not have an associated method, and forward them to another object. This trick is useful if you are writing a class that will pose as another class, or if there are many different messages to forward and you don't want to write them all out manually. The downside to using message forwarding is that you give up some control and it can be a harder to predict when a message will be handled by your class or the forwarding class. For example, if a superclass implements a method, that method will be executed and the forwarding code will not be called. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9710411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/332578/']} | jdg_72120 |
stackexchange | llm_judgeable_groundtruth_similarity | 517 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Having two different size of sets of points (2D for simplicity) dispersed within two different size squares the question are that: 1- how to find any occurrence of the the small one through the large one? 2- Any idea on how to rank the occurrences as shown on the following figure? Here is a simple demonstration of the question and a desired solution: Update 1: The following figure shows a bit more realistic view of the problem being investigated. Regarding the comments the following properties apply: exact location of points are available exact size of points are available size can be zero(~1) = only a point all points are black on a white background there is no gray-scale/anti-aliasing effect Here is my implementation of the method presented by endolith with some small changes (I rotated target instead of source since it is smaller and faster in rotation). I accepted 'endolith's answer because I was thinking about that before. About RANSAC I have no experience so far. Furthermore the implementation of RANSAC requires lots of code.
Now provide the response and nothing else.
| This is not the best solution, but it's a solution. I'd like to learn of better techniques: If they were not going to be rotated or scaled, you could use a simple cross-correlation of the images. There will be a bright peak wherever the small image occurs in the large image. Registering an Image Using Normalized Cross-Correlation Template-based matching and convolution You can speed up cross-correlation by using an FFT method, but if you're just matching a small source image with a large target image, the brute-force multiply-and-add method is sometimes (not usually) faster. Source: Target: Cross-correlation: The two bright spots are the locations that match. But you do have a rotation parameter in your example image, so that won't work by itself. If only rotation is allowed, and not scaling, then it is still possible to use cross-correlation, but you need to cross-correlate, rotate the source, cross-correlate it with the entire target image, rotate it again, etc. for all rotations. Note that this will not necessarily ever find the image. If the source image is random noise, and the target is random noise, you won't find it unless you search at exactly the right angle. For normal situations, it will probably find it, but it depends on the image properties and the angles you search in. This page shows an example of how it would be done, but doesn't give the algorithm. Any offset where the sum is above some threshold is a match. You can calculate the goodness of the match by correlating the source image with itself and dividing all your sums by this number. A perfect match will be 1.0. This will be very computationally heavy, though, and there are probably better methods for matching patterns of dots (which I would like to know about). Quick Python example using grayscale and FFT method: from __future__ import divisionfrom pylab import *import Imageimport ImageOpssource_file = 'dots source.png'target_file = 'dots target.png'# Load file as grayscale with white dotstarget = asarray(ImageOps.invert(Image.open(target_file).convert('L')))close('all')figure()imshow(target)gray()show()source_Image = ImageOps.invert(Image.open(source_file).convert('L'))for angle in (0, 180): source = asarray(source_Image.rotate(angle, expand = True)) best_match = max(fftconvolve(source[::-1,::-1], source).flat) # Cross-correlation using FFT d = fftconvolve(source[::-1,::-1], target, mode='same') figure() imshow(source) # This only finds a single peak. Use something that finds multiple peaks instead: peak_x, peak_y = unravel_index(argmax(d),shape(d)) figure() plot(peak_y, peak_x,'ro') imshow(d) # Keep track of all these matches: print angle, peak_x, peak_y, d[peak_x,peak_y] / best_match 1-color bitmaps For 1-color bitmaps, this would be much faster, though. Cross-correlation becomes: Place source image over target image bitwise-AND all overlapping pixels (much faster than multiplication) sum all the 1s in the overlapped area Move source image by 1 pixel bitwise-AND all overlapping pixels sum all the 1s ... Thresholding a grayscale image to binary and then doing this might be good enough. Point cloud If the source and target are both patterns of dots, a faster method would be to find the centers of each dot (cross-correlate once with a known dot and then find the peaks) and store them as a set of points, then match source to target by rotating, translating, and finding the least squares error between nearest points in the two sets. | {} | {'log_upvote_score': 5, 'links': ['https://dsp.stackexchange.com/questions/517', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/488/']} | jdg_72121 |
stackexchange | llm_judgeable_groundtruth_similarity | 373193 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is classpath hell and is/was it really a problem for Java?
Now provide the response and nothing else.
| Classpath hell is an unfortunate consequence of dynamic linking of the kind carried out by Java. Your program is not a fixed entity but rather the exact set of classes loaded by a JVM in a particular instance. It is very possible to be in situations where the same command line on different platforms or even on the same one would result in completely different results because of the resolution rules. There could be differences in standard libraries (very common). Libraries could be hidden by one another (an an older version may even be used instead of a newer one). The directory structure could mess resolution. A different version of the same class may appear in multiple libraries and the first one encountered will be used, etc. Since Java, by specification, uses a first-encountered policy, unknown ordering dependencies can lead to problems. Of course, since this is the command line and it is part of the spec, there are no real warnings. It is very much still a problem. For example on Mac OS the horrible support from Apple means that you machine ends up with several JVMs and several JREs, and you can never easily poart things from place to place. If you have multiple libraries that were compiled against specific but different versions of other libraries, you coulld have problems, etc. However, this problem is not inherent in Java. I remember my share of DLL hell situations while programming windows in the 90s. Any situation where you have to count on something in the file system to assemble your program rather than having a single well defined executable is a problem. However, the benefits of this model are still great, so I'm willing to tolerate this hell. There are also steps in the right direction on the side of Sun. For example, Java6 allows you to simply specify a directory with jars rather than have to enumerate them. BTW: Classpaths are also a problem if you are using an environment that uses a non-default classloader. For example, I have had a lot of problems running things like Hibernate or Digester under Eclipse because the classloaders were incompatible. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/373193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5274/']} | jdg_72122 |
stackexchange | llm_judgeable_groundtruth_similarity | 5009258 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My program (which happens to be in Perl, though I don't think this question is Perl-specific) outputs status messages at one point in the program of the form Progress: x/yy where x and yy are a number, like: Progress: 4/38 . I'd like to "overwrite" the previous output when a new status message is printed so I don't fill the screen with status messages. So far, I've tried this: my $progressString = "Progress\t$counter / " . $total . "\n";print $progressString;#do lots of processing, update $countermy $i = 0;while ($i < length($progressString)) { print "\b"; ++$i;} The backspace character won't print if I include a newline in $progressString . If I leave out the newline, however, the output buffer is never flushed and nothing prints. What's a good solution for this?
Now provide the response and nothing else.
| Use autoflush with STDOUT: local $| = 1; # Or use IO::Handle; STDOUT->autoflush;print 'Progress: ';my $progressString;while ...{ # remove prev progress print "\b" x length($progressString) if defined $progressString; # do lots of processing, update $counter $progressString = "$counter / $total"; # No more newline print $progressString; # Will print, because auto-flush is on # end of processing}print "\n"; # Don't forget the trailing newline | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5009258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/262347/']} | jdg_72123 |
stackexchange | llm_judgeable_groundtruth_similarity | 2465086 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A very specific question from a novice to TDD : I separate my tests and my application into different packages. Thus, most of my application methods have to be public for tests to access them. As I progress, it becomes obvious that some methods could become private, but if I make that change, the tests that access them won't work. Am I missing a step, or doing something wrong, or is this just one downfall of TDD?
Now provide the response and nothing else.
| This is not a downfall of TDD, but rather an approach to testing that believes you need to test every property and every method. In fact you should not care about private methods when testing because they should only exist to facilitate some public portion of the API. Never change something from private to public for testing purposes! You should be trying to verify only publicly visible behavior. The rest are implementation details and you specifically want to avoid testing those. TDD is meant to give you a set of tests that will allow you to easily change the implementation details without breaking the tests (changing behavior). Let’s say I have a type: MyClass and I want to test the DoStuff method. All I care about is that the DoStuff method does something meaningful and returns the expected results. It may call a hundred private methods to get to that point, but I don't care as the consumer of that method. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2465086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/295959/']} | jdg_72124 |
stackexchange | llm_judgeable_groundtruth_similarity | 9222 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I believe the quarks would flip the proton's internal charge, reverse the spin of the proton, transform into another flavor, and then become unconfined and free.
Now provide the response and nothing else.
| The proton ($uud$) turns into a neutron ($ddu$). Up and down quarks don't have equal charges; the up is $+\frac{2}{3}e$ and the down is $-\frac{1}{3}e$. By the way, such an operation has a name - isospin symmetry transformation - corresponding to an approximate SU(2) symmetry that makes the proton and neutron have almost similar masses. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/9222', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/3322/']} | jdg_72125 |
stackexchange | llm_judgeable_groundtruth_similarity | 30170 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Considering AES-256 encryption, what is the maximum amount of data should be encrypted with one key? Does Block cipher modes/IV/counters also governs the limit? If say the maximum amount is 50GB, does it mean the one file of 50GB has limit or 5 files of 10GB?
Now provide the response and nothing else.
| A block cipher is a Pseudorandom permutation : the key selects the function seemingly at random in the set of possible permutations of the space of block values (that space has size 2 128 for the AES, since it has 128-bit blocks). Most usages of a PRP are fine as long as it looks like a Pseudorandom function . The difference between a PRP and a PRF is that the PRP will never give you two identical outputs for two distinct inputs, whereas the PRF may do so. However, a randomly selected function will give you such a collision only out of random, and it will require a lot of invocations: on average, 2 N/2 invocations if processing blocks of size N. Translation: when you encrypt more than 2 64 blocks with AES (i.e. 2 68 bytes, since an AES block is 16 bytes), AES begins to look more like a PRP than a PRF, and that's the point where you should stop. That's more than 250 millions of terabytes, which is quite a substantial amount. It does not matter whether the said amount of data was processed as one, ten or 42 billions of whatever you may elect to call a "file". The AES processes blocks of 16 bytes and knows nothing else. On the other hand, it does not matter at all, since you will not practically reach that 2 68 bytes limit: AES was defined with 128-bit blocks precisely so that we could encrypt terabytes of data without worrying about a key running out of juice. When AES was specified, it was meant to replace 3DES , whose 64-bit block size was indeed worrying (2 32 blocks of 8 bytes, that's 32 gigabytes, which can be reached quite easily on today's machines). Key size has nothing to do whatsoever with that matter. It is all about block size , and that's 128 bits for AES (regardless of key size). | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/30170', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/20322/']} | jdg_72126 |
stackexchange | llm_judgeable_groundtruth_similarity | 550075 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to update a software sdman in my macOs But I get bash outadted version error. rajkumar.natarajan$ sdk update An outdated version of bash was detected on your system! We recommend upgrading to bash 4.x, you have: 3.2.57(1)-release Need to use brute force to replace candidates... But bash version is already latest. rajkumar.natarajan$ which bash /usr/local/bin/bash rajkumar.natarajan$ bash --version GNU bash, version 5.0.11(1)-release (x86_64-apple-darwin16.7.0)Copyright (C) 2019 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software; you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.
Now provide the response and nothing else.
| sdman is looking at /bin/bash which is version 3.2.57 because macos cannot ship with anything newer than it. The reason that Apple includes such an old version of Bash in its operating system has to do with licensing. Since version 4.0 (successor of 3.2), Bash uses the GNU General Public License v3 (GPLv3), which Apple does not (want to) support. You can find some discussions about this here and here. Version 3.2 of GNU Bash is the last version with GPLv2, which Apple accepts, and so it sticks with it. source You have installed a modern version of bash but you haven't replaced /bin/bash with it. I don't really recommend doing that as it could potentially break some legacy scripts/programs (unlikely but possible). My recommendation is to ignore that warning. It's warning you because bash v3.2 normally would suffer from the shellshock vulnerability, however Apple has patched this in their version of Bash v3.2. If you are unable to ignore that warning and really want to risk updating your /bin/bash I would move it to a backup location and symlink your new bash to it. sudo mv /bin/bash /bin/bash.baksudo ln -s /usr/local/bin/bash /bin/bash But in order to do this you will need to bypass SIP To enable or disable System Integrity Protection, you must boot to Recovery OS and run the csrutil(1) command from the Terminal. Boot to Recovery OS by restarting your machine and holding down the Command and R keys at startup. Launch Terminal from the Utilities menu. Enter the following command: $ csrutil disable After enabling or disabling System Integrity Protection on a machine, a reboot is required. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/550075', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/253851/']} | jdg_72127 |
stackexchange | llm_judgeable_groundtruth_similarity | 8917400 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are trying to configure Spring JavaMailSender to work with Amazon's SES service using SMTP, but we are getting this error: javax.mail.MessagingException: Could not connect to SMTP host: email-smtp.us-east-1.amazonaws.com, port: 465, response: -1 This is our configuration: <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="email-smtp.us-east-1.amazonaws.com" /> <property name="port" value="465" /> <property name="username" value="..." /> <property name="password" value="..." /> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.ssl.enable">true</prop> </props> </property></bean> Any ideas what could be wrong? Thanks in advance. PS: We already tried the solution here: Could not connect to SMTP host: email-smtp.us-east-1.amazonaws.com, port: 465, response: -1 without any luck.
Now provide the response and nothing else.
| Based on @GuCo answer: This is the full configuration that worked for me: <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="email-smtp.us-east-1.amazonaws.com" /> <property name="port" value="465" /> <property name="protocol" value="smtps" /> <property name="username" value="..." /> <property name="password" value="..." /> <property name="javaMailProperties"> <props> <prop key="mail.smtps.auth">true</prop> <prop key="mail.smtp.ssl.enable">true</prop> <prop key="mail.transport.protocol">smtps</prop> </props> </property></bean> Do not forget the <property name="protocol" value="smtps" /> configuration, or else the javaMailProperties are not taken into consideration. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8917400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/590894/']} | jdg_72128 |
stackexchange | llm_judgeable_groundtruth_similarity | 453394 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the polynomial $P(x)=x^{2}+2013x+1$ and a number $n\in\mathbb{N}$. Now I have to show that the polynomial $P(P(...P(x)...)$ $(n$ times$)$ has at least one real root. How can I do this?
Now provide the response and nothing else.
| Note that the quadratic equation $$P(x)=x$$has some real root $x_-<0$. For every $n\ge 1$, denote the $n$-th iteration of $P$ by $P^{\circ n}$. Then $$P^{\circ n}(x_-)=x_-<0\quad\text{and}\quad P^{\circ n}(+\infty)=+\infty,$$so there exists $x_n\in(x_-,+\infty)$, such that $P^{\circ n}(x_n)=0$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/453394', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/74812/']} | jdg_72129 |
stackexchange | llm_judgeable_groundtruth_similarity | 15057146 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking to redirect each and every page on the old domain to a single page on the new domain. It should also redirect both the www and non-www versions. Every single request to the domain old.com, whatever it may be, should lead to www.new.com root. old.com/1.phpwww.old.com/2.phpold.com/2.phpold.com/links/index.phpold.com/about-us.htmlold.com/?string=1 should all redirect to: www.new.com/ I'm looking for a .htaccess solution.
Now provide the response and nothing else.
| You can use RedirectMatch in the old.com vhost RedirectMatch permanent .* http://www.new.com/ Redirect appends the trailing portion of the matched URI to the redirection URI but with RedirectMatch it's up to you to choose the parts (if any) that you want to transfer using parentheses and $number references. If the old and new domains must be aliases for the same document root on disk then you'll probably have to use mod_rewrite RewriteEngine onRewriteCond %{HTTP_HOST} old\.com$RewriteRule .* http://www.new.com/ [L,R=301] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15057146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1121076/']} | jdg_72130 |
stackexchange | llm_judgeable_groundtruth_similarity | 3902432 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This page I have been developing for my app has been working fine locally (using sqllite3) but when I push it to Heroku, which uses PostgreSQL I get this error: NeighborhoodsController# (ActionView::Template::Error) "PGError: ERROR: column \"isupforconsideration\" does not exist\nLINE 1: ... \"photos\" WHERE (neighborhood = 52 AND isUpForCon...\n From this line of code: @photos = Photo.where(["neighborhood = ? AND isUpForConsideration = ?", @neighborhood.id, 1]) isUpForConsideration is defiantly part of the Photo column. All my migrations are up to date, and when I pull the db back locally isUpForConsideration is still there, and the app still works locally. I've also tried: @photos = @neighborhood.photos(:conditions => {:isUpForConsideration => 1}) and @photos = @neighborhood.photos.where(["isUpForConsideration = 1"]) Which gives me this error: NeighborhoodsController# (ActionView::Template::Error) "PGError: ERROR: column \"isupforconsideration\" does not exist\nLINE 1: ...tos\" WHERE (\"photos\".neighborhood = 52) AND (isUpForCon...\n Any idea what I could be doing wrong?
Now provide the response and nothing else.
| Your problem is that table and column names are case sensitive in PostgreSQL . This is normally hidden by automatically converting these to all-lowercase when making queries (hence why you see the error message reporting "isupforconsideration"), but if you managed to dodge that conversion on creation (by double quoting the name, like Rails does for you when you create a table), you'll see this weirdness. You need to enclose "isUpForConsideration" in double quotes when using it in a WHERE clause to fix this. e.g. @photos = @neighborhood.photos.where(["\"isUpForConsideration\" = 1"]) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3902432', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1704467/']} | jdg_72131 |
stackexchange | llm_judgeable_groundtruth_similarity | 38604524 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have installed redis with laravel by adding "predis/predis":"~1.0" , Then for testing i added the following code : public function showRedis($id = 1) { $user = Redis::get('user:profile:'.$id); Xdd($user); } In app/config/database.php i have : 'redis' => [ 'cluster' => false, 'default' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], ], It throws the following error : No connection could be made because the target machine actively refused it. [tcp://127.0.0.1:6379] I using virtualhost for the project.Using Xampp with windows .
Now provide the response and nothing else.
| First make sure Redis is actually listening on that port by opening up powershell and typing netstat -aon | more (this command may need to be enabled in features or installed somehow). If it is listening then check your firewall settings. If if not listening then make sure Redis is started and is configured to listen on that port. It looks like predis/predis is a client library only. See https://packagist.org/packages/predis/predis . You need to install the Redis server, but it looks like it is not officially supported on Windows. See http://redis.io/download . Per information on that page, it looks like there is a Win64 port for Redis here https://github.com/MSOpenTech/redis . If it still doesn't work after that then update your question with the new error you see. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38604524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4866624/']} | jdg_72132 |
stackexchange | llm_judgeable_groundtruth_similarity | 28812670 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I was wondering if there was a way to throw a wildcard into my CSS? I have several classes that are .button-0 , .button-1 , .button-2 , .button-3 , etc. within a button element. I want to get all the .button-* classes to define. Is it possible to do something like: button .button-[=*] { margin-right: 2rem; }
Now provide the response and nothing else.
| Use an attribute selector : button [class*="button-"] { margin-right: 2rem; } Example Here From MDN : [attr*=value] - Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring. button [class*="button-"] { color: red;} <button> <span class="button-0">text</span> <span class="button-1">text</span> <span class="button-2">text</span></button> As Chad points out , it is entirely possible that an element can contain a class such as this-is-my-button-class . In which case, that undesired element would be selected. In order to prevent this, you could use a combination of two selectors: Example Here button [class^="button-"],button [class*=" button-"] { margin-right: 2rem; } The selector button [class^="button-"] ensures that the element will be selected if it starts with button- . Since it's possible the element's first class doesn't start with button- , the selector [class*=" button-"] (note the whitespace), ensures that it will be selected. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28812670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1214914/']} | jdg_72133 |
stackexchange | llm_judgeable_groundtruth_similarity | 436999 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I ensure that I can always have Hyper-V Manager access to a Hyper-V server, even in the event that the Active Directory Server is down (in a domain-login environment)? Background: The person who managed infrastructure before me set up the company's servers as virtual machines on top of a host running Hyper-V Server 6.1 (7601) Service Pack 1. To manage Hyper-V, he installed Windows 7 onto a virtual machine (run on the same host) with Hyper-V Manager installed. When the (virtual) Active Directory server (run on this same host) is rebooted, during that reboot, I'm unable to RDP into the Windows 7 virtual machine, and I'm therefore unable to access Hyper-V Manager when the Active Directory server is down. I suspect I can't login because I can't authenticate with the Active Directory Server. I'm going to install Hyper-V Manger onto some addition manager's workstations, but how can I ensure they'll have access in a catastrophe where Active Directory authentication isn't possible?
Now provide the response and nothing else.
| Now I want one email to be sent as a report for the critical alerts of last one day daily. Edit the nagios.cfg to change the rotation method to daily: # LOG ROTATION METHOD# This is the log rotation method that Nagios should use to rotate# the main log file. Values are as follows..# n = None - don't rotate the log# h = Hourly rotation (top of the hour)# d = Daily rotation (midnight every day)# w = Weekly rotation (midnight on Saturday evening)# m = Monthly rotation (midnight last day of month)log_rotation_method=d then parse the nagios.log for the CRITICAL alerts, something like this: awk '/SERVICE ALERT: .*;CRITICAL;HARD/ { print $0 }' nagios.log | \ perl -pe 's/(\d+)/localtime($1)/e' | \ mail -s "Nagios daily report $(date +%F)" <your_email>@domain.com Run the above command at the end of day as a daily cron job if you want. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/436999', 'https://serverfault.com', 'https://serverfault.com/users/35720/']} | jdg_72134 |
stackexchange | llm_judgeable_groundtruth_similarity | 409440 |
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am currently doing Low Quality Post reviews. Strangely, I seem to be in a rough loop where I can't skip beyond the same three or four posts: I doubt this is client-side, but I'm using Firefox 90.8b8 on Arch Linux.
Now provide the response and nothing else.
| This is fixed. I shipped a change yesterday that allowed users to return to their skipped LQP tasks, and boy did I let them go back to them. Basically, I fixed the "can a user review this post" sub-query to support returning to skipped posts, but the "give me the next post for a user" query was depending on that to exclude previously skipped tasks rather than including the default logic for that. This problem was compounded for users with the trusted privilege, since if a post they can review has a recommend delete vote, they're only served review tasks with those votes. (Something similar happens with watched and ignored tags.) This meant instead of getting the skipped question 1 out of 125 times, you maybe got it one out of 5 times. All queues now consistently filter out tasks you have reviewed in that queue instead of depending on the subquery to manage that exclusion. | {} | {'log_upvote_score': 5, 'links': ['https://meta.stackoverflow.com/questions/409440', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/354577/']} | jdg_72135 |
stackexchange | llm_judgeable_groundtruth_similarity | 35305875 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can I load a spinner in placeholder with rotating animation until the image is loaded using Glide? I am trying to do that using .placeholder(R.Drawable.spinner) no animation is coming up? It would be great if somebody could help me out? Thanks!
Now provide the response and nothing else.
| Edit: This is super simple now with the CircularProgressDrawable build.gradle implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0" MyGlideModule.kt @GlideModuleclass MyGlideModule : AppGlideModule() MainActivity.kt override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val circularProgressDrawable = CircularProgressDrawable(this) circularProgressDrawable.strokeWidth = 5f circularProgressDrawable.centerRadius = 30f circularProgressDrawable.start() GlideApp.with(applicationContext) .load("https://raw.githubusercontent.com/bumptech/glide/master/static/glide_logo.png") .placeholder(circularProgressDrawable) .into(a_main_image)} These are some other Glide snippets Old answer: You could also create a normal ProgressBar, and then hide it on Glide's onResourceReady() . The method that will be called when the resource load has finished. Example : MainActivity.java @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ImageView imageView = (ImageView) findViewById(R.id.img_glide); final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress); Glide.with(this) .load("https://raw.githubusercontent.com/bumptech/glide/master/static/glide_logo.png") .listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { progressBar.setVisibility(View.GONE); return false; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { progressBar.setVisibility(View.GONE); return false; } }) .into(imageView);} activity_main.xml (layout): <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ProgressBar android:id="@+id/progress" android:layout_width="match_parent" android:layout_height="100dp" android:visibility="visible" /> <ImageView android:id="@+id/img_glide" android:layout_width="match_parent" android:layout_height="100dp" /></RelativeLayout> Result: | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/35305875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4906944/']} | jdg_72136 |
stackexchange | llm_judgeable_groundtruth_similarity | 382339 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $f$ be analytic in a domain D and $f\neq0$. Let $\gamma$ be a curve homotopic to a point in D. I want to show that $$\int_{\gamma}\frac {f'(z)} {f(z)}=0$$ Honestly I don't know how to start. Any help would be greatly appreciated. Thank you!
Now provide the response and nothing else.
| This is usally answered in the context of Grothendieck's Galois Theory (where $G$ is a profinite group, for example the etale fundamental group of a scheme, and we only consider finite continuous $G$-sets). See Lenstra's notes on Galois theory for this. I only mention this as a background, the rest of this answer explains some of these ideas and hopefully answers your question. In $\mathsf{Set}(G)$ coproducts are just disjoint unions endowed with the obvious $G$-action, and the initial object is the empty set endowed with the unique $G$-action. More generally, the forgetful functor $U : \mathsf{Set}(G) \to \mathsf{Set}$ creates all colimits. (By the way, $U$ is represented by $G$, so that in particular $\mathrm{End}(U) \cong \mathrm{End}(G) = G$ and we can reconstruct the group $G$ from $U$ - this is the discrete Tannakian reconstruction.) An object of a category with coproducts is called connected if it is not initial and cannot be written as a coproduct of two non-initial objects. One can easily check that the connected objects of $\mathsf{Set}(G)$ are precisely the transitive $G$-sets. Besides, every object is a unique(!) coproduct of connected objects: This is the usual decomposition of an action into its orbits. The connected objects can be classified (up to non-canonical isomorphism), they are precisely the coset sets $G/U$, where $U$ is a subgroup of $G$. Here, $G/U$ and $G/V$ are isomorphic iff $U$ and $V$ are conjugated to each other. How to characterize the case that $U$ is normal? A connected object $X$ of a category with coproducts and quotients is called Galois if the quotient $X/\mathrm{Aut}(X)$ is a terminal object. One should imagine this as "the automorphism group of $X$ acts transitively on $X$". For $G/U \in \mathsf{Set}(G)$, the condition means that for all $g \in G$ there is some automorphism $\sigma : G/U \to G/U$ with $\sigma([1])=[g]$. But then for $u \in U$ we have $[ug] = u [g] = u \sigma([1]) = \sigma([u])=\sigma([1])=[g]$, i.e. $g^{-1} u g \in U$. Hence, $U$ is normal. The converse is also easy to check. Hence, the Galois objects of $\mathsf{Set}(G)$ correspond to the normal subgroups of $G$. Because you are learning topology, here is a reason why these category-theoretic notions are useful: If $X$ is a nice pointed topological space, then covering theory tells us that there is an equivalence of categories $\mathrm{Cov}(X) \cong \mathsf{Set}(\pi_1(X))$. Every equivalence of categories preserves objects and properties defined in the language of category theory. So for example we see that every covering space is a unique disjoint union of connected coverings, that normal subgroups of $\pi_1(X)$ correspond to Galois coverings of $X$, etc. We don't need extra arguments for this, the equivalence of categories is everything we need! | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/382339', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/44644/']} | jdg_72137 |
stackexchange | llm_judgeable_groundtruth_similarity | 3736663 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I really tried to, but I can't understand how Android interprets layout_weight setting... What I'm trying to achieve is a header on top with a fixed height an input area at the bottom containing an EditText and a Button a content part in the middle that's taking all what's left of space When typing I'd like to grow the EditText to a specific height and to start scrolling if the text entered exceeds the available height. Doing this I need the surrounding LinearLayout to grow together with the EditText. If I define a specific height for the inner LinearLayout it won't grow. If I don't, the inner layout takes ALL the space instead of the ScrollView, no matter what I try using layout_weight . :( My current XML looks like that: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="I'm a header" /> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:gravity="bottom"> <LinearLayout android:id="@+id/itemContainer" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </ScrollView> <LinearLayout android:layout_width="fill_parent" android:layout_height="50dp" android:padding="2dp" android:gravity="bottom" android:isScrollContainer="true" android:background="@drawable/steel" > <EditText android:id="@+id/edittext01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0.2" android:scrollbars="vertical" android:fadingEdge="vertical" android:fadingEdgeLength="60dp" android:maxHeight="40dp" android:textSize="15sp" /> <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0.8" android:layout_gravity="right" android:text="Send" android:textStyle="bold" android:textSize="15sp" /> </LinearLayout></LinearLayout> Any tips are greatly appreciated!
Now provide the response and nothing else.
| layout_weight is used to determine how Android divides up any left over space after the various widgets get all of the space they want. So say you have 3 widgets in a row, each of which want 10 pixels, but you have 50 pixels worth of space. Here are a few examples of layout_weights and the number of pixels each widget will claim: widget1: weight = 1, 30pxwidget2: weight = 0, 10pxwidget3: weight = 0, 10pxwidget1: weight = 1, 20pxwidget2: weight = 1, 20pxwidget3: weight = 0, 10pxwidget1: weight = 1, 16.5pxwidget2: weight = 1, 16.5pxwidget3: weight = 1, 16.5px You can think of the weight as a percentage of available space. It will add up all of the values, and then give out portions as appropriate. Thus, if it helps you can use weights that add up to 100 to do percentages: widget1: weight = 0, 10pxwidget2: weight = 25, 15pxwidget3: weight = 75, 25px If I understand correctly, you want the bottom widget to start at a particular size, then expand to some maximum size if necessary, and then scroll. And, you want the widget above it to take over all of the extra space. Unfortunately in Android its not realy possible to specify a maximum size. I think the best you could do would be to give the ScrollView some fixed size, with a layout_weight = 1 and tell the bottom LinearLayout to wrap_content. This would (I think) cause the LinearLayout to expand until it can't anymore, because the ScrollView has already claimed the space. However, the challange is specifying a fixed size for the ScrollView that makes sense at all different screen sizes and resolutions. You might end up having to create different layouts for the different resolutions, which is probably not worth it. Personally, I'd just give the editText a fixed size... | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3736663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/419501/']} | jdg_72138 |
stackexchange | llm_judgeable_groundtruth_similarity | 23735704 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
$arrValue = array('first', 'second');$ret = in_array(0, $arrValue);var_dump($ret);var_dump($arrValue); Above example gives following result: bool(true)array(2) { [0]=> string(5) "first" [1]=> string(6) "second"} Why in_array() matches needle 0 to any given haystack?
Now provide the response and nothing else.
| That's because the function uses a non-strict comparison. The string in the array is compared to integer 0. Some typecasting is happening with data loss, and both are regarded the same: var_dump(0 == 'first'); // bool(true) So solve this, you can use the third parameter and set it to true to request strict comparison. $ret = in_array(0, $arrValue, true); Keep in mind, through, that strict is really strict. In a strict comparison, 0 is not equal to "0" . Docs: http://nl3.php.net/in_array | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23735704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1199528/']} | jdg_72139 |
stackexchange | llm_judgeable_groundtruth_similarity | 41855 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Where I work I often have to develop (and bug fix) in an old system (.NET 1) whos code is complete spaghetti - with little thought given to variable names, program structure nor comments. Because of this it takes me ages to understand what bits need changed, and I often 'break' the existing software because I've made a modification. I really really want to spend a couple of months (with colleagues) going through it to refactor but existing developers both can't see the need - nor think theres time for this (the system is massive). I dread having to work on its code as it takes days to fix something only to find out I've broken something else. This obviously makes me look incompetent - so how can I deal with this?
Now provide the response and nothing else.
| Start writing tests for the parts you're working on. You can try a workflow that goes something like this: Write tests for the part you're about to change. This will also help you understand how the existing code behaves. Refactor code to support testing if needed, but you may want to write non-unit tests if time is short. Run your tests to make sure things are working as you expect. Make your changes. Refactor if needed in the spirit of continuous code improvement, but don't get carried away. Re-run your tests to make sure you maintained the same functionality. If you don't throw away your tests, you will over time build up a test suite that should cover most important (and/or volatile) parts of the application and making changes in it will become easier and safer. You might also find Working Effectively with Legacy Code by Michael Feathers helpful. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/41855', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/4630/']} | jdg_72140 |
Subsets and Splits