text
stringlengths
64
89.7k
meta
dict
Q: How to write list to csv, with each item on a new row I am having trouble writing a list of items into a csv file, with each item being on a new row. Here is what I have, it does what I want, except it is putting each letter on a new row... import csv data = ['First Item', 'Second Item', 'Third Item'] with open('output.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) for i in data: writer.writerows(i) A: Use a nested list: writer.writerows([[i]]). Explanation from writing data from a python list to csv row-wise: .writerow takes an iterable and uses each element of that iterable for each column. If you use a list with only one element it will be placed in a single column. So, as all you need is a single column, ...
{ "pile_set_name": "StackExchange" }
Q: How to generate regular points on cylindrical surface I am a beginner in Python and I have to work on a project using Numpy. I need to generate some points (e.g. one million) on one part of the surface of a cylinder. These points should be regularly distributed on a subregion of the surface defined by a given angle. How could I go about doing this? My input parameters are: position of the center of cylinder (e.g. [0,0,0] ) the orientation of cylinder length of cylinder radius of cylinder angle (this defines the part of cylinder which the points should be distributed on it.) for alpha = 360, the whole surface delta_l is the distance between each two points in the length direction delta_alpha is the distance between each two points in the alpha (rotation) direction My output parameters : an array containing the coordinates of all points Could anyone help me, or give me a hint about how to do this? Many thanks A: This is taken from a previous project of mine: def make_cylinder(radius, length, nlength, alpha, nalpha, center, orientation): #Create the length array I = np.linspace(0, length, nlength) #Create alpha array avoid duplication of endpoints #Conditional should be changed to meet your requirements if int(alpha) == 360: A = np.linspace(0, alpha, num=nalpha, endpoint=False)/180*np.pi else: A = np.linspace(0, alpha, num=nalpha)/180*np.pi #Calculate X and Y X = radius * np.cos(A) Y = radius * np.sin(A) #Tile/repeat indices so all unique pairs are present pz = np.tile(I, nalpha) px = np.repeat(X, nlength) py = np.repeat(Y, nlength) points = np.vstack(( pz, px, py )).T #Shift to center shift = np.array(center) - np.mean(points, axis=0) points += shift #Orient tube to new vector #Grabbed from an old unutbu answer def rotation_matrix(axis,theta): a = np.cos(theta/2) b,c,d = -axis*np.sin(theta/2) return np.array([[a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)], [2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)], [2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c]]) ovec = orientation / np.linalg.norm(orientation) cylvec = np.array([1,0,0]) if np.allclose(cylvec, ovec): return points #Get orthogonal axis and rotation oaxis = np.cross(ovec, cylvec) rot = np.arccos(np.dot(ovec, cylvec)) R = rotation_matrix(oaxis, rot) return points.dot(R) Plotted points for: points = make_cylinder(3, 5, 5, 360, 10, [0,2,0], [1,0,0]) The rotation part is quick and dirty- you should likely double check it. Euler-Rodrigues formula thanks to unutbu.
{ "pile_set_name": "StackExchange" }
Q: Add class to multiple divs depending on click event This is the scenario. My client wants to be able to change the colour theme of the website I'm designing for him. I have 4 divs that, when clicked will change the border-colour of another 4 divs. Each click event will change the divs to a different colour depending on which one was clicked. I thought using some jQuery would solve it but I must be doing something wrong! Here's what I'm trying to run: $('.btn1').on('click', function(){ $('.box').removeClass('colour2, colour3, colour4'); $('.box').addClass('colour1'); }); $('.btn2').on('click', function(){ $('.box').removeClass('colour1, colour3, colour4'); $('.box').addClass('colour2'); }); $('.btn3').on('click', function(){ $('.box').removeClass('colour1, colour2, colour4'); $('.box').addClass('colour3'); }); $('.btn4').on('click', function(){ $('.box').removeClass('colour1, colour2, colour4'); $('.box').addClass('colour4'); }); Any help will be greatly appreciated. A: Take the commas out of your remove class $('.btn1').on('click', function(){ $('.box').removeClass('colour2 colour3 colour4'); $('.box').addClass('colour1'); }); $('.btn2').on('click', function(){ $('.box').removeClass('colour1 colour3 colour4'); $('.box').addClass('colour2'); }); $('.btn3').on('click', function(){ $('.box').removeClass('colour1 colour2 colour4'); $('.box').addClass('colour3'); }); $('.btn4').on('click', function(){ $('.box').removeClass('colour1 colour2 colour4'); $('.box').addClass('colour4'); }); Note: you can just call .removeClass() to get rid of all of the classes but if you have more classes on box than just those three it will delete them all. Read more at http://api.jquery.com/removeClass/
{ "pile_set_name": "StackExchange" }
Q: How to use JDBC on working Hibernate/Spring web-app? I have working Hibernate/Spring web-app (HibernateDaoSupport, getHibernateTemplate(), etc). For several tasks i need to use JDBC (jdbcTemplate ?). How to do it in that scenerio ? A: Just create JdbcTemplate and use the same DataSource that is being used by HibernateDaoSupport, HibernateTemplate. Hibernate is just a fancy library working on top of JDBC DataSource/connection. You might use it manually. Try: @Autowired private DataSource ds; If you are lucky, this should work. A better idea is to create JdbcTemplate as a Spring bean and inject proper data source: <bean id="jdbcTemplate" class="org.springframework.jdbc.coreJdbcTemplate"> <constructor-arg ref="dataSource"/> </bean> Consider using JdbcOperations interface, also look at SimpleJdbcOperations. @Autowired private JdbcOperations jdbc; If you start to access the same database/connection pool both by Hibernate and using direct JDBC access code, you have to watch out for some side effects: Hibernate L2 cache is not aware of JDBC modifications JDBC code is not aware of Hibernate optimistic locking transaction management ... Another approach is to access JDBC connection used by Hibernate session (in HibernateDaoSupport: getSession().connection() A: You may use Session.doWork to execute code using JDBC connection used by Hibernate. This of course requires that you use and have access to Hibernate's Session object.
{ "pile_set_name": "StackExchange" }
Q: Call tag-it's createTag more than once I am using tag-it to create Tags. It works like a charme, but I want to preset some tags. If I call $('#tags').tagit('createTag', 'abc'); I get my Tag, but if I call this function a second time, there will be no second tag. <script> $('#tags').tagit({ placeholderText: "Such-Tags", afterTagAdded: function(){ filter(); }, afterTagRemoved: function(){ filter(); }, fieldName: "tagsField[]" }); {foreach item=tag from=$tags|default:null} $('#tags').tagit('createTag', '{$tag}'); {/foreach} </script> Whats the problem? edit: if I add <li>Tag</li> I will get the following: A: $(function(){ $('#tags').tagit(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script> <script src="http://aehlke.github.io/tag-it/js/tag-it.js"></script> <link href='http://aehlke.github.io/tag-it/css/jquery.tagit.css' rel="stylesheet" type="text/css"> <link href='http://aehlke.github.io/tag-it/css/tagit.ui-zendesk.css' rel="stylesheet" type="text/css"> <ul id="tags"> <!-- Existing list items will be pre-added to the tags --> <li>Tag1</li> <li>Tag2</li> </ul>
{ "pile_set_name": "StackExchange" }
Q: Why the Hashcode of the HashMap is Zero I am trying to initialize with Approach One: Map<String, String> mapInter = Collections.EMPTY_MAP; mapInter = new HashMap<String, String>(); mapInter.put("one", "one"); System.out.println(mapInter.hashCode()); Approach two : HashMap<String, String> myMap = new HashMap<String, String>(10); myMap.put("key", "value"); System.out.println(myMap.hashCode()); In first approach when i print hashcode it's print zero, but in second approach it print hash code. after initialization hashcode will be returned. Why the HashCode in the first Case Printed zero but not in the second case? A: The HashCode will be 0 only if the both Key and value are same. It is happening because of the hashcode implementation of Entry inside HashMap, Which is as follows: public final int hashCode() { return (key==null ? 0 : key.hashCode()) ^ (value==null ? 0 : value.hashCode()); } It performs ^ on the hashcode's of both key and value, which always returns 0. if both are same. In your example if you change the myMap.put("key", "key") then both map's will return hashcode 0. Map<String, String> mapInter = Collections.EMPTY_MAP; mapInter = new HashMap<String, String>(); mapInter.put("one", "one"); System.out.println(mapInter.hashCode()); Approach two : HashMap<String, String> myMap = new HashMap<String, String>(10); myMap.put("key", "key"); System.out.println(myMap.hashCode()); Output: 0 0
{ "pile_set_name": "StackExchange" }
Q: Create or update script of given HTML The code is getting an HTML file and configObject and according to this config object need to modify this htmlFile content(the code is working) This is the input: please notice that that in the firstobj of the array (there is scenario which the next attribute is not provided which say to put the new script at the bottom) the next said put the script tag after script that have ID "ui-boot" var extendedHtmlObject = [{ type: 'script', action: 'new', content: 'console.log(‘hello world’);', next: "ui-boot" }, { type: 'script', id: "ui-boot", action: 'upd', innerElem: [{ type: 'attr', id: 'data--ui-comersion', content: '1.17' }, { type: 'attr', id: 'src', content: '/test/test2/-co.js' }] } This is the main function: getExtend: function(htmlContent, extendedHtmlObject) { var self = this; if (extendedHtmlObject) { extendedHtmlObject.forEach(function(configs) { switch (configs.type) { case 'script': htmlContent = self._handleScriptElement(htmlContent, configs); break; case 'head': break; } }); } return htmlContent; }, This method determines if I need to create a new script or update existing script attributes according to the input object _handleScriptElement: function(htmlFilecontent, configEntry) { var oExtendedHTML = htmlFilecontent; switch (configEntry.action) { case 'new': oExtendedHTML = this._createNewScript(htmlFilecontent, configEntry); break; case 'upd': var sParsedHtml = this._htmlParser(oExtendedHTML); oExtendedHTML = this._updateScript(oExtendedHTML, configEntry, sParsedHtml); oExtendedHTML = this._convertHtmlBack(oExtendedHTML); break; } return oExtendedHTML; }, This is the method for creating new script with two option 1. the first fork need to parse the html 2. the second for doesn't. _createNewScript: function(htmlFilecontent, configEn) { var sScriptContent = this._createScript(configEntry.content); if (configEn.next != null) { var sParsedHtml = this._htmlParser(htmlFilecon); $(sScriptContent).insertAfter(sParsedHtml.find('#' + configEn.next)); htmlFilecontent = this._convertHtmlBack(sParsedHtml); } else { //when the script is at the end of file var iHeadEndTagPos = htmlFilecon.search("(| )* )*head(|*>"); htmlFilecon = htmlFilecon.substr(0, iHeadEndTagPos) + sNewScript + htmlFilecon.substr(iHeadEndTagPos); } return htmlFilecon; }, This code is redundant and not efficient(I'm fairly new to JS), could I maybe improve it with JS prototype? I want to do the parse just once in the start and the parseBack at the end(of looping the input object) but the problem is that in the createNewScript the second fork doesn't need to use the parser... The code inside module of requireJS update To make it more clear, The external API have two input and one output HTML file content config object which determine how to update the HTML, for example to create new script (as the first object in the array extendedHtmlObject ) or update existing script content such as attributes values) the output should be the extended HTML with all the modification **update 2 ** If I can provide additional data to make it more clear please let me know what. A: Maybe have a look at some of the multitude of templating systems out there. Alternatively, simplify your html creation. If you use innerHTML to create DOM nodes, have the HTML file content just be a long string containing the full markup with placeholders for all values/classnames/etc. eg: <script src="{{src}" id="{{id}}"></script> and then just replace all the placeholders with the values. Then you can just update the innerHTML of the target with this string. If you use DOM node creation, document.createElement(), create all those template nodes in advance (documentFragments are really handy here). Then have one function that will check the 'extendedHtmlObject' settings and select either the node already on the page in case of update, or select your premade nodeList. Once you have the html structure as nodes, hand it off to a different function that will update all the nodes inside the structure with the new values in the 'extendedHtmlObject'. You can then append the nodes to their target. In both cases you can juist throw the back and forth html parsing and branching away. pseudocode: (function myModule() { var templates = {}, createTemplates = function() { // Create all templates you'll use and save them. // If you create nodes, also include a mapping from each node to its respective value // eg: children[0] = 'label', children[1] = 'value' }, updateTemplate = function( template, values ) { // INNERHTML: for each placeholder 'valueName' in string template, replace placeholder by values[valueName] // NODE CREATION: use the node mapping in the template to select each node in the template and replace its current value with values[valueName] return template; }, getTemplate = function( type, reference ) { return (type === 'new') ? templates[reference] : $('#' + reference); }, update = function( config ) { var html = getTemplate(config.action, (config.next || config.id)), updated = updateTemplate(html, config); if (config.next) $('#' + config.next).insertAfter(html); else $('#' + config.id).innerHTML = html /* OR */ $('#' + config.id).appendChild(html); }, init = function() { createTemplates(); }; }()); TLDR: Create new or grab existing HTML first, then update either the string or the nodes, then determine where it has to go. Make everything as general as possible. The html creation function should be able to create any html element/update any template, not just script nodes. The update function should not care if the html its updating existed before or is newly generated. The function that puts the html back into the website should not be inside the creation functions. This way you'll probably at first end up with just one big switch statement that will call the same functions with different parameters, which can easily be replaced by adding another config setting to the 'extendedHtmlObject'. UPDATE: I've created an example of a usable structure. It uses the DOM methods (createElement, etc) to create a new document containing the updated input string. You can change it to better match your specific input/output as much as you want. It's more of an example of how you can create anything you want with just a few general functions and alot of config settings. This doesn't use the templetes I spoke before of though, since that would take longer to make. Just have a look at handlebars.js or mustache.js if you want templating. But it better matches the structure you had yourself, so I hope it's easier for you then to pick the parts you like. var originalHTML = '<script id="ui-boot" src="path/to/script/scriptname.js"></script>', imports = {}, // IMPORTANT NOTE: // Using a string as the body of a script element might use eval(), which should be avoided at all costs. // Better would be to replace the 'content' config setting by a 'src' attribute and ahve the content in a seperate file you can link to. configAry = [ { // script-new type: 'script', action: 'new', content: 'console.log(‘hello world’);', next: "ui-boot" }, { // script-upd type: 'script', id: "ui-boot", action: 'upd', innerElem: [ { type: 'attr', id: 'data--ui-comersion', content: '1.17' }, { type: 'attr', id: 'src', content: '/test/test2/-co.js' } ] } ], // Extra helpers to make the code smaller. Replace by JQuery functions if needed. DOM = { 'create' : function create( name ) { return document.createElement(name); }, // Create a new document and use the string as the body of this new document. // This can be replaced by other functions of document.implementation if the string contains more than just the content of the document body. 'createDoc' : function createDoc( str ) { var doc = document.implementation.createHTMLDocument('myTitle'); doc.body.innerHTML = str; return doc; }, 'insertAfter' : function insertAfter(node, target, content ) { target = content.querySelector(target); if (target.nextSibling) target.nextSibling.insertBefore(node); else target.parentNode.appendChild(node); return content; }, 'replace' : function replace( node, target, content ) { target = content.querySelector(target); target.parentNode.replaceChild(node, target); return content; }, 'update' : function update( node, textContent, attributes ) { if (textContent) node.textContent = textContent; return (attributes) ? Object.keys(attributes).reduce(function( node, attr ) { node.setAttribute(attr, attributes[attr]); return node; }, node) : node; } }, // The actual module moduleHTMLExtender = (function( imports ) { var createExtension = function createExtension( extension, content ) { switch (extension.action) { case 'new' : return { 'method' : 'insertAfter', 'node' : DOM.update(DOM.create(extension.type), extension.content), 'target' : '#' + extension.next }; break; case 'upd' : return { 'method' : 'replace', 'node' : DOM.update(content.querySelector('#' + extension.id).cloneNode(), null, extension.innerElem.reduce(function( map, config ) { if (config.type === 'attr') map[config.id] = config.content; return map; }, {})), 'target' : '#' + extension.id } break; default: return false; break; } }, addExtensions = function addExtensions( content, extensions ) { return extensions.reduce(function( content, extension ) { return DOM[extension.method](extension.node, extension.target, content); }, content); }, // Returns new document as an [object Document] extendContent = function extendContent( content, extensions ) { var doc = DOM.createDoc(content), toExtend = (extensions) ? extensions.map(function( extension ) { return createExtension(extension, doc); }) : null; var res = null; if (toExtend) return addExtensions(doc, toExtend); else return doc; }; // Export public interface. Replace this by your require.js code or similar. return { 'extendContent' : extendContent }; }( imports )), extendedHTMLDoc = moduleHTMLExtender.extendContent(originalHTML, configAry); console.log(extendedHTMLDoc.documentElement.outerHTML); // output = '<html><head><title>myTitle</title></head><body><script id="ui-boot" src="/test/test2/-co.js" data--ui-comersion="1.17"></script><script>console.log(hello world);</script></body></html>';
{ "pile_set_name": "StackExchange" }
Q: get array of number of days of specified day with moment.js there is a way to obtain an array with day numbers of a specified month (current month) of a specified day name? E.g. I want to obtain all Saturdays of June 2016. I would like to have the array with [4,11,18,25] values. (4th June is Saturday, 11 too, and so on...). Regards A: Solved. Suppose that I want to obtain all Sundeys (so call function with 0 that is the number for Sundays) function getDays(num){ var dArray = new Array(); var cMonth = moment().get('month'); dArray.push(moment().day(num)); if (moment().day(num-7).get('month') == cMonth) {dArray.push(moment().day(num-7));} if (moment().day(num-14).get('month') == cMonth) {dArray.push(moment().day(num-14));} if (moment().day(num-21).get('month') == cMonth) {dArray.push(moment().day(num-21));} if (moment().day(num-28).get('month') == cMonth) {dArray.push(moment().day(num-28));} if (moment().day(num+7).get('month') == cMonth) {dArray.push(moment().day(num+7));} if (moment().day(num+14).get('month') == cMonth) {dArray.push(moment().day(num+14));} if (moment().day(num+21).get('month') == cMonth) {dArray.push(moment().day(num+21));} if (moment().day(num+28).get('month') == cMonth) {dArray.push(moment().day(num+28));} return dArray; };
{ "pile_set_name": "StackExchange" }
Q: What is meant by the term ‘random-state’ in 'KMeans' function in package 'sklearn.cluster' in python What is meant by "random-state" in python KMeans function? I tried to find out from Google and referred https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html but I could not find a precise answer. A: A gotcha with the k-means alogrithm is that it is not optimal. That means, it is not sure to find the best solution, as the problem is not convex (for the optimisation). You may be stuck into local minima, and hence the result of your algorithm depends of your initialization (of your centroids). A good practice in order to find a good minimum is to rerun the algortihm several times with several initializations and keep the best result. As stated by the others, random_state makes the results reproducible and can be useful for debugging A: Bear in mind that the KMeans function is stochastic (the results may vary even if you run the function with the same inputs' values). Hence, in order to make the results reproducible, you can specify a value for the random_state parameter.
{ "pile_set_name": "StackExchange" }
Q: What are those things in text design? What are those things? What are they for? How do I enable them? A: They are substitution or pre-composed variant that are alternate glyphs and may not be available on all fonts; you will see them only when the font was created to incorporate them in a specific way. Example from Myriad Pro Bold from the Typekit: Top example is without using the "Fraction" substitution, bottom example is using it. You can't really enable them if the font doesn't have these substitutions included already in their set. They will be accessible only for certain fonts. You'll find them on Open-Type fonts. If they are available, you can enable or disable them by clicking on the icon. There's also fonts that include these substitutions but they might be part of another font family named differently and won't be available on this small Character menu. They're not as convenient to use as the option above. For example, the Helvetica Fractions.
{ "pile_set_name": "StackExchange" }
Q: Formatting dataframe to rows based on keys in a column I have a data-frame like one below: tag_id value time_stamp tag_1 1 2017-05-01 00:00:00 tag_2 2 2017-05-01 00:00:00 tag_3 3 2017-05-01 00:00:00 tag_1 4 2017-05-01 00:10:00 tag_2 5 2017-05-01 00:10:00 tag_3 6 2017-05-01 00:10:00 I want to format it as under, can someone please help? time_stamp tag_1 tag_2 tag_3 2017-05-01 00:00:00 1 2 3 2017-05-01 00:10:00 4 5 6 A: This is a classic case of pivot. Assuming df is your dataframe. df.pivot(index='time_stamp', values='value', columns='tag_id')
{ "pile_set_name": "StackExchange" }
Q: Integer pre-increment error Atleast in C#, ++int increments the integer by 1 before use of it, and -- before int decrements it. But I get this confusing error when using this piece of code. ++int_name *= 10; I increment the integer with 1 and * with 10, still throws compiler error. Some advise would be nice :) A: Your syntax is not valid. Use this one instead: int_name = ++int_name * 10; The compiler error you get is: The left-hand side of an assignment must be a variable, property or indexer ++int_name is not a variable but an expression yielding an integer number. How could you possibly assign a new value to a number?
{ "pile_set_name": "StackExchange" }
Q: Settings to create transparent PNG's with minimal file size for mobile devices I want to create a theme for android phones. I guess the best way to go is to create a file that is as light as possible. Now I want to create the files in photoshop, they have to be transparent PNG's. Now I see that there are a lot of different settings I can use, for example the image mode: lab, rbg, etc. There are also different bits, 8 bit, 16 bit etc. Now what settings can I use to create good sharp png's but with a minimal size. Maybe someone could share some tips on exporting. I now export for web & devices, but maybe there is another option. Maybe there is also better software than photoshop to do this. A: All pngs are 'good' and 'sharp' as they are losslessly compressed, unlike jpgs. It's just a matter of experimenting with settings that keep an amount of colour that you're happy with while keeping file sizes as low as possible. In Photoshop, the 'Save for web' exporter allows you to view 3 different optimised versions of the output as well as the original. Use these to compare the outputs and find one that's acceptable for you. A: The only color space to use for image prep for mobile devices is RGB. (You can use others temporarily for retouching purposes, but your final output will always be RGB, so best work in that space all the time.) sRGB is the safest, since you don't know the capabilities of specific devices at design-time. Save for Web is your best option inside Photoshop. 8-bit will result in significantly smaller file sizes than 24-bit, and the visible difference is often negligible, especially for small screens. See this question on superuser for a comparison of several PNG compression utilities.
{ "pile_set_name": "StackExchange" }
Q: Wrong Output from Query I am unable to get data from bnrcno column while using the below query. select 'insert into table values('||id||','||bnrcno||','||chargetype||','||domno||','||coa_id||','||liability_gl||','||revenue_gl||','||taxno||')' from bill_charges_map where domno=5 The brcno column is of integer type, where most of values in it are null. A: Use the format() function with placeholder for literals: %L select format('insert into table values(%s, %L, %L, %s, %s, %L, %L, %L)', id, bnrcno, chargetype, domno, coa_id, liability_gl, revenue_gl, taxno) from bill_charges_map where domno=5; For numeric columns (integer, numeric, float etc) use %s as the placeholder. For all other types use %L as the placeholder to quote them properly. Note that it is good coding practice to explicitly list the columns in the target table: insert into the_table (col1, col2, col3) values (...)
{ "pile_set_name": "StackExchange" }
Q: Code fix for document different from code fix for line I have written a Roslyn code Analyzer and related CodeFixProvider, which works. When I use it against individual lightbulbs it works perfectly, when I choose to do the whole document, it seems to be getting corrupted results as if several fixes were merged together. I am using the WellKnownFixAllProviders to provide the infrastructure for fixing the problem. Debugging the code and what is happening, all looks fine, but the previewed (and accepted) document seems to have some duplicated or corrupted results. A: The WellKnownFixAllProvider works by batching all the fixes in parallel, passing the same, immutable, document. Each fix returns the result of a single change to the original document and those changed documents are merged together to produce the final result. This means that if the fixes overlap the merge can produce results that would not happen if the document was mutated in sequence. The only real cure for this is to either not have overlapping fixes or to write your own fixallprovider that operates in sequence instead of in parallel. If the CodeFixProvider is being used for a one shot change to your codebase, it might be possible to hack a workaround where your fix provider keeps track of it’s changes and doesn’t produce conflicting changes. But that would be inherently fragile and not so thing you’d want to do for a fix that would be used by the general public.
{ "pile_set_name": "StackExchange" }
Q: System.UnauthorizedAccessException in mscorwks.dll causing app pool crashes My app pools keep randomly crashing in IIS 6.0 MS Debug Diag points to kernel32.dll every time. The entry point is always mscorwks!CreateApplicationContext+bbef and the result is always a System.UnauthorizedAccessException. Stack Trace: Function Arg 1 Arg 2 Arg 3 kernel32!RaiseException+3c e0434f4d 00000001 00000001 mscorwks!GetMetaDataInternalInterface+84a9 18316b3c 00000000 00000000 mscorwks!GetAddrOfContractShutoffFlag+ac01 18316b3c 00000000 023cfbd8 mscorwks!GetAddrOfContractShutoffFlag+ac73 00000000 000e8c88 8038b2d0 mscorwks!GetAddrOfContractShutoffFlag+aca4 18316b3c 00000000 023cfbe4 mscorwks!GetAddrOfContractShutoffFlag+acb2 18316b3c acc05c33 7a399bf0 mscorwks!CoUninitializeCor+67be 00000000 023cfc1c 023cfc8c mscorwks!CoUninitializeCor+87a1 001056e8 79fd87f6 023cfeb0 mscorwks!CorExitProcess+4ad3 023cfeb0 023cfd20 79f40574 mscorwks!CorExitProcess+4abf 001056e8 79f405a6 023cfd04 mscorwks!CorExitProcess+4b3e 000e8c88 00000000 023cfda7 mscorwks!StrongNameErrorInfo+1ddab 00000000 00000000 023cfeb0 mscorwks!StrongNameErrorInfo+1e07c 023cfeb0 00000000 00000000 mscorwks!CoUninitializeEE+4e0b 023cfeb0 023cfe5c 79f7762b mscorwks!CoUninitializeEE+4da7 023cfeb0 acc05973 00000000 mscorwks!CoUninitializeEE+4ccd 023cfeb0 00000000 001056e8 mscorwks!GetPrivateContextsPerfCounters+f1cd 79fc24f9 00000008 023cff14 mscorwks!GetPrivateContextsPerfCounters+f1de 79fc24f9 acc058c3 00000000 mscorwks!CorExeMain+1374 00000000 00000003 00000002 mscorwks!CreateApplicationContext+bc35 000e9458 00000000 00000000 kernel32!GetModuleHandleA+df 79f9205f 000e9458 00000000 Does anybody know what this means and how to fix it? Edit: The above stack trace turned out to be a symptom and not the cause. The above stack trace only shows the unmanaged stack but the problem happened in managed code. I used the steps in my answer below to dig into the crash dump and extract the managed exception. A: The reference to mscorwks.dll was only a symptom of the problem. mscorwks.dll is the dll that contains the common language runtime. To diagnose the root cause of the problem, I followed the following steps: Use DebugDiag to capture a crash dump when IIS recycled the app pool. Open the crash dump in windbg. Type ".loadby sos mscorwks" (no quotes) at the windbg command line to load the CLR debug tools Use the !PrintException command to print out the last exception recorded in the crash dump. This is most likely the one that caused the IIS app pool recycle Use the !clrstack command to view the stack on the current thread that threw the exception More command references for windbg can be found here and here. Lastly, this MSDN blog has great tutorials on using windbg. Good luck on your debuging adventure!
{ "pile_set_name": "StackExchange" }
Q: Magento 2. What is the role of the search_query table Magento 2. What is the role of the search_query table? Where is it used? Should I ever clear it? What would be the impact of clearing it? A: This table contains the previous search terms of previous customers. it is also used to display search suggestions for new customers based on what the old customers searched. If you clear it, the only effect would be that the customers will not see search suggestions until the table is populated again. If you are using a custom search solutions you can just truncate it.
{ "pile_set_name": "StackExchange" }
Q: Validating StringLength but reserving more space on DB column I have a password field that i would like the user type only between 5 to 10 characters. However, i will apply md5 and save that value, so i need more space than 10. But StringLength sets nvarchar to 10. [Required, StringLength(10, MinimumLength = 5)] public string Password { get; set; } Resuming, I want to use that validation but thats not what I want to use in DB. A: you should ideally make 2 models. One view model for binding to the posted values and other as a DB model.
{ "pile_set_name": "StackExchange" }
Q: Which vessel could a pumping vessel in the left middle side of forehead be? There is a vessel located on the left middle side of my forehead which keeps pumping for few times noticeably every few minutes, my question is: What are vessels flowing on the left-mid side of the forehead that can be felt pulsating? A: Map of the superficial arteries (the arteries close beneath the skin), taken from ClinicalGate, which I believe they have taken from Gray's Anatomy for Students Map of the deeper arteries, ibid I'm unsure which you consider the left-mid side of your forehead, but you probably felt one of the larger arteries like the superficial temporal artery or the facial artery, but please check for yourself.
{ "pile_set_name": "StackExchange" }
Q: Will changing app name in iOS app store affect/reset app ranking? I want to change the name of my app but was wondering if that would change/affect/reset the ranking it already has. Anyone know? A: There should be three names of your app: Bundle Identifier - this is the main ID Bundle Display Name - this is displayed in iPhone App Name - this is probably the one in the iTunes/App Store I believe you can change the App Name during uploading and update (with the updated Bundle Display Name) and if you don't change the Bundle Identifier all reviews and rankings should remain the same. Users will also automatically receive this update. This is most likely dependent on Apple approval after the update. Hopefully this is still valid with the App Store changes. Also I have seen this many times as a user.
{ "pile_set_name": "StackExchange" }
Q: Column String Access for date using day How do I access all the days of the 12 month in a dataset? The structure of data is: print(df.head(n=1)) Date_Time IPAddress Visitors OS Browser \ 0 2016-10-18 12:57:45 104.236.233.18 1001 Mac OS Google Chrome Browser_Version Location Referrer PageID 0 39.0.2171.95 NaN creditcommerty.in index.php Why do the vdf index values 6 and 2 in this code: print(vdf['new_day'][6][2]) gives this error? print(vdf['new_day'][6][2]) Traceback (most recent call last): File "<ipython-input-196-c01f93f97338>", line 1, in <module> print(vdf['new_day'][6][2]) KeyError: 6 A: First you need to present us with the dataset or any appropriate reference. I have no clue as to what your data looks like, and I can only guess. All I can tell you is that The KeyError is thrown because there IS no 7th element in the "new_day" column. To access every single data point in your dataframe, simply do vdf.iloc[:,:] or vdf[:][:], or df. Printing any three of these will return the same. EDIT: From your comments, it seems like your new_day column has lists with three elements, where first is the year, second month, and third day. And you want to return all the days in like a list I assume? vdf['new_day'][:][2] should give you a list of all the day elements. >>> vdf = pd.DataFrame([ [[1,2,3]], [[4,5,6]], [[7,8,9]] ]) >> vdf 0 0 [1, 2, 3] 1 [4, 5, 6] 2 [7, 8, 9] >>> vdf[0][:][2] [7, 8, 9] Again, the KeyError: 6 is thrown because vdf['new_day'[6] is not there. Look at your data again. Do you have a 7th row?
{ "pile_set_name": "StackExchange" }
Q: Is there higher quality way of converting php image resources to jpeg or png besides using imagejpeg or imagepng Currently I am using imagepng to convert an image resource based off of an original image to an png image type. This proved to have a higher level of quality than the imagejpeg function was creating for my jpg. However you can clearly see that the compression algorithms in these two functions are not of as high quality as one that would be in something like Photoshop. Does anyone know of a way to get a higher quality jpeg? Is there documentation on the format of the image resource and how it is converted to a jpeg or png? If I had that information I could at least try to implement a better algorithm. //Create image $im = apppic($filename, $colors); imagepng($im, "images/app/".rtrim($path_array[$count],"jpeg")."png", 0); function promopic ($filename, $colors){ if(@imagecreatefromjpeg($filename)) $img = imagecreatefromjpeg($filename); elseif(@imagecreatefrompng($filename)) $img = imagecreatefrompng($filename); elseif(@imagecreatefromgif($filename)) $img = imagecreatefromgif($filename); $width = imagesx($img); $height = imagesy($img); $imHeight = 625; if( $width/$height > 4/5){$imWidth = 800; $imHeight = $height/$width*$imWidth ; } else { $imWidth = $width/$height*$imHeight; } $colorWidth = 1200 - $imWidth; $numColors = count($colors); $colorHeight = ceil($imHeight/$numColors) - 2; $imHeight = ceil($imHeight/$numColors)* $numColors - 2; $im = @imagecreate(1200, $imHeight+50) or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($im, 250, 250, 250); $text_color = imagecolorallocate($im, 255, 255, 251); $blue_color = imagecolorallocate($im, 40, 5, 251); //Add color boxes for ($i = 1; $i <= $numColors; $i++) { $imcolorbox = @imagecreate($colorWidth, $colorHeight); $rgb = hex2rgb($colors[($i-1)]); $colorbox_color = imagecolorallocate($imcolorbox, $rgb[0], $rgb[1], $rgb[2]); $dest_x = 1200-$colorWidth; $dest_y = ($colorHeight + 2) * ($i-1); $copy_image = imagecopy($im, $imcolorbox, $dest_x, $dest_y, 0, 0, $colorWidth, $colorHeight); imagedestroy($imcolorbox); //imagestring($im, 5, 1075, 2+$dest_y, "Reinvogue.com", $text_color); //imagestring($im, 5, $imWidth+5, 2+$dest_y, "Reinvogue.com", $text_color); //imagestring($im, 5, 1050, 17+$dest_y, "Hex: ".$colors[($i-1)], $text_color); //imagestring($im, 5, 1050, 2+$dest_y, "RGB: ".$rgb[0]." ".$rgb[1]." ".$rgb[2], $text_color); } imagestring($im, 5, 10, $imHeight+15, "Powered by the Reinvogue.com Colorway Engine", $blue_color); $copy_image = imagecopyresampled($im, $img, 0, 0, 0, 0, $imWidth-2, $imHeight, $width, $height); return $im; } A: This should create a high quality image with a white background: $im = @imagecreatetruecolor(1200, $imHeight+50) $white = imagecolorallocate($im, 255, 255, 255); imagefill($im, 0, 0, $white); If you're working with png images you can even have a look at imagecolorallocatealpha (http://www.php.net/manual/en/function.imagecolorallocatealpha.php) Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: How can i tag the x largest numbers in a query Given the following simple table: Value 10 4 7 2 4 6 How do i write a select query that tags the x biggest values. For example below the desired query output if the 3 biggest values are tagged. Value IsBiggest 10 true 4 false 7 true 2 false 4 false 6 true A: One possible way: (select value, 'true' as IsBiggest from simple_table order by value desc limit 3) union all (select value, 'false' as IsBiggest from simple_table order by value desc limit 3, 9223372036854775807)
{ "pile_set_name": "StackExchange" }
Q: 3 and 4 degree curves in three.js I am trying to reproduce the degree-3 or degree-4 3D curves typically found in parametric cad programs like Rhino or Autocad, which take any number of 3D points to create long curves. I've found that three.js has Cubic (degree-3) and Quadratic (degree-4) Bezier curves available but they take exactly three and 4 vectors, respectively. I'd like to create curves with 10 or more inputs, not just 3 or 4. I've also found that three.js has 'Path' which allows building a 2D curve of mixed degree segments using the .bezierCurveTo() or .quadraticCurveTo() methods. So my question: Is there currently a way to construct long chains of CubicBezierCurve3 curves that join smoothly? Ideally with a constructor that takes a simple array of vertices? If I need to implement this myself, where is the best place to start? I'm thinking the .quadraticCurveTo() method could be extended to use a z component and added to SplineCurve3? I'm not 100% clear on how the array of curves works in the 'Path' object. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) { var args = Array.prototype.slice.call( arguments ); var lastargs = this.actions[ this.actions.length - 1 ].args; var x0 = lastargs[ lastargs.length - 2 ]; var y0 = lastargs[ lastargs.length - 1 ]; var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( aCPx, aCPy ), new THREE.Vector2( aX, aY ) ); this.curves.push( curve ); this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } ); }; Thanks for your help! A: If you are fine with using a high degree Bezier curve, then you can implement it using De Casteljau algorithm. The link in karatedog's answer provides a good source for this algorithm. If you want to stick with degree 3 polynomial curve with many control points, B-spline curve will be a good choice. B-spline curve can be implemented using Cox de Boor algorithm. You can find plenty of reference on the internet. B-spline curve definition requires degree, control points and knot vector. If you want your function to simply take an array of 3d points, you can set degree = 3 and internally define the knot vector as [0, 0, 0, 0, 1/(N-3), 2/(N-3),....., 1, 1, 1, 1]. where N = number of control points. For example, N=4, knot vector=[0, 0, 0, 0, 1, 1, 1, 1], N=5, knot vector=[0, 0, 0, 0, 1/2, 1, 1, 1, 1], N=6, knot vector=[0, 0, 0, 0, 1/3, 2/3, 1, 1, 1, 1]. For the N=4 case, the B-spline curve is essentially the same as a cubic Bezier curve.
{ "pile_set_name": "StackExchange" }
Q: Is there a $k$-structure for Hodge modules over a $k$-variety? I am trying to understand (Saito's?) category of mixed Hodge modules as a category (i.e. I am not interested in its construction, just in properties of objects and morphisms). I would be grateful for any nice references for this (though I have some texts already); yet currently I am interested in the following question. For algebraic varieties over a subfield $k$ of the field of complex numbers, can one define certain mixed Hodge modules with some $k$-structure that would be related with the $k$-structure on the De Rham cohomology of $k$-varieties? Please tell me also if such a structure could be obtained from the usual 'complex' Hodge modules, or if the presence of a $k$-structure 'does not affect morphisms significantly'. A: When $X$ is a $k$-variety the category $MHM(X_{\mathbb{C}})$ of mixed Hodge modules on $X\otimes_k \mathbb{C}$ doesn't remember the $k$-structure. For example you have $Ext^1_{MHM(X_{\mathbb{C}})}(Q_X, Q_X(1)) = \mathbb{C}(X)^\times \otimes_{\mathbb{Z}} \mathbb{Q}$. In a category of mixed Hodge modules with de Rham $k$-structure this group would be $k(X)^\times \otimes_{\mathbb{Z}} \mathbb{Q}$ instead. A: I think that the answer is "yes". If you denote by $MFW(X)$ (resp. $MFW(X_\mathbb{C})$) the category of regular holonomic $D$-modules on $X$ (resp. $X_\mathbb{C}$) with a good filtration $F$ and a finite filtration $W$, then there are obvious functors $MFW(X)\rightarrow MFW(X_\mathbb{C})$ and $MHM(X_\mathbb{C})\rightarrow MFW(X_\mathbb{C})$, where $MHM(X_\mathbb{C})$ is the category of mixed Hodge modules on $X_\mathbb{C}$. So you can consider the fiber product of $MFW(X)$ and $MHM(X_\mathbb{C})$ over $MFW(X_\mathbb{C})$, and indeed things should work nicely for this category, at least if you believe Saito (the construction is taken from his paper "On the formalism of mixed sheaves", here; it's example 1.8(ii)). (I don't think that this paper of Saito has appeared in any peer-reviewed journal, so you should check whatever you want to take from it. It's a pity because it's a nice reference.)
{ "pile_set_name": "StackExchange" }
Q: PickerView make individual colors for rows So what I want, is to make individual colors for my rows in a PickerView, but I really don't know how to do this. And it would also be cool to know how to make indivial textcolors. Thanks. A: So, if you are checking the UIPickerView datasource, you will find the following method: - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view; I guess you can use it in order to modify the view in your pickerView by processing something like this: Initiate your pickerView In your viewDidLoadfor example: UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 4, self.view.frame.size.width, self.view.frame.size.height / 2)]; pickerView.delegate = self; pickerView.dataSource = self; [self.view addSubview:pickerView]; Call the desired method and make your changes: Example: - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { UIView *customRow = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)]; switch (row) { case 0: customRow.backgroundColor = [UIColor redColor]; return customRow; break; case 1: customRow.backgroundColor = [UIColor orangeColor]; return customRow; case 2: customRow.backgroundColor = [UIColor yellowColor]; return customRow; case 3: customRow.backgroundColor = [UIColor greenColor]; return customRow; case 4: customRow.backgroundColor = [UIColor blueColor]; return customRow; case 5: customRow.backgroundColor = [UIColor purpleColor]; return customRow; default: return nil; break; } } Do not forget the required method in your implementation: In your controller: #pragma mark: UIPickeView datasource - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 1; } - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { return 6; }
{ "pile_set_name": "StackExchange" }
Q: Geotools ViewType on GridCoverage2D I am currently updating our projects Geotools jars from 10.8 to RC 21. I've run into an issue where in the coverage jar(gt-coverage-21-RC.jar) the ViewType class no longer exists. Also the code that uses that class on the GridCoverage2D class doesn't exist. So the following no longer works: GridCoverage2D coverage = (GridCoverage2D) reader.read(null); coverage = coverage.view(ViewType.GEOPHYSICS); The ".view" function doesn't exist on the GridCoverage2D class and the ViewType class is completely removed from the jar file. We perform this specific operation many times throughout our application with different "ViewType" settings so I don't think this is something I can just comment out and expect it to work. But I can't find any instructions on when and how this was changed/updated. I would love any information on this if anyone has had to deal with it. A: It appears that they were removed in this change which seems to indicate they were deprecated back in geotools 13 and so were removed in geotools 14. I've opened a ticket to get the documentation updated to match.
{ "pile_set_name": "StackExchange" }
Q: Empty Regex response using finditer and lookahead I'm having trouble understanding regex behaviour when using lookahead. I have a given string in which I have two overlapping patterns (starting with M and ending with p). My expected output would be MGMTPRLGLESLLEp and MTPRLGLESLLEp. My python code below results in two empty strings which share a common start with the expected output. Removal of the lookahead (?=) results in only ONE output string which is the larger one. Is there a way to modify my regex term to prevent empty strings so that I can get both results with one regex term? import re string = 'GYMGMTPRLGLESLLEpApMIRVA' pattern = re.compile(r'(?=M(.*?)p)') sequences = pattern.finditer(string) for results in sequences: print(results.group()) print(results.start()) print(results.end()) A: The overlapping matches trick with a look-ahead makes use of the fact that the (?=...) pattern matches at an empty location, then pulls out the captured group nested inside the look-ahead. You need to print out group 1, explicitly: for results in sequences: print(results.group(1)) This produces: GMTPRLGLESLLE TPRLGLESLLE You probably want to include the M and p characters in the capturing group: pattern = re.compile(r'(?=(M.*?p))') at which point your output becomes: MGMTPRLGLESLLEp MTPRLGLESLLEp
{ "pile_set_name": "StackExchange" }
Q: jquery slider rotation function I'm using a small plug-slider that has 2 main functions rotate() and rotateSwitch() rotate = function(){ var triggerID = $active.attr("rel") - 1; var image_reelPosition = triggerID * imageWidth; $(".paging a").removeClass('active'); $active.addClass('active'); //Slider Animation $(".image_reel").animate({ left: -image_reelPosition }, 500 ); }; rotateSwitch = function(){ play = setInterval(function(){ $active = $('.paging a.active').next(); if ( $active.length === 0) { $active = $('.paging a:first'); //go back to first } rotate(); //Trigger the paging and slider function }, 7000); (7 seconds) }; rotateSwitch(); This works well if the paging buttons are as follows: <div class="paging"> <a href="#" rel="1">1</a> <a href="#" rel="2">2</a> <a href="#" rel="3">3</a> <a href="#" rel="4">4</a> </div> But my problem (for needs of style) is that the pagination is made in this way; <div class="paging"> <ul> <li><a href="#" rel="1">1</a></li> <li><a href="#" rel="2">2</a></li> <li><a href="#" rel="3">3</a></li> <li><a href="#" rel="4">4</a></li> </ul> </div> Then the rotation is not working. I think the problem is not finding the link below because this line: (in the rotateSwitch() function ) $active = $('.paging a.active').next(); if ( $active.length === 0) { $active = $('.paging a:first'); //go back to first } If this is the error, how to find the next() child of the list? A: Yes, a.active doesn't have siblings inside the li, hence no result from .next(). You'll need to traverse through the parent to locate the next li first and then dive back down to the link within: $active = $('.paging a.active').parent().next().find('a');
{ "pile_set_name": "StackExchange" }
Q: How do I delete an extension in my Chrome developer dashboard? I have uploaded an extension to my dashboard but I don't want to publish it any more. The extension remained "draft" status, and I want to get it removed from the dashboard. However, I cannot find any way to do so so far. Can anyone help please? A: You can't delete an extension from the Chrome developer dashboard. In the past, there was a delete button at the dashboard, but it has been removed because developers accidentally removed apps/extensions (and then tried to re-upload the app/extension with the same ID, which failed). Unpublished extensions/apps do not count toward the extension limit, so there are no consequences for having a lot of unpublished apps/extensions besides the clutter at the dashboard. If you're really bothered by the entry at your dashboard, create a user style, user script or extension to hide it. A: The new beta dashboard has an archive option. (more -> archive) A: You can not delete an extension/APP from the developer dashboard of chrome web store. Chrome web store have released new developers dashboard. You can Archive an extension/APP from the same. It is possible that developers accidentally removed extensions/APP. Then using the same extension/APP id for publication is not possible. To handle these type of human mistakes its mandatory to first unpublish the extension/APP and then Archive the same. Steps to Archive the extension/APP: Open old developers dashboard: https://chrome.google.com/webstore/developer/dashboard click on respective unpublish button of your extension Open new developers dashboard: https://chrome.google.com/webstore/devconsole Select your extension from the given list Click on "MORE" (top right corner) Select "Archive" Done Note: We do not have unpublish option in new developers dashboard. Because its still in beta phase. So for unpublish the extension, you can still use old dashboard.
{ "pile_set_name": "StackExchange" }
Q: Android service terminates when app terminates I am currently trying to implement an app that has a service running until the user explicitly ends it via the app. I would like the service to remain on otherwise. My current problem is that whenever the app is removed from the recent apps, it terminates the service as well. I have tried using START_STICKY in my onStartCommand but it doesn't change anything. public class TriggerService extends Service{ @Override public int onStartCommand(Intent intent, int flags, int startId) { // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } } and here is my code for when I call the service: public void startServ(boolean state){ editor = sp.edit(); if (state == true) { startService(new Intent(currentActivity, TriggerService.class)); editor.putBoolean("service_status", true); toast = Toast.makeText(currentActivity, "Service Running", Toast.LENGTH_SHORT); toast.show(); } else { stopService(new Intent(currentActivity, TriggerService.class)); editor.putBoolean("service_status", false); toast = Toast.makeText(currentActivity, "Service Not Running", Toast.LENGTH_SHORT); toast.show(); } editor.commit(); } EDIT: I added android:isolatedProcess="true" to the androidmanifest for the service as suggested but the service terminates when the app does. A: When a user swipes an app out of the recent history list, the process is terminated. If you start a service inside the same process as your activity, that service will be terminated when the user swipes the app out. The guide mentions starting services in different processes by simply setting a flag in the manifest but that will require you to use AIDL to move data between the service and the app or move the data indirectly via intents. http://developer.android.com/guide/topics/manifest/service-element.html <service android:enabled=["true" | "false"] android:exported=["true" | "false"] android:icon="drawable resource" android:isolatedProcess=["true" | "false"] android:label="string resource" android:name="string" android:permission="string" android:process="string" > . . . </service> A: Found the problem. The above code will work. The problem is there is a bug in the code for 4.4.2 which terminates services related to apps when you terminate those apps. An example of the issue is here http://www.androidpolice.com/2014/03/07/bug-watch-stopping-apps-on-android-4-4-2-can-silently-kill-related-background-services-a-fix-is-on-the-way/ with the bug tracker here https://code.google.com/p/android/issues/detail?id=63793
{ "pile_set_name": "StackExchange" }
Q: Copy a file from a network folder using applescript Iam very new to applescript and am currently trying to copy a file from a network share. I have an iMac server on my network and this script will be distributed to all the mac computers connected to it. Below is the code i have at the moment :- set mycopypath to "Volumes:Work Basket:LabRat:LabRat For Client Side.xlsx" as alias --set mycopypath to choose file tell application "Finder" to set startup_Disk to (name of startup disk) set mypastepath to startup_Disk & ":Users:Arjun:Desktop:" as alias tell application "Finder" to duplicate mycopypath to mypastepath with replacing In the above code , 'Work Basket' in the 'mycopypath' is the shared network folder. Currently when i run this code i get an error stating - File Volumes:Work Basket:LabRat:LabRat For Client Side.xlsx wasn’t found. But when i use the commented out part set mycopypath to choose file it works fine. Also, if i use the above code to copy paste a file from one location to another on the local computer itself, it works fine. The network folder "Work Basket" is mounted in both cases. I'v been at it for quite a few hours and must have tried many combinations of file paths but haven't been able to find a solution.Any help will be great. A: Try the following solution: When you only uncomment the set mycopypath to choose file and comment the rest, you will get the correct path as a result in the bottom half of Script Editor. (See red arrow in screenshot). After that copy that path to the set mycopypath to "" part and restore the original comments. This should work. EDIT I believe this is how to mount a network disk: tell application "Finder" to mount volume "Your disk path/name" EDIT 2 Mounting a network disk with user and pass: mount volume "afp://192.168.200.1/" as user name "your username" with password "your password"
{ "pile_set_name": "StackExchange" }
Q: Angular 2 post request not send image data I'm sending an image using a form and when it does the submit send the request without data. Here my code: component.html <form [formGroup]="logoImageForm" *ngIf="representativeSelected != null" (ngSubmit)="onSubmit(logoImageForm)"> <md-grid-list cols="6" rowHeight="50"> <md-grid-tile> <input type="file" id="logo_image" formControlName="logo_image" name="logo_image" ngModel (change)="onChange($event)"> </md-grid-tile> </md-grid-list> <md-card-actions> <button md-raised-button color="primary" type="submit">Save</button> </md-card-actions> </form> component.ts onChange(event){ this.file = event.target.files[0]; } onSubmit(logoImage){ this.representativeS.uploadLogoImage(this.file) .subscribe( data => { swal('', 'Image updated!', 'success'); }, error => { swal('Error', '<p>' + error.message + '</p>', 'success'); }); } representativeS (service) uploadLogoImage(file){ let url = this.routesS.getApiRoute('logoImage'); console.log(file); return this.http.post(url, JSON.stringify({fileData: file}),{ withCredentials: true, headers: this.headersImage }) .map((response: Response) => { return response.json(); }) .catch(this.handleError); } NodeJS var storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, 'path/test'); }, filename: function (req, file, callback) { callback(null, 'logo-image') } }); var upload = multer({ storage: storage }).single('logo-image'); router.route('/representatives/:id/logoImage') .post((req, res, next) => { upload(req, res, function (err) { if (err) { console.log('Error Occured'); return; } res.end('Your File Uploaded'); }) }); When I do the submit, if I check my request sended it shows something like that {fileData: {}}. Why is it sending a void data? A: I think the problem is how you send your file. This answer in another question might help you: https://stackoverflow.com/a/35669598/5049472
{ "pile_set_name": "StackExchange" }
Q: alpha numeric validation is not working For a Angular 2 application, I wrote a custom validator TypeScript class like below, import { FormControl } from '@angular/forms'; export class AlphaNumericValidator { static invalidAlphaNumeric(control: FormControl): { [key: string]: boolean } { if (control.value.length && !control.value.match(/^[a-z0-9]+$/i)) { return { invalidAlphaNumeric: true }; } return null; } } I am applying this validator for a Model Driven Form, 'name': [this.exercise.name, [Validators.required, AlphaNumericValidator.invalidAlphaNumeric]], And Here is the HTML, <label *ngIf="exerciseForm.controls.name.hasError('invalidAlphaNumeric') && (exerciseForm.controls.name.touched || submitted)" class="alert alert-danger validation-message">Name must be alphanumeric</label> I notice that whenever I am typing a character in input, the above TypeScript class code called, but every time it's return Null. Is there any issue on typeScript class? Thanks! A: use !/^[a-z0-9]+$/i.test(control.value) to get a boolean result
{ "pile_set_name": "StackExchange" }
Q: How does Google Reader get every item in an RSS feed? Slashdot's RSS feed is http://rss.slashdot.org/Slashdot/slashdot. If I download the XML file directly, I only get a few of the posts from today. However, if I subscribe to the feed in Google Reader, and keep scrolling down in their "infinite scroll" interface, it seems like I can get an arbitrary number of Slashdot posts from the past - maybe I can get every Slashdot post ever? How does Google Reader retrieve an unlimited number of posts from an RSS feed? How can I do the same? A: Google follows one instance of the feed for all its users, so they've been tracking and storing Slashdot articles, for example, long before any new subscriber starts reading. To do the same, you would have to poll the RSS feeds you want at regular intervals and store any unique articles you find locally. A: I just discovered that if you're authenticated you can do something like: http://www.google.com/reader/atom/feed/http://rss.slashdot.org/Slashdot/slashdot?n=100 to get an arbitrary number of results from a feed.
{ "pile_set_name": "StackExchange" }
Q: Google Analytics - Access api without login I had successfully configured google analytics api and get successful data. I want to access analytics api without gmail login. i.e. I will hard code credentials to for login, but how to do it with PHP? Is there any api function to achive this task (for PHP) Thanks! A: The Hello Analytics API: PHP Quickstart Guide for Service Accounts will walk you through the steps necessary to create and add a service account to your existing Google Analytics Account/Property/View. Once you download have the php client libs and the p12 file downloaded from developer console you can create an authorized analytics service object as follows: // Creates and returns the Analytics service object. // Load the Google API PHP Client Library. require_once 'google-api-php-client/src/Google/autoload.php'; // Use the developers console and replace the values with your // service account email, and relative location of your key file. $service_account_email = '<Replace with your service account email address.>'; $key_file_location = '<Replace with /path/to/generated/client_secrets.p12>'; // Create and configure a new client object. $client = new Google_Client(); $client->setApplicationName("HelloAnalytics"); $analytics = new Google_Service_Analytics($client); // Read the generated client_secrets.p12 key. $key = file_get_contents($key_file_location); $cred = new Google_Auth_AssertionCredentials( $service_account_email, array(Google_Service_Analytics::ANALYTICS_READONLY), $key ); $client->setAssertionCredentials($cred); if($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion($cred); } return $analytics; With the returned service object you can now make calls to the Google Analytics APIs: // Calls the Core Reporting API and queries for the number of sessions // for the last seven days. $analytics->data_ga->get( 'ga:' . $profileId, '7daysAgo', 'today', 'ga:sessions');
{ "pile_set_name": "StackExchange" }
Q: Ускорение обработки ~ 1000000 записей У меня есть форма для выбора адреса по КЛАДР. Она состоит из нескольких TcxExtLookupComboBox. В каждом TcxExtLookupComboBox отображаются данные по одному из уровней данных КЛАДРа. Если, например, мы выбрали Кировскую область, то в остальных произойдет перезагрузка данных только этой области - города, районы, улицы, все перезагрузится. Если выбрать другой регион, произойдет тоже самое. Задача: Мне нужно ускорить обработку и отображение данных для выбора пользователем адреса. Исходные данные: Есть база данных FireBird 2.5, в которой больше 1000000 записей. Для получения и отображения данных используются компоненты TpFIBDataSet [FIBPlus] и TcxExtLookupComboBox [DevExpress]. Сейчас работает так: есть 6 TpFIBDataSet, которые связаны между собой, и 6 TcxExtLookupComboBox, в которых отображаются данные из тех шести датасетов. Каждый раз при выборе записи в одном из датасетов, происходит перевыборка во всех подчиненных. Я хочу этого избежать, то есть уменьшить количество обращений к базе данных. Мое предположительное решение: убрать связь master-detail, и использовать свойство Filtered. Вопрос: Насколько вырастет или упадет производительность отображения данных? И есть ли еще какие решения? A: Ускорить целую выборку так и не получилось. Как решение - делить ее на части и обрабатывать по очереди данные в них.
{ "pile_set_name": "StackExchange" }
Q: Should minor edits not be rejected? Why are those types of forceful edits approved when the content is logically and syntactically sound? Below I have provided some of my posts which have been edited in this fashion. So I would like to know, should minor edits not be rejected? Edit:1 Edit:2 Edit:3 A: These are all users who have the privilege to edit without the need for review, because of their reputation being over 2000. As a result there is nothing to reject. Whether or not those edits are the best they can be is another matter altogether. (I would personally have fixed several other issues in each post you show us) In general, minor edits are okay if they fix all the problems in a post. Then they are not too minor.
{ "pile_set_name": "StackExchange" }
Q: How to put a key as an argument I'm trying to put a key as an argument of this function, i just don't find how to do that : city = {"Paris": 183, "Lyon": 220, "Marseille": 222 ,"Surfers Paradise": 475} def plane_ride_cost(city): for key, value in city(): return value print(plane_ride_cost("Marseille")) I got this answer : Traceback (most recent call last): File "C:/Users/vion1/ele/Audric/TP 9.py", line 25, in <module> print(plane_ride_cost("Marseille")) File "C:/Users/vion1/ele/Audric/TP 9.py", line 9, in plane_ride_cost for key, value in city(): TypeError: 'str' object is not callable Thx for your help ! A: city = {"Paris": 183, "Lyon": 220, "Marseille": 222 ,"Surfers Paradise": 475} ##define the parameter as the key def plane_ride_cost(cityName): return city[cityName] #return the value from dictionary using the key passed print(plane_ride_cost("Marseille")) #returns 222
{ "pile_set_name": "StackExchange" }
Q: Applying css to the ticks and line of an axis I have this in the css (code line 108): .domain { fill: 'none'; stroke-width: 0.7; stroke: 'black'; } .tick { fill: 'none'; stroke-width: 0.7; stroke: 'black'; } And this in the javascript (code line 358): // Add y axis with ticks and tick markers var axisPadding = 2; var leftAxisGroup = svg .append('g') .attr({ transform: 'translate(' + (margin.left - axisPadding) + ',' + (margin.top) + ')', id: "yAxisG" }); var axisY = d3.svg.axis() .orient('left') .scale(yScale); leftAxisGroup.call(axisY); Why is the style not being applied? How do I make sure it is applied? The full script and context is here: https://plnkr.co/edit/aSgNLb?p=preview A: The above CSS could be changed to selector { fill: none; /* no quotes */ stroke: black; /* no quotes */ } Keyword values are identifiers and have to be used as they are without quotes. When placed inside quotes these turn into strings which have no meaning under the value definition for their properties. Thus its not parsed as valid by the UA/browser. CSS specs: Textual Values & strings: Identifiers cannot be quoted; otherwise they would be interpreted as strings. Footnotes: SVG's fill and stroke properties: https://www.w3.org/TR/SVG/painting.html#SpecifyingPaint
{ "pile_set_name": "StackExchange" }
Q: jQuery UI Sortable Position How do I track what position an element is when its position in a sortable list changes? A: You can use the ui object provided to the events, specifically you want the stop event, the ui.item property and .index(), like this: $("#sortable").sortable({ stop: function(event, ui) { alert("New position: " + ui.item.index()); } }); You can see a working demo here, remember the .index() value is zero-based, so you may want to +1 for display purposes. A: I wasn't quite sure where I would store the start position, so I want to elaborate on David Boikes comment. I found that I could store that variable in the ui.item object itself and retrieve it in the stop function as so: $( "#sortable" ).sortable({ start: function(event, ui) { ui.item.startPos = ui.item.index(); }, stop: function(event, ui) { console.log("Start position: " + ui.item.startPos); console.log("New position: " + ui.item.index()); } }); A: Use update instead of stop http://api.jqueryui.com/sortable/ update( event, ui ) Type: sortupdate This event is triggered when the user stopped sorting and the DOM position has changed. . stop( event, ui ) Type: sortstop This event is triggered when sorting has stopped. event Type: Event Piece of code: http://jsfiddle.net/7a1836ce/ <script type="text/javascript"> var sortable = new Object(); sortable.s1 = new Array(1, 2, 3, 4, 5); sortable.s2 = new Array(1, 2, 3, 4, 5); sortable.s3 = new Array(1, 2, 3, 4, 5); sortable.s4 = new Array(1, 2, 3, 4, 5); sortable.s5 = new Array(1, 2, 3, 4, 5); sortingExample(); function sortingExample() { // Init vars var tDiv = $('<div></div>'); var tSel = ''; // ul for (var tName in sortable) { // Creating ul list tDiv.append(createUl(sortable[tName], tName)); // Add selector id tSel += '#' + tName + ','; } $('body').append('<div id="divArrayInfo"></div>'); $('body').append(tDiv); // ul sortable params $(tSel).sortable({connectWith:tSel, start: function(event, ui) { ui.item.startPos = ui.item.index(); }, update: function(event, ui) { var a = ui.item.startPos; var b = ui.item.index(); var id = this.id; // If element moved to another Ul then 'update' will be called twice // 1st from sender list // 2nd from receiver list // Skip call from sender. Just check is element removed or not if($('#' + id + ' li').length < sortable[id].length) { return; } if(ui.sender === null) { sortArray(a, b, this.id, this.id); } else { sortArray(a, b, $(ui.sender).attr('id'), this.id); } printArrayInfo(); } }).disableSelection();; // Add styles $('<style>') .attr('type', 'text/css') .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }') .appendTo('head'); printArrayInfo(); } function printArrayInfo() { var tStr = ''; for ( tName in sortable) { tStr += tName + ': '; for(var i=0; i < sortable[tName].length; i++) { // console.log(sortable[tName][i]); tStr += sortable[tName][i] + ', '; } tStr += '<br>'; } $('#divArrayInfo').html(tStr); } function createUl(tArray, tId) { var tUl = $('<ul>', {id:tId, class:'sortableClass'}) for(var i=0; i < tArray.length; i++) { // Create Li element var tLi = $('<li>' + tArray[i] + '</li>'); tUl.append(tLi); } return tUl; } function sortArray(a, b, idA, idB) { var c; c = sortable[idA].splice(a, 1); sortable[idB].splice(b, 0, c); } </script>
{ "pile_set_name": "StackExchange" }
Q: Arduino Automatic Light Switch 2 I'm currently working on an automatic light switch. Here's my code: #include <Servo.h> boolean time = false; const int timeLim = 10000; const int delLen = 5000; int pirVal = 0; const int pirPin = 2; const int sensePin = 5; boolean timeRet = false; int lightVal; Servo myServo; unsigned long limit; void setup() { Serial.begin(9600); pinMode(pirPin, INPUT); myServo.attach(11); myServo.write(40); } void loop() { unsigned long Timer = millis(); pirVal = digitalRead(pirPin); int lightVal = analogRead(sensePin); Serial.print(pirVal); Serial.print(' '); Serial.print(lightVal); Serial.print(' '); Serial.print(Timer); Serial.print(' '); Serial.print(time); Serial.print(' '); Serial.print(limit); Serial.print(' '); Serial.println(timeRet); if ( lightVal < 400 ) { time = false; limit = 0; timeRet = false; } if ( lightVal < 400 && pirVal == 1 ) { unsigned long time = false; pirVal = 0; myServo.write(160); } if ( lightVal > 400 && pirVal == 0 && timeRet == false){ limit = getTimeLim( timeLim, Timer ); pirVal = 0; timeRet = true; } if ( lightVal > 400 && pirVal == 0 && timeRet == true ) { time = timeStat ( limit, Timer ); } if ( lightVal > 400 && time == true ) { myServo.write(40); } } int getTimeLim( const int timeLim, unsigned long Timer ) { unsigned long limit = Timer + timeLim; return limit; } boolean timeStat( unsigned long limit, unsigned long Timer ) { if ( Timer < limit ) { time = false; } else if ( Timer > limit ) { time = true; } return time; } The problem is that when you look at the serial the first time the getTimeLim function it works, but the second time is always some outrageous number (e.g. 4294937965). I don't know why it would give me this huge number. Help would be much appreciated. A: since your code works now and you want to optimize it, i would suggest this: // ( pseudo code since i'm not familiar with arduino ) void loop( ){ if( ( analogRead( sensePin ) < 400 ) && ( digitalRead( pirPin ) ) ){ myServo.write( 160 ); // turn on light int time_end = millis( ) + 60,000; // initiate timer value while( millis( ) < time_end ); // poll time until at 60s myServo.write( 40 ); // turn off light } }
{ "pile_set_name": "StackExchange" }
Q: How to design filters for a generic, pluggable collection? I am developing a web application that features a timeline, much like a Facebook timeline. The timeline itself is completely generic and pluggable. It's just a generic collection of items. Anything with the proper interface (Dateable) can be added to the collection and displayed on the timeline. Other components (Symfony bundles) define models that implement the Dateable interface and set up a provider that can find and return these models. The code is much like this: class Timeline { private $providers = []; // Filled by DI public function find(/* ... */) { $result = []; foreach ($this->providers as $provider) { $result = array_merge($result, $provider->find(/* ... */)); } return $result; } } The problem is that there needs to be a set of filters next to the timeline. Some filter options (like date) apply to all providers. But most options do not. For example, most providers will be able to use the author filter option, but not all. Some notification item are dynamically generated and don't have an author. Some filter options just apply to a single provider. For example, only event items have a location property. I can't figure out how to design a filter form that is just as modular as the timeline itself. Where should the available filter options be defined? Bundle-specific filter options could probably come from the bundle itself, but how about filter options (like user) that can be used by multiple bundles? And what if some filter options later become usable by multiple bundles? For example, only events have a location now, but what if another module is added that also has items with a location? And how will each provider determine if the submitted filter form only contains options it understands? If I set a location in the filter then the BlogPostProvider should not return any messages, because blog posts have no location. But I can't check for location in the filter because the BlogPostBundle shouldn't know about other providers and their filtering options. Any ideas on how I can design such a filter form? A: This is how I solved it in the end. First off, I have a FilterRegistry. Any bundle can add filters to it using a Symfony DI tag. A filter is simply a form type. Example filter: class LocationFilterType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('location', 'choice', [ /* ... */ ]); } } DI configuration: <service id="filter.location" class="My\Bundle\Form\LocationFilterType"> <tag name="form.type" alias="filter_location" /> <tag name="filter.type" alias="location" /> </service> The FilterRegistry knows how to get those form types from the DI container: class FilterRegistry { public function getFormType($name) { if (!isset($this->types[$name])) { throw new \InvalidArgumentException(sprintf('Unknown filter type "%s"', $name)); } return $this->container->get($this->types[$name]); } } The Timeline class and the providers use the FilterBuilder to add new filters to the filter form. The builder looks like this: class FilterBuilder { public function __construct(FilterRegistry $filterRegistry, FormBuilderInterface $formBuilder) { $this->filterRegistry = $filterRegistry; $this->formBuilder = $formBuilder; } public function add($name) { if ($this->formBuilder->has($name)) { return; } $type = $this->filterRegistry->getFormType($name); $type->buildForm($this->formBuilder, $this->formBuilder->getOptions()); return $this; } } In order to display the form, a filter is build using the options of all providers. This happens in Timeline->getFilterForm(). Note that there is no data object tied to the form: class Timeline { public function getFilterForm() { $formBuilder = $this->formFactory->createNamedBuilder('', 'base_filter_type'); foreach ($this->providers as $provider) { $provider->configureFilter(new FilterBuilder($this->filterRegistry, $formBuilder)); } return $formBuilder->getForm(); } } Each provider implements the configureFilter method: class EventProvider { public function configureFilter(FilterBuilder $builder) { $builder ->add('location') ->add('author') ; } } The find method of the Timeline class is also modified. Instead of building a filter with all options, it builds a new filter form with just the options for that provider. If form validation fails then the provider cannot handle the currently submitted combination of filters. Usually this is because a filter option is set that the provider does not understand. In that case, form validation fails due to extra data being set. class Timeline { public function find(Request $request) { $result = []; foreach ($this->providers as $provider) { $filter = $provider->createFilter(); $formBuilder = $this->formFactory->createNamedBuilder('', 'base_filter_type', $filter); $provider->configureFilter(new FilterBuilder($this->filterRegistry, $formBuilder)); $form = $formBuilder->getForm(); $form->handleRequest($request); if (!$form->isSubmitted() || $form->isValid()) { $result = array_merge($result, $provider->find($filter)); } } return $result; } } In this case, there is a data class tied to the form. $provider->createFilter() simply returns an object that has properties matching the filters. The filled and validated filter object is then passed to the provider's find() method. E.g: class EventProvider { public function createFilter() { return new EventFilter(); } public function find(EventFilter $filter) { // Do something with $filter and return events } } class EventFilter { public $location; public $author; } This whole thing together makes it pretty easy to manage the filters. To add a new type of filter: Implement a FormType Tag it in the DI as a form.type and as a filter.type To start using a filter: Add it to the FilterBuilder in configureFilters() Add a property to the filter model Handle the property in the find() method
{ "pile_set_name": "StackExchange" }
Q: Stan Model Posterior Predictions Outside Possible Range of Data I am having a lot of fun right now learning the ropes of modeling in Stan. Right now I'm wrestling with my model of a mixed between- and within-subjects factorial experimental design. There are different groups of subjects, Each subject indicates how much they expect each of three different beverages (water, decaf, and coffee) to reduce their caffeine withdrawal. The outcome variable - expectancy of withdrawal reduction - was measured via a Visual Analog Scale from 0 - 10 with 0 indicating no expectation of withdrawal reduction and 10 indicating a very high expectation of withdrawal reduction. I want to test if there are between-group differences in the amount of expected withdrawal-reduction potential of the three different beverages. Here is the data df <- data.frame(id = rep(1:46, each = 3), group = c(3,3,3,1,1,1,3,3,3,1,1,1,3,3,3,1,1,1,3,3,3,2,2,2,1,1,1,3,3,3,3,3,3,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3,2,2,2,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3,2,2,2,3,3,3,3,3,3,2,2,2,3,3,3,3,3,3,1,1,1,3,3,3,3,3,3,1,1,1,2,2,2,2,2,2,1,1,1,2,2,2,2,2,2,1,1,1,1,1,1,2,2,2,2,2,2,1,1,1,1,1,1,3,3,3,1,1,1,3,3,3), bevType = rep(c(3,2,1), times = 46), score = c(2.9,1.0,0.0,9.5,5.0,4.5,9.0,3.0,5.0,5.0,0.0,3.0,9.5,2.0,3.0,8.5,0.0,6.0,5.2,3.0,4.0,8.4,7.0,2.0,10.0,0.0,3.0,7.3,1.0,1.8,8.5,2.0,9.0,10.0,5.0,10.0,8.3,2.0,5.0,6.0,0.0,5.0,6.0,0.0,5.0,10.0,0.0,5.0,6.8,1.0,4.8,8.0,1.0,4.0,7.0,4.0,6.0,6.5,1.0,3.1,9.0,1.0,0.0,6.0,0.0,2.0,9.5,4.0,6.0,8.0,1.0,3.8,0.4,0.0,7.0,7.0,0.0,3.0,9.0,2.0,5.0,9.5,2.0,7.0,7.9,5.0,4.9,8.0,1.0,1.0,9.3,5.0,7.9,6.5,2.0,3.0,8.0,2.0,6.0,10.0,0.0,5.0,6.0,0.0,5.0,6.8,0.1,7.0,8.0,3.0,9.1,8.2,0.0,7.9,8.2,5.0,0.0,9.2,1.0,3.1,9.1,3.0,0.6,5.7,2.0,5.1,7.0,0.0,7.4,8.0,1.0,1.5,9.1,4.0,4.3,8.5,8.0,5.0)) Now for the model. The model has a grand mean parameter a, a categorical predictor representing groups deflections from the grand mean bGroup, a term for deflections of the different beverage types from the grand mean bBev, a term for each subject's intercept bSubj, and a term for the group by beverage interaction bGxB. I also estimated separate noise parameters for each beverage type. To allow posterior predictive checks I drew from the joint posterior using the generated quantities block and the normal_rng function. ### Step 1: Put data into list dList <- list(N = 138, nSubj = 46, nGroup = 3, nBev = 3, sIndex = df$id, gIndex = df$group, bIndex = df$bevType, score = df$score, gMean = 4.718841, gSD = 3.17) #### Step 1 model write(" data{ int<lower=1> N; int<lower=1> nSubj; int<lower=1> nGroup; int<lower=1> nBev; int<lower=1,upper=nSubj> sIndex[N]; int<lower=1,upper=nGroup> gIndex[N]; int<lower=1,upper=nBev> bIndex[N]; real score[N]; real gMean; real gSD; } parameters{ real a; vector[nSubj] bSubj; vector[nGroup] bGroup; vector[nBev] bBev; vector[nBev] bGxB[nGroup]; // vector of vectors, stan no good with matrix vector[nBev] sigma; real<lower=0> sigma_a; real<lower=0> sigma_s; real<lower=0> sigma_g; real<lower=0> sigma_b; real<lower=0> sigma_gb; } model{ vector[N] mu; //hyper-priors sigma_s ~ normal(0,10); sigma_g ~ normal(0,10); sigma_b ~ normal(0,10); sigma_gb ~ normal(0,10); //priors sigma ~ cauchy(0,1); a ~ normal(gMean, gSD); bSubj ~ normal(0, sigma_s); bGroup ~ normal(0,sigma_g); bBev ~ normal(0,sigma_b); for (i in 1:nGroup) { //hierarchical prior on interaction bGxB[i] ~ normal(0, sigma_gb); } // likelihood for (i in 1:N){ score[i] ~ normal(a + bGroup[gIndex[i]] + bBev[bIndex[i]] + bSubj[sIndex[i]] + bGxB[gIndex[i]][bIndex[i]], sigma[bIndex[i]]); } } generated quantities{ real y_draw[N]; for (i in 1:N) { y_draw[i] = normal_rng(a + bGroup[gIndex[i]] + bBev[bIndex[i]] + bSubj[sIndex[i]] + bGxB[gIndex[i]][bIndex[i]], sigma[bIndex[i]]); } } ", file = "temp.stan") ##### Step 3: generate the chains mod <- stan(file = "temp.stan", data = dList, iter = 5000, warmup = 3000, cores = 1, chains = 1) Next we extract the draws from the joint posterior, and generate estimates of the group mean, upper and lower 95% HPDI. First we need a function to calculate the HPDI HPDIFunct <- function (vector) { sortVec <- sort(vector) ninetyFiveVec <- ceiling(.95*length(sortVec)) fiveVec <- length(sortVec) - length(ninetyFiveVec) diffVec <- sapply(1:fiveVec, function (i) sortVec[i + ninetyFiveVec] - sortVec[i]) minVal <- sortVec[which.min(diffVec)] maxVal <- sortVec[which.min(diffVec) + ninetyFiveVec] return(list(sortVec, minVal, maxVal)) } Now to extract the draws from the posterior #### Step 5: Posterior predictive checks y_draw <- data.frame(extract(mod, pars = "y_draw")) And plot the mean, lower HPDI and upper HPDI draws of these draws against the actual data. df$drawMean <- apply(y_draw, 2, mean) df$HPDI_Low <- apply(y_draw, 2, function(i) HPDIFunct(i)[[2]][1]) df$HPDI_Hi <- apply(y_draw, 2, function(i) HPDIFunct(i)[[3]][1]) ### Step 6: plot posterior draws against actual data ggplot(df, aes(x = factor(bevType), colour = factor(group))) + geom_jitter(aes(y = score), shape = 1, position = position_dodge(width=0.9)) + geom_point(aes(y = drawMean), position = position_dodge(width=0.9), stat = "summary", fun.y = "mean", shape = 3, size = 3, stroke = 2) + geom_point(aes(y = HPDI_Low), position = position_dodge(width=0.9), stat = "summary", fun.y = "mean", shape = 1, size = 3, stroke = 1) + geom_point(aes(y = HPDI_Hi), position = position_dodge(width=0.9), stat = "summary", fun.y = "mean", shape = 1, size = 3, stroke = 1) + scale_colour_manual(name = "Experimental Group", labels = c("Group 1", "Group 2", "Group 3"), values = c("#616a6b", "#00AFBB", "#E7B800")) + scale_x_discrete(labels = c("Water", "Decaf", "Coffee")) + labs(x = "Beverage Type", y = "Expectancy of Withdrawal Alleviation") + scale_y_continuous(breaks = seq(0,10,2)) + theme(axis.text.x = element_text(size = 12), axis.title.x = element_text(face = "bold"), axis.title.y = element_text(face = "bold"), axis.text.y = element_text(size = 12), legend.title = element_text(size = 13, face = "bold")) Looking at the graph, for Water expectancies the model seems to represent the centre (crosses) and spread (open circles) of the data quite well. But this breaks down for the Decaf and Coffee expectancies. For Decaf expectancies the lower HPDI is below the range of possible values (lower limit = 0) and the spread of the draws from the posterior (represented in each group by the open circles) is too large. The Coffee group's upper HPDI limit is also above the range of the data (upper limit = 10) and the spread is too large for the actual data. So my question is: How do I constrain the draws from the joint posterior to the actual range of the data? Is there some sort of brute-force way to constrain the draws from the posterior in Stan? Or would a more adaptable estimation of differences in the variance across the three beverage conditions be more effective (in which case this would be more of a CV question than a SO question)? A: The standard way to constrain a posterior variable is to use a link function to transform it. That's the way generalized linear models (GLMs) like logistic regression and Poisson regression work. For example, to go from positive ot unconstrained, we use a log transform. To go from a probability in (0, 1) to unconstrained, we use a log odds transform. If your outcomes are ordinal values on a 1-10 scale, a common approach that respects that data scale is ordinal logistic regression. A: To expand on @Bob Carpenter's answer, here are two ways you could approach the problem. (I've had cause to use both of these recently and struggled to get them up and running. This may be useful to other beginners like me.) Method 1: Ordered Logistic Regression We're going to assume that each user has a "true" expectancy for each response, which is on an arbitrary continuous scale, and model it as a latent variable. If the user's actual responses fall into K categories, we also model K - 1 cutpoints between those categories. The probability that the user selects a given response category is equal to the area under the logistic pdf between the relevant cutpoints. The Stan model looks like this. The main difference is that the model fits an additional ordered vector of cutpoints, and uses the ordered_logistic distribution. (I also changed the priors on the sigmas to Cauchy, to keep them positive, and switched to non-centered parameterization. But those changes are independent of the question at hand.) Edit: Also added inputs for new (hypothetical) observations about which we want to make predictions, and added a new generated quantity for those predictions. data { // the real data int<lower=1> N; int<lower=1> nSubj; int<lower=1> nGroup; int<lower=1> nBev; int minResponse; int maxResponse; int<lower=1,upper=nSubj> sIndex[N]; int<lower=1,upper=nGroup> gIndex[N]; int<lower=1,upper=nBev> bIndex[N]; int<lower=minResponse,upper=maxResponse> score[N]; // hypothetical observations for new predictions int<lower=1> nNewPred; int<lower=0> nNewSubj; int<lower=0> nNewGroup; int<lower=0> nNewBev; int<lower=1,upper=nSubj+nNewSubj> sNewIndex[nNewPred]; int<lower=1,upper=nGroup+nNewGroup> gNewIndex[nNewPred]; int<lower=1,upper=nBev+nNewBev> bNewIndex[nNewPred]; } parameters { real a; vector[nSubj] bSubj; vector[nGroup] bGroup; vector[nBev] bBev; vector[nBev] bGxB[nGroup]; real<lower=0> sigma_s; real<lower=0> sigma_g; real<lower=0> sigma_b; real<lower=0> sigma_gb; ordered[maxResponse - minResponse] cutpoints; } model { // hyper-priors sigma_s ~ cauchy(0, 1); sigma_g ~ cauchy(0, 1); sigma_b ~ cauchy(0, 1); sigma_gb ~ cauchy(0, 1); // priors a ~ std_normal(); bSubj ~ std_normal(); bGroup ~ std_normal(); bBev ~ std_normal(); for (i in 1:nGroup) { bGxB[i] ~ std_normal(); } // likelihood for(i in 1:N) { score[i] ~ ordered_logistic(a + (bGroup[gIndex[i]] * sigma_g) + (bBev[bIndex[i]] * sigma_b) + (bSubj[sIndex[i]] * sigma_s) + (bGxB[gIndex[i]][bIndex[i]] * sigma_gb), cutpoints); } } generated quantities { real y_draw[N]; real y_new_pred[nNewPred]; vector[nGroup+nNewGroup] bNewGroup; vector[nBev+nNewBev] bNewBev; vector[nSubj+nNewSubj] bNewSubj; vector[nBev+nNewBev] bNewGxB[nGroup+nNewGroup]; // generate posterior predictions for the real data for (i in 1:N) { y_draw[i] = ordered_logistic_rng(a + (bGroup[gIndex[i]] * sigma_g) + (bBev[bIndex[i]] * sigma_b) + (bSubj[sIndex[i]] * sigma_s) + (bGxB[gIndex[i]][bIndex[i]] * sigma_gb), cutpoints); } // generate predictions for the new observations for (i in 1:(nGroup+nNewGroup)) { if (i <= nGroup) { bNewGroup[i] = bGroup[i]; } else { bNewGroup[i] = normal_rng(0, 1); } } for (i in 1:(nBev+nNewBev)) { if (i <= nBev) { bNewBev[i] = bBev[i]; } else { bNewBev[i] = normal_rng(0, 1); } } for (i in 1:(nSubj+nNewSubj)) { if (i <= nSubj) { bNewSubj[i] = bSubj[i]; } else { bNewSubj[i] = normal_rng(0, 1); } } for (i in 1:(nBev+nNewBev)) { for(j in 1:(nGroup+nNewGroup)) { if (i <= nBev && j <= nGroup) { bNewGxB[i][j] = bGxB[i][j]; } else { bNewGxB[i][j] = normal_rng(0, 1); } } } for (i in 1:nNewPred) { y_new_pred[i] = ordered_logistic_rng(a + (bNewGroup[gNewIndex[i]] * sigma_g) + (bNewBev[bNewIndex[i]] * sigma_b) + (bNewSubj[sNewIndex[i]] * sigma_s) + (bNewGxB[gNewIndex[i]][bNewIndex[i]] * sigma_gb), cutpoints); } } It looks like responses in your dataset are recorded to the nearest tenth, so that gives us 101 possible categories between 0 and 10. To keep everything as Stan-friendly integers, we can multiply all the responses by 10. (I also added one to each response because I had trouble fitting the model when one of the possible categories was zero.) Edit: Added new test data for a hypothetical "subject 47", one observation for each group/beverage. new.pred.obs = expand.grid(group = 1:3, bevType = 2:3) %>% mutate(id = max(df$id) + 1) dList <- list(N = 138, nSubj = 46, nGroup = 3, nBev = 3, minResponse = 1, maxResponse = 101, sIndex = df$id, gIndex = df$group, bIndex = df$bevType, score = (df$score * 10) + 1, nNewPred = nrow(new.pred.obs), nNewSubj = 1, nNewGroup = 0, nNewBev = 0, sNewIndex = new.pred.obs$id, gNewIndex = new.pred.obs$group, bNewIndex = new.pred.obs$bevType) After we extract y_draw, we can convert it back to the original scale: y_draw <- (data.frame(extract(mod, pars = "y_draw")) - 1) / 10 Everything else is the same as before. Now the posterior predictions are correctly confined to [0, 10]. To draw inferences on the original scale about differences between beverages, we can use the predictions for our hypothetical data. For each sample, we have one predicted output for a new subject in each group/beverage combination. We can compare the "coffee" vs. "decaf" responses within each sample and group: # Get predictions for hypothetical observations new.preds.df = data.frame(rstan::extract(mod, pars = "y_new_pred")) %>% rownames_to_column("sample") %>% gather(obs, pred, -sample) %>% mutate(obs = gsub("y_new_pred\\.", "", obs), pred = (pred - 1) / 10) %>% inner_join(new.pred.obs %>% rownames_to_column("obs") %>% mutate(bevType = paste("bev", bevType, sep = ""), group = paste("Group", group)), by = c("obs")) %>% select(-obs) %>% spread(bevType, pred) %>% mutate(bevTypeDiff = bev3 - bev2) (Alternatively, we could have done this prediction for new observations in R, or in a separate Stan model; see here for examples of how this could be done.) Method 2: Beta Regression Once we get up to 101 response categories, calling these possibilities discrete categories seems a little strange. It feels more natural to say, as your original model tried to do, that we're capturing a continuous outcome that happens to be bounded between 0 and 10. Also, in ordered logistic regression, the response categories don't have to be regularly spaced with respect to the latent variable. (This is a feature, not a bug; for example, for Likert responses, there's no guarantee that the difference between "Strongly agree" and "Agree" is the same as the difference between "Agree" and "Neither agree not disagree".) as a result, it's difficult to say anything about the "distance" a particular factor causes a response to move on the original scale (as opposed to the scale of the latent variable). But the cutpoints inferred by the model above are pretty regularly spaced, which again suggests that the outcome in your dataset is already reasonably scale-like: # Get the sampled parameters sampled.params.df = data.frame(as.array(mod)[,1,]) %>% select(-matches("y_draw")) %>% rownames_to_column("iteration") # Plot selected cutpoints sampled.params.df %>% select(matches("cutpoints")) %>% gather(cutpoint, value) %>% mutate(cutpoint.num = as.numeric(gsub("^cutpoints\\.([0-9]+)\\.$", "\\1", cutpoint))) %>% group_by(cutpoint.num) %>% summarize(mean.value = mean(value), lower.95 = quantile(value, 0.025), lower.50 = quantile(value, 0.25), upper.50 = quantile(value, 0.75), upper.95 = quantile(value, .975)) %>% ggplot(aes(x = cutpoint.num, y = mean.value)) + geom_point(size = 3) + geom_linerange(aes(ymin = lower.95, ymax = upper.95)) + geom_linerange(aes(ymin = lower.50, ymax = upper.50), size = 2) + scale_x_continuous("cutpoint", breaks = seq(0, 100, 10)) + scale_y_continuous("") + theme_bw() (Thick and thin lines represent 50% and 95% intervals, respectively. I'm enjoying the little "jump" every 10 cutpoints, which suggests subjects treated, say, 5.9 vs. 6.0 as a larger difference than 5.8 vs. 5.9. But the effect seems to be quite mild. The scale also seems to stretch out a bit towards the high end, but again, it's not too drastic.) For a continuous outcome in a bounded interval, we can use the beta distribution; see here and here for further discussion. For the beta distribution, we need two parameters, mu and phi, both of which must be positive. In this example, I allowed mu to be unbounded and applied inv_logit before feeding it into the beta distribution; I constrained phi to be positive and gave it a Cauchy prior. But you could do it in any number of ways. I also coded a full set of mu parameters but only a single phi; again, you can experiment with other options. data { int<lower=1> N; int<lower=1> nSubj; int<lower=1> nGroup; int<lower=1> nBev; int<lower=1,upper=nSubj> sIndex[N]; int<lower=1,upper=nGroup> gIndex[N]; int<lower=1,upper=nBev> bIndex[N]; vector<lower=0,upper=1>[N] score; } parameters { real a; real a_phi; vector[nSubj] bSubj; vector[nGroup] bGroup; vector[nBev] bBev; vector[nBev] bGxB[nGroup]; real<lower=0> sigma_s; real<lower=0> sigma_g; real<lower=0> sigma_b; real<lower=0> sigma_gb; } model { vector[N] mu; //hyper-priors sigma_s ~ cauchy(0, 1); sigma_g ~ cauchy(0, 1); sigma_b ~ cauchy(0, 1); sigma_gb ~ cauchy(0, 1); //priors a ~ std_normal(); a_phi ~ cauchy(0, 1); bSubj ~ std_normal(); bGroup ~ std_normal(); bBev ~ std_normal(); for (i in 1:nGroup) { bGxB[i] ~ std_normal(); } // likelihood for(i in 1:N) { mu[i] = a + (bGroup[gIndex[i]] * sigma_g) + (bBev[bIndex[i]] * sigma_b) + (bSubj[sIndex[i]] * sigma_s) + (bGxB[gIndex[i]][bIndex[i]] * sigma_gb); score[i] ~ beta(inv_logit(mu[i]) .* a_phi, (1 - inv_logit(mu[i])) .* a_phi); } } generated quantities { real y_draw[N]; real temp_mu; for (i in 1:N) { temp_mu = a + (bGroup[gIndex[i]] * sigma_g) + (bBev[bIndex[i]] * sigma_b) + (bSubj[sIndex[i]] * sigma_s) + (bGxB[gIndex[i]][bIndex[i]] * sigma_gb); y_draw[i] = beta_rng(inv_logit(temp_mu) .* a_phi, (1 - inv_logit(temp_mu)) .* a_phi); } } The beta distribution is supported on (0, 1), so we divide the observed scores by 10. (The model also fails if we give it scores of exactly 0 or 1, so I converted all such scores to 0.01 and 0.99, respectively.) dList.beta <- list(N = 138, nSubj = 46, nGroup = 3, nBev = 3, sIndex = df$id, gIndex = df$group, bIndex = df$bevType, score = ifelse(df$score == 0, 0.01, ifelse(df$score == 10, 0.99, df$score / 10))) Undo the transformation when extracting y_draw, and then the procedure is the same as before. y_draw.beta <- data.frame(extract(mod.beta, pars = "y_draw")) * 10 Once again, the posterior draws are correctly bounded.
{ "pile_set_name": "StackExchange" }
Q: Integral over Fractals with respect to fractal dimension I understand that there is type of integral with respect to measures that can return values when evaluated over an integral. But is there an Integral that returns d dimensional volume where d is the fractal dimension of the fractal. Basically, I'm asking about finding an integral that can find the volume of say the cantor set in terms of $m^{ln2/ln3}$. This question is mostly motivated by the fact that the area of 2-d objects can vary a lot, yet they all have units of $m^2$. I'd assume this would be the case for fractal objects as well. As an example, if I wanted to take the integral of the siernpinski triangle and get a $ln3/ln2$ dimensional volume instead of taking the area of a square, could I? If so, could you provide a link or an explanation? A: If $\mu$ is a measure and $1_E$ is the characteristic function of a set $E$ then, in principle, $$\int 1_E \, d\mu$$ returns the measure $\mu(E)$. If $\mu_s$ is an $s$-dimensional measure (like the Hausdorff or Packing measure), then I guess the integral returns what you're looking for. I don't think that makes computing the exact value any easier, though. If you are interested in an introduction to integration using fractal measures, I highly recommend the paper Evaluating Integrals Using Self-similarity by Bob Strichartz. The paper gives an excellent introduction to integration with respect to self-similar measures.
{ "pile_set_name": "StackExchange" }
Q: Regular expression or other get all elements names from a list I started with regular expression but for what I have found, I think is better to do it another way. I want to get an array of the images name from the following text: The following images failed: [T430040.tif, T432040.tif, T411030.tif, CH1090.tif, T432050.tif, T432090.tif, T432020.tif, CRP040.tif, T432070.tif, T040060.tif] Array: T430040 T432040 T411030 CH1090 T432050 T432090 T432020 CRP040 T432070 T040060 Any help will be appreciated. A: Without regex: String str = "The following images failed: [T430040.tif, T432040.tif, T411030.tif, CH1090.tif, T432050.tif, T432090.tif, T432020.tif, CRP040.tif, T432070.tif, T040060.tif]"; String[] array = str.substring(str.indexOf("[") + 1, str.length() - 1) .replace(".tif", "") .split(","); System.out.println(Arrays.toString(array)); will print the array: [T430040, T432040, T411030, CH1090, T432050, T432090, T432020, CRP040, T432070, T040060] A: This java code uses regex \w+(?=\.) does what you need. String s = "The following images failed: [T430040.tif, T432040.tif, T411030.tif, CH1090.tif, T432050.tif, T432090.tif, T432020.tif, CRP040.tif, T432070.tif, T040060.tif]"; Pattern p = Pattern.compile("\\w+(?=\\.)"); Matcher m = p.matcher(s); while(m.find()) { System.out.println(m.group()); } And prints, T430040 T432040 T411030 CH1090 T432050 T432090 T432020 CRP040 T432070 T040060
{ "pile_set_name": "StackExchange" }
Q: Python I/O operation on a closed file, why the error? Code below I have the following code, and am getting an error: I/O operation on a closed file despite having opened the file. I am creating a .txt file and writing values of a dictionary to the .txt file, then closing the file. After that I am trying to print the SHA256 digest for the file created. sys.stdout = open('answers.txt', 'w') for key in dictionary: print(dictionary[key]) sys.stdout.close() f = open('answers.txt', 'r+') #print(hashlib.sha256(f.encode('utf-8')).hexdigest()) m = hashlib.sha256() m.update(f.read().encode('utf-8')) print(m.hexdigest()) f.close() Why am I getting this error? Traceback (most recent call last): File "filefinder.py", line 97, in <module> main() File "filefinder.py", line 92, in main print(m.hexdigest()) ValueError: I/O operation on closed file. A: Here, you override sys.stdout to point to your opened file: sys.stdout = open('answers.txt', 'w') Later, when you try to print to STDOUT sys.stdout is still pointing to the (now closed) answers.txt file: print(m.hexdigest()) I don't see any reason to override sys.stdout here. Instead, just pass a file option to print(): answers = open('answers.txt', 'w') for key in dictionary: print(dictionary[key], file=answers) answers.close() Or, using the with syntax that automatically closes the file: with open('answers.txt', 'w') as answers: for key in dictionary: print(dictionary[key], file=answers)
{ "pile_set_name": "StackExchange" }
Q: good ways of adding/removing multiple directories to/from git repo? Let's say I have this dir structure: /project1 /SomeFolder /obj /bin /project2 /obj /bin Let's say each directory has source files I want to check in, but I don't want to check in /obj and /bin directories or their contents... The way I did was git add . and than browse to each dir and do git rm obj git rm bin As you can imagine this gets tedious especially if there are many directories... What is a better way to do something like that? Namely add multiple files with some exceptions, or remove all subdirectories with certain name? update to update multiple directories this will also work: git rm */obj A: You could just add a .gitignore file for each project, right? According to the docs: The git add command will not add ignored files by default. If any ignored files were explicitly specified on the command line, git add will fail with a list of ignored files. A: You should add these to the .gitignore file in the root of your git project: echo obj >> .gitignore echo bin >> .gitignore
{ "pile_set_name": "StackExchange" }
Q: Display bar charts in ArcMap I am trying to symbolize data as bar charts in ArcMap. I have a feature class with two sets of data, and I want the bar charts next to each other on the map. The problem I am having is that the map will only display the bars if both sets of data are not Null. Is there a way to display all the bars with data? If I put 0 for the Nulls, then a flat bar appears, and I don't want that either. A: There is an option to exclude certain data in the layer itself. You could do this, and then it will graph everything else. Select layer-> Options->Symbology-> Charts-> Exclusion-> SQL query "Field" IS NULL This will make it so that all the null values do not appear in the bar graph. let me know if this solved it
{ "pile_set_name": "StackExchange" }
Q: Why "RUN rm /etc/nginx/conf.d/default.conf" did not succeed? I don't want my nginx docker image to have /etc/nginx/conf.d/default.conf so I wrote a simple nginx dockerfile, mainly to add RUN rm /etc/nginx/conf.d/default.conf To my surprise it did not work. /etc/nginx/conf.d/default.conf is still there. Why and how do I delete it ? My dockerfile: FROM nginx:latest # Copy custom configuration file from the current directory RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/nginx.conf COPY conf.d/node2 /etc/nginx/conf.d/node2 EXPOSE 80 8080 My docker-compose.yml for nginx service adds a name volumn volumes: - conf:/etc/nginx/conf.d Update: I finally found out that it is because I created a name volume in my docker-compose.yml that create /etc/nginx/conf.d/default.conf so rm in dockerfile won't work at all. But why creating a name volume will result in creating `/etc/nginx/conf.d/default.conf ? Update2: With the second answer I got I finally figure out why. So RUN rm /etc/nginx/conf.d/default.conf did work. The problem is I used a volume in my docker-compose.yml that was created before I run RUN rm /etc/nginx/conf.d/default.conf and that volume has default.conf. It happened like this, I first used a dockerfile without rm and run docker-compose up, then I added rm to it to rebuild the image and run docker-compose up again. But I never change my docker-compose.yml or clean my volume. So the file was there no matter how I build/rebuild my image. After I deleted all the old volume (using docker volume rm docker volume ls -q -f dangling=true) it finally works. I leave my question here instead of deleting it just in case someone else may make the same mistake like I did :$ A: Volumes are a run time change to the filesystem. The build runs without your volume to create the image. Therefore the file is deleted in the image, but then you mount a volume in your container that has the file. The fix is to either not use a volume so you can see the filesystem as it exists in the image, or you can delete the file from the volume. The following should work for cleaning the file from the volume: docker run -it --rm -v ${vol_name}:/target busybox rm /target/default.conf
{ "pile_set_name": "StackExchange" }
Q: Setting initial values of Angular-UI Select2 multiple directive I have a select2 directive for a multiple select of countries with a custom query to grab the data: // Directive <input ng-model="filters.countries" ui-select2="filters.countryOptions" data-placeholder="Choose a country..."> // filters.countryOptions { multiple: true, query: function() { get_list_of_countries(); } } // Formatted data from remote source [ {id: 'US', text: 'United States'}, {id: 'CA', text: 'Canada'} ... ] I'm trying to set the initially selected values in my controller using: $scope.filters.countries = [{id: 'US', text: 'United States'}]; This does correctly set the model, however this is happening before the select2 initialization has occurred. As I step through the remaining initialization code the input temporarily displays [Object] before finally blanking out $scope.filters.countries and the input, but it does not display the placeholder text in the input. To get around this I'm using the following to reset the models' initial value: $scope.$on('$viewContentLoaded', function() { setTimeout(function() { $scope.filters.countries = [{id: 'US', text: 'United States'}]; }, 100); }); It seems really hackish to be using a setTimeout. Is there a better way that I'm missing? Update 1 As requested by ProLoser here is a demo and github ticket. Demo: http://plnkr.co/edit/DgpGyegQxVm7zH1dZIJZ?p=preview GitHub Issue: https://github.com/angular-ui/angular-ui/issues/455 Following ProLoser's advice I started using select2's initSelection function: initSelection : function (element, callback) { callback($(element).data('$ngModelController').$modelValue); }, It does the trick but still feels like a workaround. A: As requested by ProLoser here is a demo and github ticket. Demo: http://plnkr.co/edit/DgpGyegQxVm7zH1dZIJZ?p=preview GitHub Issue: https://github.com/angular-ui/angular-ui/issues/455 Following ProLoser's advice I started using select2's initSelection function: initSelection : function (element, callback) { callback($(element).data('$ngModelController').$modelValue); }, It does the trick but still feels like a workaround.
{ "pile_set_name": "StackExchange" }
Q: How to see when a SQL Server 2008 Certificate Object Expires (& other properties) I have a SQL Server 2008 mirroring setup where CREATE CERTIFICATE was used to generate the SQL Certificate Objects to enable mirroring between workgroup-based servers. Q. How can I view the expiration date and other properties of the existing certificate objects? (I understand that these are SQL "Objects" as they don't show up in the usual MMC certificates console). A: You can write sql queries to get the expiration dates from sys.certificates Please follow the Remus Rusanu's excellent posts on this topic. http://rusanu.com/2008/10/25/replacing-endpoint-certificates-that-are-near-expiration/ http://rusanu.com/2008/11/26/replacing-service-certificates-that-are-near-expiration/ http://rusanu.com/2008/10/23/how-does-certificate-based-authentication-work/
{ "pile_set_name": "StackExchange" }
Q: How to place a file on classpath in Eclipse? As this documentation says, "For example if you place this jndi.properties file on your classpath", but how can I place the .properties file on my classpath if I am using Eclipse? A: Just to add. If you right-click on an eclipse project and select Properties, select the Java Build Path link on the left. Then select the Source Tab. You'll see a list of all the java source folders. You can even add your own. By default the {project}/src folder is the classpath folder. A: One option is to place your properties file in the src/ directory of your project. This will copy it to the "classes" (along with your .class files) at build time. I often do this for web projects. A: This might not be the most useful answer, more of an addendum, but the above answer (from greenkode) confused me for all of 10 seconds. "Add Folder" only lets you see folders that are the sub-folders of the project whose build path you are looking at. The "Link Source" button in the above image would be called "Add External Folder" in an ideal world. I had to make a properties file that is to be shared between multiple projects, and by keeping the properties file in an external folder, I am able to have only one, instead of having a copy in each project.
{ "pile_set_name": "StackExchange" }
Q: Intuitive explanation of moments as they relate to center of mass I would appreciate it if someone could give me an intuitive explanation of moments. I understand that that the center of mass could be thought of as the point which an object would balance on a fulcrum. But how do moments relate to this idea? My calculus book connects the ideas with equations and formulas, but I can't seem to get an intuition of what is actually happening. If someone could offer up a useful way of thinking of moments it would be most helpful. Thanks. A: A moment is the twist as a result of a force at a distance. Go try to loosed the lug nuts of a tire and you will notice that the further away you can push on the wrench, the less effort is needed for the same amount of twisting force. A simpler example is to try to open a (unlocked & unlatched) door by pushing on it a various distances from the hinge. Try it, and let us know if that gave you a more intuitive feel for moments.
{ "pile_set_name": "StackExchange" }
Q: git add all except ignoring files in .gitignore file I am adding source control to a project that had none. The problem is that there are a lot of files to initially add to git with a .gitignore file, but I can't figure out how to add all files without including the files matching something in the .gitignore file. git add * The above command will not add any files because it detects files which are ignored by the .gitignore. git add -f * The above command will add all files including the files I wish to ignore. So, how do I add all files while still adhering to the .gitignore file? A: I think you mean git add . which will add all of the files to the repo that AREN'T specified in the .gitignore - you can see these changes by typing git status The . in bash usually means this directory and all other directories recursively, so if you do this from the bottom level of your repo, you should add all of the files. My usual git flow is to create the .gitignore file and add the project files to the repo. I'll test the .gitignore file by typing git status after importing the files - if I see the files that I've added (for example only .php or .html, NOT .mp3 or .mov), then you can git add . to add all, and git commit -m "initial commit" to commit them and you should be set. A: git add . This will add all paths and ignore matches from .gitignore A: Try git add . (which means "add all files in the current directory and below")
{ "pile_set_name": "StackExchange" }
Q: Where to find extensions installed folder for Google Chrome on Mac? I can not find them under ~/Library/Application Support/Google/Chrome/; Where are they? Mac Pro 10.8.4 Chrome Version 26.0.1410.65 A: The default locations of Chrome's profile directory are defined at http://www.chromium.org/user-experience/user-data-directory. For Chrome on Mac, it's ~/Library/Application\ Support/Google/Chrome/Default The actual location can be different, by setting the --user-data-dir=path/to/directory flag. If only one user is registered in Chrome, look in the Default/Extensions subdirectory. Otherwise, look in the <profile user name>/Extensions directory. If that didn't help, you can always do a custom search. Go to chrome://extensions/, and find out the ID of an extension (32 lowercase letters) (if not done already, activate "Developer mode" first). Open the terminal, cd to the directory which is most likely a parent of your Chrome profile (if unsure, try ~ then /). Run find . -type d -iname "<EXTENSION ID HERE>", for example: find . -type d -iname jifpbeccnghkjeaalbbjmodiffmgedin Result: A: You can find all Chrome extensions in below location. /Users/{mac_user}/Library/Application Support/Google/Chrome/Default/Extensions A: For Mac EI caption/Mac Sierra, Chrome extension folders were located at /Users/$USER/Library/Application\ Support/Google/Chrome/Profile*/Extensions/
{ "pile_set_name": "StackExchange" }
Q: Simple JavaScript empty string check, what does (an empty string) mean and why is it failing? Here's my code: $("#ddlCiudad").change(function () { var idCity = $("#ddlCiudad").val(); $.getJSON("/ProductCheckout/GetPriceForLocation", { cityId: idCity, productId: idProduct, type: "land" }, function (cityData) { console.log("Recieved json data."); landCost = cityData.LandCost; $("#billingshippingcost").text(landCost); console.log("Assigned value of LandCost"); airCost = cityData.AirCost; console.log("Assigned value of AirCost"); console.log(landCost); //Logs: 25,00 console.log(airCost); //Logs: "(an empty string)" if (landCost == "") { $(".land").removeClass("land").addClass("land-disabled"); } else { $(".land-disabled").removeClass("land-disabled").addClass("land"); } if (airCost = "") { $(".air").removeClass("air").addClass("air-disabled"); } else { $(".air-disabled").removeClass("air-disabled").addClass("air"); } } ); }); That if statement is not being fired, any suggestions on why it's not firing? Maybe an empty string isn't the same as "" in Javascript. A: Try: if (!airCost) { $(".air").removeClass("air").addClass("air-disabled"); } else { $(".air-disabled").removeClass("air-disabled").addClass("air"); }
{ "pile_set_name": "StackExchange" }
Q: Unable to import my own class into another class I am coding in blueJ. My objectives are this: 1)Write a User class A User: has a username e.g 'fj3' has a userType which can be: 'user', 'editor' or 'admin' has a name e.g 'Francis' has a constructor which takes the username, userType and name as parameters has a getUsername() method has a getUserType() method has a getName() method has a setUserType() method which takes one of the user types as a parameter 2)Write a UserGroup class -The UserGroup class must have an ArrayList of Users. Write a constructor for the UserGroup class. It should instantiate the ArrayList. In UserGroup write a method called .addSampleData() which creates 10 Users and using the ArrayList's add() method put the 10 new User objects into the ArrayList. In UserGroup write a getUser method which takes an int as a parameter and returns the User in that slot of the ArrayList. In UserGroup write a printUsernames() method in UserGroup: Using an enhanced for loop (see above), loop through the ArrayList and print the username and userType of each user in the ArrayList. What I have so far is: package user; public class User{ public enum UserType{ ADMIN, EDITOR, USER; } private String id; private UserType userPermissions; private String actualName; public User(String username, UserType userType, String name){ id = username; userPermissions = userType; actualName= name; } public String getUsername(){ return id; } public UserType getUserType(){ return userPermissions; } public String getName(){ return actualName; } public void setUserType(UserType input){ userPermissions = input; } } And my UserGroup class: package user; import java.util.*; import user.User.UserType; public class UserGroup{ private ArrayList<User> people; public UserGroup(){ people = new Arraylist<User>(); } public static void addSampleData(String username, UserType userType, String name){ People.add(new User(username, userType,name)); } public String getUser(int list){ return User; } public void printUsernames(){ for (User user: groupArray){ System.out.printf("%s %s\n", user.getUsername(), user.getuserType); } } } This is obviously far from being complete but I am completely stuck. My first problem is that "for (User user : groupArray)" is giving me the error illegal start of type. Please help me with this!! I think my User class is fine but my UserGroup class is nowhere enar completing all the objectives and I don't know how to do them!! A: The specification requires a UserGroup's list of users to be instantiated within the constructor. Thus, it should be not be static but an instance variable: public class UserGroup { private ArrayList<User> people; public UserGroup() { people = new ArrayList<User>(); } // ... } This way, you can create multiple UserGroup instances, each having their own list of users. With a static variable, this would not be possible. Your getUser(int) method does not do what it is supposed to do and will not compile. You are returning the type User there instead of a specific User instance. The enhanced for loop you use for printing user names is a free floating block of code. It should be inside the method printUsernames() as prescribed by your specification. Your User class will work fine, but its instance variables should be private instead of public. To resolve your import issues, put your User class into a package, e.g. user, and have UserGroup import User.UserType (the "User." part is needed since UserType is an inner class within User) from this package. package user; public class User{ // ... } package user; import java.util.*; import user.User.UserType; public class UserGroup{ // ... }
{ "pile_set_name": "StackExchange" }
Q: Getting html content for buttons using an event handler wrapper I'm using a wrapper to attach event handlers to some buttons on a page. Using the following code I can get the button ID when I clicl each of the buttons. However, I need to get the content of the pre tags and concatenate the content of the two divs to create a command when each of the buttons are clicked. Could somebody please help. const wrapper = document.getElementById('wrapper'); wrapper.addEventListener('click', (event) => { var parent=event.target.parentElement; console.log(parent.getElementsByTagName('pre')[0].innerHTML); const isButton = event.target.nodeName === 'BUTTON'; if (!isButton) { return; } }) <div id="wrapper"> <div class="command"> <p>description 1</p> <div> <pre><div>kubectl&nbsp;</div><div>create cluster</div></pre> </div> <button id="button1" class="demo-button-small">Run</button> </div> <div class="command"> <p>description 2</p> <div> <pre><div>kubectl&nbsp;</div><div>delete cluster</div></pre> </div> <button id="button2" class="demo-button-small">Run</button> </div> <div class="command"> <p>description 3</p> <div> <pre><div>kubectl&nbsp;</div><div>list cluster</div></pre> </div> <button id="button3" class="demo-button-small">Run</button> </div> </div> A: Use .closest() to find the containg DIV, then use .querySelector() to find the <pre> tag inside that and get its innerText. const wrapper = document.getElementById('wrapper'); wrapper.addEventListener('click', (event) => { const isButton = event.target.nodeName === 'BUTTON'; if (!isButton) { return; } const div = event.target.closest("div.command"); if (div) { const pre = div.querySelector("pre"); if (pre) { console.log(pre.innerText); } } }) <div id="wrapper"> <div class="command"> <p>description 1</p> <div> <pre><div>kubectl&nbsp;</div><div>create cluster</div></pre> </div> <button id="button1" class="demo-button-small">Run</button> </div> <div class="command"> <p>description 2</p> <div> <pre><div>kubectl&nbsp;</div><div>delete cluster</div></pre> </div> <button id="button2" class="demo-button-small">Run</button> </div> <div class="command"> <p>description 3</p> <div> <pre><div>kubectl&nbsp;</div><div>list cluster</div></pre> </div> <button id="button3" class="demo-button-small">Run</button> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Release disk space used by cgi.FieldStorage temp files I am writing a pyramid application that accepts many large file uploads (as a POST). Similar to How can I serve temporary files from Python Pyramid, I'm having a problem where the the temp files created by cgi.FieldStorage are orphaned, consuming GB's of disk space. lsof indicates that my wsgi process has deleted files from /tmp but the files haven't been closed. Restarting the application clears the orphans. How can I cause these files to be closed so that the disk space is returned to the OS? A: This problem I encountered was unrelated to cgi.FieldStorage, pyramid actually uses WebOb for serializing data. The cause of the high disk space usage was pyramid_debugtoolbar. The debugger states in it's documentation that it maintains the data from the previous 100 requests, which took up a great amount of memory and disk space in my case. Removing the include for the debugger from __init__.py and restarting the server resolved the problem.
{ "pile_set_name": "StackExchange" }
Q: Python Maria DB Syntax Does anyone know where I am going wrong here? The syntax for the DB update looks correct to me. Also I am wondering if I need to close connection say to open and close a connection within each function. Lets say for example that each function performs a different type of DB command, one for insert, one for update and one for delete, just as a generic example. Output: [root@localhost student_program]# python modify_student.py Connection successful!! Enter the id of the student record you wish to modify: 21 Is this student personal information you want to modify - y or n: y Enter the first name: Jake Enter the last name: Mc Intyre Enter the email address: [email protected] Enter the address: 300 Main Street, New York Enter the DOB in YYYY-MM-DD: 1960-01-01 Traceback (most recent call last): File "modify_student.py", line 38, in <module> modify_student() File "modify_student.py", line 29, in modify_student cur.execute(sql, [firstname, lastname, email, address, DOB, student_id]) File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query conn.query(q) File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 893, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1103, in _read_query_result result.read() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1396, in read first_packet = self.connection._read_packet() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1059, in _read_packet packet.check_error() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 384, in check_error err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.6/site-packages/pymysql/err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(firstname, lastname, email, address, DOB)VALUES ('Jake','Mc Intyre','jake@noema' at line 1") My code: import os,pymysql db_root = '/var/lib/mysql/' db_to_create = 'students' db_to_use = 'students' conn = pymysql.connect(host='localhost', user='root', passwd='dbadmin', cursorclass=pymysql.cursors.DictCursor) print('Connection successful!!') def modify_student(): student_id = input("Enter the id of the student record you wish to modify: ") student_info = input("Is this student personal information you want to modify - y or n: ") if student_info == 'y': firstname = input("Enter the first name: ") lastname = input("Enter the last name: ") email = input("Enter the email address: ") address = input("Enter the address: ") DOB = input("Enter the DOB in YYYY-MM-DD: ") cur = conn.cursor() command = "use %s; " %db_to_use cur.execute(command) sql = 'UPDATE students_info SET (firstname, lastname, email, address, DOB)VALUES (%s,%s,%s,%s,%s) WHERE ID = (%s);' cur.execute(sql, [firstname, lastname, email, address, DOB, student_id]) print(cur.execute) conn.commit() cur.close() conn.close() else: print("else") modify_student() A: The syntax for update is: UPDATE tablename SET name='%s', email='%s' WHERE id='%s' You are trying to UPDATE like an INSERT. But UPDATE only supports setting each column name independently, Not with a column list. Try: sql = "UPDATE students_info SET firstname='%s', lastname='%s', email='%s', address='%s', DOB='%s' WHERE ID='%s'" cur.execute(sql, [firstname, lastname, email, address, DOB, student_id]) See https://mariadb.com/kb/en/library/update/
{ "pile_set_name": "StackExchange" }
Q: how to change UIPickview height I have seen so many posts but none of them gives answer for this question. How to change this? Can anyone please help with it? Thank you, Ankita A: You can't change the height of the pickerView as it is kept fixed by Apple. Hence it does not allow you to change its height. If you want more flexibility you may go for some custom created controls available on internet that would enable you to have more freedom over setting the size and all. NOTE: Please keep in mind that the more custom controls you use, the more are the chances of your app getting rejected by Apple. Hope this helps you.
{ "pile_set_name": "StackExchange" }
Q: Carriage return in String Tokenizer in Java If I only specify carriage return (\r) in the String Tokenizer like this: StringTokenizer st1 = new StringTokenizer(line,"\r"); where 'line' is the input string. When I provide the following text as input: Hello Bello Cello ie. with two carriage return. (I press 'Enter'after Hello and Bello.) But the output of this is 3 in System.out.println(st1.countTokens()); Is there an explanation? A: When you split a string using a separator, then, provided that your separator occurs n times, the number of elements after the split will be n+1. Look at this visual example, using comma as separator: text1,text2,text3,text4 It will yield 4 results Look at another example: text1,text2,text3, It will yield 4 results as well, the last being an empty string.
{ "pile_set_name": "StackExchange" }
Q: What is the data structure of this variable in perl? I am new to perl and reading a code written in perl. A line reads like this: $Map{$a}->{$b} = $c{$d}; I am familiar with hash looking like %samplehash and accessed as $samplehash{a}="b" but what does the above line say about what is Map actually? A: Given these variables: my $a = "apples"; my $b = "pears"; my %c = ("bananas" => 2); my $d = "bananas"; my %Map; The assignment $Map{$a}->{$b} = $c{$d}; Results in a hash looking like this: %Map = ( "apples" => { "pears" => 2 } ); %Map is a hash, which after the assignment contains a hash ref through autovivification: If not already there, the inner hash ref is automatically created by Perl by accessing the element $Map{$a}->{$b} in the %Map hash. A: $Map{$a}->{$b} is equivalent to ${ $Map{$a} }{$b} which is like $hash{$b} only using the hash reference $Map{$a} instead of %hash. See http://perlmonks.org/?node=References+quick+reference for some easy to remember rules about how to use nested data structures. Additionally, with autovivification on (which it is by default), if $Map{$a} starts as not existing or undef, it will be implicitly initialized to be a new hash reference.
{ "pile_set_name": "StackExchange" }
Q: MySQL error "Query execution was interrupted" after query_posts I use query_posts in long search query. My query: <?php $args = array( 'tag_slug__in' => $cat_id, 'posts_per_page' => 15, 'paged' => $page, 'meta_query' => array( array( 'key' => 'Пол', 'value' => $value_sex, 'compare' => 'EXISTS', 'type' => 'CHAR', ), array( 'key' => 'Английский', 'value' => $english, 'compare' => 'EXISTS', 'type' => 'CHAR', ), array( 'key' => 'Французский', 'value' => $france, 'compare' => 'EXISTS', 'type' => 'CHAR', ), array( 'key' => 'Немецкий', 'value' => $germany, 'compare' => 'EXISTS', 'type' => 'CHAR', ), array( 'key' => 'Итальянский', 'value' => $italy, 'compare' => 'EXISTS', 'type' => 'CHAR', ), array( 'key' => 'Испанский', 'value' => $spain, 'compare' => 'EXISTS', 'type' => 'CHAR', ), array( 'key' => 'Китайский', 'value' => $chine, 'compare' => 'EXISTS', 'type' => 'CHAR', ), array( 'key' => 'Длина волос', 'value' => $hair_length, 'compare' => 'EXISTS', 'type' => 'CHAR', ), array( 'key' => 'Цвет волос', 'value' => $hair_color, 'compare' => 'EXISTS', 'type' => 'CHAR', ), array( 'key' => 'Удобные дни работы', 'value' => $value_days, 'compare' => 'EXISTS', 'type' => 'CHAR', ), array( 'key' => 'Удобное время работы', 'value' => $value_time, 'compare' => 'IN', 'type' => 'CHAR', ), array( 'key' => 'Рост (см)', 'value' => array( $value_height, $value_height_max ), 'type' => 'numeric', 'compare' => 'BETWEEN', ), array( 'key' => 'Размер одежды', 'value' => array( $value_dress, $value_dress_max ), 'type' => 'numeric', 'compare' => 'BETWEEN', ), array( 'key' => 'Размер бюста', 'value' => array( $value_bust, $value_bust_max ), 'type' => 'numeric', 'compare' => 'BETWEEN', ), ) ); ?> <?php query_posts($args); ?> This code is good work in new installed wordpress, but the old site is crashes. I have "Query execution was interrupted", "Lost connection to MySQL server during query" and "MySQL server has gone away" errors in error.log Key and value in meta_query in Russian. I'm sorry for my English. Please help. link to error.log A: It might be a timeout problem, in which case you should tinker with your my.cnf, or maybe your mysql just becomes unresponsive due to excessive load, in which case raising the timeout limit won't help you. There isn't much room to optimize wordpress default functions, but you could write your own query using $wpdb->query() method, and maybe give a look at current db indexes for the post's metadata.
{ "pile_set_name": "StackExchange" }
Q: Typescript 2.1.5 Function calls are not supported I have the following ngrx reducer function export const raceReducer: ActionReducer<IRace> = ( state: IRace = new Race(), action?: Action ) => { switch ( action.type ) { case RaceActions.ADD_OLP: return ngrxStateUpdater( state, action ) default: return state; } }; Running the application gives the following error: ERROR in Error encountered resolving symbol values statically. Function calls are not s upported. Consider replacing the function or lambda with a reference to an exported fun ction (position 40:50 in the original .ts file), resolving symbol raceReducer in J:/wor kspace/angular2/ts/epimss/src/app/registration/race/race.ngrx-store.ts, resolving symbo l AppModule in J:/workspace/angular2/ts/epimss/src/app/app.module.ts, resolving symbol AppModule in J:/workspace/angular2/ts/epimss/src/app/app.module.ts, resolving symbol Ap pModule in J:/workspace/angular2/ts/epimss/src/app/app.module.ts The function referred to is the ( state: IRace = new Race(), action?: Action ) Why is this and what is the solution. I thinks this should be legitimate typescript2.1.5 code, but it does not seem that way. Thanks A: AoT needs to statically analyze some code and can't analyze function invocations. For more details about the limitations of AoT see https://github.com/qdouble/angular-webpack2-starter#aot--donts For a discussion see this issue https://github.com/angular/angular/issues/11262
{ "pile_set_name": "StackExchange" }
Q: How to use arrayUnion with AngularFirestore? I have a basic database that essentially stores an array of product id's underneath a user. The user can select products to add to the array so it makes sense to use 'arrayUnion' so I avoid reading and re-writing the array constantly, however, I keep getting the error *"Property 'firestore' does not exist on type 'FirebaseNamespace'." I've followed the documentation found at: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array but I fear I'm still using it incorrectly. My code for updating the array is: addToPad(notepadName: string){ const updateRef = this.db.collection('users').doc(this.activeUserID).collection('notepads').doc(notepadName); updateRef.update({ products: firebase.firestore.FieldValue.arrayUnion(this.productId) }); } A: First you need to import firestore: import { firestore } from 'firebase/app'; Then you will be able to use arrayUnion: addToPad(notepadName: string){ const updateRef = this.db.collection('users').doc(this.activeUserID).collection('notepads').doc(notepadName); updateRef.update({ products: firestore.FieldValue.arrayUnion(this.productId) }); }
{ "pile_set_name": "StackExchange" }
Q: Jackson Json Escaping I created json using Jackson. It is working fine. But while parsing json using jackson i had issues in Escaping trademark symbol. can any one please suggest me how to do escape in json jackson provided library. Thanks in advance. A: Well, basically you don't have to do that. I have written a small test case to show you what I mean: public class JsonTest { public static class Pojo { private final String value; @JsonCreator public Pojo(@JsonProperty("value") final String value) { this.value = value; } public String getValue() { return value; } } @Test public void testRoundtrip() throws IOException { final ObjectMapper objectMapper = new ObjectMapper(); final String value = "foo ™ bar"; final String serialized = objectMapper.writeValueAsString(new Pojo(value)); final Pojo deserialized = objectMapper.readValue(serialized, Pojo.class); Assert.assertEquals(value, deserialized.getValue()); } } The above illustrates that the trademark symbol can be serialized and deserialized without escaping. With that being said, to solve your problem make sure that you are reading the input using the correct encoding. The encoding can e.g. be set when opening the URL or opening the file BufferedReader urlReader = new BufferedReader( new InputStreamReader( url.openStream(), "UTF-8")); BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(file), "UTF-8")); Also, if you wish to escape characters you do that by using the \ character. From the docs on json.org: A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
{ "pile_set_name": "StackExchange" }
Q: Allow dots in filenames while searching for extension using pathinfo I want to use pathinfo() to extract the extension from filenames. As it prints now: array(4) { ["dirname"]=> string(33) "E:/folder/some-folder-with.dots" ["basename"]=> string(13) "some-folder-with.dots" ["extension"]=> string(10) ".dots" ["filename"]=> string(2) "some-folder-with" } The code I use now: function rglob($pattern, $flags = 0) { $files = glob($pattern, $flags); foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) { $files = array_merge($files, rglob($dir.'/'.basename($pattern), $flags)); } return $files; } $dir = 'E:/folder/*/*.*'; $files = rglob($dir); # LOOP foreach($files AS $file) { # KONTROLL if($file != '.' AND $file != '..') { # VARIABEL $testing = pathinfo($file); $fname = glob($dir.'/*/*.'.$testing['extension']); echo '<pre>'; var_dump($testing); echo '</pre>'; } } The function of this code, is that I want to get every file that are in one folder and then get the extension of every file it finds in order to find the right extension for my website. As it is right now, I can't have dots in my filenames which I want to have. How can I accomplish this? A: You want DirectoryIterator class from SPL. http://php.net/manual/en/class.directoryiterator.php This is just a sample you can do with it, but you can customize a lot what you get out from it: array ( 0 => '/var/www/html/UusProjekt/intl/homepage_template.php', 1 => '/var/www/html/UusProjekt/intl/config.php', 2 => '/var/www/html/UusProjekt/intl/english.php', 3 => '/var/www/html/UusProjekt/intl/spanish.php', 4 => '/var/www/html/UusProjekt/intl/index.php', )
{ "pile_set_name": "StackExchange" }
Q: "INSTALL_PARSE_FAILED_MANIFEST_MALFORMED" Error when running project in Android Studio I realize this may come as a duplicate question, I have found multiple questions looking for the same error but am still unable to solve the issue. I am working on an Android application and for now only have one activity (a login screen) and when I attempt to run the application an error message appears: pkg: /data/local/tmp/MyName.myapp Failure [INSTALL_PARSE_FAILED_MANIFEST_MALFORMED] As I said, I am dumbfounded. Has anyone experienced this, or notice something out of the ordinary in my manifest file? <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="AdamMc.myapp" > <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".LoginActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> A: Aha, I continued to dig and dig and finally found it. Thanks to this question here I realized it is because the package name cannot have capital letters. I changed my package name to simply 'myappname' instead of 'MyName.myappname' that android studio set it automatically, and was able to build and run. Thank you to anyone who took the time to look into this.
{ "pile_set_name": "StackExchange" }
Q: How to add new element to structure array in Matlab? How to add new element to structure array? I am unable to concatenate with empty structure: >> a=struct; >> a.f1='hi' a = f1: 'hi' >> a.f2='bye' a = f1: 'hi' f2: 'bye' >> a=cat(1,a,struct) Error using cat Number of fields in structure arrays being concatenated do not match. Concatenation of structure arrays requires that these arrays have the same set of fields. So is it possible to add new element with empty fields? UPDATE I found that I can add new element if I simultaneously add new field: >> a=struct() a = struct with no fields. >> a.f1='hi'; >> a.f2='bye'; >> a(end+1).iamexist=true a = 1x2 struct array with fields: f1 f2 iamexist It is incredible that there is no straight way! May be there is some colon equivalent for structures? A: If you're lazy to type out the fields again or if there are too many then here is a short cut to get a struct of empty fields a.f1='hi' a.f2='bye' %assuming there is not yet a variable called EmptyStruct EmptyStruct(2) = a; EmptyStruct = EmptyStruct(1); now EmptyStruct is the empty struct you desire. So to add new ones a(2) = EmptyStruct; %or cat(1, a, EmptyStruct) or [a, EmptyStruct] etc... a(2) ans = f1: [] f2: [] A: You can only concatenate structures with identical fields. Let's denote your second struct by b. As you have already checked, the following won't work, because struct a has two fields and b has none: a = struct('f1', 'hi', 'f2', 'bye'); b = struct; [a; b] However, this works: a = struct('f1', 'hi', 'f2', 'bye'); b = struct('f1', [], 'f2', []); [a; b] If you want to "automatically" create an empty structure with the same fields as a (without having to type all of them), you can either use Dan's trick or do this: a = struct('f1', 'hi', 'f2', 'bye'); C = reshape(fieldnames(a), 1, []); %// Field names C(2, :) = {[]}; %// Empty values b = struct(C{:}); [a; b] I also recommend reading the following: Stack Overflow - What are some efficient ways to combine two structures Stack Overflow - Update struct via another struct Loren on the Art of MATLAB - Concatenating structs
{ "pile_set_name": "StackExchange" }
Q: Iterate id from the controller rails How can I iterate in the controller, I want to replace the view and create object an for @reserve = Reserve.where(:user_id=>user.id), how can I get each user.id from @user_list = User.where.not(id: 1) and output the view as <% @reserve.each do |a| %> <td><%= a.date %></td> <td><%= a.time %></td> <% end %> Model class Reserve < ApplicationRecord belongs_to :user, optional: true end View <% @user_list.each do |user| %> <td><%= user.name %></td> <% Reserve.where(:user_id=>user.id).each do |a| %> <td><%= a.date %></td> <td><%= a.time %></td> <% end %> Controller @user_list = User.where.not(id: 1) The reason why I want to do it this way is because I am using a gem for sorting and I want to place the sort on their respective model instead of using User for both reserve and user which would cause an error. when /^created_at_/ order("user.created_at #{ direction }") A: If I understand your question (which I'm not sure I do), in your controller, do something like: @user_list.each do |user| @user = user @reserve = Reserve.where(user: user) # <= do some sorting around here render partial: 'user_list' end Now, you'll have @user and @reserve available in a partial, something like: # _user_list.html.erb <td><%= @user.name %></td> <% @reserve.each do |a| %> <td><%= a.date %></td> <td><%= a.time %></td> <% end %>
{ "pile_set_name": "StackExchange" }
Q: xsl is generating output even when no element is matching An xsl to convert an xml file is generating output even when no input elements are satisfying the condtiton. the xsl file is as below <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="UTF-8"/> <xsl:template match="Root/Order"> <xsl:choose> <xsl:when test="Order1/task or Order2/task or task"> <xsl:value-of select="ID"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/custId"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/System"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/Number"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Number"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Status"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Indi"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Code"/><xsl:text>|</xsl:text> <xsl:value-of select="tasks/lno"/><xsl:text>|</xsl:text> <xsl:value-of select="tasks/val"/><xsl:text>&#xa;</xsl:text> </xsl:when> <xsl:otherwise></xsl:otherwise> </xsl:choose> <xsl:for-each select="task"> <xsl:value-of select="ID"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/custId"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/System"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/Number"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Number"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Status"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Indi"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Code"/><xsl:text>|</xsl:text> <xsl:value-of select="tasks/lno"/><xsl:text>|</xsl:text> <xsl:value-of select="tasks/val"/><xsl:text>&#xa;</xsl:text> </xsl:for-each> <xsl:for-each select="Order1"> <xsl:for-each select="task"> <xsl:value-of select="ID"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/custId"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/System"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/Number"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Number"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Status"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Indi"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Code"/><xsl:text>|</xsl:text> <xsl:value-of select="tasks/lno"/><xsl:text>|</xsl:text> <xsl:value-of select="tasks/val"/><xsl:text>&#xa;</xsl:text> </xsl:for-each> </xsl:for-each> <xsl:for-each select="Order2"> <xsl:for-each select="task"> <xsl:value-of select="ID"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/custId"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/System"/><xsl:text>|</xsl:text> <xsl:value-of select="cust/Number"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Number"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Status"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Indi"/><xsl:text>|</xsl:text> <xsl:value-of select="make/Code"/><xsl:text>|</xsl:text> <xsl:value-of select="tasks/lno"/><xsl:text>|</xsl:text> <xsl:value-of select="tasks/val"/><xsl:text>&#xa;</xsl:text> </xsl:for-each> </xsl:for-each> </xsl:template> </xsl:stylesheet> Input xml file is as below. <cust> <Date>2018-04-16</Date> <name>abc</name> <code>xyz10</code> <custId>abc123</custId> <System>main</System> <Number>TANK</Number> </cust> My understanding is as the cust is not matching the defined template match or when condition, there should no be an output. But when I do the conversion output is as below. 2018-04-16 abc xyz10 abc123 main TANK I believe as there are no defined template rules for the input, built in template rules are called during processing and they are generating output. I am not certain whether that is the correct reason or not. request you for an answer. thanks in advance. A: Add this template: <xsl:template match="/"> <xsl:apply-templates select="Root"/> </xsl:template> When this is run against your input XML file above, you will get no output.
{ "pile_set_name": "StackExchange" }
Q: Create Carriage Return in PHP String? We have written a small PHP Hook for our billing system that opens a new support ticket with us when an order is placed. It works except that for the "Open Ticket" API function, it takes a string for the message, but we cannot figure out how to put carriage returns in it. I have tried <p>, <br>, \n, \r\n, etc. As it appears to just be completely plain text though, all of these are just being read verbatim rather than made into carriage returns. Does anyone have any thoughts on how this could be done? http://docs.whmcs.com/API:Open_Ticket A: Carriage return is "\r". Mind the double quotes! I think you want "\r\n" btw to put a line break in your text so it will be rendered correctly in different operating systems. Mac: \r Linux/Unix: \n Windows: \r\n A: There is also the PHP 5.0.2 PHP_EOL constant that is cross-platform ! Stackoverflow reference A: PHP_EOL returns a string corresponding to the line break on the platform(LF, \n ou #10 sur Unix, CRLF, \n\r ou #13#10 sur Windows). echo "Hello World".PHP_EOL;
{ "pile_set_name": "StackExchange" }
Q: jQuery works in jsFiddle but not on my computer I'm new to jQuery and have been scratching my head all day trying to determine why this script runs in jsFiddle but not on my computer. I do not have a server setup, I am merely launching the html in my browser from the desktop. The code works fine here: http://jsfiddle.net/9Dubr/164/. However when I create the following html file: <html> <head> <title>this better work</title> <script src="jquery-latest.js"></script> <script type="text/javascript"> $('#submit').click(function(){ $('#myfrom').fadeOut("slow", function(){ var dot = $("<div id='foo'>Goodmorning Mr. Patti<br/><br/>Thank you.</div>".hide(); $(this).replaceWith(dot); $('#foo').fadeIn("slow"); }); }); </script> <style type="text/css"> #container{ width:342px; height:170px; padding:10px; background-color:grey; } #myform{ width:322px; height:100px; color:#6F6F6F; padding: 0px; outline:none; background-color:white; } #foo{ width:322px; height:100px; color:#6F6F6F; padding: 0px; outline:none; background-color:white; } #submit{ color:#6F6F6F; padding: 10px 2px 0px 0px; margin: 0px 0px 0px 0px; outline:none; } </style> </head> <body> <div id="container"> <div id="myform"> <p> blah blah blah blah blah </p> <input id="submit" value="send" type="submit"/> </div> </div> </body> </html> I get no results when I click the submit button. Please help, I've spent 6 hours on this. Thanks, A: You have to execute the code on DOM ready. Wrap your code in $(function(){ }); Also, you're missing a ). $(function () { $('#submit').click(function () { $('#myfrom').fadeOut("slow", function () { var dot = $("<div id='foo'>Goodmorning Mr. Patti<br/><br/>Thank you.</div>").hide(); $(this).replaceWith(dot); $('#foo').fadeIn("slow"); }); }); }); EDIT: <!DOCTYPE html> <html> <head> <title>This better work</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript"> $(function () { $('#submit').click(function () { $('#myfrom').fadeOut("slow", function () { var dot = $("<div id='foo'>Goodmorning Mr. Patti<br/><br/>Thank you.</div>").hide(); $(this).replaceWith(dot); $('#foo').fadeIn("slow"); }); }); }); </script> </head> <body> <div id="container"> <form id="myform"> <p> blah blah blah blah blah </p> <input id="submit" value="send" type="submit"/> </form> </div> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Microsoft Graph API - cannot access individual message (exception) We have some code which has been running successfully for months now, and all of a sudden yesterday, it is failing. Basically, we have a process which logs into mailboxes via the Graph API C# SDK (v1.12.0), gets the unread messages, iterates through each one, does some processing, and then tries to mark each message as "read". Here is the relevant code: var graphserviceClient = new GraphServiceClient(_metaData.GraphBaseURL, new DelegateAuthenticationProvider( (requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); requestMessage.Headers.Add("Prefer", "outlook.body-content-type='text'"); return Task.FromResult(0); })); var unreadMails = graphserviceClient .Users[_metaData.MailBox] .MailFolders .Inbox .Messages .Request() .Filter("isRead eq false") .Top(1000) .Select("Body, Subject") .GetAsync() .Result; emailRetrievalCount = unreadMails.Count(); // Determine if any results were returned if (unreadMails.Count > 0) { // Create loop to process each item in the newResult object foreach (var unreadMail in unreadMails) { // Set the isRead flag of the message to true var readMail = graphserviceClient .Me .Messages[unreadMail.Id] //BREAKS HERE!!! .Request() .Select("IsRead") .UpdateAsync(new Message { IsRead = true }) .Result; } } Exception Message: Microsoft.Graph.ServiceException: Code: ErrorInternalServerError\r\nMessage: An internal server error occurred. The operation failed., Cannot open mailbox. We checked permissions on the mailbox or account, nothing has changed. Also, it doesn't seem to be a permissions issue since we can get a token, log in, and get the list of messages fine. It's just when we try to get a specific message to update the "Read" status, it fails. Also, we tried updating the SDK to the latest version v1.19.0, but the same issue occurs. A: I was able to confirm that there was a service behavior change that now prevents access to an email message from a different mailbox. This was not correct behavior and has been fixed. By changing your call to access .Users[_metaData.MailBox].Messages[unreadMail.Id] the problem should be resolved.
{ "pile_set_name": "StackExchange" }
Q: Can I obtain $z$ value of circumference center given two points? Given two points of a circumference in $\mathbb{R}^3$ space $P_1 = (x_1,y_1,z_1)$ and $P_2 = (x_2,y_2,z_2)$, and two coordinates of its center $x_c$, $y_c$, is it possible to obtain the missing $z_c$? A: Note that $$(x_1-x_c)^2+(y_1-y_c)^2+(z_1-z_c)^2=(x_2-x_c)^2+(y_2-y_c)^2+(z_2-z_c)^2.$$ Expand, simplify and find $z_c$, given that $z_1\not=z_2$, \begin{align}z_c&=\frac{(x_1-x_c)^2-(x_2-x_c)^2+(y_1-y_c)^2-(y_2-y_c)^2+z_1^2-z_2^2}{2(z_1-z_2)}\\ &=\frac{(x_1-x_2)(\frac{x_1+x_2}{2}-x_c)+(y_1-y_2)(\frac{y_1+y_2}{2}-y_c)+\frac{z_1+z_2}{2}}{z_1-z_2}. \end{align} When $z_1=z_2$ if $$(x_1-x_c)^2+(y_1-y_c)^2=(x_2-x_c)^2+(y_2-y_c)^2$$ then any $z_c$ is fine, otherwise the problem of finding $z_c$ has no solution.
{ "pile_set_name": "StackExchange" }
Q: How do i add a key value pair to an asociative array in javascript let finaloutput = {}; $.each( arr, function(index,key) { let outarray = []; // var id sourced from another function outarray.push(id,index,key); //??finaloutput[id].push(outarray); } In the above code i am trying to store an object similar to below. Each time the loop grabs the same id it appends the array in the finaloutput object eg id:index:key 1st loop where id = 7 index=param 1 key=val1 {"7":[{param1:val1}]} 2nd .. id = 7 index=param 2 key=val2 {"7":[{param1:val1,param2:val2}]} 3rd ... id = 8 index=param 1 key=val1 {"7":[{param1:val1,param2:val2}],"8":[{param1:val1}]} How do i achieve this A: I tried to generated similar output using sample data: `let indx = ["param1", "param2", "param3", "param4", "param5"] let key = ["k1", "k2", "k3", "k4", "k5"] let id = ["1", "2", "3", "4", "5"] let resultObj = {} for (let i = 0; i < 5; i++) { if (resultObj[id]) { let temp=Object.assign({}, {[indx[i]]:key[i]}, ...resultObj[id[i]]) resultObj[id[i]] = [temp]; } else{ let ob=[{[indx[i]]:key[i]}] resultObj[id[i]]=ob } } console.log(resultObj)` In your case you can do something like : let finaloutput = {}; $.each(arr, function (index, key) { if (finaloutput[id]) { let temp = Object.assign({}, { [index]: key }, ...finaloutput[id]) finaloutput[id] = [temp]; } else { let temp2 = [{ [index]: key }] finaloutput[id] = temp2 } } Note Please refer to my example to get better understanding incase I was not able to exactly formulate answer of your code or it gives error
{ "pile_set_name": "StackExchange" }
Q: Difference between ARM Simulator and Verilog Simulator? Basically , I want to know What an ARM Simulator is ? IS it something like an Assembly language simulator ? If so what are the differences in comparison with Verilog Simulators? A: Your question is quite broad/vague. but here goes. An arm simulator, from the context of what you are asking, is likely an instruction set simulator. Software that just like a processor decodes the instructions, keeps track of the registers, and simulates the execution (if an instruction says add 1 to r1 then you have a variable in software that represents r1 and you add one to it). A verilog simulator, is not really any different just a different language. verilog is a hardware design language, before you can simulate it you need to compile it. Just like any other high level language it needs to be compiled down to something related to the target. simulators will have their own target logic blocks. The verilog is compiled down to these blocks then that logic is simulated, not unlike the arm simulator. For each clock cycle you update the inputs to each logic element based on the output of the connected block from the prior cycle, then evaluate each logic element and determine the outputs. repeat forever. for each verilog simulator you have a different target at its core, partly why you (can) get different results from each simulator for the same code. Likewise when you compile for the actual target, fpga, asic, etc, it is compiled differently than the simulator (or can be, depends on the environment, simulator, etc). There is no magic at all to any of these simulators, an instruction set simulator is generally easy to write, a worthwhile task for anyone wanting to get a good strong knowledge of an instruction set or how computers work (start with something small like lc-3, should take less than half an hour). A FAST simulator, that is another story, but a FUNCTIONAL simulator is fairly easy to write. Once compiled to a netlist of simple logic components a verilog simulator is probaby easy as well the biggest task though is the volume of signals and items to evaluate and parsing the code to get at the list of signals and logic functions and who is tied to what. Not as easy as an instruction set simulator, but quite understandable how it works and what the task would be...Verilator is pretty cool as it turns it into lines of C++ code, MANY lines, and a good sized project can take many hours to days to compile even on a screaming machine. (hint turn off waveforms to cut the compile time way down). But the task is understandable when you look at what is going on.
{ "pile_set_name": "StackExchange" }
Q: Was Leonard Nimoy a vegetarian? In the episode "All Our Yesterdays" of TOS, Spock reveals he is a vegetarian. The other day I was reading that Leonard was a vegetarian in real life. But I also read a 1967 magazine where he said his favorite food was steak. So was he really a vegetarian or did someone make a mistake? A: Probably not. As you mention yourself in your question, he was quoted once as saying his favourite food is steak. Despite the many vegetarian / vegan lifestyle web sites that claim he is a vegetarian, I see no hard evidence of this. Rather, there seems to be evidence to the contrary. Here he is enjoying BBQ with his cast mates during the filming of The Original Series: Also, here is an animated version of Nimoy (which he provided the voice for) in The Simpsons enjoying a hot dog: I suspect that, if he felt strongly about vegetarianism, he would have objected to this portrayal of himself as a meat eater. A: In the Star Trek Cookbook (published 1999), Leonard Nimoy provided a "favourite recipe" for fans, "Kasha Varnishkas a la Vulcan". It contains beef bouillon broth. He notes that it tastes especially delicious when combined with the cooked meat juices from a pot roast. This is my favorite dish. The recipe was handed down by my mother, who brought it from her village in the Ukraine, which is a small town in Western Vulcan. 1 cup kasha (whole-wheat or buckwheat groats) 1 egg or egg white only as a substitute 2 cups beef or vegetable bouillon broth or boiled water 1 16-ounce package bow-tie pasta 1/2 medium onion, finely chopped 1 tablespoon vegetable oil 1 pinch of salt or garlic salt Heat water or bouillon mixture to rolling boil, then keep on low heat at a slow boil. Saute onion in oil until just transparent and set aside. Separate egg white from yolk. Stir kasha and egg white into a medium-sized bowl then pour mixture into a heavy saucepan, stirring constantly until the particles separate. Add the bouillon broth or boiling water and salt to taste. Stir the mixture, cover tightly, and reduce heat to simmer for 10 minutes. Cook the bow ties in boiling water until soft, drain and set aside. After the liquid has all been absorbed, mix the kasha with the cooked pasta and sauteed onions and serve. This dish is particularly delicious when served with pot roast gravy. If you want to stay traditionally Vulcan vegetarian, you can make a brown mushroom gravy and use that instead. Serves four.
{ "pile_set_name": "StackExchange" }
Q: UIScrollView - Adding / Removing labels I am trying to add/remove UILabels to a ScrollView. The adding takes place just fine, but I can not seem to get the labels removed, before adding new ones. Can anyone shed some light on this situation? -(void)setMessage:(MessageData *)m{ //Attempting to remove any previous labels iPhone_PNPAppDelegate *mainDelegate = (iPhone_PNPAppDelegate *)[[UIApplication sharedApplication] delegate]; UILabel *l; for (NSInteger i=0; i<[[scrollView subviews] count]; i++){ l=[[scrollView subviews] objectAtIndex:0]; [l removeFromSuperview]; l=nil; } //Adding my new Labels CGPoint pt=CGPointMake(5,5); if ([[[mainDelegate messageFieldCaptions] objectAtIndex:0] length]>0){ NSArray *p=[[[mainDelegate messageFieldCaptions] objectAtIndex:0] componentsSeparatedByString:@"|"]; l= [self newLabelWithPrimaryColor:[mainDelegate navColor] selectedColor:[UIColor whiteColor] fontSize:12.0 bold:YES]; if (m.sValue0.length>0) l.text=[NSString stringWithFormat:@"%@ %@",[p objectAtIndex:0], m.sValue0]; else l.text=[NSString stringWithFormat:@"%@ None",[p objectAtIndex:0]]; [l setFrame:CGRectMake(pt.x,pt.y,310,20)]; [scrollView addSubview:l]; [l release]; pt.y+=20; } //This is done about 10 more times to add new labels. } A: The issue is in your for loop. As you remove labels, [[scrollView subviews] count] decreases, which means you won't get to all your labels since the loop runs less times than there are labels. Imagine you had 5 labels: (At time of comparison) i | [[scrollView subviews] count] ================================= 0 | 5 1 | 4 2 | 3 <-- loop ends here since i+1 >= [[scrollView subviews] count] 3 | 2 You should save the initial count to a variable and use that in your for loop condition. Since you are always removing index 0, you don't have to worry about going out of bounds of the array.
{ "pile_set_name": "StackExchange" }
Q: iphone sdk In-App Purchase Error I struck in implementing In-app Purchase in my application. I need to purchase products using in-app purchase in my application. For this i added my products app_id with my iTunes a/c. Here is my code reference, Code: ViewController.m NSMutableArray *featuredappidArray; - (void)viewDidLoad { [super viewDidLoad]; featuredappidArray=[[NSMutableArray alloc]init]; } -(void)parseRecentPosts:(NSString*)responseString { NSString *app_store_id = [NSString stringWithFormat:@"%@",[post objectForKey:@"app_store_id"]]; NSLog(@"Recent Post app_store_id: %@",app_store_id); [featuredappidArray addObject:app_store_id]; indexvalue=ndx; } - (void)buttonTapped:(UIButton *)sender { [detailview Receivedappidurl:featuredappidArray idx:indexvalue]; } DetailViewController.h -(void)Receivedappidurl:(NSMutableArray*)recentappidArray idx:(int)index; DetailViewController.m NSMutableArray *appidArray; -(void)Receivedappidurl:(NSMutableArray*)recentappidArray idx:(int)index { NSLog(@"recentappidArray:%@",recentappidArray); appidArray=recentappidArray; } Now my console window receives all app_id's from my web service. I added the necessary classes for In-App purchase like IAPHelper, InAppRageIAPHelper,MBProgressHUD,Reachability classes into my project. -(IBAction)purchaseButton { NSLog(@"appidarray:%@",appidArray); NSLog(@"pdt index:%d",productIndex); NSLog(@"APPLe indentifier:%@",[[appidArray objectAtIndex: productIndex] objectForKey: @"app_store_id"]); [InAppRageIAPHelper sharedHelper].productIndex = productIndex; [[InAppRageIAPHelper sharedHelper] buyProductIdentifier:[[appidArray objectAtIndex: productIndex] objectForKey: @"app_store_id"]]; self.hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES]; _hud.labelText = @"Buying Book..."; [self performSelector:@selector(timeout:) withObject:nil afterDelay:60*5]; } Here when am tapping the buy button my app getting crashed and getting the following error, " Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x9154ad0' " I referred many tutorials.How to purchase using this? Please help me out of this. Any help will be greatly appreciated. Thanks in advance. A: This is crashing your code [[appidArray objectAtIndex: productIndex] objectForKey: @"app_store_id"] This most likely is because [appidArray objectAtIndex: productIndex] returns a string, and not a dictionary. First step: you need to load the items from the store like this: [[SKPaymentQueue defaultQueue] addTransactionObserver:self]; SKProductsRequest *productsRequest = [[[SKProductsRequest alloc] initWithProductIdentifiers:yourProductIdentifiers autorelease]; productsRequest.delegate = self; [productsRequest start]; PS. you can find your product identifiers on the web, in the Manage InApp Purchases section after doing this, you will receive a list of products, and to purchase any of them: SKPayment *payment = [SKPayment paymentWithProduct:product]; [[SKPaymentQueue defaultQueue] addPayment:payment];
{ "pile_set_name": "StackExchange" }
Q: generic memoization approach in Javascript I understand that a number of generic memoized approaches rely on stringifying the argument list and using that as a key. E.g. as in: Function.prototype.memoized = function() { this._values = this.values || {}; var fn = this; return function() { var key = JSON.stringify( Array.prototype.slice.call(arguments) ); if (fn._values[key]===undefined) { fn._values[key]=fn.apply(this, arguments); } return fn._values[key]; }; }; This obviously fails when one tries to memoize a "member function" since one would have to also JSON-stringify the context as well, i.e. treat it as an implicitly passed parameter. But that wouldn't work very well when the context is the global object or something equally deep or subject to change in various ways not related with the function itself. But even if we stick to non-"member functions" it may not always be possible to complete strigify the passed arguments list, right? Three questions: do I understand correctly that memoizing member functions in a generic way is non-sensical? do I understand correctly that memoizing even non-member functions in a generic way is also impossible due to the inability / impracticability to fully stringify any conceivable argument list? if 2 holds, then why do so many books and blogs try to define a generic memoize function in Function.prototype ? What's the point? A: Methods are functions with this as a source of side effects. As you might know functions with side effects can't be memoized, since these effects don't depend on the method's argument list on which memoization relies on. But there is a workaround of course. Instead of serializing the whole object (referenced by this), we can manually specify those properties of which the method is dependent: function memoize(f, deps) { let cache = {}; return function(...args) { let key = JSON.stringify([deps(), args]), v; return cache[key] || (v = f.apply(this, args), cache[key] = v, v); }; } function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.fullName = memoize( function(title) { // memoized function console.log('memoizing...'); return title + ' ' + this.firstName + ' ' + this.lastName; }, function() { // dependencies return [this.firstName, this.lastName]; }.bind(this)); } let person = new Person('Jane', 'Doe'); // initial call console.log(person.fullName('Ms.')); // memoizing...Ms. Jane Doe // successive call console.log(person.fullName('Ms.')); // Ms. Jane Doe This is just a proof of concept, not a fully optimized and tested solution. All the credit goes to In Lehman's Terms To your questions: If a method is very expensive regarding its computation and thus justifies the effort, which entails the manual definition of its implicit dependencies (by this), then no, it may be useful Yes, sometimes it is impossible, but why give up an almost generic solution entirely? Dunno! Lemmings? :D
{ "pile_set_name": "StackExchange" }
Q: How to get current user latitude and longitude and calculate distance with location B? May I know how to get current user location and calculate distance between location B in kilometer? I tried below codes but seems like does not work. <?php echo "<script type = 'text/javascript'> function showPosition(){ if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position){ var latitude = position.coords.latitude; var longitude = position.coords.longitude; }); } else { alert(\"Sorry, your browser does not support HTML5 geolocation.\"); } } </script>"; $point1 = array("lat" => $latitude, "long" => $longitude); $point2 = array("lat" => $row_Merchant['latitude'], "long" => $row_Merchant['longitude']); $km = distanceCalculation($point1['lat'], $point1['long'], $point2['lat'], $point2['long']); // Calculate distance in kilometres (default) echo "$km km"; ?> <?php function distanceCalculation($point1_lat, $point1_long, $point2_lat, $point2_long, $unit = 'km', $decimals = 2) { // Calculate the distance in degrees $degrees = rad2deg(acos((sin(deg2rad($point1_lat)) * sin(deg2rad($point2_lat))) + (cos(deg2rad($point1_lat)) * cos(deg2rad($point2_lat)) * cos(deg2rad($point1_long - $point2_long))))); // Convert the distance in degrees to the chosen unit (kilometres, miles or nautical miles) switch ($unit) { case 'km': $distance = $degrees * 111.13384; // 1 degree = 111.13384 km, based on the average diameter of the Earth (12,735 km) break; case 'mi': $distance = $degrees * 69.05482; // 1 degree = 69.05482 miles, based on the average diameter of the Earth (7,913.1 miles) break; case 'nmi': $distance = $degrees * 59.97662; // 1 degree = 59.97662 nautic miles, based on the average diameter of the Earth (6,876.3 nautical miles) } return round($distance, $decimals); } ?> How can I pass in value latitude and longitude in $point1 = array("lat" => $latitude, "long" => $longitude); so that I can calculate distance between user location and lcoation B? Please help. Thank you. A: Eddy currently you're planning to assign javascript variable to PHP variable which is not the right way to do things as one in Client-side and other is Server-side. Reference. I have changed your code to find distance between user's location and merchant's location. <script type = 'text/javascript'> function distance(lat1, lon1, lat2, lon2, unit) { var radlat1 = Math.PI * lat1/180; var radlat2 = Math.PI * lat2/180; var radlon1 = Math.PI * lon1/180; var radlon2 = Math.PI * lon2/180; var theta = lon1-lon2; var radtheta = Math.PI * theta/180; var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); dist = Math.acos(dist); dist = dist * 180/Math.PI; dist = dist * 60 * 1.1515; if (unit=="K") { dist = dist * 1.609344; } if (unit=="N") { dist = dist * 0.8684; } return dist; } function showPosition(dest_lon, dest_lat){ if(navigator.geolocation) { console.log('hhhh'); navigator.geolocation.getCurrentPosition(function(position){ latitude = position.coords.latitude; longitude = position.coords.longitude; console.log(latitude+','+longitude+','+ dest_lat+','+ dest_lon); dist = distance(latitude, longitude, dest_lat, dest_lon, 'K'); console.log(dist); //final distance present in dist variable }); } else { alert("Sorry, your browser does not support HTML5 geolocation."); } } var merch_longitude = 47.683277; var merch_latitude = 3.210482; showPosition(merch_longitude, merch_longitude); </script> In above code you'll pass database value to merch_longitude and merch_latitude currently it is hard coded. We will get current location of user using geolocation of Javascript, then showPosition() will calculate distance. Distance function takes 5 parameter lat1, long1, lat2, long2, unit. By default unit is Miles, you can pass K for KM and N for NM.
{ "pile_set_name": "StackExchange" }
Q: Traversing through array in an IF-conditional in Javascript I am creating a very lightweight search functionality that takes the following: if (searchStr == people.first_name || searchStr == people.last_name || searchStr == people.job || searchStr == people.skills.forEach(function(x) { return x })) { Results.push(people) } searchStr is the search string; 'people' is a person object that has a single first and last name and a job, but only one of those thats an array is people.skills -- is there anyway I can traverse through that array in the if-conditional with an anonymous function? A: You can use Array.prototype.some to evaluate whether a condition is true on at least one entry in an array. This is better than Array.prototype.filter because it will exit early on the first entry to evaluate as true. if (searchStr == people.first_name || searchStr == people.last_name || searchStr == people.job || people.skills.some(function(x) { return searchStr == x })) { Results.push(people) } Array.prototype.some is new in Ecmascript 5 which is fairly well supported now. You could potentially improve on your search by doing a partial term search instead of an exact search by switching your equality comparisons with Array.prototype.indexOf to see if the string contains the search term. if (contains(people.first_name, searchStr) || contains(people.last_name, searchStr) || contains(people.job, searchStr) || people.skills.some(function(x) { return contains(x, searchStr); })) { Results.push(people) } function contains(a, b) { return a.indexOf(b) >= 0; } A: The Array.prototype.some method serves this purpose: if (searchStr == people.first_name || searchStr == people.last_name || searchStr == people.job || people.skills.some(function(skill) { return searchStr == skill; })) { Results.push(people) } But using an anonymous function is unnecessary in this case. We can use the Array.prototype.indexOf method: if (searchStr == people.first_name || searchStr == people.last_name || searchStr == people.job || people.skills.indexOf(searchStr) != -1) { Results.push(people) } or, more idiomatically: people.skills.indexOf(searchStr)+1 Be aware that the Array.prototype.every, some, forEach, filter, reduce and reduceRight methods are a part of ECMAScript 5 and are therefore not supported in older browsers supporting only ECMAScript <=3.1. You should use a polyfill, if this is an issue.
{ "pile_set_name": "StackExchange" }
Q: Oracle SQL - Add a column with data not included in any table I have this query: Select Trunc(Red.Fulfilled_Dtime), P.Email, (Red.Points_Deducted *.003)*(1/1.02) As Redeem_Amt, Red.Player_Id, Red.Prize_Id, Red.Points_Deducted From Redemption_Log Red Inner Join Player P On Red.Player_Id=P.Player_Id Where Red.Prize_Id In (8907,8906,8905,8904,8903,8902,8901) I want to add a column to my result called "Currency" in which every row in my results has the output "USD". Is this possible? A: You can add virtual column on your SELECT statement, SELECT Trunc(Red.Fulfilled_Dtime), P.Email, (Red.Points_Deducted *.003)*(1/1.02) As Redeem_Amt, Red.Player_Id, Red.Prize_Id, Red.Points_Deducted, 'USD' AS "Currency" -- <<== virtual column FROM Redemption_Log Red Inner Join Player P On Red.Player_Id=P.Player_Id WHERE Red.Prize_Id In (8907,8906,8905,8904,8903,8902,8901)
{ "pile_set_name": "StackExchange" }
Q: Fastest algorithm to output array containing all integers in range excluding duplicate digits Input is a single integer in ascending digit order. The only valid inputs are: 12 123 1234 12345 123456 1234567 12345678 123456789 The only valid output is an array (set; list) of length equal to the factorial of input: Input - Factorial of input - Output array length 12 -> 1*2 -> 2 123 -> 1*2*3 -> 6 1234 -> 1*2*3*4 -> 24 12345 -> 1*2*3*4*5 -> 120 123456 -> 1*2*3*4*5*6 -> 720 1234567 -> 1*2*3*4*5*6*7 -> 5040 12345678 -> 1*2*3*4*5*6*7*8 -> 40320 123456789 -> 1*2*3*4*5*6*7*8*9 -> 362880 The output array is all integers of input length in lexicographical order. For example, given input 123 -> factorial of input is 1*2*3=6 -> for each of the six array elements output the input integer and the five remaining integers of the array in lexicographic order -> [123,132,213,231,312,321]. Notice that the last element is always the input integer in reverse order. Test Cases Input Output `12` -> `[12,21]` // valid output, ascending numeric order `12` -> `[12.0,21.0]` // invalid output, output must be rounded to integer `123` -> `[123,132,213,231,312,321]` // valid output `123` -> `[123,132,213,222,231,312,321]` // invalid output: `222` are duplicate digits `123` -> `[123,142,213,231,213,321]` // invalid output: `142` outside range `1-3` `123456789` -> `[987654321,...,123456789]` // valid output, descending numeric order `123456789` -> `[987654321,...,123456798]` // invalid output, `123456798` is greater than the minimum required integer in resulting array `123456789` Rules Do not use standard library functions for permutations or combinatorics. If the algorithm produces an integer greater or less than input minimum or maximum only the integers in the specified range must be output. (Technically, if input is 12345 we could generate all integers to 21 or 12, though for input 12345 the only valid output must be within the range 12345 through 54321). Output must be an array (set; list) of integers, not strings. The integers output must not be hardcoded. The output integers must not include duplicate digits (more than one of the same digit at that array index). Winning criteria fastest-code Hardware, OS Where submissions will be run ~$ lscpu Architecture: i686 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 2 On-line CPU(s) list: 0,1 Thread(s) per core: 1 Core(s) per socket: 2 Socket(s): 1 Vendor ID: GenuineIntel CPU family: 6 Model: 37 Model name: Intel(R) Pentium(R) CPU P6200 @ 2.13GHz Stepping: 5 CPU MHz: 2133.000 CPU max MHz: 2133.0000 CPU min MHz: 933.0000 BogoMIPS: 4256.26 L1d cache: 32K L1i cache: 32K L2 cache: 256K L3 cache: 3072K ~$ free -m total used free shared buff/cache available Mem: 3769 1193 802 961 1772 1219 Swap: 0 0 0 ~$ uname -r 4.8.0-36-lowlatency Kindly explain the algorithm within the body of the answer. For languages used other than JavaScript (which will test at Chromium 70) will take the time to install the language and test the code for the time taken to output the requirement, as there is no way (that have found) to provide uniform results as to time for every possible language used to derive output (see this comment). A: Haskell, 6.9 s f [] [x] = [[x]] f [] [x,y] = [[x,y],[y,x]] f l (x:r) = map (x:) (f [] $ l++r) ++ f (l++[x]) r f _ [] = [] g :: Int -> [Int] g = map read . f [] . show Try it online! g is the main function which converts the input to a string and the result to a list of integers. f recursively performs the shuffling. The algorithm works as follows: Given 123, we need to generate [123,132,213,231,312,321]. This can be done in parts by taking the first digit 1, recursively computing the list for the remaining digits 23 -> [23,32] and adding 1 to the front again: [123,132]. Then we do the same with 2 and the remaining digits 13 to get [213,231] and with 3 and 12 to get [312,321]. Finally, the three lists are concatenated. This works in the same way for larger numbers. f handles two lists, the first one (l) contains all digits left from the current digit, the second one (x:r) has the current digit x at the first position, followed by the remaining digits r. We recursively call f with all but the current digit (that is l and r concatenated) (f [] $ l++r) and add the current digit x to the front of each element in the resulting list: map (x:). We then finished processing x and add it to the end of the l list and recursively call f (l++[x]) r to handle the next digit. The largest test case g 123456789 takes ~6.9s on OPs machine: real 0m6.877s user 0m4.439s sys 0m0.056s (~0.1s on my own machine)
{ "pile_set_name": "StackExchange" }
Q: Does decrease in temperature affect mass $E=mc^2$? My understanding of Quantum physics and String Theory is very basic and I don't yet have a grasp on the maths, but in my research I have come up with a question. Does a decrease in temperature also signify/create a decrease in mass? I am quite willing to believe the concepts I think I am beginning to understand are totally misconceptions on my part. But, as I see it mass is a product/mark of disruption to the Higgs field as a particle moves. If these particles are ultimately composed of vibrating Strings, their mass is given by the rate at which they vibrate and how it interacts with the Higgs field. I don't have any idea if, as the temperature (as we know it) approaches 0k, the string/quark/sparticle would change its state in any way or if the changing of the state of the String would change what type of particle it represents. It seems I'm more full of questions than answers, but that's why I love these topics! I know what I'm learning is new if the best and brightest are still working on the 'basics' to just make their systems work :). A: The answer is that a decrease in temperature does decrease the mass, though in most cases that change is exceedingly small. Temperature is a macroscopic phenomenon, so you can't really talk about the temperature of a single string or an atom. However consider the following analogy: If you have an isolated string (or atom) in some excited state, then to relax into a lower energy state it must emit a photon or conversely to move to a more excited state it must absorb a photon. As discussed in the question Does the mass of a body absorbing photons increase? emitting or absorbing photons will change its mass. For a macroscopic object the arguament is a bit more subtle. In macroscopic objects temperature is normally a measure of the kinetic energy of the vibrating atoms in your system. When you are calculating the gravitational field of the object you're probably used to using Newton's law. However general relativity tells us that the source of the field is an object called the stress-energy tensor. This does include the rest mass of the object(s) but it also includes momentum and pressure. Temperature increases the momentum of the atoms in your material and that contributes to the increase in the gravitational field. A: You seem to have overcomplicated this question quite a bit, you don't need to go further than the theory of relativity to find the answer. Heat is simply chaotic movement on the molecular and submolecular level, and as relativity dictate that any object moving relative to an observer will to that observer appear to have greater mass with greater relative speed, heat naturally increases mass.
{ "pile_set_name": "StackExchange" }
Q: std::tuple and a type cartesian_product The following code doesn't compile, but I don't found the error (I don't unsderstand the message error). My basic template type, 'int_mod_N', is an integer from 0 to 'N', an integer module 'N' (to represent elements of a cyclic group). This is very easy and I have constructed a library of integers represented in radix 'B', where the digits are of 'int_mod_N', and the integer is represented as 'std::basic_strings< int_mod_N >'. It works. The problematic thing is the type I need to represent elements of a cartesian product of 'n' sets, for each of them integers module a const integer 'N_i'. Mathematically, I want to represent elements of Z_Nn x ... x Z_N1, only the additive group. The next code don't compile. #include <tuple> #include "int_mod_N_t.hpp" template< unsigned N_n,unsigned ... N_nm1 > struct elem_set_t : public decltype( std::tuple_cat( std::tuple< int_mod_N_t<N_n> >{}, elem_set_t< N_nm1 ... >{} ) ) {}; template<unsigned N_n,unsigned N_nm1> struct elem_set_t<N_n,N_nm1> : public std::tuple< int_mod_N_t<N_n> , int_mod_N_t<N_nm1> > {}; template<unsigned N_n> struct elem_set_t<N_n> : public std::tuple< int_mod_N_t<N_n> > {}; The error message of compiler (g++ 7.2.0), is In file included from /tuplas_y_tipos/main.cpp:3:0: /tuplas_y_tipos/elem_set_t.hpp: In instantiation of 'struct elem_set_t<2, 2, 2>': /tuplas_y_tipos/main.cpp:8:20: required from here /tuplas_y_tipos/elem_set_t.hpp:10:21: error: no matching function for call to 'tuple_cat(std::tuple >, elem_set_t<2, 2>)' std::tuple_cat( ~~~~~~~~~~~~~~^ std::tuple< int_mod_N_t >{}, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ elem_set_t< N_nm1 ... >{} ~~~~~~~~~~~~~~~~~~~~~~~~~ ) ~ In file included from /tuplas_y_tipos/elem_set_t.hpp:1:0, from /tuplas_y_tipos/main.cpp:3: c:\mingw\include\c++\7.2.0\tuple:1575:5: note: candidate: template constexpr typename std::__tuple_cat_result<_Tpls ...>::__type std::tuple_cat(_Tpls&& ...) tuple_cat(_Tpls&&... __tpls) ^~~~~~~~~ c:\mingw\include\c++\7.2.0\tuple:1575:5: note: template argument deduction/substitution failed: c:\mingw\include\c++\7.2.0\tuple:1572:31: error: no type named 'type' in 'struct std::enable_if' template elem_set_t<2,2,2> elem; ^~~~ make.exe[1]: * [tuplas_y_tipos.mk:97: Debug/main.cpp.o] Error 1 make.exe: * [Makefile:5: All] Error 2 make.exe[1]: Leaving directory '/tuplas_y_tipos' ====1 errors, 6 warnings==== A: I don't recommend inheriting from std::tuple at all, and for this, you don't need to. template <unsigned ... N_ns> using elem_set_t = std::tuple<int_mod_N_t<N_ns>...>; If you have some methods in mind, you should have a tuple data member, not base class template <unsigned ... N_ns> struct elem_set_t { std::tuple<int_mod_N_t<N_ns>...> data; // other members }
{ "pile_set_name": "StackExchange" }
Q: how to print specific content in json with php I have a json print like this; https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=26162616&retmode=json&tool=my_tool&[email protected] When i want to get result->26162616->pubdate i am getting error or null. my code : $source = file_get_contents("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=26162616&retmode=json&tool=my_tool&[email protected]"); $source = json_decode($source); echo $source->result->26162616->pubdate; i think reason is integer 26162616 value. how can i fix this? A: Turn JSON into an associative array (true in json_decode) and reference as follows: $source = json_decode($source, true); echo $source["result"]["26162616"]["pubdate"]; // 2015 Aug
{ "pile_set_name": "StackExchange" }
Q: Cant hover the second like nav { font-family: Arial, sans-serif; border: 1px solid #ccc; bordnaver-right: none; width: 100%; } nav ul { display: flex; flex-pack: center } nav ul { margin: 0; padding: 0; display: -webkit-box; display: -moz-box; display: -webkit-flex; display: -ms-flexbox; display: box; display: flex; -webkit-box-lines: multiple; -moz-box-lines: multiple; -o-box-lines: multiple; -webkit-flex-wrap: wrap; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-orient: horizontal; -moz-box-orient: horizontal; -o-box-orient: horizontal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } nav ul li { list-style: none; text-align: center; //border-left: 1px solid #fff; //border-right: 1px solid #ccc; background-color: #feaa38; background-image: -webkit-gradient(linear, left top, left bottom, from(#F5F5F5), to(#feaa38)); background-image: -webkit-linear-gradient(top, #F5F5F5, #feaa38); background-image: -moz-linear-gradient(top, #F5F5F5, #feaa38); background-image: -o-linear-gradient(top, #F5F5F5, #feaa38); background-image: linear-gradient(to bottom, #F5F5F5, #feaa38); position: relative; -webkit-box-flex: 1; -moz-box-flex: 1; -o-box-flex: 1; box-flex: 1; flex: 1 0 auto; } nav ul li:hover { background-color: #feaa38; } nav ul li a { text-decoration: none; color: #000; display: block; padding: 10px 0; } nav ul li:hover a { color: #FFF; } nav ul li ul { display: flex; } nav ul li ul { position:absolute; top:-999em; display: -webkit-box; display: -moz-box; display: -webkit-flex; display: -ms-flexbox; display: box; display: flex; -webkit-box-lines: multiple; -moz-box-lines: multiple; -o-box-lines: multiple; -webkit-flex-wrap: wrap; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-orient: vertical; -moz-box-orient: vertical; -o-box-orient: vertical; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; justify-content: space-around; width:100%; } nav ul li:hover > ul { top: auto; display: flex; flex-direction: column; margin: 0; padding: 0; z-index: 9998; } nav ul li ul li { background: #b56906; } nav ul li ul li a { text-decoration: none; color:#000000 !important; display: block; padding: 10px 0; } nav ul li ul li ul { position: absolute; left: 100%; display: -webkit-flex; display: -moz-flex; display: -ms-flex; display: -o-flex; display: flex; -webkit-flex-flow: column wrap; -moz-flex-flow: column wrap; -ms-flex-flow: column wrap; flex-flow: column wrap; justify-content: space-around; width:100%; } nav ul li ul li:hover > ul { top: 0; display: flex; flex-direction: column; margin: 0; padding: 0; z-index: 9999; } nav ul li:Last-child { border-right: none; } <nav> <ul> <li>first <ul> <li>1st <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>2nd <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>3rd <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>4th <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>5th <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> </ul> </li> <li>second <ul> <li>1st <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>2nd <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>3rd <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>4th <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>5th <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> </ul> </li> <li>third <ul> <li>1st <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>2nd <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>3rd <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>4th <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>5th <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> </ul> </li> <li>fourth <ul> <li>1st <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>2nd <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>3rd <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>4th <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>5th <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> </ul> </li> <li>fifth <ul> <li>1st <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>2nd <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>3rd <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>4th <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> <li>5th <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </li> </ul> </li> </ul> </nav> I have this nav bar. What I want is to get the hover state of UL LI UL LI but I cant hover it. How did I know it?Because when I add nav ul li ul li:hover a { color: #FFF; } The text color of 1st should be white. But it is not working A: You got :hover pseudoclass in the wrong place. nav ul li ul li a:hover { color: #FFF; }
{ "pile_set_name": "StackExchange" }
Q: How to test correct return String in Try construct after exception was thrown? I want to test if there was an IOException thrown and if the correct String value of "[ ]" is returned. I'm only able to check the exception message and other stuff but I cannot assert the "[ ]" def readJsonFile(myJson: String): String = Try { FileSystems.getDefault().getPath(myJson) } match { case Success(path) => new String(Files.readAllBytes(path)) case Failure(ioe: IOException) => "[]" case Failure(e) => sys.error(s"There was a problem with: $e") } I checked assertThrows[IOException] and intercept[IOException] but they only let me check for common exception stuff but not for the return value in case this kind of exception was thrown. Am I overlooking something? What's the easiest way to accomplish it? A: The problem here is that IOException is thrown outside of Try. If you read the file inside Try, it may satisfy your expectation: def readJsonFile(myJson: String): String = Try { Files.readAllBytes(FileSystems.getDefault().getPath(myJson)) } match { case Success(bytes) => new String(bytes) case Failure(ioe: IOException) => "[]" case Failure(e) => sys.error(s"There was a problem with: $e") }
{ "pile_set_name": "StackExchange" }
Q: Why opposite of electrophilic is not Protophilic In organic chemistry , considering definitions of electrophilic and nucleophilic: Electrophilic:having an affinity for electrons : being an electron acceptor. nucleophilic : having an affinity for atomic neuclei (also can we say proton?) : being an electron donor. So both being opposite to each, why dont we say nucleophilic as protophilic? A: Because not all "nucleophilic" agents react equally well with all types of relatively exposed nuclei. Phosphines are very unwilling to extract a proton but quite nucleophilic if the available electronic vacancy is in carbon or a transition metal.
{ "pile_set_name": "StackExchange" }
Q: Line joins not covering (miter) I have the following code of a voltage source connected to two resistors. \documentclass{standalone} \usepackage{tikz} \usepackage{circuitikz} \begin{document} \begin{circuitikz}[line width=1pt] \draw[line join=miter] (0,0) to[V=$U$] ++(0,2) to[R=$R_i$, -*] ++(2,0) to[short, i=$I$] ++(1,0) to[R=$R_u$] ++(0,-2) to[short, -*] ++(-1,0) to[short] (0,0); \end{circuitikz} \end{document} which creates the following schematics. As you can see, the beginpoint and endpoint (lower left corner) do not connect properly. I tried to use line join=miter but with no succes. How to do it properly? A: Here are a couple more variants: \documentclass[multi=circuitikz]{standalone} \usepackage{circuitikz} \begin{document} \begin{circuitikz}[line width=1pt] \draw[line join=miter] (0,0) to[V=$U$,name=U] ++(0,2) to[R=$R_i$, -*] ++(2,0) to[short, i=$I$] ++(1,0) to[R=$R_u$] ++(0,-2) to[short, -*] ++(-1,0) to[short] (0,0) to[short] (U.west); \end{circuitikz} \begin{circuitikz}[line width=1pt] \draw[line join=miter] (2,0) to[short,*-] (0,0) to[V=$U$] ++(0,2) to[R=$R_i$, -*] ++(2,0) to[short, i=$I$] ++(1,0) to[R=$R_u$] ++(0,-2) to[short,-*] (2,0); \end{circuitikz} \end{document} A: My first reaction was to tell you to use cycle but this does not work, as mentioned in section 5.10 of the circuitikz manual. The reason is, as explained a bit more below, that the path gets decomposed into subpaths such that you need to add -.. In situations in which the path does not get divided into subpaths, you should use cycle, but this does not work here, so you need to "help" TikZ doing the right thing. \documentclass{standalone} \usepackage{tikz} \usepackage{circuitikz} \begin{document} \begin{circuitikz}[line width=1pt] \draw[line join=miter] (0,0) to[V=$U$] ++(0,2) to[R=$R_i$, -*] ++(2,0) to[short, i=$I$] ++(1,0) to[R=$R_u$] ++(0,-2) to[short, -*] ++(-1,0) to[short,-.] (0,0); \end{circuitikz} \end{document} NOTE ADDED: As this has lead to some confusion, I'd like to add some information. The obvious puzzle is why cycle doesn't work. This is because he behavior of to changes in circuitikz when one uses certain keys. Consider the MWE \documentclass[border=3.14mm]{standalone} \usepackage{tikz} \usepackage{circuitikz} \begin{document} \begin{tikzpicture}[line width=1pt] \draw[line join=miter] (0,0) to[->] ++(0,2) to ++(2,0) -- cycle; \end{tikzpicture} \begin{circuitikz}[line width=1pt] \draw[line join=miter] (0,0) to[-*] ++(0,2) to ++(2,0) -- cycle; \end{circuitikz} \begin{circuitikz}[line width=1pt] \draw[line join=miter] (0,0) to[short,-*] ++(0,2) to ++(2,0) -- cycle; \end{circuitikz} \end{document} As you can see, the cycle key "does not work" in the last example. On the other hand, the arrow directives -> in the first two examples had no effect. This is because to in connection with short (or other circuitikz directives) decomposed the path. To understand these things better, you may want to look through pgfcircpath.tex, where some of the definitions are made. (Comment: one also finds there \ifx\pgf@temp\pgf@circ@temp % if it has not a name \pgfmathrandominteger{\pgf@circ@rand}{1000}{9999} \ctikzset{bipole/name = #2\pgf@circ@rand} % create it \fi I guess that at a given point someone may report some strange behavior because accidentally a wrong path got referenced, but perhaps I am missing something here.) In the vicinity of this block you'll find the path decomposition routines. Altogether, the simplest fix is to look at section 5.10 of the circuitikz manual, where it is suggested to use -., to use what @Kpym suggested, or some of the tricks in John Kormylo's answer (the ordering is random and I am not ranking one proposal over another here).
{ "pile_set_name": "StackExchange" }
Q: Why do we not use the SI system for distance in space? One of the closest stars to Sol is Alpha Centauri at 4.367 Ly according to wikipedia. Why do we not say that it is 41.343 Peta-meters rather? (4.367 Ly = 41.343 Pm) Why does Light-years or Parsecs seem to be the standard rather than SI? A: Light years and parsecs have been used since long before SI existed, so a lot of it is tradition. But using light years also makes it very obvious how long the light has traveled to get here, and thus which era of the universe we are seeing the object in. Something that is 11 billion light years away dates from the era of early galaxies, for example. If you gave the distance as 100 yottameters instead, it would be far from obvious unless your listener was particularly familiar with distances on that scale. For closer objects, parsecs are useful because they directly relate to the amount of parallax shift seen between opposite sides of the Earth's orbit. This is not so relevant now, but in the days when parallax was a standard method of measuring distance to astronomical objects, it was very convenient to be able to convert a parallax directly to a distance. (The name "parsec" actually comes from "parallax arcsecond".)
{ "pile_set_name": "StackExchange" }
Q: How can I store the conversation of LINE Bot using LINE API and HEROKU? I created line bot using LINE API and HEROKU. My bot works perfectly(echo example) but I wanna store the conversation with bot. So I added the code using bufferedwriter and filewriter but txt file doesn't be created.. If I run my code on Spring boot app, the txt file created properly in the path. But if I run my code on Heroku, it doesn't. what should I do? A: There is another answer that tells you why this isn't working, but I want to point out that you shouldn't do it this way on Heroku. If you need to store data that is persistent, you should put it in a database. Heroku gives you a free Postgres database. Run the following command: $ heroku addons:create heroku-postgresql Then add the code that uses it by following the Heroku guide for Connecting to Relational Databases.
{ "pile_set_name": "StackExchange" }
Q: Why is the max function applied on a dictionary not giving the maximum value but retuning the key with maximum value? Why the following code is returning the output as 'c' instead of 7 even though we are checking the dictionary values in the lambda function? >>> a={'a': 1, 'c': 7, 'b': 5, 'd': 5} >>> max(a, key=lambda x:a[x]) 'c' >>> A: Iteration over a dictionary happens over the keys by default. Another way to see what's going on in your case is to call list, which also iterates over the keys by default: >>> list(a) ['a', 'c', 'b', 'd'] You explicitly specify iteration over the values, using .values. >>> max(a.values()) 7 If you want both key as well as value, you can call max over .items: >>> max(a.items(), key=lambda x: x[1]) ('c', 7) .items returns a tuple in python2.x, you can have max iterate over it and pick the tuple corresponding to the max value in the 2nd position of each tuple.
{ "pile_set_name": "StackExchange" }
Q: How to write a MATLAB code for this kind of Heaviside step function? To solve one dimensional advection equation denoted by u_t+u_x = 0, u=u(x,t), and i.c. u(x,0)= 1+H(x+1)+H(x-1) using Lax Wanderoff method, I need to write a Heaviside step function H(x) and it needs to be zero when x <= 0, 1 when x>0 . The problem is I also need to use that function writing H(x-t+1), H(x-t-1) as I will compare what I find by the exact solution: u(x,t) =1 + H(x-t+1) -H(x-t-1) Here, the "x" and "t" are vectors such that; x=-5:0.05:5 t=0:0.05:1 I wrote the Heaviside step function as the following; however, I need it without the for loop. L=length(x) function H_X= heavisidefunc(x,L) H_X=zeros(1,L); for i= 1:L if x(i)<= 0 H_X(i)=0; else H_X(i)=1; end end end I get "Dimensions must agree." error if I write H_X3 = heavisidefunc(x-t+1,L); H_X4 = heavisidefunc(x-t-1,L); A: I came up with a solution. My new Heaviside function is; function H_X= heavisidefunc(x) if x<= 0 H_X=0; else H_X=1; end end The problem I had was because I was storing the output as a vector and it just complicated things. Now,writing H(x-t+1), H(x-t-1) is easier. Just put "heavisidefunc(x(i)-t(j)-1)" and loop from 1 to the length of x and l in two loops. Thanks to everyone!
{ "pile_set_name": "StackExchange" }
Q: Find all strings in NSArray that are a particular length I have an NSArray filled with 200,000 words, where each word could have 1-10 characters. I would like to create a second array based on the first, containing only the words that have exactly 5 characters. How would I do this? A: Use a predicate to filter the array and produce a new array containing only those words whose length is 5. Something like: NSPredicate *p = [NSPredicate predicateWithFormat:@"length == 5"]; NSArray *fiveCharWords = [myWordList filteredArrayUsingPredicate:p]; I always seem to get the predicate format slightly wrong the first time around, so don't be surprised if there's an error there. The point is that you should read up on NSPredicate and learn about how you can use predicates to filter collections like arrays and sets.
{ "pile_set_name": "StackExchange" }
Q: Kotlin - generate toString() for a non-data class Situation: I have a class with lateinit fields, so they are not present in the constructor: class ConfirmRequest() { lateinit var playerId: String } I'd like to have a toString() method with all fields and don't want to write it manually, to avoid boiler print. In Java I'd use the Lombok @ToString annotation for this problem. Question: Is there any way to implement it in Kotlin? A: The recommended way is to write toString manually (or generate by IDE) and hope that you don't have too many of such classes. The purpose of data class is to accommodate the most common cases of 85%, which leaves 15% to other solutions. A: Like you, I was used to using lombok for toString() and equals() in Java, so was a bit disappointed that non-data classes in Kotlin required all of the standard boilerplate. So I created Kassava, an open source library that lets you implement toString() and equals() without any boilerplate - just supply the list of properties and you're done! e.g. // 1. Import extension functions import au.com.console.kassava.kotlinEquals import au.com.console.kassava.kotlinToString import java.util.Objects class Employee(val name: String, val age: Int? = null) { // 2. Optionally define your properties for equals()/toString() in a companion // object (Kotlin will generate less KProperty classes, and you won't have // array creation for every method call) companion object { private val properties = arrayOf(Employee::name, Employee::age) } // 3. Implement equals() by supplying the list of properties to be included override fun equals(other: Any?) = kotlinEquals( other = other, properties = properties ) // 4. Implement toString() by supplying the list of properties to be included override fun toString() = kotlinToString(properties = properties) // 5. Implement hashCode() because you're awesome and know what you're doing ;) override fun hashCode() = Objects.hash(name, age) } A: I find Apache Commons Lang's ToStringBuilder with reflection useful, but it calls hashCode() and other methods when I don't need that (and one called hashCode() from a 3rd-party lib generates an NPE). So I just go with: // class myClass override fun toString() = MiscUtils.reflectionToString(this) // class MiscUTils fun reflectionToString(obj: Any): String { val s = LinkedList<String>() var clazz: Class<in Any>? = obj.javaClass while (clazz != null) { for (prop in clazz.declaredFields.filterNot { Modifier.isStatic(it.modifiers) }) { prop.isAccessible = true s += "${prop.name}=" + prop.get(obj)?.toString()?.trim() } clazz = clazz.superclass } return "${obj.javaClass.simpleName}=[${s.joinToString(", ")}]" }
{ "pile_set_name": "StackExchange" }