title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
How to use Docx.js?
<p>i have use docx.js for generate docx file, but generaeted docx doenot open. my generated docx file output is</p> <p><a href="https://i.stack.imgur.com/fk5hL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fk5hL.png" alt="enter image description here"></a></p> <p>i have included following js file into my Html page</p> <pre><code>&lt;script type="text/javascript" src="js/Docx/jszip.js"&gt;&lt;/script&gt; &lt;!-- Include main js lib --&gt; &lt;script type="text/javascript" src="js/Docx/DOCX.js"&gt;&lt;/script&gt; </code></pre> <p>and javascript function is</p> <pre><code>function test() { //alert("test fn call"); var doc = new DOCXjs(); doc.text('DOCX.js is a free open source library for generating Microsoft Word Documents using pure client-side JavaScript.'); //doc.text('It was developed by James Hall at Snapshot Media.'); var output = doc.output('datauri'); } </code></pre> <p>when i click button this function will be calling, and also i want to add datatable as a content of word document so how to add content using Docx.js? </p>
2
Disable text prediction on samsung Keybord
<p>i have a textedit field in my android app, this text field is intended for a serial key so text should not be autocompleted.</p> <p>i managed to solve it on the stock android keyboard but the samsung keyboard is still showing suggestions and autocompleting no matter what flags i set, these are my current flags:</p> <pre><code> android:inputType="textFilter|textNoSuggestions|textCapCharacters|textVisiblePassword" </code></pre> <p>i have also tried with </p> <pre><code>android:privateImeOptions="nm" </code></pre> <p>so, any other idea on how to programmatically disable this?</p>
2
Array and __rmul__ operator in Python Numpy
<p>In a project, I created a class, and I needed an operation between this new class and a real matrix, so I overloaded the <code>__rmul__</code> function like this</p> <pre><code>class foo(object): aarg = 0 def __init__(self): self.aarg = 1 def __rmul__(self,A): print(A) return 0 def __mul__(self,A): print(A) return 0 </code></pre> <p>but when I called it, the result wasn't what I expected</p> <pre><code>A = [[i*j for i in np.arange(2) ] for j in np.arange(3)] A = np.array(A) R = foo() C = A * R </code></pre> <p>Output:</p> <pre><code>0 0 0 1 0 2 </code></pre> <p>It seems that the function is called 6 times, once for each elements.</p> <p>Instead, the <code>__mul__</code> function works greatly</p> <pre><code>C = R * A </code></pre> <p>Output:</p> <pre><code>[[0 0] [0 1] [0 2]] </code></pre> <p>If <code>A</code> isn't an array, but only a list of lists, both work fine</p> <pre><code>A = [[i*j for i in np.arange(2) ] for j in np.arange(3)] R = foo() C = A * R C = R * A </code></pre> <p>Output</p> <pre><code>[[0, 0], [0, 1], [0, 2]] [[0, 0], [0, 1], [0, 2]] </code></pre> <p>I'd really want for my <code>__rmul__</code> function to work also on arrays (my original multiplication function isn't commutative). How can I solve it?</p>
2
How to move from CocoaPods to Carthage?
<p>My project has linked with like 30 different libraries. Very few of them support Carthage.</p> <p>Do I need to make a branch and make them support Carthage one by one? Is there any better way to do so?</p>
2
How to pass data from one controller to another in CakePHP 3?
<p>I wanna pass a variable from userscontroller to salescontroller in my project in CakePHP 3 and use it in salescontroller .But I don`t wanna to redirect from an action to another one (not passing variables in url) how can I do it? </p>
2
Mysql UNION as a subquery with an alias field
<p>I have a UNION query as bellow (I have simplified my working query so it is easier to read) :</p> <pre><code>SELECT count(*) FROM (SELECT DISTINCT `tableA`.`Store Name` FROM `tableA` UNION SELECT DISTINCT `tableB`.`Store Name` FROM `tableB`) t </code></pre> <p>This works fine and results in a single number with column name COUNT(*)</p> <p>I want to get this value as another column in another query so I do :</p> <pre><code>SELECT DISTINCT `tableC`.`id as PID, (SELECT count(*) from (SELECT DISTINCT `tableA`.`Store Name` FROM `tableA` UNION SELECT DISTINCT `tableB`.`Store Name` FROM `tableB`) t) AS noofstores WHERE .....; </code></pre> <p>But it wont work! What am I doing wrong? This is part of a bigger query, and all the other subqueries work fine when I do</p> <pre><code>, (SELECT .... ) AS column_name , </code></pre> <p>Sorry for poor error description. Update : This is my full query :</p> <pre><code>SELECT DISTINCT `tableC`.`id` as PID, (SELECT count(*) from (SELECT DISTINCT `tableA`.`Store Name` FROM `tableA` WHERE `tableA`.`id` = PID union SELECT DISTINCT `tableB`.`Store Name` FROM `tableB` WHERE `tableB`.`id` = PID) t) AS mycolumn_name FROM `tableC` </code></pre> <p>Looks like I had the union right and all, but the problem is the PID I am reffering to in the union :</p> <h1>1054 - Unknown column 'PID' in 'where clause'</h1> <p>So how do I solve this?</p>
2
how to save time as timestamp in influxdb
<p>I want save time as timestamp format from influxdb admin interface .but is not possible it show time in date format</p> <p>{"database":"mydb", "retentionPolicy":"default", "points":[ {"name":"old", "time": -1422, "precision": "s", "fields":{"value":10000000}}, {"name":"old", "time": 1422568543, "precision": "s", "fields":{"value":10000}}, {"name":"old", "time": 1422568543, "precision": "s", "fields":{"value":100}}, {"name":"old", "fields":{"value":1}}] }</p> <p>time value 2016-06-30T06:32:31.0133595Z 1 2016-06-30T06:36:38.3625607Z 100 2016-06-30T07:24:59Z 100 2016-06-30T07:24:59.27Z 10000 2016-06-30T07:24:59.2700914Z 1</p>
2
Python/Pandas - Replacing an element in one dataframe with a value from another dataframe
<p>I have an issue with replacing an element in one pandas DataFrame by a value from another pandas DataFrame. Apologies for the long post. I have tried to give many inbetween examples to clarify my problem. I use Python 2.7.11 (Anaconda 4.0.0, 64bit).</p> <p><strong>Data</strong></p> <p>I have a pandas DataFrame containing many user item pairs. This DataFrame (let's call it the <em>initial_user_item_matrix</em>) is of the form:</p> <pre><code> userId itemId interaction 1 1 1 1 2 1 2 0 3 1 3 1 4 1 4 1 5 2 9 1 6 3 3 1 7 3 5 0 </code></pre> <p>Furthermore, I have a DataFrame containing only the user item pairs of user 1. I call this the <em>cold_user_item_matrix</em>, this DataFrame is of the form:</p> <pre><code> userId itemId interaction 1 1 1 1 2 1 2 0 3 1 3 1 4 1 4 1 </code></pre> <p>Next, I have a numpy ndarray with items, which I call the <em>ranked_items</em>. It is of the form:</p> <pre><code>[9 5 3 4] </code></pre> <p>Finally, I change the interactions of user 1 in the <em>initial_user_item_matrix</em> to <code>NaN</code>'s which gives the following DataFrame (call it <em>new_user_item_matrix</em>):</p> <pre><code> userId itemId interaction 1 1 1 NaN 2 1 2 NaN 3 1 3 NaN 4 1 4 NaN 5 2 9 1 6 3 3 1 7 3 5 0 </code></pre> <p><strong>What do I want to achieve?</strong></p> <p>I want to change the interaction of the user 1 - item pairs in the <em>new_user_item_matrix</em> (currently <code>NaN</code>'s) to the value of that particular interaction in the <em>initial_user_item_matrix</em> <strong>IF AND ONLY IF</strong> the item is contained in the <em>ranked_items</em> array. Afterwards, all user item pairs (rows of the DataFrame) where the interaction is still <code>NaN</code> should be removed (user 1 - item pairs for which the itemId is not in <em>ranked_items</em>). See below what the result set should look like.</p> <p>Inbetween result:</p> <pre><code> userId itemId interaction 1 1 1 NaN 2 1 2 NaN 3 1 3 1 4 1 4 1 5 2 9 1 6 3 3 1 7 3 5 0 </code></pre> <p>Final result:</p> <pre><code> userId itemId interaction 3 1 3 1 4 1 4 1 5 2 9 1 6 3 3 1 7 3 5 0 </code></pre> <p><strong>What have I tried?</strong></p> <p>This is my code:</p> <pre><code>for item in ranked_items: if new_user_item_matrix.loc[new_user_item_matrix['userId']==cold_user].loc[new_user_item_matrix['itemId']==item].empty: pass else: new_user_item_matrix.replace(to_replace=new_user_item_matrix.loc[new_user_item_matrix['userId']==1].loc[new_user_item_matrix['itemId']==item].iloc[0,2],value=cold_user_item_matrixloc[cold_user_item_matrix['itemId']==item].iloc[0,2],inplace=True) new_user_item_matrix.dropna(axis=0,how='any',inplace=True) </code></pre> <p>What does it do? It loops over all items in the <em>ranked_items</em> array. First, it checks whether user 1 has interacted with the item (the if-part of the if statement). If not, then go to the next item in the <em>ranked_items</em> array (pass). If user 1 did interact with the item (the else-part of the if statement), replace the interaction of user 1 with the item from the <em>new_user_item_matrix</em> (currently a <code>NaN</code>) by the value of the interaction of user 1 with the item from the <em>cold_user_item_matrix</em>, which is either a 1 or a 0 (I hope you are all still with me).</p> <p><strong>What is going wrong?</strong></p> <p>The if-part of the if statement does not give any problems. It is going wrong when I'm trying to replace the value from the <em>new_user_item_matrix</em> (the else-part of the if statement). When replacing the particular element (the interaction), it does not only replace that element, but also <strong>ALL</strong> other values that are <code>NaN</code> in the <em>new_user_item_matrix</em>. To illustrate, if the loop starts, it first loops over itemId's 9 and 5, which user 1 has not interacted with (hence nothing happens). Next, it loops over itemId 3, and the interaction for userId 1 and itemId 3 should change from <code>NaN</code> to 0. But it does not only change the interaction for userId 1 and itemId 3 to 0, but also all other interactions of user 1 that are <code>NaN</code>'s. Giving the following result set:</p> <pre><code> userId itemId interaction 1 1 1 1 2 1 2 1 3 1 3 1 4 1 4 1 5 2 9 1 6 3 3 1 7 3 5 0 </code></pre> <p>Which is obviously incorrect, as itemId 1 and 2 are not in the <em>ranked_items</em> array and hence their true interaction should not be uncovered. Also, the interaction (a 1) for user 1 and itemId 3 are filled in for all interactions (even if their interaction is not a 1 but a 0).</p> <p>Anybody that can help me out here?</p>
2
Winforms - MVP Pattern: Using static ApplicationController to coordinate application?
<p><strong>Background</strong></p> <p>I'm building a two-tiered C# .net application:</p> <ol> <li>Tier 1: Winforms client application using the MVP (Model-View-Presenter) design pattern.</li> <li>Tier 2: WebAPI RESTful service sitting on top of Entity Framework and SQL Server.</li> </ol> <p>Currently, I have questions relating to the overall architecture of the Winforms client application. I'm new to programming (about a year) but I've made good progress with this application. I want to step back and re-evaluate my current approach to check that I'm generally heading in the right direction.</p> <p><strong>Application Domain</strong></p> <p>The Winforms application is a fairly simple security personnel tracking application. The main view (Form) is the focus of the application, and has different sections which group content into functional areas (e.g. a section for tracking personnel schedules, a section for tracking who is assigned where, etc.). A menu on the side of the application launches secondary views (e.g. history, statistics, contacts, etc.). The idea is that the app could be used by a security office to organize daily operations and then keep a detailed history of everything in a database for reporting on in the future.</p> <p><strong>Technical Details</strong></p> <p>As mentioned, the Winforms client is built using the MVP pattern (passive view), focusing on using dependency injection as much as possible (via SimpleInjector IoC container). Each view (form) is paired up with a single presenter. The views implement interfaces, allowing the presenter to control the view (regardless of the concrete implementation). The view raises events for the presenter to subscribe to. Currently, presenters are not allowed to directly communicate to another presenter.</p> <p>An application controller is used to coordinate the application. This is the area of my application architecture where I'm the most shakey (hence the post title). The application controller is currently used to:</p> <ol> <li>Open new views (forms) and manage open forms.</li> <li>Facilitate communication between application components via an event aggregator. One presenter publishes an event and any number of presenter can subscribe to that event.</li> <li>Host session information (i.e. security context/logon, config data, etc.)</li> </ol> <p>The IoC container is registered into the application controller at application start-up. This allows the application controller, for example, to create a presenter from the container, and then have all subsequent dependencies (view, services, etc.) to be automatically handled by the container.</p> <p><strong>Question</strong></p> <p>In order to make the Application Controller accessible to all presenters, I have created the controller as a static class.</p> <pre><code>public static class ApplicationController { private static Session _session; private static INavigationWorkflow _workflow; private static EventAggregator _aggregator; #region Registrations public static void RegisterSession(Session session) {} public static void RegisterWorkflow(INavigationWorkflow workflow) {} public static void RegisterAggregator(EventAggregator aggregator) {} #endregion #region Properties public static Session Session { get { return _session; } } #endregion #region Navigation public static void NavigateToView(Constants.View view) {} #endregion #region Events public static Subscription&lt;TMessageType&gt; Subscribe&lt;TMessageType&gt;(Action&lt;TMessageType&gt; action) {} public static void Publish&lt;TMessageType&gt;(TMessageType message) {} public static void Unsubscribe&lt;TMessageType&gt;(Subscription&lt;TMessageType&gt; subscription) {} #endregion } </code></pre> <p>Is this considered an acceptable practice to make a static class like this? I mean, it certainly works. It just feels... off? Are there any other holes that you can see in my architecture based on what I have described?</p> <p>-</p> <p>** <strong>EDIT</strong> **</p> <p>This edit is made in response to Ric .Net’s answer posted below.</p> <p>I have read through all of your suggestions. As I am committed to utilizing dependency injection to the fullest extent I can, I’m onboard with all of your suggestions. That was my plan from the beginning, but when I ran into things I didn’t understand how to accomplish via injection, I turned to the global static controller class to solve my problems (A god class it is becoming, indeed. Yikes!). Some of those questions still exist:</p> <p><strong>Event Aggregator</strong></p> <p>The defining line here is what should be considered optional, I think. I’ll provide a bit more context about my app before outlining my problem. Using web terminology, my main form generally acts like a <a href="http://www.tutorialsteacher.com/mvc/layout-view-in-asp.net-mvc" rel="nofollow">layout view</a>, hosting navigation controls and a notification section in the left menu, and partial views being hosted in the center. Coming back to winforms terminology, the partial views are just custom made UserControls that I treat like views, and each of them are paired up with their own presenter. I have 6 of these partial views hosted on my main form, and they serve as the meat and potatoes of the application. </p> <p>As an example, one partial view lists available security guards and another lists potential patrol areas. In a typical use case, a user would drag an available security guard from the available list to one of the potential patrol areas, effectively becoming assigned to that area. The patrol area view would then update to show the assigned security guard and the guard would be removed from the available list view. Utilizing drag-and-drop events, I can handle this interaction.</p> <p>My questions come when I need to handle other types of interactivity between the various partial views. For example, double clicking on guard that is assigned to a location (as seen in one partial view) could highlight that guard’s name on another partial view showing all personnel schedules, or bring up employee details/history on another partial view. I could see the graph/matrix of what partial views are interested in events occurring in other partial views as becoming quite complex, and I’m not sure how to handle that via injection. With 6 partial views, I wouldn’t want to inject the other 5 partial views/presenters into each one. I was planning on accomplishing this via the event aggregator. Another example I could think of is needing to update data on a separate view (its own form) based off an event that occurs on one of the partial views on the main form.</p> <p><strong>Session &amp; Form Opener</strong></p> <p>I really like your thoughts here. I’m going to take these ideas and run with them, and see where I end up!</p> <p><strong>Security</strong></p> <p>What are your thoughts on controlling user access to certain functionality based on what type of account they have? The recommendations I’ve been reading online say that security could be implemented by modifying the views based on their account type. The thought being, if a user can’t interact with a UI element to kick off a certain task, then the presenter will never be asked to perform that task. I’m curious if you inject the WindowsUserContext into each presenter and do additional checks, especially for http service bound requests?</p> <p>I haven’t done too much development on the service side of things yet, but for http service bound requests, I imagine you need to send security information along with each request so that the service can authenticate the request. My plan was to inject the WindowsUserContext directly into the winforms service agents that end up making the service requests (i.e. the security validation would not be coming from the presenter). In that case, the service agents could potentially do a last minute security check before sending off a request.</p>
2
Cakephp 3.0 read local file contents using fget
<p>I have worked out the PHP code required to upload data from a .csv file to a database, not using CakePHP3.x, but I am struggling integrating this into my framework. I don't want to upload the file to the database, only read the data from the CSV file. </p> <p>This is my code that works on the localhost to upload the data to my database.</p> <pre><code>// Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } $fp = fopen("CSV_Upload_Test.csv", "r"); while( !feof($fp)) { if( !$line = fgetcsv($fp, 1000, ',', '"')) { continue; } $mysqlimport = "INSERT INTO divisiontwosix.csvtestsystems VALUES('".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[4]."')"; mysql_query($mysqlimport) or die(mysql_error()); } fclose($fp); </code></pre> <p>This is my code for the CakePHP installation on my server, but I can't seem to find (or more likely ask the correct question to find) an answer on how to implement it.</p> <p>This is my Controller:</p> <pre><code> public function upload() { $system = $this-&gt;Systems-&gt;newEntity(); //Check if file has been uploaded. if(!empty($this-&gt;request-&gt;data['Systems']['upload']['name'])) { $file = $this-&gt;request-&gt;data['Systems']['upload']; } if ($this-&gt;request-&gt;is('post')) { $system = $this-&gt;Systems-&gt;patchEntity($system, $this-&gt;request-&gt;data); // add upload data to controller function upload $file = $_REQUEST['text']; $fp = fopen("$file","r"); while( !feof($fp)) { if( !$line = fgetcsv($fp, 1000, ',', '"')) { continue; } $mysqlimport = "INSERT INTO divtwosix.systems VALUES('".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[4]."')"; mysql_query($mysqlimport) or die(mysql_error()); } fclose($fp); if ($this-&gt;Systems-&gt;save($system)) { $this-&gt;Flash-&gt;success(__('The system has been saved.')); return $this-&gt;redirect(['action' =&gt; 'index']); } else { $this-&gt;Flash-&gt;error(__('The system could not be saved. Please, try again.')); } } $estimates = $this-&gt;Systems-&gt;Estimates-&gt;find('list', ['limit' =&gt; 200]); $this-&gt;set(compact('system', 'estimates')); $this-&gt;set('_serialize', ['system']); } </code></pre> <p>And this is my form (upload.ctp) as you can see I have tried a couple of things:</p> <pre><code>&lt;?= $this-&gt;Form-&gt;create($system) ?&gt; &lt;fieldset&gt; &lt;legend&gt;&lt;?= __('Upload System') ?&gt;&lt;/legend&gt; &lt;?php echo $this-&gt;Form-&gt;create('User', array('url' =&gt; array('action' =&gt; 'create'), 'enctype' =&gt; 'multipart/form-data')); // echo $this-&gt;Form-&gt;create($system, ['type'=&gt;'file']); echo $this-&gt;Form-&gt;input('estimates_id', ['label'=&gt;'Select Estimate Name','options' =&gt; $estimates]); // echo $this-&gt;Form-&gt;input('file', ['label'=&gt;'Upload works with CSV files only','type' =&gt; 'file']); echo $this-&gt;Form-&gt;input('text', ['label'=&gt;'Input File location']); ?&gt; &lt;/fieldset&gt; &lt;?= $this-&gt;Form-&gt;button(__('Upload')) ?&gt; </code></pre> <p>And the error I get is </p> <pre><code>fopen(C:\Users\jrogers\Desktop\Book1.csv): failed to open stream: No such file or directory [APP/Controller/SystemsController.php, line 86] </code></pre> <p>or</p> <pre><code>fopen(Book1.csv): failed to open stream: No such file or directory [APP/Controller/SystemsController.php, line 86] </code></pre> <p>It is not my intent to add the file to the database, but only to add the data from the .csv file to the database. I realize I am probably missing something simple, but would greatly appreciate the assistance. The examples I am finding only show how to upload the file to the database and not how to read the data from the local file. Thanks in advance for your help. </p>
2
smack / ejabberd Connection Timeout
<p>We are using the Pub/Sub mechanism of ejabberd to send messages between multiple clients. The ejabberd version running on the server is 16.04 and the smack library version is 4.1.1.</p> <p>The publishing and subscribing of messages work fine for a period of time, after some time we get the following exception on the client side :</p> <pre><code>org.jivesoftware.smack.SmackException$NoResponseException: No response received within reply timeout. Timeout was 15000ms (~15s). Used filter: IQReplyFilter: iqAndIdFilter (AndFilter: (OrFilter: (IQTypeFilter: type=error, IQTypeFilter: type=result), StanzaIdFilter: id=T89NL-174)), : fromFilter (OrFilter: (FromMatchesFilter (full): pubsub.unio.com)) </code></pre> <p>Tried googling the cause but was unable to find out a resolution. Any help is appreciated.</p> <p>Thanks in advance.</p>
2
Alasql is undefined
<p>I can't seem to get the Alasql to become defined, i have installed it via node and I'm fairly certain that it is installed proplery however whenever i load my front end. i'm not 100% sure where it's going wrong, any help would be greatly appreciated!</p> <pre><code>require is not defined at Scope.$scope.exportData $scope.exportData = function () { var mystyle = { sheetid: 'Account sheet', headers: true, caption: { title:'My Big Table', }, style:'background:#00FF00', column: { style:'font-size:30px' }, columns: [ {columnid:'Date'}, {columnid:'Description'}, {columnid:'Due'}, {columnid:'Charged £'}, {columnid:'Received £'}, {columnid:'Balanced £'}, { columnid:'name', title: 'Number of letters in name', width: '300px', cell: { value: function(value){return value.length} } }, ], row: { style: function(sheet,row,rowidx){ return 'background:'+(rowidx%2?'red':'yellow'); } }, rows: { }, cells: { 2:{ 2:{ } } } }; $scope.exportData = function () { var alasql = require('alasql'); alasql('SELECT * INTO XLS("report.xls",?) FROM ?',[mystyle,records]); }; </code></pre>
2
El Capitan php version update using brew
<p>I just updated my Mac to OS X El Capitan 10.11.5. The stable version of php is 5.5.34. What I need something newer than that like 5.6.21. </p> <p>First step I did to update my php is: </p> <p><code>brew install php56</code>. brew installs all the packages under this dir: <code>/usr/local/Cellar</code>.</p> <p>OS X El Capitan path to php is <code>usr/bin</code></p> <p>I tried creating a symbolic link so that my php version from Cellar dir points to the one of El capitan:</p> <pre><code>sudo ln -sv /usr/local/Cellar/php56/5.6.21/bin/php /usr/bin/php </code></pre> <p>But I get this error message:</p> <pre><code>ln: /usr/bin/php: Operation not permitted </code></pre> <p>and there is nothing I can do...? </p> <p>Maybe there is a another way of updating my php version on mack rather than brew and symbolic link. </p> <p>Also when I want to check where is my php.ini <code>php --ini</code> i get this:</p> <pre><code>Configuration File (php.ini) Path: /etc Loaded Configuration File: (none) </code></pre>
2
Selecting Guidelines : MISRA 1998 or MISRA 2004 or MISRA 2012?
<p>I always wondered how does a project/team/company selects or qualifies for choosing a specific guideline to be followed like MISRA 1998/2004/2012? How should one know and decide that which guideline will be sufficient (cost vs time vs quality) for qualifying a project?</p> <p>(I know his question is a bit blunt, but any answers will be appreciated)</p>
2
finding hadoop-core-2.7.2.jar path
<p>I am new to hadoop and I am trying to run a code that use hadoop 1.2.1 version using hadoop 2.7.2 version. This is part of the code:</p> <pre><code>MR_HADOOPJAR=/usr/local/hadoop/hadoop-1.2.1/hadoop-core-1.2.1.jar MR_MANIFEST=${rootPath}mp/src/manifest.txt echo "Compiling mp source code.." javac -classpath $MR_HADOOPJAR ${rootPath}mp/src/*.java </code></pre> <p>However, I can not find the hadoop-core-2.7.2.jar?? Any thoughts about the path of hadoop-core-2.7.2.jar??</p>
2
Sticky sidebar overlaps to the footer?
<p>I have Created custom sticky sidebar for ADS, it works but there is an issue. when I scroll it to the bottom, it overlaps on the footer. pls check. - <a href="http://screencast.com/t/oEjcrbocB05C" rel="nofollow">http://screencast.com/t/oEjcrbocB05C</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var stickySidebar = $('.sticky'); if (stickySidebar.length &gt; 0) { var stickyHeight = stickySidebar.height(), sidebarTop = stickySidebar.offset().top; } // on scroll move the sidebar $(window).scroll(function () { if (stickySidebar.length &gt; 0) { var scrollTop = $(window).scrollTop(); if (sidebarTop &lt; scrollTop) { stickySidebar.css('top', scrollTop - sidebarTop); // stop the sticky sidebar at the footer to avoid overlapping var sidebarBottom = stickySidebar.offset().top + stickyHeight, stickyStop = $('.main-content').offset().top + $('.main-content').height(); if (stickyStop &lt; sidebarBottom) { var stopPosition = $('.main-content').height() - stickyHeight; stickySidebar.css('top', stopPosition); } } else { stickySidebar.css('top', '0'); } } }); $(window).resize(function () { if (stickySidebar.length &gt; 0) { stickyHeight = stickySidebar.height(); } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.sticky { position: relative; top: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>Check for site url is - <a href="http://www.test2.guru99.com/java-tutorial.html" rel="nofollow">http://www.test2.guru99.com/java-tutorial.html</a></p> <p>Please Help Me !</p>
2
How to change the default Wordpress upload folder to a shared network one?
<p>I have a webserver setup in 2 separate pc's . <br></p> <p>First machine holds the MySql server and folder for uploads, shared on the network, that i can access using UNC path like <code>//PC1/uploads</code>.</p> <p>Second machine holds the ISS server and the Wordpress files. I can use <code>file://</code> to embed existing images, etc from the first machine in the wordpress site.</p> <p>What I don't know is how to setup Wordpress to change it's default upload folder to <code>//PC1/uploads</code> instead of the default local folder.</p> <p>I have tried with <code>define('UPLOADS','file://PC1/uploads');</code> and with a ftp server</p> <pre><code>define ('UPLOADS','ftp://User:[email protected]'); </code></pre> <p>I get and error <code>Is its parent directory writable by the server?</code> The upload folder has Everyone read/write in permisions setting , and I can use <code>mput</code> to upload files with ftp.</p> <p>Thank you</p>
2
Is there a difference between `TRUE` and `true`?
<p>There are two instances of <code>TrueClass</code>, <code>FalseClass</code> and <code>NilClass</code> with different names: one in lowercase and one in uppercase. One instance appears to evaluate to the other:</p> <pre><code>true # =&gt; true TRUE # =&gt; true true == TRUE # =&gt; true </code></pre> <p>Is there a difference between these two constants, and if so, what are the differences? If they are the same, which of these constants should I use in my code? Should I write <code>some_value = true</code> or <code>some_value = TRUE</code>?</p>
2
Finding DLL Dependencies for Classic ASP Web application
<p>I am a system admin tasked with migrating Classic ASP based web application from Windows Server 2003 (IIS 6) to Windows Server 2008 r2 (IIS 7.5)</p> <p>The application is very old written in around 2002-03 and the concerned developer people are not around anymore to let me know anything related to this Web Application.</p> <p>After lot of trial and error, I have been able to get the Web Application running on 2008 r2.</p> <p>While navigating through application, I am getting various errors which on further investigation I understood are related to DLLs which the Web Application is invoking.</p> <p>My issue is, I don't know what all DLLs are used/invoked on the source server, which I need to copy &amp; register on the new server.</p> <p>I tried to use DependancyWalker but I am not able to find a way to use this tool for Web Application.</p> <p>I would really appreciate this community's help in this regard.</p>
2
python smtp check if username and pass are correct
<p>Do you have any idea how would i check if username and password are typed correctly before sending smtp mail with python?</p> <p>meaning: connect to smpt server, give feedback on username and password</p>
2
How to print the value of a web element in console?
<p>I have a web element which I have found css selector for and now I want to print its value in console. How to achieve this?</p>
2
Vibrate is not working when Screen Locked Mode in Android
<p>I wan to start Vibrate When Locked Screen. My Screen is open/working when wake lock. My Question is that Vibrate is not working when Screen Locked Mode. if Device Locked is open then working.</p> <blockquote> <p>onCreate() </p> </blockquote> <pre><code>KeyguardManager myKM = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE); if( myKM.inKeyguardRestrictedInputMode()) { //it is locked Log.e("Incomimg","Device Locked"); onStartVibrate(); } else { //it is not locked Log.e("Incomimg","Device Not Locked"); } </code></pre> <blockquote> <p>See Below Methods are for Vibrate on/off</p> </blockquote> <pre><code> public void onStartVibrate() { long[] pattern = {500, 250, 0 ,100,0, 250, 500}; vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(pattern,0); } public void onStopVibrate(){ try{ vibrator.cancel(); }catch (Exception ex) { } } </code></pre>
2
Choosing programming language: Text-based adventure game
<p>Since I'm finally on summer holidays, I have been wanting to sit down and develop an idea for a text-based adventure game I have. </p> <p>As such, I'm curious to know <strong>which language you would recommend</strong> for writing said game. Or rather; what was/is the industry standard? </p> <p>I'm not to keen on using Quest (or similar tools), but that may change if highly recommended. </p> <p>Nonetheless: <strong>Which language should I opt for when developing a text-based adventure</strong>?</p> <p>Thanks in advance!</p>
2
Simple code to read local file from a selection from dropdown box and display it in a textarea (Javascript/ XHTML)
<p>I've been trying for days to create a simple code to create a page that can display text files from a local directory. These are the specifications.</p> <ul> <li>XHTML/ Javascript only</li> <li>Files are local and from the same directory as the homepage</li> <li>Files are in txt/ log form</li> <li>Files to be displayed are to be selected from a dropdown box</li> <li>Files are to be displayed in a text area</li> <li>Compatible for all web browsers, can't use ActiveXObject</li> </ul> <p>This was my closest attempt.</p> <p><strong>JavaScript</strong></p> <pre><code>function populate(filename) { var file = document.getElementById('log1').files.(0); var reader = new FileReader(); reader.onload = function(e) { document.getElementById('myTextarea').value = e.target.result; }; reader.readAsText(file); } </code></pre> <p><strong>(X)HTML</strong></p> <pre><code>&lt;div id="source1"&gt; &lt;form id="log1"&gt; Select File from cng1wlsbe1b:&lt;br /&gt; &lt;select name="file1"&gt; &lt;option value="CCS1be1" onclick="populate('log1','ACCS1be1.txt')"&gt;CCS1be1&lt;/option&gt; &lt;option value="CCS1beadm1" onclick="populate('log1','cng1wlsbe1bCCS1beadm1.txt')"&gt;CCS1beadm1&lt;/option&gt; &lt;option value="engine_A" onclick="populate('log1','cng1wlsbe1bengine_A.txt')"&gt;engine_A&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; &lt;textarea rows="10" id="myTextarea" name="comment" form="log1" style="width:100%"&gt;&lt;/textarea&gt; &lt;/div&gt; </code></pre> <p>I just learned coding and I've been taking in bits and pieces of codes from everywhere, so I'm quite sure it's littered with errors. Will any kind Samaritan please enlighten me?</p> <p>Thank you!</p> <ul> <li>Robin :)</li> </ul>
2
New to C# and SQL - Why does my .AddWithValue not work?
<p>So currently I have this:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { string username = txtboxUsername.Text; string password = txtboxPassword.Text; string salt = string.Empty; connection.Open(); MySqlCommand sql = new MySqlCommand("SELECT salts FROM users WHERE usernames = @username;", connection); sql.Parameters.AddWithValue("@username", username); using (MySqlDataReader reader = sql.ExecuteReader()) { if (reader.HasRows) { reader.Read(); salt = reader.GetString(0); } else { MessageBox.Show(sql.CommandText); } } } </code></pre> <p>Now here is the issue, I don't get a compiler error when I run this, yet the sql.Parameters.AddWithValue( .. ); part doesn't actually add the string 'username' to the sql query. It simply leaves it at @username. Does anyone know what I am doing wrong here?</p>
2
MySQL MIN & MAX on alpha numeric column
<p>Simple <code>MAX</code> query:</p> <pre><code>SELECT MAX(Group) FROM acme </code></pre> <p>Works fine on a numeric column.</p> <p>Is it possible to use to this on an alpha-numeric column and ignore anything other than a number?</p>
2
Vertical scrolling on mobile
<p>I have the following markup:</p> <pre><code>&lt;div&gt; &lt;a&gt;..&lt;/a&gt; &lt;i&gt;..&lt;/i&gt; &lt;a&gt;..&lt;/a&gt; &lt;i&gt;..&lt;/i&gt; &lt;a&gt;..&lt;/a&gt; &lt;i&gt;..&lt;/i&gt; &lt;/div&gt; </code></pre> <p>Which just shows all the elements horizontally inline on desktops and other screens which are wide enough to hold the content. However when it comes to mobile, the elements wrap across two lines. Is it possible to keep everything on one line and have it be horizontally scrollable?</p> <p>I've tried:</p> <pre><code>div { overflow-x: scroll; overflow-y: hidden; } </code></pre> <p>But that doesn't seem to do anything. </p>
2
Matplotlib: Logarithmic scale with imshow and "extent"?
<p>I am having issues making a plot with a logarithmic y axis using imshow. My relevant code is as follows:</p> <pre><code>plt.imshow(power[channel], extent=(0,600,1,45), \ origin='lower', cmap='jet', aspect='auto', vmin=0, vmax=0.00025) plt.colorbar() plt.show(block=False) </code></pre> <p>Which gives the following plot:</p> <p><a href="https://i.stack.imgur.com/oyEok.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oyEok.png" alt="Wavelet plot"></a></p> <p>My problem is that I need the "extent" parameter because otherwise the y axis labeling is incorrect in my case. However it seems that imshow (which includes the "extent" parameter) does not allow logarithmic axis scaling. Adding the line</p> <pre><code>plt.yscale('log') </code></pre> <p>gives me the warning "Images are not supported on non-linear axes."</p> <p>Is there a way I can get logarithmic y axis scaling while keeping the "extent" function?</p>
2
SQL Query - Getting Sum Of Multiple Column with Id in Table Using Inner Join
<p>Good day,</p> <p>I'm creating a query where I can throw inside the data grid view. Suppose I have 2 table namely table A and table B. Table A has StaffId column and while Table B has StaffId too. Table B can have multiple value of cost with foreign key of StaffId. What I'm trying to do is, get all the sum value inside the Table B with the same StaffId.</p> <p>Here's the sample table definitions and contents.</p> <pre><code>// Table A | StaffId | Name | | 1 | Dummmy | // Table B | Id | StaffId | Cost | | 1 | 1 | 10.00 | | 2 | 1 | 10.00 | | 3 | 1 | 10.00 | </code></pre> <p>I already tried this query, but I can't get the correct answer.</p> <pre><code>SELECT A.Name, Sum(B.Cost) FROM B INNER JOIN A ON A.StaffId=B.StaffId </code></pre> <p>The answer should be like this</p> <pre><code>Dummy | 30.00 </code></pre> <p>but my query doesn't work. How can I get the value of all the cost in the table B?</p> <p>Any help would be much appreciate. Thank you in advance. </p>
2
asp.net core session not working , set cookie in response header but not set in browser
<p>I am using sessions to manage application state in ASP.NET CORE and it's configured as below.</p> <pre><code> services.AddSession(options =&gt; { options.CookieName = ".my.Session"; options.IdleTimeout = TimeSpan.FromSeconds(20); }); </code></pre> <p>It's working on localhost but on remote IIS 8 it's not creating cookies so not able to get the values. I also have enabled CORS and don't know what exactly caused this problem. In log it's not showing error either. In response header set cookie is present but not set in browser</p>
2
E/SQLiteLog: (1) near "ENTER": syntax error
<p>I'm getting this weird error while trying to create a database. I'm building an expense manager app and want to store the data from textview into SQLite database but I'm getting these errors when I press the save button. <strong>IS This because I'm trying to create database in another activity rather than the MainActivity??</strong></p> <pre><code>07-20 01:49:31.032 28795-28795/com.example.alkesh.expensemanager101 E/SQLiteLog: (1) near "ENTER": syntax error 07-20 01:49:31.032 28795-28795/com.example.alkesh.expensemanager101 D/AndroidRuntime: Shutting down VM --------- beginning of crash 07-20 01:49:31.042 28795-28795/com.example.alkesh.expensemanager101 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.alkesh.expensemanager101, PID: 28795 Theme: themes:{default=overlay:com.baranovgroup.nstyle, iconPack:com.baranovgroup.nstyle, fontPkg:com.baranovgroup.nstyle, com.android.systemui=overlay:com.baranovgroup.nstyle, com.android.systemui.navbar=overlay:com.baranovgroup.nstyle} android.database.sqlite.SQLiteException: near "ENTER": syntax error (code 1): , while compiling: ENTER INTO money (name) VALUES ('25'); at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) at android.database.sqlite.SQLiteProgram.&lt;init&gt;(SQLiteProgram.java:58) at android.database.sqlite.SQLiteStatement.&lt;init&gt;(SQLiteStatement.java:31) at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674) at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605) at com.example.alkesh.expensemanager101.AddMoney.insertIntoDatabase(AddMoney.java:95) at com.example.alkesh.expensemanager101.AddMoney.onClick(AddMoney.java:63) at android.view.View.performClick(View.java:5204) at android.view.View$PerformClick.run(View.java:21158) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5461) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132) </code></pre> <p><strong>Here's my code for the AddMoney Activity</strong></p> <pre><code>package com.example.alkesh.expensemanager101; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class AddMoney extends AppCompatActivity implements View.OnClickListener{ Button Save,Cancel; EditText expText; int[] expense=new int[100]; int temp=900; int c=0; int sum=0; String DBOnce; private SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_money); expText=(EditText)findViewById(R.id.expense); Cancel=(Button)findViewById(R.id.cancelbutton); Cancel.setOnClickListener(this); Save = (Button)findViewById(R.id.savebutton); Save.setOnClickListener(this); CreateDatabase(); } @Override public void onClick(View view) { if(view== Save){ insertIntoDatabase(); } if(view==Cancel){ Intent intent =new Intent(AddMoney.this,MainActivity.class); startActivity(intent); finish(); } } protected void CreateDatabase(){ db=openOrCreateDatabase("MoneyDB", Context.MODE_PRIVATE,null); db.execSQL("CREATE TABLE IF NOT EXISTS money(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR);"); } protected void insertIntoDatabase(){ String amount = expText.getText().toString().trim(); if(amount.equals("")){ Toast.makeText(this,"Please enter your expense or press Cancel to go back",Toast.LENGTH_LONG).show(); return; } String query="ENTER INTO money (name) VALUES ('"+amount+"');"; db.execSQL(query); Toast.makeText(this,"Expense Saved",Toast.LENGTH_LONG).show(); } } </code></pre> <p><strong>Here's my code for MainActivity.</strong></p> <pre><code>package com.example.alkesh.expensemanager101; import android.content.Intent; import android.os.Parcelable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button Add; TextView expense; int c=0; String DBonce="0"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Add = (Button) findViewById(R.id.addbutton); Add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, AddMoney.class); intent.putExtra("counter", DBonce); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menuhome,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case R.id.feedback:{} break; case R.id.exit: finish(); break; } return super.onOptionsItemSelected(item); } } </code></pre>
2
Set spark executor ip address
<p>In my current setup, there's two networks that each spark node has access to: an internal one connecting each of the nodes that's blazing fast, and an external one that can connect to other machines but is slow. The problem is that, even with setting SPARK_LOCAL_IP to be the internal ip address, all traffic goes through the slow public network according to nload. However, the references in the web ui are all to the internal ip address, as well as the references in the log messages (192.168.xx.xx is the internal network):</p> <pre><code>INFO ExecutorRunner: Launch command:... "--hostname" "192.168.xx.xx" "--cores" "16" "--app-id" "app-xxxxx-yyyy" "--worker-url" "spark://[email protected]:12344" </code></pre> <p>Do I have to change the hostname to correspond with the internal ip address, or is there a better way to configure the spark executor nodes to pass traffic through the internal network while having the public hostname correspond to the slower external network?</p>
2
Django Save Override Throwing Primary Duplicate Errors
<p>So, I have a model called ScheduleItem</p> <pre><code>class ScheduleItem(models.Model): agreement = FK location = FK start = models.DateTimeField() end = models.DateTimeField() totalHours = DecimalField def get_total_hours(self): start = timedelta(hours=self.start.hour, minutes=self.start.minute) end = timedelta(hours=self.end.hour, minutes=self.end.minute) td = (end-start).seconds totalHours=Decimal(td/Decimal(60)/Decimal(60)) return totalHours def save(self,*args,**kwargs): if self.pk == None: super(ScheduleItem,self).save(self,*args,**kwargs) self.refresh_from_db() # to access the datetime values, rather than unicode POST self.totalHours = self.get_total_hours() else: self.totalHours = self.get_total_hours() super(ScheduleItem,self).save(self,*args,**kwargs) </code></pre> <p>This throws PRIMARY key errors. I get duplicate entries with the second super(ScheduleItem,self). I cannot for the life of me figure out how to check for pk to access the datetime value and then save again within the save override method. I've tried moving things around, I've tried saving within the get_total_hours() function, with nothing but trouble.</p> <p>I just want the object to be committed to the db so I can get the datetime objects and then calculate the total hours. </p> <p>I'd rather not convert to datetime within the save function. </p> <p>Does anyone have any tip or can anyone tell me where I'm going wrong? </p>
2
Auto convert Xls to CSV
<p>I am using the following VBS script found on stackoverflow to convert xls to csv. It works fine. I want to run it with the batch file at the bottom. I don't know how to achieve what I want. The batch file gives the csv file the same name as the xls file. Because the xls file has two worksheets in it I need to produce two csv's for each xls file</p> <pre><code>if WScript.Arguments.Count &lt; 2 Then WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv" Wscript.Quit End If Dim oExcel Set oExcel = CreateObject("Excel.Application") Dim oBook Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0)) oBook.SaveAs WScript.Arguments.Item(1), 6 Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(1)) oBook.SaveAs WScript.Arguments.Item(2), 6 oBook.Close False oExcel.Quit WScript.Echo "Done" </code></pre> <p>Here's the batch file</p> <pre><code>FOR /f "delims=" %%i IN ('DIR *.xlsx /b') DO ExcelToCSV.vbs "%%i" "%%i.csv" </code></pre> <p>I need to pass in 2 output .csv file names one should be nnnnn_1.csv the other should be nnnnn_2.csv to account for the 2 worksheets in the xls files.</p> <p>Thanks for any help</p>
2
Cobol - syntax error, unexpected $undefined, expecting "end of file"
<p>I have a problem with syntax in cobol. I'm using open-cobol package on Ubuntu 4.2.0-16-generic, and i've got error:</p> <pre><code>~/cobol$ cobc -free -x -o cal cal.cbl cal.cbl:6: Error: syntax error, unexpected $undefined, expecting "end of file" </code></pre> <p>My cal.cbl file:</p> <pre><code>IDENTIFICATION DIVISION. PROGRAM-ID. cal. ENVIRONMENT DIVISION. DATA DIVISION. ?? OPTION PIC 9 VALUE ZERO. ?? NUM1 PIC 9(5)V9(2) VALUE ZERO. ?? NUM2 PIC 9(5)V9(2) VALUE ZERO. ?? RESULT PIC 9(10)V9(2) VALUE ZERO. PROCEDURE DIVISION. ACCEPT OPTION. DISPLAY "INSERT FIRST OPTION". ACCEPT NUM1. DISPLAY "INSERT SECOND OPTION". ACCEPT NUM2. STOP RUN. </code></pre> <p>I'm new in cobolt, i know something about columns and thats why I'm using -free flag to compile, but this error have no sense for me.</p> <p>Why this error occurs, please help:)</p>
2
ns0 is an undeclared prefix while Deserialising XML
<p>I am trying to De-serialize XML below to C# classes:</p> <pre><code>&lt;StaffingOrder xmlns="NameSpaceName"&gt; &lt;ReportingRequirements&gt; &lt;ns0:ManagerName&gt;__MANAGER_NAME&lt;/ns0:ManagerName&gt; &lt;ns0:SupervisorName&gt;__SUPERVISOR_NAME&lt;/ns0:SupervisorName&gt; &lt;/ReportingRequirements&gt; &lt;Comments&gt;Comment&lt;/Comments&gt; &lt;/StaffingOrder&gt; </code></pre> <p>But while deserializing I am getting following Error:</p> <pre><code>Error: There was an error processing 'Test.xml'. - 'ns0' is an undeclared prefix </code></pre> <p>How can i deserialize ns0 tags.</p>
2
Trigger callback after bindings reevaluate in Aurelia
<p>I'm building a drag-and-drop workspace, similar to the ones you find for making mockups. I have a workspace custom element that has a larger, nested element that can be zoomed and panned. Therefore, I need to carefully track size and position data of the workspace and all contained elements.</p> <p>In my attached event of my custom element, I programatically set the height and width of the workspace as a JavaScript object, which is bound to the css in the view:</p> <p><strong>workspaceCustomElement.js</strong></p> <pre><code>export class WorkspaceCustomElement { constructor(element) { this.element = element; } attached() { this.workspace.size = { height: this.element.height * 5, width: this.element.width * 5 } } } </code></pre> <p><strong>workspaceCustomElement.html</strong></p> <pre><code>&lt;div css="height: ${workspace.height}px; width: ${workspace.width}px; left: ${(element.clientWidth - workspace.width)/2}px; top: ${(element.clientHeight - workspace.height)/2}px;"&gt;&lt;/div&gt; </code></pre> <p>Now I'm running into problems trying to grab the positions of my child elements. I have attached callbacks on them as well, but they are being evaluated <em>before</em> the attached callback above, and so the css binding hasn't been evaluated, and the size and positions are wrong.</p> <p><strong>I need to add a callback <em>after</em> the <code>attached()</code> has been evaluated and the bindings have been updated.</strong> I can accomplish this by using a <code>setTimeout</code> hack, but I have no confidence that this will always work.</p> <pre><code>attached() { this.workspace.size = { height: this.element.height * 5, width: this.element.width * 5 } setTimeout(() =&gt; { let components = this.element.querySelectorAll('.component'); Array.prototype.forEach.call(components, (component) =&gt; { let model = component.model; model.position = { x: component.clientLeft, y: component.clientTop }; } }, 0) } </code></pre> <p>Is there a better, more reliable way to queue an instruction after the next binding update?</p>
2
Finding all combinations of paths from a graph with a given distance from the origin
<p><br /> I'm trying to find all combinations of paths from a graph with a given distance from the origin.</p> <p>In fact, the new expansion of World of Warcraft (Legion) will introduce the Artifact system to the game.<br /> It's a feature that you can level up, each level give you 1 rank and you can spend 1 point for each rank in a tree.<br /> You can find a calculator of each artifact on WowHead and I will use this one as example : <a href="http://legion.wowhead.com/artifact-calc/rogue/subtlety/" rel="nofollow">http://legion.wowhead.com/artifact-calc/rogue/subtlety/</a></p> <p>Basically, the aim of the program would be :<br /> "I give a rank, let's say 7, and it returns to me every path combinations from the graph which I had to spent 7 points to get there (ie, list of 7 unique nodes)".</p> <p>When I saw the calculator, I thought that it was solvable by transposing it to a graph, so I made one to help me to get through : <a href="http://i.stack.imgur.com/3RGot.png" rel="nofollow">Graph</a></p> <p>On the graph, I had to make little adjustments from the calculator, for example each trait which got 3 ranks had to be represented as 3 nodes linked each other. Also, for the traits which were unlocking 2 ways to continue, I had to represent them as 4 nodes to "emulate" the 3 nodes requirements to get through. (But we'll see after that is still an issue and it didn't really fixed the problem)</p> <p>Then from there I tried to find a good way to list every possibilities, so I made a lot of research over the internet to find the best way to handle my issue.<br /> I firstly tried to solve it using the Breadth-first search, but having the distance from the origin of each node didn't helped much. Then I tried to use the exhaustive search.<br /> I'm currently using an adaption of the code posted there : "Finding all paths from a given graph" on CodeReview@StackEchange (can't post more than 2 links)</p> <pre><code>def paths(graph, v, lmax): """Generate the maximal cycle-free paths with a given maximum length lmax in graph starting at v. Graph must be a mapping from vertices to collections of neighbouring vertices. &gt;&gt;&gt; g = {1: [2, 3], 2: [3, 4], 3: [1], 4: []} &gt;&gt;&gt; sorted(paths(g, 1, 3)) [[1, 2, 3], [1, 2, 4], [1, 3]] &gt;&gt;&gt; sorted(paths(g, 3, 4)) [[3, 1, 2, 4]] Credit to Gareth Rees from StackExchange for the original code. """ path = [v] # path traversed so far seen = {v} # set of vertices in path def search(): dead_end = True if len(seen) &lt; lmax: for neighbour in graph[path[-1]]: if neighbour not in seen: dead_end = False seen.add(neighbour) path.append(neighbour) yield from search() path.pop() seen.remove(neighbour) if dead_end: yield list(path) yield from search() </code></pre> <p>Then I make a function to sort the results and display only the one that had the required length.</p> <pre><code>def artifact(graph, maxrank, start): for i in range(1, maxrank+1): print("---------") print("Rank: " + str(i)) print("---------") # Get all the Paths at "i" Rank RawPaths = sorted(paths(g, start, i), key=len) # Remove paths that doesn't satisfact our rank requirement and sort it ValidPaths = [sorted(j) for j in RawPaths if len(j) == i] # Remove duplicates UniquePaths = sorted([list(j) for j in set(map(tuple, ValidPaths))]) # Display the Paths for j in range(len(UniquePaths)): PathString = ""; for k in range(len(UniquePaths[j])): PathString += str(UniquePaths[j][k]) + " " print(PathString) print("") </code></pre> <p>From there, I built list of adjacent nodes (neighbors) of a portion of nodes from the graph. I can't post more than 2 link, but the subgraph end at 8/7/32/31 nodes from the graph linked earlier.</p> <pre><code>g = { 1: [2, 38], 2: [1, 3], 3: [2, 4], 4: [3, 5], 5: [4, 6], 6: [5, 7, 8], 7: [6], 8: [6], 31: [33], 32: [33], 33: [31, 32, 34], 34: [33, 35], 35: [34, 36], 36: [35, 37], 37: [36, 38], 38: [1, 37] } </code></pre> <p>And then I called my function:</p> <pre><code>artifact(g, 8, 1) </code></pre> <p>But using this list, I was facing a major issue. In fact, the algorithm go straight until the end but it doesn't do any backtrack to reach the rank wanted (ie, after going all the way through 1 - 38 - 37 - 36 - 35 - 34 - 33 - 31, it wouldn't go back to 2 - 3 - ... if I had let's say 10 points to spend).<br /> I was able to solve it for this subgraph by adding either as neighbour 2 to the 38, 37, ... branch or 38 to the 2, 3, ... branch.</p> <p>So my list became :</p> <pre><code>g = { 1: [2, 38], 2: [1, 3, 38], 3: [2, 4, 38], 4: [3, 5, 38], 5: [4, 6, 38], 6: [5, 7, 8, 38], 7: [6, 38], 8: [6, 38], 31: [2, 33], 32: [2, 33], 33: [2, 31, 32, 34], 34: [2, 33, 35], 35: [2, 34, 36], 36: [2, 35, 37], 37: [2, 36, 38], 38: [1, 2, 37] } </code></pre> <p>And then I was able to get everything I wanted for this part of the graph. Now I'm trying to extend my reasoning to the entire graph. But I'm failing hard due to main 2 issues :<br /> - The 4 nodes to represent the traits with 3 ranks is working when I'm going in one direction, but if I have filled the entire branch and then I try to go back, I count the 4th node. (I could still make something in the artifact function to remove the 4th node but I don't think it's a good way to deal with it and should find a clever way to handle it.<br /> - The trick that I used to link the first 2 branches isn't directly applicable to the whole graph. For example, following what I did, I would add 32 to the 29s neighbors since when I come from 35, 32 is accessible from 29. But, if I come from 28 and didn't added 27 to the path, then 32 is not normally reachable from 29. Then my paths became invalid.</p> <p>I'm not sure if I can solve it this way, I hope you would be able to help me. Also, I have the feeling that my way of backtracking the search is not perfect. I also thought this :<br /> As soon as I'm at the end of a branch, I would go back to the previous separation and explore from there. But as the node would have been already explored, it don't go the other way and stop there.</p> <p>Finally, I'm up to any other way to handle my problem, I don't want especially to solve it using graph.<br /> Maybe there is another way to solve it efficiently (like building the graph step by step and having a number of ranks to spend and spent them gradually while nodes are unlocked maybe ?).</p> <p>Thank you in advance for your help and sorry for my English mistakes, I'm French :)</p>
2
Print empty list in Haskell
<p>This is haskell code. I'm finding why I am wrong with below.</p> <pre><code>main = do print [1] -- Okay print [] -- error </code></pre> <p>Error strings are following.</p> <blockquote> <p>P07.hs:38:11: error: ? Ambiguous type variable ‘t0’ arising from a use of ‘print’ prevents the constraint ‘(Show t0)’ from being solved. Probable fix: use a type annotation to specify what ‘t0’ should be. These potential instances exist: instance Show Ordering -- Defined in ‘GHC.Show’ instance Show Integer -- Defined in ‘GHC.Show’ instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’ ...plus 22 others ...plus five instances involving out-of-scope types (use -fprint-potential-instances to see them all) ? In a stmt of a 'do' block: print [] In the expression: do { print [] } In an equation for ‘main’: main = do { print [] }</p> </blockquote> <p>I tried <code>[] :: Show</code> not working. I think I just don't know what the errors mean.. please help me. Thanks.</p>
2
How to load the data when the page first load When I use vue js?
<p>This is my code:</p> <pre><code>&lt;div id="app"&gt; &lt;ul&gt; &lt;li v-for="task in tasks"&gt;@{{task.body}}&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;script src="//cdn.bootcss.com/vue/1.0.24/vue.min.js"&gt;&lt;/script&gt; &lt;script&gt; new Vue({ el:"#app", data:{ tasks:[ {body:'go to home',complete:true}, {body:'watch tv',complete:true}, {body:'go to bed',complete:true}, ] } }); &lt;/script&gt; </code></pre> <p>How I should do load the data 'tasks' from database when the page first load,I use php,vue js!!!</p>
2
Get background color after CSS filters
<p>I have a div, filled with a background color. With Javascript i dinamically change the hue, saturation and lightness filters using 3 wrappers around the div, each one with a filter.</p> <pre><code> &lt;div class="filterHue"&gt; &lt;div class="filterSaturation"&gt; &lt;div class="filterLightness"&gt; &lt;div class="baseColor"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>How I can get the resulting background color of the <code>baseColor</code> div after the filters, in order to apply that color to multiple text elements?</p> <p>The only solution that i came up with, is to wrap the text elements the same way as the div, but i think that is a overkill to have too many filters on the page, i prefer another solution if it is possible.</p>
2
Google places API authorization error
<p>I used this <a href="https://examples.javacodegeeks.com/android/android-google-places-autocomplete-api-example/" rel="nofollow noreferrer">tutorial</a> to get address in autocompletetextview as suggestions. I activated Google Places API and generated Android Key. But when I run the app I get this error <code>This IP, site or mobile application is not authorized to use this API key. Request received from IP address &lt;IP&gt;, with empty referer</code>. Is there something I'm doing wrong. If any one can help me in this regard, it would be great. Thanks.</p> <p><a href="https://i.stack.imgur.com/lKkJs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lKkJs.png" alt="I got this error as link in logcat"></a></p> <p><a href="https://i.stack.imgur.com/UUiAi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UUiAi.png" alt="credentials"></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>public class MainActivity extends Activity implements AdapterView.OnItemClickListener { private static final String LOG_TAG = "ExampleApp"; private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place"; private static final String TYPE_AUTOCOMPLETE = "/autocomplete"; private static final String OUT_JSON = "/json"; //------------ make your specific key ------------ private static final String API_KEY = "&lt;GooglePlaceAndroidKey as in credentials&gt;"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.query); autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item)); autoCompView.setOnItemClickListener(this); } public void onItemClick(AdapterView&lt;?&gt; adapterView, View view, int position, long id) { String str = (String) adapterView.getItemAtPosition(position); Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } public static ArrayList&lt;String&gt; autocomplete(String input) { ArrayList&lt;String&gt; resultList = null; HttpURLConnection conn = null; StringBuilder jsonResults = new StringBuilder(); try { StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON); sb.append("?key=" + API_KEY); sb.append("&amp;components=country:gr"); sb.append("&amp;input=" + URLEncoder.encode(input, "utf8")); URL url = new URL(sb.toString()); System.out.println("URL: "+url); conn = (HttpURLConnection) url.openConnection(); InputStreamReader in = new InputStreamReader(conn.getInputStream()); // Load the results into a StringBuilder int read; char[] buff = new char[1024]; while ((read = in.read(buff)) != -1) { jsonResults.append(buff, 0, read); } } catch (MalformedURLException e) { Log.e(LOG_TAG, "Error processing Places API URL", e); return resultList; } catch (IOException e) { Log.e(LOG_TAG, "Error connecting to Places API", e); return resultList; } finally { if (conn != null) { conn.disconnect(); } } try { // Create a JSON object hierarchy from the results JSONObject jsonObj = new JSONObject(jsonResults.toString()); JSONArray predsJsonArray = jsonObj.getJSONArray("predictions"); // Extract the Place descriptions from the results resultList = new ArrayList&lt;String&gt;(predsJsonArray.length()); for (int i = 0; i &lt; predsJsonArray.length(); i++) { System.out.println(predsJsonArray.getJSONObject(i).getString("description")); System.out.println("============================================================"); resultList.add(predsJsonArray.getJSONObject(i).getString("description")); } } catch (JSONException e) { Log.e(LOG_TAG, "Cannot process JSON results", e); } return resultList; } class GooglePlacesAutocompleteAdapter extends ArrayAdapter&lt;String&gt; implements Filterable { private ArrayList&lt;String&gt; resultList; public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } @Override public int getCount() { return resultList.size(); } @Override public String getItem(int index) { return resultList.get(index); } @Override public Filter getFilter() { Filter filter = new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filterResults = new FilterResults(); if (constraint != null) { // Retrieve the autocomplete results. resultList = autocomplete(constraint.toString()); // Assign the data to the FilterResults filterResults.values = resultList; filterResults.count = resultList.size(); } return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { if (results != null &amp;&amp; results.count &gt; 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } }; return filter; } } }</code></pre> </div> </div> </p>
2
How to pre-select option from <select> tag in Angular with options from a different controller?
<p>I'm using two controllers here. One, <code>productComponentsController</code>, handles a call to our database that pulls back an array of <code>productComponent</code> objects. The other, <code>AddEditArticleController</code>, controls the 'Create New / Edit Existing Article' page.</p> <p>On my Add/Edit Article page, I want a <code>&lt;select&gt;</code> to populate with <code>productComponents</code>, and, if I am editing an existing Article, to be pre-selected with that Article's current <code>productComponent</code>. </p> <p>Simple as this seems, I cannot make the field pre-select with the existing <code>productComponent</code>, though it does populate the <code>&lt;select&gt;</code> with them correctly. I've tried ngRepeat and ngOptions and both work for populating the dropdown, but neither works for pre-selecting the existing <code>productComponentID</code> from the array returned by the server.</p> <p>My HTML, using ngOptions: <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!-- productComponentsController as pvm, AddEditArticleController as vm --&gt; &lt;select id="componentBox" ng-model="vm.selectedComponent" placeholder="Select a Product Component" ng-change="vm.changeProductID()" class="form-control input-md" ng-options="component.name for component in pvm.productComponents track by component.id"&gt;&lt;/select&gt;</code></pre> </div> </div> </p> <p>My HTML, using ngRepeat:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!-- productComponentsController as pvm, AddEditArticleController as vm --&gt; &lt;select id="componentBox" ng-model="vm.selectedComponent" placeholder="Select a Product Component" ng-change="vm.changeProductID()" class="form-control input-md"&gt; &lt;option value="{{component.id}}" ng-repeat="component in pvm.productComponents" ng-selected="vm.selectOption(component.id)" ng-bind-html="component.name"&gt;&lt;/option&gt; &lt;/select&gt; &lt;!-- vm.selectOption() returns true if the current option's ID equals the productComponentID of the current Article. Therefore this option would be selected. --&gt;</code></pre> </div> </div> </p> <p>In my <code>AddEditArticleController</code>, I set vm.selectedComponent equal to the <code>productComponentID</code> of the Article that was returned by the database, in the promise.then() of my call. While <code>vm.selectedComponent</code> does change, this doesn't do anything to the dropdown.</p> <p>Also, in my generated HTML, I get the option: <code>&lt;option value="? number:47 ?"&gt;&lt;/option&gt;</code> (for an Article where the productComponentID is = 47). Apparently this happens as a result of the model being set to an unknown value but I don't know why the model would be set to anything other than an integer id.</p> <p>Is this because my select is accessing multiple controllers, or am I missing something obvious here? Any help is greatly appreciated, let me know if more info is needed.</p>
2
How to build multiple executables with different compilers with cmake?
<h3>following situation:</h3> <p>At the moment, I have a C++/CUDA project and I use <em>make</em> to produce two different executables: The first one is only a CPU version, which ignores the CUDA parts, and the second one is the GPU version.</p> <p>I can run <em>make</em> to build both versions, <em>make cpu</em> to only build the CPU version and <em>make gpu</em> to only build the GPU version. For the CPU version, the Intel compiler is used , and for the GPU version, nvcc with g++ is used instead.</p> <h3>Why I consider using cmake:</h3> <p>Now I would also like to be able to build the project under Windows with nmake. Therefore, I thought that cmake was the appropriate solution to generate a make or nmake file based on the platform.</p> <h3>Problem:</h3> <p>However, it seems to be difficult to specify a compiler based on a target (<a href="https://stackoverflow.com/questions/9542971/using-cmake-with-multiple-compilers-for-the-same-language">Using CMake with multiple compilers for the same language</a>).</p> <h3>Question:</h3> <p>Which is the best way to achieve the behavior as described above, building different executables for different architectures with different compilers out of the same code base as well for Windows as for Linux, by using cmake?</p>
2
jQuery Counter: Stop type when reach limit
<p>I create a counter for text area and for now I success to count the length, but I want after it reach the limit, user can't type anymore.</p> <p>How to make it stop able to type when reach the limit?</p> <pre><code>$('textarea').keyup(function () { var max = 10; var len = $(this).val().length; var char = max - len; if (len &gt;= max) { $(this).parent().find('.counter').text(char + '/'+max); $(this).parent().find('.counter').css({"color":"red"}); } else { $(this).parent().find('.counter').text(char + '/'+max); $(this).parent().find('.counter').css({"color":"#ccc"}); } }); </code></pre> <p>heres the jsfiddle <a href="https://jsfiddle.net/5vf8pce3/" rel="nofollow">https://jsfiddle.net/5vf8pce3/</a></p>
2
How to enter arguments of celery jobs into database to be queried; using mysql
<p>I am using MySql as result backend for celery. I want to store program arguments in DB too.</p> <p>For example: </p> <pre><code>add.apply_async(args=[num1, num2, user] </code></pre> <p>In this case I want to store user argument in DB, so that I can query later.</p> <p>Currently, I return arguments provided which is stored in DB.</p> <pre><code>def add(num1, num2, user): return [num1+num2, user] </code></pre> <p>However when the task is running state, user is not inserted and I am unable to query it in DB. Is there any solution/hack for this?</p>
2
SQL getting people within 30 days of birthday (regardless of year)
<p>i am trying to get all employees whose birthday is coming up, It seems what i am trying to go isn't functioning properly because the year is being considered each time. </p> <p>so the query i got now is </p> <pre><code>SELECT [emp].[FirstName] ,[emp].[LastName] ,[emp].[Birthday] FROM [Employees] AS [emp] WHERE [emp].[ID] != 12 AND [emp].[Birthday] &gt;= GETDATE() AND [emp].[Birthday] &lt;= DATEADD(dd,20,GETDATE()) </code></pre> <p>the problem is no employees birthday is in 2016. any idea how i can check this </p>
2
uniform initialization on struct with in-struct initialised members
<p>Uniformed initialization of a struct instance which contains in-struct initialised members follows me to the following error on Apple LLVM version 7.3.0:</p> <pre><code>error: no matching constructor for initialization of 'Foo' </code></pre> <p>Here is code sample:</p> <pre><code>struct Foo { int foo1 = 0; int foo2; }; int main() { Foo foo{0, 1}; } </code></pre> <p>It seems that in-struct initialisation suppresses generation of initializer list struct constructor. Why?</p>
2
ANDROID Time picker how to display two numbers in hour and minute
<p>Hi everyone i would like to display when i click a button, two number in hour and minute.</p> <p>my code is: </p> <pre><code>button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int hour= timePicker.getCurrentHour(); int minute=timePicker.getCurrentMinute(); Toast.makeText(MainActivity.this,"CLOCK--&gt; "+ String.valueOf(hour)+":"+String.valueOf(minute),Toast.LENGTH_LONG).show(); } }); </code></pre> <p>But the output is for example "9:8".</p> <p>I want display "09:08".</p> <p>Sorry for my english =)</p>
2
Extracting data from li tag under ul using Selenium Webdriver
<pre><code>&lt;ul class="dropdown-menu" aria-labelledby="dLabel"&gt; &lt;li&gt;&lt;a href="Resource/Guide/TCS Health Insurance - Hospitalisation Claim Reimbursement Guidelines.pdf" target="_blank"&gt;Hospitalization Guide&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="Resource/Guide/TCS Helath Insurance - Domiciliary Claim Reimbursement Guidelines.pdf" target="_blank"&gt;Domiciliary Guide&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I am trying to get data under each li list but not able to extract value <strong>Domiciliary Guide</strong> from the above li list. </p> <p>In the below code, list of elements is displayed as elements but first list element, <code>ele.getText()</code> is not giving any output. </p> <p>Can anyone help me in extracting data from <code>Li</code>? </p> <pre><code>WebElement ul=testDriver.findElement(By.xpath("//*[@id='header']/div/div/ul[1]/li[5]/div/ul")); List&lt;WebElement&gt; elements=ul.findElements(By.tagName("li")); System.out.println("elements::"+elements); for(WebElement ele:elements){ System.out.println("text"+ele.getText()); } </code></pre> <p>Thanks!</p>
2
Best way to join vertical table and horizontal table in SQL
<p>What is the best way to join a horizontal and vertical table in SQL? (i.e. in this case, join ItemID of both table) </p> <p>I have a table that is like this: </p> <p><a href="https://i.stack.imgur.com/KZEnH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KZEnH.png" alt="enter image description here"></a></p> <p>And Another table that is like this: </p> <p><a href="https://i.stack.imgur.com/K6Hol.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K6Hol.png" alt="Table 2"></a></p> <p>Ideally I would like to arrange them into something like this: </p> <p><strong>OrderID ItemID ClientID Description Quantity Price</strong> </p> <p>What would be the neatest simplest way to join these two different type table based on OrderID?</p> <p>Right now I am converting the Item Table from vertical to horizontal first, and then joining the 2 tables. But that becomes a lot of lines of code. Just wondering if there is any simpler way. Thanks!</p>
2
gauge the rate of inflation for c++
<p>Write a program to gauge the rate of inflation for the past year. The program asks for the price of an item (such as a hot dog or a 1-carat diamond) both one year ago and today. It estimates the inflation rate as the difference in price divided by the year-ago price. Your program should allow the user to repeat this calculation as often as the user wishes. Define a function to compute the rate of inflation. The inflation rate should be a value of type double giving the rate as a percent, for example 5.3 for 5.3 percent.</p> <p>Your program must use a function to compute the rate of inflation. A program which does not use a function will be awarded a score of zero, even if all tests pass.</p> <p>I want to repeat the loop, but no wonder I input Y or N, the loop will also repeat. Suppose the loop should repeat when I input 'Y' or 'y'. Can anyone tell me what's wrong with my code?</p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; using namespace std; double calculate_inflation(double, double); int main() { double yearAgo_price; double currentYear_price; double inflation_Rate; char again; do{ cout &lt;&lt; "Enter the item price one year ago (or zero to quit) : " &lt;&lt; endl; cin &gt;&gt; yearAgo_price; cout &lt;&lt; "Enter the item price today: " &lt;&lt; endl; cin &gt;&gt; currentYear_price; cout.setf(ios::fixed) cout.setf(iOS::showpoint); cout.precision(2); inflation_rate=calculate_inflation(yearAgo_price, currentYear_price); cout &lt;&lt; "The inflation rate is " &lt;&lt; (inflation_rate*100) &lt;&lt; " percent." &lt;&lt; endl; cout &lt;&lt; "Do you want to continue (Y/N)?" &lt;&lt; endl; cin &gt;&gt; again; }while((again =='Y') || (again =='y')); return 0; } double calculate_inflation (double yearAgo_price, double currentYear_price) { return ((currentYear_price-yearAgo_price)/ yearAgo_price); } </code></pre>
2
'NoneType' object has no attribute '_fields' (odoo)
<p>I am using Odoo v9 to create a website, when someone navigates to one of the pages in my website (/order/time), he gets the error detailed below.</p> <p>Model:</p> <pre><code>from openerp import models, fields, api class odss_sale_order(models.Model): _name = "_order" order_date = fields.Text(required=True) </code></pre> <p>The Important Part of the View:</p> <pre><code>&lt;div class="row form-group"&gt; &lt;div class="input-group"&gt; &lt;div t-field="odss_order.order_date"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Error:</p> <blockquote> <p>'NoneType' object has no attribute '_fields'</p> </blockquote> <p>Traceback:</p> <blockquote> <p>Traceback (most recent call last): File "/opt/odoo/addons/website/models/ir_http.py", line 243, in _handle_exception response = super(ir_http, self)._handle_exception(exception) File "/opt/odoo/openerp/addons/base/ir/ir_http.py", line 157, in _handle_exception return request._handle_exception(exception) File "/opt/odoo/openerp/http.py", line 784, in _handle_exception return super(HttpRequest, self)._handle_exception(exception) File "/opt/odoo/openerp/addons/base/ir/ir_http.py", line 182, in _dispatch result = request.dispatch() File "/opt/odoo/openerp/http.py", line 843, in dispatch r = self._call_function(**self.params) File "/opt/odoo/openerp/http.py", line 319, in _call_function return checked_call(self.db, *args, **kwargs) File "/opt/odoo/openerp/service/model.py", line 118, in wrapper return f(dbname, *args, **kwargs) File "/opt/odoo/openerp/http.py", line 315, in checked_call result.flatten() File "/opt/odoo/openerp/http.py", line 1444, in flatten self.response.append(self.render()) File "/opt/odoo/openerp/http.py", line 1437, in render context=request.context) File "/opt/odoo/openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/addons/website/models/ir_ui_view.py", line 166, in render return super(view, self).render(cr, uid, id_or_xml_id, values=values, engine=engine, context=context) File "/opt/odoo/openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/addons/web_editor/models/ir_ui_view.py", line 29, in render return super(view, self).render(cr, uid, id_or_xml_id, values=values, engine=engine, context=context) File "/opt/odoo/openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/openerp/addons/base/ir/ir_ui_view.py", line 1074, in render return self.pool[engine].render(cr, uid, id_or_xml_id, qcontext, loader=loader, context=context) File "/opt/odoo/openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 254, in render return self.render_node(element, qwebcontext, generated_attributes=qwebcontext.pop('generated_attributes', ''))<br> File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 297, in render_node result = self.render_element(element, template_attributes, generated_attributes, qwebcontext) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 320, in render_element generated_attributes= name == "t" and generated_attributes or '')) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 295, in render_node result = self._render_tag[t_render](self, element, template_attributes, generated_attributes, qwebcontext) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 448, in render_tag_call d[0] = self.render_element(element, template_attributes, generated_attributes, d) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 320, in render_element generated_attributes= name == "t" and generated_attributes or '')) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 297, in render_node result = self.render_element(element, template_attributes, generated_attributes, qwebcontext) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 320, in render_element generated_attributes= name == "t" and generated_attributes or '')) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 297, in render_node result = self.render_element(element, template_attributes, generated_attributes, qwebcontext) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 320, in render_element generated_attributes= name == "t" and generated_attributes or '')) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 297, in render_node result = self.render_element(element, template_attributes, generated_attributes, qwebcontext) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 320, in render_element generated_attributes= name == "t" and generated_attributes or '')) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 297, in render_node result = self.render_element(element, template_attributes, generated_attributes, qwebcontext) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 320, in render_element generated_attributes= name == "t" and generated_attributes or '')) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 297, in render_node result = self.render_element(element, template_attributes, generated_attributes, qwebcontext) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 320, in render_element generated_attributes= name == "t" and generated_attributes or '')) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 297, in render_node result = self.render_element(element, template_attributes, generated_attributes, qwebcontext) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 320, in render_element generated_attributes= name == "t" and generated_attributes or '')) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 297, in render_node result = self.render_element(element, template_attributes, generated_attributes, qwebcontext) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 320, in render_element generated_attributes= name == "t" and generated_attributes or '')) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 297, in render_node result = self.render_element(element, template_attributes, generated_attributes, qwebcontext) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 325, in render_element raise_qweb_exception(message="Could not render element %r" % element.tag, node=element, template=template) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 320, in render_element generated_attributes= name == "t" and generated_attributes or '')) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 295, in render_node result = self._render_tag[t_render](self, element, template_attributes, generated_attributes, qwebcontext) File "/opt/odoo/openerp/addons/base/ir/ir_qweb.py", line 503, in render_tag_field field = record._fields[field_name] QWebException: 'NoneType' object has no attribute '_fields'</p> </blockquote> <p>QWeb:</p> <pre><code>Could not render element 'div' The error occured while rendering the template 900 &lt;div class="input-group"&gt; &lt;div t-field="odss_sale_order.order_date"/&gt;&lt;/div&gt; </code></pre> <p>What is the problem, and how do I fix it?</p> <p>Thanks in advance, Hamza Tahboub</p>
2
How to fill PDF form in Django/Python?
<p>I'm trying to fill pre-made pdf form with database data and flatten it. For example, if the user inputs a field called "name", it should be placed in the name field of the pdf form.</p>
2
filter words that contain some letters in a specific order
<p>In Python, I would like to search through a dictionary such as the Scrabble official list and identify all the words with x number of characters in a particular order. For example, I have "mmt" and would like the output to generate a list of words such as what you see below. </p> <p>"mmt":</p> <ul> <li>A<strong>M</strong>ALGA<strong>M</strong>A<strong>T</strong>ED</li> <li>A<strong>MM</strong>ONIA<strong>T</strong>ED</li> <li>CIRCU<strong>M</strong>A<strong>M</strong>BULA<strong>T</strong>ED</li> <li>CO<strong>MM</strong>EN<strong>T</strong>ATED</li> </ul> <p>Thank you!!</p>
2
java application running on tomcat. Unable to access over ajp.
<p>Application is accessible over tomcat http port. Application when accessed from web server(Apache http server) gives bad gateway error. worker.properties(apache http server) &amp; server.xml(tomcat) are tuned well. Socket/connection timeout is 20 sec on both sides.</p> <p>Jk.log shows below error. <a href="http://i.stack.imgur.com/12xjp.png" rel="nofollow">enter image description here</a></p> <p>The error says tomcat is not accepting any connections. But how come at the same time, application is accessible over http.</p> <p>On tomcat side I dont see any errors in the log. </p>
2
Powerbuilder 11.2 has stopped working Windows 64 bit
<p>I am running and supporting a PowerBuilder 11.2 application running in windows 7 64bit environment. The previous version of this program ran without a problem, and 99% of this new program runs without a problem. However, when I run a specific bit of functionality, at times the program throws an exception "Sybase PowerBuilder 11.0 has stopped working" Problem event name APPCRASH Application Name PB110.EXE, Fault Module Name PBSHR110.dll, Exception code c0000005 in the dev environment. In the compiled version running on the client machine the error "A breakpoint in an application indicates a program error. After this dialog is dismissed, the application will continue to run, but it may be in an unstable state" and the program closes</p> <p>There are shared PBL files throughout this whole application. It is a framework that supports 6 MDI programs. I have performed a full build on the main objects and it compiles without error. The other programs that in the framework that use these common objects to not have this problem. I have tried to step through the code doing a debug, but when I step through the code, it does not crash.</p> <p>I have re-installed PB 11.0 and the PB 11.2 upgrade again and of course rebooted numerous times. I am at a loss here. I have tried everything that worked before and have spent over a week trying to find something online, so I am now appealing to the group. Any help at all will be so very much appreciated. Until then, I'll keep trying.</p> <p>Thanks.</p> <p>John</p>
2
Changing all markers icons except for the one clicked on in Google Maps
<p>I need to set up a map with several markers.</p> <p>I know it is possible to change the icon marker on click, and to change the icon marker on click on an external link. I would like to know if it is possible with the Google Maps API do to the following :</p> <ul> <li>On clic on a marker, changing the icons of <strong>all other markers</strong> (in order to have the marker I clicked on be on highlight and the others fade) ? </li> <li>On clic on an element, change the icon of <strong>all other markers</strong> (for exemple, clicking on "show event" would put the corresponding marker on highlight and the others would fade) ?</li> </ul> <p>Thank you !</p>
2
"Reverse" wrong parsed date
<p>we run a REST-webservice which consumes different data, my current issue belongs to a date, received as String and parsed by a java.text.SimpleDateFormat (java 8):</p> <p>We received a lot (>50k) of 'wrong' formatted Strings, which were parsed by the SimpleDateFormat anyways.</p> <p>The SimpleDateFormat is configured with the pattern "yyyy-MM-dd". We received Strings the other way around "dd-MM-yyyy".</p> <p>For Example the String "07-07-1950" was parsed to the date "0012-10-31" (Starting from July in year 7, added 1950 days).</p> <p>We fixed the implementation, so these Strings are now parsed as expected. But we have all the corrupt dates in the system. The final question is now:</p> <p>Is there a way to conclude from the date "0012-10-31" to possible original inputs (e.g. "07-07-1950", "07-06-1980" and maybe more...)?</p> <p>Best regards</p>
2
How to publish a Xamarin.Forms App on Windows?
<p>I have developed a cross-platform application in Visual Studio 2015, with Xamarin.Forms. My application is ok and works on Visual Studio. </p> <p>What I want is very basic but I can't find how to do it. I need to give this application to my friend because I want him to test it on Windows, but I do not want to give him Visual Studio. I'd expect to be able to give him a .exe file or something like that.</p> <p>How can I do that ?</p>
2
Can I import .csv files based on a partial filename?
<p>So the data that I need to work with comes as a set of 10 .csv files each with names of the following format:</p> <p>Example_datatype_date_IDnumber.csv</p> <p>Each of the 10 files requires different manipulation/analysis and I'd like to do it all with one python script. I can do it successfully with pandas but the issue is that every time I get a new set I have to go in and manually change the date and ID number in the filename when I import the file. Is there a way to import the files and ignore the date and ID number (differentiate only based on datatype)? I would just create a new folder/directory for each set of 10.</p>
2
Handling code/configuration error from entry action classes in spring state machine
<p>I am using a state machine builder to build state machine in my app. Also the application has Action classes which implements org.springframework.statemachine.action.Action. These Action classes are for executing entry actions for each stages. If any exception is thrown from these Action classes, ie from execute(StateContext paramStateContext) method, I wanted to catch that exception and send an event(Terminated) and drive the state machine to End state, after updating the db with error details. I tried to use state machine listener by overriding stateMachineError(StateMachine stateMachine, Exception e) method. But unfortunately this is not working. Any other spring state machine component to catch exceptions, before I go to wrap the entire code in Action classes with try catch, and inside catch block sending the Terminated event so that state machine would navigate End state. Here is the builder Iam using.</p> <pre><code>Builder&lt;String, String&gt; builder = StateMachineBuilder .&lt;String, String&gt; builder(); builder.configureConfiguration() .withConfiguration() .autoStartup(false) .listener(listener()) .beanFactory( this.applicationContext.getAutowireCapableBeanFactory()); </code></pre> <hr> <pre><code>private StateMachineListener&lt;String, String&gt; listener() { return new StateMachineListenerAdapter&lt;String, String&gt;() { @Override public void stateChanged( org.springframework.statemachine.state.State&lt;String, String&gt; from, org.springframework.statemachine.state.State&lt;String, String&gt; to) { LOGGER.debug("State change to " + to.getId()); } @Override public void stateMachineError( StateMachine&lt;String, String&gt; stateMachine, Exception e) { e.printStackTrace(); LOGGER.debug("Ah... I am not getting executed when exception occurs from entry actions"); LOGGER.debug("Error occured from " + stateMachine.getState() + "and the error is" + e.toString()); } }; } </code></pre> <p>Iam using 1.1.0.RELEASE version of spring-statemachine-core</p>
2
StringFormat in GroupBox header binding doesn't seem to work
<p>I'm trying to bind the header text of a<code>GroupBox</code> to a property and display it using <code>StringFormat</code>.</p> <p>The first part works and it returns the text as expected. But I want the final text to be formatted. For example when I return <code>cm</code> I want it to be displayed as <code>Foundation Height (cm)</code>, but the code below only shows <code>cm</code>.</p> <pre><code>&lt;GroupBox Header="{Binding CurrentTargetUnit, Converter={StaticResource QuantityToTextConverter}, ConverterParameter={x:Static enumerations:Quantity.Length}, StringFormat='Foundation Height ({0})'}"&gt; &lt;/GroupBox&gt; </code></pre>
2
Changing dataframes in Loop r
<p>I have many dataframes that I would like to run though a code. Is there a way to change the dataframe name in a loop?</p> <pre><code>df01$x = rnorm(100) df02$x = rnorm(100)+2 df03$x = rnorm(100)*2 dflist &lt;- c("df01", "df02", "df03") for (i in 1:length(dflist){ { #complete tasks by changing df name in existing code ifelse([[i]]$x &gt; 0,1,[[i]]$x) } #I want to do this for a number of different fuctions, so it is best to change the df name before "$" df[[i]]$Varible = aggregate(df$Varible, .. ,..)} </code></pre>
2
Serial Execution of Promise
<p>I would like to execute a function with a parameter looping from an array of values. Every execution must waits the previous to be completed. The example code below should print:</p> <pre><code>Done: 1 Done: 2 Done: 3 Done: 4 Done: 5 </code></pre> <p>Thanks!</p> <p>p.</p> <pre class="lang-js prettyprint-override"><code>'use strict'; function f1(value) { return new Promise((resolve, reject) =&gt; { setTimeout(function() { console.log('Done: ' + value); resolve(true) }, Math.random() * 2000 + 1000); }); } const vs = [0,1,2,3,4,5]; vs.reduce((start, next) =&gt; { return f1(next) }) </code></pre>
2
What goes in the main method of JUnit test classes?
<p>What is supposed to go in the main method for JUnit test classes? This is one example I use but don't really understand it and am curious to other options?</p> <pre><code>public static void main(String[] args) { junit.textui.TestRunner.run(new JUnit4TestAdapter(InflectionPointTest.class)); } </code></pre> <p>I'm focusing on learning it from Notepad++ but noticed Netbeans uses JUnit without even having a main method in the class.</p>
2
CSS Hover over div to change another div's element
<p>So i am trying to change the element of a different div using the :hover effect in CSS.</p> <p>If you check my code you should understand what I am trying to accomplish.</p> <p>When you hover over the project button i would like the slider-container to have the text 'projects' and so on for all of the buttons</p> <p>I understand that the button needs to be before the slider container which it is, so i really don't understand why this is not working?</p> <p>If anybody could either direct me to a better tutorial on using this hover effect and help me understand what the issue is i would be really appreciative.</p> <p>Thanks Guys! :)</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#content { position: relative; overflow: hidden; width: 900px; height: 440px; background: #D5D5D5; margin: auto; top: 50px; left: 0; bottom: 0; right: 0; -webkit-box-shadow: 0px 0px 23px 3px rgba(0,0,0,0.75); -moz-box-shadow: 0px 0px 23px 3px rgba(0,0,0,0.75); box-shadow: 0px 0px 23px 3px rgba(0,0,0,0.75); } .logo-container{ display: flex; flex-direction: row; position: relative; width: 100%; height: 100px; justify-content: center; margin: auto; float: right; top: 0px; } .blockicon { position: relative; width: 50px; height: 50px; top: 15px; border-radius: 50%; border: solid 5px black; cursor: pointer; font-size: 30px; text-align: center; vertical-align: middle; line-height: 50px; margin: 0 0.8%; } .projects { background: #801113; } .projects:hover &gt; .slider-container { background: #801113; } .projects:hover &gt; .slider-container:before { content:"Projects"; } .aboutme { background: #1A8305; } .aboutme:hover &gt; .slider-container { background: #1A8305; } .aboutme:hover &gt; .slider-container:before { content:"About Me"; } .contactme { background: #E8BA1A; } .contactme:hover &gt; .slider-container { background: #E8BA1A; } .contactme:hover &gt; .slider-container:before { content:"Contact Me"; } .helped { background: #0049BB; } .helped:hover &gt; .slider-container { background: #0049BB; } .helped:hover &gt; .slider-container:before { content:"Helped"; } .hobbys { background: #A40CA3; } .hobbys:hover &gt; .slider-container { background: #A40CA3; } .hobbys:hover &gt; .slider-container:before { content:"Hobbys"; } .slider-container { position:absolute; background: #CF4000; width: 95%; height: 320px; margin: auto; top: 400px; left: 0; bottom: 0; right: 0; } .slider-container:before { position:absolute; content:"Test"; font-size: 30px; bottom: 20%; left: 40%; font-family: Aldrich; padding: 0; font-weight: bold; color: white; z-index: 999; } @media screen and (max-width: 900px) { #content { width: 100%; } #content-container { width: 100%; } #footer { width: 100%; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="content"&gt; &lt;div class="logo-container"&gt; &lt;div class="blockicon projects"&gt; P &lt;/div&gt; &lt;div class="blockicon aboutme"&gt; A &lt;/div&gt; &lt;div class="blockicon contactme"&gt; C &lt;/div&gt; &lt;div class="blockicon helped"&gt; H &lt;/div&gt; &lt;div class="blockicon hobbys"&gt; H &lt;/div&gt; &lt;div class="slider-container"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
2
OSGi Http Whiteboard pattern
<p>Moving from web.xml to OSGi Http Whiteboard pattern created bundle-context.xml how to pass below properties from web.xml in jspServletfilter's osgi:service-properties</p> <pre><code> &lt;jsp-config&gt; &lt;jsp-property-group&gt; &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt; &lt;el-ignored&gt;true&lt;/el-ignored&gt; &lt;/jsp-property-group&gt; &lt;/jsp-config&gt; </code></pre> <p>I tried below solution but it does not work.</p> <pre><code>&lt;bean id="jspServlet" class="com.test.servlet.web.servlet.TestJSPServlet"/&gt; &lt;osgi:service ref="jspServlet" interface="javax.servlet.Servlet" &gt; &lt;osgi:service-properties&gt; &lt;entry key="osgi.http.whiteboard.filter.name" value="JSPServlet" /&gt; &lt;entry key="osgi.http.whiteboard.servlet.pattern" value-ref="jspPatternsList"/&gt; &lt;entry key="osgi.http.whiteboard.context.select" value="(osgi.http.whiteboard.context.name=cb)" /&gt; &lt;entry key="servlet.init.el-ignored" value="true" /&gt; &lt;/osgi:service-properties&gt; &lt;/osgi:service&gt; </code></pre>
2
Telegram bot api inlineKeyboard not worked
<p>I use <a href="https://github.com/yagop/node-telegram-bot-api" rel="nofollow">node_telegram_bot_api</a> for my Telegram bot. I create an inline keyboard buttons : </p> <pre><code>var bot = new loader.Bot(config.botToken,{polling:true}); var options = { reply_markup: JSON.stringify({ inline_keyboard: [ [{text: 'Some button text 1', callback_data: '1'}], // Clicking will send "1" [{text: 'Some button text 2', callback_data: '2'}], // Clicking will send "2" [{text: 'Some button text 3', callback_data: '3'}] // Clicking will send "3" ] }) }; bot.sendMessage(msg.from.id, "Click a button to display data", options); </code></pre> <p>And I told a callback_query function for listen to click the buttons:</p> <pre><code>bot.on('callback_query', function(msg) { var user = msg.from.id; var data = msg.data; bot.sendMessage(msg.from.id, "You clicked button with data '"+ data +"'"); }); </code></pre> <p>After clicking on the buttons this function is not implemented. Can you help me?</p>
2
How to read data from a text file/dat file,Dynamically create columns and load the data into a data table using c#
<p>How to load data from a text/dat file into a data table in c#,Here i need to dynamically generate columns based on the data in a text file.</p>
2
In netty, how we can send string messages with different arbitrary length?
<p>I want to send string message by netty. To do that I need to use StringDecoder and encoder as follows: </p> <pre><code> ch.pipeline().addLast("frameDecoder", new LineBasedFrameDecoder(**maxLength**)); ch.pipeline().addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8)); // Encoder ch.pipeline().addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8)); </code></pre> <p>It is nice, but the only part that make me disappointed in the maxLengh?! I don't know the maximum size of my string messages? Why it needs that, it can find string by a delimiter or \r\n why it need the maxLength? </p> <p>Is there any way to send string messages without specifying a length for them? And by the way, if I set the limit to a large number, and only use the small portion, do I loose anything? Am I wasting space? </p> <p>I am writing a distributed key-value store, servers in my system replicate new write to each other, I don't know how large is a the value of a key. </p> <p>Thanks</p>
2
Apply and lubridate
<p>I have a problem with dates convertion. If I use ymd in apply, it returns a numeric, or if I use only ymd it's works. Someone would have any idea ?</p> <pre><code>library(lubridate) a &lt;- data.frame(dates1=c("2011-01-01",'2011-02-01','2011-03-01'), dates2=c("2013-01-01",'2013-02-01','2013-03-01')) apply(a, 2, FUN = function(x) ymd(x)) dates1 dates2 [1,] 1293840000 1356998400 [2,] 1296518400 1359676800 [3,] 1298937600 1362096000 ymd(a$dates1) [1] "2011-01-01 UTC" "2011-02-01 UTC" "2011-03-01 UTC" ymd(a$dates2) [1] "2013-01-01 UTC" "2013-02-01 UTC" "2013-03-01 UTC" </code></pre>
2
Angular - Open a view in a modal
<p>I built my login page as a view using angularjs which is perfectly working, now I want to open the same screen but using a modal. In order to open that modal from any page without being redirected to another screen. Is that possible? Can I reuse the code in that view/controller? Or I should create a different screen? If I need to create a new screen for the modal, could you point me to the right direction for that?</p>
2
How to integrate Azure media player in android
<p>I have a manifest streaming url which I have to play. How can I integrate azure media player in android to play the streaming video? </p>
2
MySQL date column in phpmyadmin
<p>I'm building registration form for my teacher's website. I have created database called "students" with various rows like "name, surname etc." Now I would like to add a column named "date_submitted" which will automatically insert current date and time to the row when data is submitted.</p> <p>For example a student submits his data, the data is inserted into the table and mysql automatically fills the date and time when this insertion occured.</p> <p>I tried @MLBDG answer from this question <a href="https://stackoverflow.com/questions/21226571/mysql-date-column-auto-fill-with-current-date">MySQL date column auto fill with current date</a> but it doesn't work.</p> <p>This is the way I do it: <a href="https://i.stack.imgur.com/LUcoD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LUcoD.png" alt="enter image description here"></a> Query:</p> <pre><code>ALTER TABLE `students` ADD `date_submitted` TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER ; </code></pre> <p>The error I'm receiving:</p> <p><em>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1</em> </p> <p>Server version: 5.5.34 - MySQL Community Server (GPL)</p>
2
Apply GPUImage filter to part of video
<p>I want to add two filters to one video, so half of the screen shows one filter and the other half another filter. But they should be applied to the same video, just on different parts of the screen.</p> <p>Is it possible to do with GPUImage? If not, what are the alternatives?</p> <p><a href="https://i.stack.imgur.com/ERbET.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ERbET.png" alt="enter image description here"></a></p>
2
How to find the key for a JSON value
<p>I have a JSON string <code>"{name :\"daijiepei\"}"</code>. I'm using a JObject to deserialize it: </p> <pre><code>JObject json = JObject.Parse(str); string value = obj["name"]; </code></pre> <p>So I can get the value, but I can't get the JSON key. How do I get the key for a JSON value?</p>
2
Adding Color to new style ipython (v5) prompt
<p>Update to the newly release ipython5 today. Started up the interactive prompt and received:</p> <pre><code>/usr/local/lib/python3.5/site-packages/IPython/core/interactiveshell.py:440: UserWarning: As of IPython 5.0 `PromptManager` config will have no effect and has been replaced by TerminalInteractiveShell.prompts_class warn('As of IPython 5.0 `PromptManager` config will have no effect' </code></pre> <p>Yanked out my old config settings to customize and colorize the prompt and went looking for the new way to customize the prompt and found it, very cool. Used the new class style from the <a href="http://ipython.readthedocs.io/en/latest/config/details.html#custom-prompts" rel="noreferrer">example code</a>:</p> <pre><code>class MyPrompt(Prompts): def in_prompt_tokens(self, cli=None): return [(Token, os.getcwd()), (Token.Prompt, ' &gt;&gt;&gt;')] </code></pre> <p>Put this into a startup script and it works great, except it by default doesn't colorize the Token line, the Token.Prompt is made light green. </p> <p>Attempted to use the old config method colors, (r'{color.Green}') but that doesn't work here. Any pointers in the correct direction would be great.</p> <p>Thanks! </p>
2
C# Reflection Delegate exception: Must derive from Delegate
<p>I'm trying to understand delegations so I just wrote small try project; I have class D:</p> <pre><code>class D { private static void Func1(Object o) { if (!(o is string)) return; string s = o as string; Console.WriteLine("Func1 going to sleep"); Thread.Sleep(1500); Console.WriteLine("Func1: " + s); } } </code></pre> <p>and in the main im using:</p> <pre><code> MethodInfo inf = typeof(D).GetMethod("Func1", BindingFlags.NonPublic | BindingFlags.Static); Delegate d = Delegate.CreateDelegate(typeof(D), inf); </code></pre> <p>The method info gets the correct info but the CreateDelegate method throws an exception, saybg that the type must derive from Delegate.</p> <p>How can i solve this?</p>
2
How to get correct decimal answer in java
<p>Eg: I divide manually <code>8/3 = 2.666666</code>.</p> <p>When I divide in Java, I've got <code>8/3 = 2.0</code> instead.</p> <p>How can I get the answer to display <code>2.667</code> or <code>2.67</code>?</p> <p>Thank you.</p>
2
Error while installing APC
<p>I am getting following error while installing APC</p> <p>I also followed the guidelines mentioned at <a href="https://wiki.bitnami.com/Components/PHP#How_to_install_APC_module.3f" rel="noreferrer">https://wiki.bitnami.com/Components/PHP#How_to_install_APC_module.3f</a> but same error.</p> <p>I am trying to install it in a Bitnami Image for Wordpress in Google App Engine.</p> <pre><code> pecl install apc WARNING: configuration download directory "/tmp/pear/download" is not writeable. Change download_dir config variable to a writeable dir to avoid this warning Cannot install, php_dir for channel "pecl.php.net" is not writeable by the current user user@edudrona-prod-vm:~$ sudo pecl install apc downloading APC-3.1.13.tgz ... Starting to download APC-3.1.13.tgz (171,591 bytes) .....................................done: 171,591 bytes 55 source files, building running: phpize Configuring for: PHP Api Version: 20151012 Zend Module Api No: 20151012 Zend Extension Api No: 320151012 Enable internal debugging in APC [no] : Enable per request file info about files used from the APC cache [no] : Enable spin locks (EXPERIMENTAL) [no] : Enable memory protection (EXPERIMENTAL) [no] : Enable pthread mutexes (default) [no] : Enable pthread read/write locks (EXPERIMENTAL) [yes] : building in /tmp/pear/temp/pear-build-rootJudBGM/APC-3.1.13 running: /tmp/pear/temp/APC/configure --with-php-config=/opt/bitnami/php/bin/php-config --enable-apc-debug=no --enable-apc-filehits=no --enable-apc-spinlocks=no --enable-apc-memprotect=no --enable-apc-pthreadmutex=no --enable-apc-pthreadrwlocks=yes checking for grep that handles long lines and -e... /bin/grep checking for egrep... /bin/grep -E checking for a sed that does not truncate output... /bin/sed checking for cc... cc checking whether the C compiler works... yes checking for C compiler default output file name... a.out checking for suffix of executables... checking whether we are cross compiling... no checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether cc accepts -g... yes checking for cc option to accept ISO C89... none needed checking how to run the C preprocessor... cc -E checking for icc... no checking for suncc... no checking whether cc understands -c and -o together... yes checking for system library directory... lib checking if compiler supports -R... no checking if compiler supports -Wl,-rpath,... yes checking build system type... x86_64-unknown-linux-gnu checking host system type... x86_64-unknown-linux-gnu checking target system type... x86_64-unknown-linux-gnu checking for PHP prefix... /opt/bitnami/php checking for PHP includes... -I/opt/bitnami/php/include/php -I/opt/bitnami/php/include/php/main -I/opt/bitnami/php/include/php/TSRM -I/opt/bitnami/php/include/php/Zend -I/opt/bitnami/php/include/php/ext -I/opt/bitnami/php/include/php/ext/date/lib checking for PHP extension directory... /opt/bitnami/php/lib/php/extensions checking for PHP installed headers prefix... /opt/bitnami/php/include/php checking if debug is enabled... no checking if zts is enabled... no checking for re2c... re2c checking for re2c version... 0.13.5 (ok) checking for gawk... gawk checking whether to enable APC support... yes, shared checking whether we should enable cache request file info... no checking whether we should use mmap... yes checking whether we should use semaphore locking instead of fcntl... no checking whether we should use pthread mutex locking... no checking whether we should use pthread read/write locking... yes pthread rwlocks are supported! checking whether the target compiler supports builtin atomics... yes checking whether we should use spin locks... no checking whether we should enable memory protection... no checking for zend_set_lookup_function_hook... no checking for sigaction... yes checking for union semun... no checking whether we should enable valgrind support... checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes yes checking valgrind/memcheck.h usability... no checking valgrind/memcheck.h presence... no checking for valgrind/memcheck.h... no checking for shm_open in -lrt... yes checking whether to include code coverage symbols... no checking for ld used by cc... /usr/bin/ld checking if the linker (/usr/bin/ld) is GNU ld... yes checking for /usr/bin/ld option to reload object files... -r checking for BSD-compatible nm... /usr/bin/nm -B checking whether ln -s works... yes checking how to recognize dependent libraries... pass_all checking dlfcn.h usability... yes checking dlfcn.h presence... yes checking for dlfcn.h... yes checking the maximum length of command line arguments... 1572864 checking command to parse /usr/bin/nm -B output from cc object... ok checking for objdir... .libs checking for ar... ar checking for ranlib... ranlib checking for strip... strip checking if cc supports -fno-rtti -fno-exceptions... no checking for cc option to produce PIC... -fPIC checking if cc PIC flag -fPIC works... yes checking if cc static flag -static works... yes checking if cc supports -c -o file.o... yes checking whether the cc linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes checking whether -lc should be explicitly linked in... no checking dynamic linker characteristics... GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether stripping libraries is possible... yes checking if libtool supports shared libraries... yes checking whether to build shared libraries... yes checking whether to build static libraries... no creating libtool appending configuration tag "CXX" to libtool configure: creating ./config.status config.status: creating config.h running: make /bin/bash /tmp/pear/temp/pear-build-rootJudBGM/APC-3.1.13/libtool --mode=compile cc -D_GNU_SOURCE -I. -I/tmp/pear/temp/APC -DPHP_ATOM_INC -I/tmp/pear/temp/pear-build-rootJudBGM/APC-3.1.13/include -I/tmp/pear/temp/pear-build-rootJudBGM/APC-3.1.13/main -I/tmp/pear/temp/APC -I/opt/bitnami/php/include/php -I/opt/bitnami/php/include/php/main -I/opt/bitnami/php/include/php/TSRM -I/opt/bitnami/php/include/php/Zend -I/opt/bitnami/php/include/php/ext -I/opt/bitnami/php/include/php/ext/date/lib -DHAVE_CONFIG_H -I/opt/bitnami/common/include -c /tmp/pear/temp/APC/apc.c -o apc.lo mkdir .libs cc -D_GNU_SOURCE -I. -I/tmp/pear/temp/APC -DPHP_ATOM_INC -I/tmp/pear/temp/pear-build-rootJudBGM/APC-3.1.13/include -I/tmp/pear/temp/pear-build-rootJudBGM/APC-3.1.13/main -I/tmp/pear/temp/APC -I/opt/bitnami/php/include/php -I/opt/bitnami/php/include/php/main -I/opt/bitnami/php/include/php/TSRM -I/opt/bitnami/php/include/php/Zend -I/opt/bitnami/php/include/php/ext -I/opt/bitnami/php/include/php/ext/date/lib -DHAVE_CONFIG_H -I/opt/bitnami/common/include -c /tmp/pear/temp/APC/apc.c -fPIC -DPIC -o .libs/apc.o In file included from /tmp/pear/temp/APC/apc_main.h:38:0, from /tmp/pear/temp/APC/apc_compile.h:43, from /tmp/pear/temp/APC/apc_cache.h:40, from /tmp/pear/temp/APC/apc.c:36: /tmp/pear/temp/APC/apc_serializer.h: In function ‘apc_register_serializer’: /tmp/pear/temp/APC/apc_serializer.h:45:33: warning: passing argument 1 of ‘zend_get_constant’ from incompatible pointer type #define APC_SERIALIZER_CONSTANT "\000apc_register_serializer-" APC_SERIALIZER_ABI ^ /tmp/pear/temp/APC/apc_serializer.h:64:27: note: in expansion of macro ‘APC_SERIALIZER_CONSTANT’ if (zend_get_constant(APC_SERIALIZER_CONSTANT, sizeof(APC_SERIALIZER_CONSTANT)-1, &amp;apc_magic_constant TSRMLS_CC)) { ^ In file included from /opt/bitnami/php/include/php/main/php.h:396:0, from /tmp/pear/temp/APC/apc.h:61, from /tmp/pear/temp/APC/apc.c:34: /opt/bitnami/php/include/php/Zend/zend_constants.h:68:16: note: expected ‘struct zend_string *’ but argument is of type ‘char *’ ZEND_API zval *zend_get_constant(zend_string *name); ^ In file included from /tmp/pear/temp/APC/apc_main.h:38:0, from /tmp/pear/temp/APC/apc_compile.h:43, from /tmp/pear/temp/APC/apc_cache.h:40, from /tmp/pear/temp/APC/apc.c:36: /tmp/pear/temp/APC/apc_serializer.h:64:9: error: too many arguments to function ‘zend_get_constant’ if (zend_get_constant(APC_SERIALIZER_CONSTANT, sizeof(APC_SERIALIZER_CONSTANT)-1, &amp;apc_magic_constant TSRMLS_CC)) { ^ In file included from /opt/bitnami/php/include/php/main/php.h:396:0, from /tmp/pear/temp/APC/apc.h:61, from /tmp/pear/temp/APC/apc.c:34: /opt/bitnami/php/include/php/Zend/zend_constants.h:68:16: note: declared here ZEND_API zval *zend_get_constant(zend_string *name); ^ In file included from /tmp/pear/temp/APC/apc.c:36:0: /tmp/pear/temp/APC/apc_cache.h: At top level: /tmp/pear/temp/APC/apc_cache.h:136:9: error: unknown type name ‘zend_uint’ zend_uint *exec_refcount; /* refcount member of zend_op_array refreshed before execution */ ^ /tmp/pear/temp/APC/apc.c:47:43: fatal error: ext/standard/php_smart_str.h: No such file or directory # include "ext/standard/php_smart_str.h" ^ compilation terminated. Makefile:195: recipe for target 'apc.lo' failed make: *** [apc.lo] Error 1 ERROR: `make' failed </code></pre>
2
Table caption width in firefox
<p>The table on this page has a caption with display: table-caption set.</p> <p><a href="http://www.petersen-stainless.co.uk/lifting/CE-swage-sockets/stainless-steel-threaded-sockets.html" rel="nofollow">http://www.petersen-stainless.co.uk/lifting/CE-swage-sockets/stainless-steel-threaded-sockets.html</a></p> <p>The HTML is:</p> <pre><code>&lt;table class="product-data"&gt; &lt;caption&gt; Rated for lifting in accordance with EN 13411-8. WLLs stated based on 90% of wire MBL at a 6:1 factor of safety. All terminals permanently etched with CE mark and batch identification number. &lt;/caption&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td data-th="Product Code"&gt;SCM6X3R-EN&lt;/td&gt; &lt;td data-th="Wire (mm)"&gt;3&lt;/td&gt; &lt;td data-th="Thread"&gt;M6&lt;/td&gt; &lt;td data-th="D (mm)"&gt;6.3&lt;/td&gt; &lt;td data-th="L (mm)"&gt;97.0&lt;/td&gt; &lt;td data-th="CT (mm)"&gt;47.0&lt;/td&gt; &lt;td data-th="WLL 7x19 / 6x19-IWRC"&gt;70kg&lt;/td&gt; &lt;td data-th="WLL 6x36-IWRC"&gt;N/A&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;` </code></pre> <p>And the css I used:</p> <pre><code>.content .product-data { float: left; margin-right: 20px; width: 70% } .product-data caption { display: table-caption; width: 100%; margin-bottom: 2em; border: 1px solid #ccc; box-sizing: border-box; border-top: none; } </code></pre> <p>It displays at 100% width of the table in webkit browsers but in firefox it is 100% width of the page. How can i get this caption to fit properly in firefox? Is it a bug? It seems like it shouldnt be behaving this way. If so are there any work arounds? </p>
2
Error in using react-bootstrap
<p>I'm using React-bootstrap package on my Keystone.JS project. To test I tried putting a button in my index page. However, I get the following warning: </p> <blockquote> <p><strong>Warning:</strong> Unknown props <code>bsStyle</code>, <code>active</code>, <code>block</code>, <code>navItem</code>, <code>navDropdown</code>, <code>bsClass</code> on tag. Remove these props from the element.</p> </blockquote> <p>This is the code where I use <code>Button</code>:</p> <pre><code>var React = require('react'); var Layout = require('../../layouts/defaultLayout'); var ReactDOMServer = require('react-dom/server'); var Button = require('react-bootstrap').Button; module.exports = React.createClass({ render: function () { return ( &lt;Button bsStyle="primary"&gt;Default button&lt;/Button&gt; ); } }); </code></pre> <p>What am I missing? Thanks for the help.</p>
2
Successfully enabling -fno-finite-math-only on NaN removal method
<p>In finding a bug which made everything turn into <code>NaN</code>s when running the optimized version of my code (compiling in <code>g++ 4.8.2</code> and <code>4.9.3</code>), I identified that the problem was the <code>-Ofast</code> option, specifically, the <code>-ffinite-math-only</code> flag it includes.</p> <p>One part of the code involves reading floats from a <code>FILE*</code> using <code>fscanf</code>, and then replacing all <code>NaN</code>s with a numeric value. As could be expected, however, <code>-ffinite-math-only</code> kicks in, and removes these checks, thus leaving the <code>NaN</code>s. </p> <p>In trying to solve this problem, I stumbled uppon <a href="https://stackoverflow.com/questions/22931147/stdisinf-does-not-work-with-ffast-math-how-to-check-for-infinity">this</a>, which suggested adding <code>-fno-finite-math-only</code> as a method attribute to disable the optimization on the specific method. The following illustrates the problem and the attempted fix (which doesn't actually fix it):</p> <pre><code>#include &lt;cstdio&gt; #include &lt;cmath&gt; __attribute__((optimize("-fno-finite-math-only"))) void replaceNaN(float * arr, int size, float newValue){ for(int i = 0; i &lt; size; i++) if (std::isnan(arr[i])) arr[i] = newValue; } int main(void){ const size_t cnt = 10; float val[cnt]; for(int i = 0; i &lt; cnt; i++) scanf("%f", val + i); replaceNaN(val, cnt, -1.0f); for(int i = 0; i &lt; cnt; i++) printf("%f ", val[i]); return 0; } </code></pre> <p>The code does not act as desired if compiled/run using <code>echo 1 2 3 4 5 6 7 8 nan 10 | (g++ -ffinite-math-only test.cpp -o test &amp;&amp; ./test)</code>, specifically, it outputs a <code>nan</code> (which should have been replaced by a <code>-1.0f</code>) -- it behaves fine if the <code>-ffinite-math-only</code> flag is ommited. Shouldn't this work? Am I missing something with the syntax for attributes in gcc, or is this one of the afforementioned "there being some trouble with some version of GCC related to this" (from the linked SO question)</p> <p>A few solutions I'm aware of, but would rather something a bit cleaner/more portable:</p> <ul> <li>Compile the code with <code>-fno-finite-math-only</code> (my interrim solution): I suspect that this optimization may be rather useful in my context in the remainder of the program; </li> <li>Manually look for the string <code>"nan"</code> in the input stream, and then replace the value there (the input reader is in an unrelated part of the library, yielding poor design to include this test there).</li> <li>Assume a specific floating point architecture and make my own <code>isNaN</code>: I may do this, but it's a bit hackish and non-portable.</li> <li>Prefilter the data using a separately compiled program without the <code>-ffinite-math-only</code> flag, and then feed that into the main program: The added complexity of maintaining two binaries and getting them to talk to each other just isn't worth it. </li> </ul> <hr> <p>Edit: As put in the accepted answer, It would seem this is a compiler "bug" in older versions of <code>g++</code>, such as <code>4.82</code> and <code>4.9.3</code>, that is fixed in newer versions, such as <code>5.1</code> and <code>6.1.1</code>. </p> <p>If for some reason updating the compiler is not a reasonably easy option (e.g.: no root access), or adding this attribute to a single function still doesn't completely solve the <code>NaN</code> check problem, an alternate solution, if you can be certain that the code will always run in an <code>IEEE754</code> floating point environment, is to manually check the bits of the float for a <code>NaN</code> signature. </p> <p>The accepted answer suggests doing this using a bit field, however, the order in which the compiler places the elements in a bit field is non-standard, and in fact, changes between the older and newer versions of <code>g++</code>, even refusing to adhere to the desired positioning in older versions (<code>4.8.2</code> and <code>4.9.3</code>, always placing the mantissa first), regardless of the order in which they appear in the code. </p> <p>A solution using bit manipulation, however, is guaranteed to work on all <code>IEEE754</code> compliant compilers. Below is my such implementation, which I ultimately used to solve my problem. It checks for <code>IEEE754</code> compliance, and I've extended it to allow for doubles, as well as other more routine floating point bit manipulations.</p> <pre><code>#include &lt;limits&gt; // IEEE754 compliance test #include &lt;type_traits&gt; // enable_if template&lt; typename T, typename = typename std::enable_if&lt;std::is_floating_point&lt;T&gt;::value&gt;::type, typename = typename std::enable_if&lt;std::numeric_limits&lt;T&gt;::is_iec559&gt;::type, typename u_t = typename std::conditional&lt;std::is_same&lt;T, float&gt;::value, uint32_t, uint64_t&gt;::type &gt; struct IEEE754 { enum class WIDTH : size_t { SIGN = 1, EXPONENT = std::is_same&lt;T, float&gt;::value ? 8 : 11, MANTISSA = std::is_same&lt;T, float&gt;::value ? 23 : 52 }; enum class MASK : u_t { SIGN = (u_t)1 &lt;&lt; (sizeof(u_t) * 8 - 1), EXPONENT = ((~(u_t)0) &lt;&lt; (size_t)WIDTH::MANTISSA) ^ (u_t)MASK::SIGN, MANTISSA = (~(u_t)0) &gt;&gt; ((size_t)WIDTH::SIGN + (size_t)WIDTH::EXPONENT) }; union { T f; u_t u; }; IEEE754(T f) : f(f) {} inline u_t sign() const { return u &amp; (u_t)MASK::SIGN &gt;&gt; ((size_t)WIDTH::EXPONENT + (size_t)WIDTH::MANTISSA); } inline u_t exponent() const { return u &amp; (u_t)MASK::EXPONENT &gt;&gt; (size_t)WIDTH::MANTISSA; } inline u_t mantissa() const { return u &amp; (u_t)MASK::MANTISSA; } inline bool isNan() const { return (mantissa() != 0) &amp;&amp; ((u &amp; ((u_t)MASK::EXPONENT)) == (u_t)MASK::EXPONENT); } }; template&lt;typename T&gt; inline IEEE754&lt;T&gt; toIEEE754(T val) { return IEEE754&lt;T&gt;(val); } </code></pre> <p>And the <code>replaceNaN</code> function now becomes:</p> <pre><code>void replaceNaN(float * arr, int size, float newValue){ for(int i = 0; i &lt; size; i++) if (toIEEE754(arr[i]).isNan()) arr[i] = newValue; } </code></pre> <p>An inspection of the assembly of these functions reveals that, as expected, all masks become compile-time constants, leading to the following (seemingly) efficient code:</p> <pre><code># In loop of replaceNaN movl (%rcx), %eax # eax = arr[i] testl $8388607, %eax # Check if mantissa is empty je .L3 # If it is, it's not a nan (it's inf), continue loop andl $2139095040, %eax # Mask leaves only exponent cmpl $2139095040, %eax # Test if exponent is all 1s jne .L3 # If it isn't, it's not a nan, so continue loop </code></pre> <p>This is one instruction less than with a working bit field solution (no shift), and the same number of registers are used (although it's tempting to say this alone makes it more efficient, there are other concerns such as pipelining which may make one solution more or less efficient than the other one).</p>
2
java Presenting an InputStream as a ByteBuffer without loading the whole thing into an array
<p>My application gets a large number of large InputStreams, and needs to hand them off to a driver expecting ByteBuffers. <a href="https://stackoverflow.com/questions/30026060/java-inputstream-to-bytebuffer">Java InputStream to ByteBuffer</a> recommends converting them to byte arrays first; however, that is expensive, and indeed ruins the whole point of using NIO. I'm looking for a way that a driver expecting a ByteBuffer can read from the InputStream as it needs to.</p> <p>In the case I'm dealing with, consuming the entire InputStream at once and turning it into an array is too expensive and wasteful.</p>
2
Rails has_many STI
<p>I've trying to implement a STI on rails 4, but I can't make it work, I've search a lot of results but none worked. Here is the problem:</p> <p>I have an instance class, using STI I have a subclass Car (a dummy subclass) and ScheduledInstance class.</p> <pre><code>class Instance &lt; ActiveRecord::Base belongs_to :task end class Car &lt; Instance end class ScheduledInstance &lt; Instance end class Task &lt; ActiveRecord::Base has_many :instances, dependent: :destroy has_many :cars has_many :scheduledinstances end </code></pre> <p>When trying to get a task's cars or a task's scheduledinstances, it doesn't work.(I have a type column on Instance table)</p> <pre><code>Task.first.cars Task Load (0.8ms) SELECT "tasks".* FROM "tasks" ORDER BY "tasks"."id" ASC LIMIT 1 NameError: uninitialized constant Task::Car </code></pre> <p>however, if I do Task.first.instances, and then Task.first.cars, it works ok. What I am missing?.</p> <p>Also based on your answer, what changes do I need to apply to make it work with a has_many through?</p> <pre><code>class Project &lt; ActiveRecord::Base has_many :tasks, dependent: :destroy has_many :instances, through: :tasks end </code></pre>
2
Vue-Resource gives TokenMismatchException in Ajax POST call
<p>Please note, I'm using the Laravel framework. Also please note, there are similar questions on SO, I've checked them, but wasn't able to solve my problem based on those solutions...</p> <p>Even though I set my CSRF token right to my knowledge, I'm not sure why it won't work.</p> <p>When checking the console, it seems I have 3 cookies: two Request cookies of which one is called <code>XSRF-TOKEN</code> and one is called <code>laravel_session</code>. And one respone <code>laravel_session</code> cookie. All have a different value!!!</p> <p>My Vue:</p> <pre><code>new Vue({ el:'body', http: { root: '/root', headers: { 'X-CSRF-Token': $('meta[name=_token]').attr('content') } }, }); </code></pre> <p>My head:</p> <pre><code>&lt;meta name="_token" content="{!! csrf_token() !!}"/&gt; </code></pre> <p>My Vue component addNew method:</p> <pre><code>Vue.component('things',{ template:'#things-panel-template', data(){ return { list: [], newThing: { body: '', // _token: $('meta[name=_token]').attr('content'), // tried removing token from head meta and adding up here. }, } }, methods:{ addNew(){ var thing = this.newThing; // get input this.newThing = {body:''}; // clear input this.$http.post('/api/things/add',thing) // send }, }, }); </code></pre> <p>My route:</p> <pre><code>Route::post('/api/things/add',function(){ return App\Thing::create(Request::get()); }); </code></pre> <p>And finally, the form in my Vue Template:</p> <pre><code>&lt;form action="/things/add" method="POST" @submit.prevent="addNew" &gt; &lt;div class="form-group"&gt; {{ csrf_field() }} &lt;label for=""&gt;Add&lt;/label&gt; &lt;input type="text" name="body" id="task-body" class="form-control" v-model="newThing.body" &gt; &lt;button :disabled="!isValid" class="btn btn-primary" type="submit" &gt;Add&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; </code></pre>
2
get rows between two date range in codeigniter
<p>I wrote the following query to fetch rows from database between two given date range.But it is not fetching any data.What is wrong in this query and how it can be fixed</p> <pre><code>$from=date_format(date_create($this-&gt;input-&gt;post('from_date')),'ym'); $to=date_format(date_create($this-&gt;input-&gt;post('to_date')),'ym'); $this-&gt;db-&gt;from('tab1'); $this-&gt;db-&gt;join('tab2','tab1.party_id=tab2.party_id','inner'); $this-&gt;db-&gt;where("EXTRACT(YEAR_MONTH FROM tab2.incoming_call_date ) BETWEEN {$from} AND {$to}"); $query = $this-&gt;db-&gt;get(); $data = $query-&gt;result(); return $data; </code></pre>
2
Bootstrap Dropdown Keeps Collapsing on Mobile
<p>Site: <a href="http://pegasusbus.com/ebrochure" rel="nofollow">http://pegasusbus.com/ebrochure</a></p> <p>My menu works great, but when i click on the dropdown for "packages" in the nav, the dropdown closes before i can select an option. This only happen on mobile. </p> <p>Can anyone please tell me whats going on here please?</p>
2
How to match a string not followed by a word using sed
<p>I need to delete all strings consisting of a hyphen followed by a whitespace, but only when the whitespace is not followed by the word "og". Example file:</p> <pre><code>Kultur- og idrettsavdelinga skapar nyska- pande kunst og utvik- lar samfunnet </code></pre> <p>I tried negative lookahead :</p> <pre><code>sed -e 's/- (?!og)//g' </code></pre> <p>but it doesn't work. What I want is something like this:</p> <pre><code>Kultur- og idrettsavdelinga skapar nyskapande kunst og utviklar samfunnet. </code></pre> <p>Any ideas?</p>
2
Why does the "Default" site route to the site root in ASP.NET MVC work?
<p>ASP.NET MVC sites come with the following default root that executes the Index action of the Home controller when the root of the site is visited (e.g. <code>http://localhost:12345</code>)</p> <pre><code>routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); </code></pre> <p>So it's a kind of fallback when no route is found then?</p> <p>Not so fast. If we try and navigate to <code>http://localhost/a/b</code> (where no 'a' controller exists) it will not execute the Index action of the Home controller - an error will be returned.</p> <p>Why does that fail to execute Home/Index in that scenario - but entering absolutely nothing in the path does execute Home/Index?</p> <p>What is the logic here - and why is this route called 'defaults'?</p> <p>I've seen a lot of articles cover routing - but not one where this is explained.</p> <p><strong>Related Question</strong></p> <p>In other situations what is in 'defaults' seems more like a mapping of a route. For example </p> <pre><code>url: "abc/def", defaults: new { controller = "bongo", action = "bingo" } </code></pre> <p>This just executes the bingo action on the bongo controller - whenever the exact url "abc/def" is entered. Why is it called 'defaults' - that term doesn't seem to fit really. (does removing 'defaults' have any effect, I have seen it omitted).</p> <p>In the Default route it seems more like a fallback, in the latter example more like a mapping?</p> <p>I feel like there is something at the conceptual level I am missing here.</p> <p>thx.</p>
2
iOS - App description showing incorrect language in App Store
<p>I localised my app via iTunesConnect but it does not show up in App Store. The primary language of my app is English.</p> <p>When I go to Japanese App Store my app's description is still showing English while other apps show localised language.</p> <p>In iTunesConnect, after I added a new version, I select Japanese on the top right, typed in Japanese app description, keywords and screenshots.</p> <p>I also made sure that my phone language is Japanese.</p> <p>What am I doing wrong?</p>
2
Localization from .json file [swift]
<p>I need to do localization for different language from a api, which get a json response, and i have already done with the parsing part and save the response as .json file and add as a library inside my project, but how do i match the key with all the strings? Can someone guide me and maybe provide me some tutorial or example for me to follow?</p>
2
VS code version for CentOS 5 or 6?
<p>Can I ask if there is a version of VS Code that works for CentOS 5 or 6? When trying installing VS, I encountered this error message</p> <p><a href="https://i.stack.imgur.com/RavoT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RavoT.png" alt="enter image description here"></a></p> <p>Many thanks in advance!</p>
2
Anylogic stopwatch/timer
<p>I'm wondering if there is something in anylogic that's the opposite to an event, this is, an object that counts the lapse of time instead of the time remaining.</p> <p>Example:</p> <ul> <li>I have a factory simulation where I want to visualize the amount of time that a specific worker (agent that is a resource) has been working since his shift started --> I could query for a function created in worker which is what I currently do but it would be neater to have a timer with the time worked</li> <li>On the other hand I want to account for the busy time of a machine in a way that it's computed life (there's also the option of querying it)</li> </ul> <p>For those two examples an object like an Event that has a counter and functionality around it would be useful if it could be used with increasing time instead of decreasing</p> <p>I haven't found anything of the sort...</p>
2
How to populate a nested List Class using linq
<p>Not even sure I knew how to give the correct title for this question...</p> <p>I have a class:</p> <p>~ in 1st DLL</p> <pre><code>namespace ServerEnd { class A { string field1 {get; set;} List&lt;B&gt; Nested {get;set;} } class B { string field1 { get; set;} } } </code></pre> <p>~in 2nd DLL</p> <pre><code>namespace ClientEnd { class A { string field1 {get; set;} List&lt;B&gt; Nested {get;set;} } class B { string field1 { get; set;} } } </code></pre> <p>Now if I want to populate the client objects with the server objects I would use this:</p> <pre><code>var test = new ServerEnd.A(); test.field1 = "a test"; test.Nested = new ServerEnd.A.B(); test.Nested.Add(new (){field1 = "hi1" } ; var clientModel = from x in test select new ClientEnd.A { field1 = x.field1, * what do i put here to transpose data from list object * }; </code></pre> <p>But how do I populate the List from Server to Client?</p> <p>Hope this is clear?</p> <p>thanks</p>
2
Generating a Linked List by reading numbers from text file
<p>I want to read in numbers from text file and create a linked list dynamically, although I am able to do it, the last node with value of 0 is also added to the list. How can I correct this? Also I should be able to add value 0 if i want but not in this way.</p> <pre><code> #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct node { int data; struct node *next; }node; int main(int argc, char const *argv[]) { FILE *fp = fopen("data.txt", "r"); node *prev = NULL; while(!feof(fp)){ node *curr = malloc(sizeof(node)); fscanf(fp, "%d", &amp;(curr-&gt;data)); fprintf(stdout, "%d--&gt;", curr-&gt;data); if(prev != NULL){ prev-&gt;next = curr; } prev = curr; } printf("NULL\n"); fclose(fp); return 0; } </code></pre> <p>The input file is this single column of integers 1 5 2 3 6 4</p> <p>The output comes like this, the 0 is not part of input 1-->5-->2-->3-->6-->4-->0-->NULL</p>
2
Android Notification to country specific users
<p>I am developing an android application. I want to send some notification to the user in a particular country. For example I want to send notification to US users only. I am trying to use FCM(Firebase cloud messagging) for the same but I can not find any option in user property to select country. Someone please tell me how to do that.</p>
2
How to add some space under the last item in a Navigation Drawer?
<p>I have a Navigation Drawer that contains several items. I added a button on the bottom of the Navigation Drawer. The problem is that in small size screens the button covers the last item in the Drawer.</p> <p>How can I add some space under the last item so the button won't cover anything?</p> <p>activity_main.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"&gt; &lt;include layout="@layout/app_bar_main" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;android.support.design.widget.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_main" app:menu="@menu/activity_main_drawer" &gt; &lt;Button android:id="@+id/remove_ads_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:background="@color/red" android:text="@string/remove_ads" android:textColor="@color/white" android:textSize="15sp" /&gt; &lt;/android.support.design.widget.NavigationView&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre> <p>activity_main_drawer.xml: </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;group android:checkableBehavior="none"&gt; &lt;item android:id="@+id/action_contact_us" android:icon="@drawable/ic_contact_us" android:title="@string/action_contact_us" /&gt; &lt;item android:id="@+id/action_share" android:icon="@drawable/ic_share_24dp" android:title="@string/action_share" /&gt; &lt;item android:id="@+id/action_rate_us" android:icon="@drawable/ic_rate_us_24dp" android:title="@string/action_rate_us" /&gt; &lt;item android:id="@+id/action_follow_us" android:icon="@drawable/ic_follow_us_24dp" android:title="@string/action_follow_us" /&gt; &lt;item android:id="@+id/action_help" android:icon="@drawable/ic_help_name" android:title="@string/action_help" /&gt; &lt;item android:id="@+id/action_about_us" android:icon="@drawable/ic_info_24dp" android:title="@string/action_about_us" /&gt; &lt;item android:id="@+id/action_settings" android:icon="@drawable/ic_settings_24dp" android:title="@string/action_settings" /&gt; &lt;/group&gt; &lt;/menu&gt; </code></pre>
2
Correct way to wait a condition variable that is notified by several threads
<p>I'm trying to do this with the C++11 concurrency support. </p> <p>I have a sort of thread pool of worker threads that all do the same thing, where a master thread has an array of condition variables (one for each thread, they need to 'start' synchronized, ie not run ahead one cycle of their loop).</p> <pre><code> for (auto &amp;worker_cond : cond_arr) { worker_cond.notify_one(); } </code></pre> <p>then this thread has to wait for a notification of each thread of the pool to restart its cycle again. Whats the correct way of doing this? Have a single condition variable and wait on some integer each thread that isn't the master is going to increase? something like (still in the master thread)</p> <pre><code> unique_lock&lt;std::mutex&gt; lock(workers_mtx); workers_finished.wait(lock, [&amp;workers] { return workers = cond_arr.size(); }); </code></pre>
2