input
stringlengths
51
42.3k
output
stringlengths
18
55k
Using Java Domain Object Instead of Scala Case Class in Spark DataSet Creation <p>I'm trying to create a Spark DataSet from an RDD using the RDD#toDS method.</p> <p>However, instead of using the Scala case class to specify the schema, I want to use an existing domain object defined in a 3rd party library. But, when I do that I get the following error:</p> <pre><code>scala&gt; import org.hl7.fhir.dstu3.model.Patient import org.hl7.fhir.dstu3.model.Patient scala&gt; val patients = sc.loadFromMongoDB(ReadConfig(Map("uri" -&gt; "mongodb://mongodb/fhir.patients"))) patients: com.mongodb.spark.rdd.MongoRDD[org.bson.Document] = MongoRDD[0] at RDD at MongoRDD.scala:47 scala&gt; val patientsDataSet = patients.toDS[Patient]() &lt;console&gt;:44: error: not enough arguments for method toDS: (beanClass: Class[org.hl7.fhir.dstu3.model.Patient])org.apache.spark.sql.Dataset[org.hl7.fhir.dstu3.model.Patient]. Unspecified value parameter beanClass. val patientsDataSet = patients.toDS[Patient]() ^ </code></pre> <p>This is what I get when I remove the parenthesis:</p> <pre><code>scala&gt; val patientsDataSet = patients.toDS[Patient] &lt;console&gt;:46: error: missing arguments for method toDS in class MongoRDD; follow this method with `_' if you want to treat it as a partially applied function val patientsDataSet = patients.toDS[Patient] </code></pre> <p>Is there anyway, I can use a Java Object in place of a case class here?</p> <p>Thanks!</p>
<p>It might work to create a case class that extends your java object.</p> <p>Java:</p> <pre><code>public class Patient { private final String name; private final String status; public Patient(String name, String status) { this.name = name; this.status = status; } public String getName() { return name; } public String getStatus() { return status; } } </code></pre> <p>Scala:</p> <pre><code> case class Patient0(name: String, status: String) extends Patient(name, status) val patientsDataSet = patients.toDS[Patient]() val patients = sc.loadFromMongoDB(ReadConfig(Map("uri" -&gt; "mongodb://mongodb/fhir.patients"))) </code></pre>
Java Linked List unique Keyword Sorting <p>I'm trying to read a file (in this case a text file with song lyrics) and create a linked list using only unique strings from said file. There cannot be any two same strings in the list. It needs to be stored in a Linked List and can't use the built-in one for it. Right now this is what I have:</p> <pre><code>public String createSuperList(String newKey) { SuperLink newSuperLink = new SuperLink(newKey); SuperLink current = first; if(isEmpty()) { incertLast(newKey); } else if (newSuperLink != last) { while(current != newSuperLink &amp;&amp; current != null){ if(current.equals(newSuperLink)){ return null; } else { incertLast(newKey); } current = current.next; } } else { return null; } return newKey; } HOW THE NEWKEY IS SENT TO THIS METHOD: File file = new File("MYFILEPATH"); try { Scanner sc = new Scanner(new FileInputStream(file)); while (sc.hasNextLine()) { content = sc.next(); if(SuperList.createSuperList(content) == null){ BabyList.incertLast(content); } } sc.close(); } catch (FileNotFoundException fnf) { fnf.printStackTrace(); } catch (Exception e) { e.printStackTrace(); System.out.println("\nProgram terminated Safely..."); } </code></pre> <p>The <code>newKey</code> is the string that I'm comparing to the rest of the Linked List to see if it is repeated anywhere in the list and, if it is seen in the List somewhere, it will return a <code>null</code>. </p> <p>My issue right now is that it just keeps going and there's no stopping (runaway), it doesn't end at all. The program doesn't stop. I keeps looping forever. I had it running for an hour with nothing changing and it still running. </p> <p>Right now what its suposed to do Is create a LinkedList called superLinkList that only has unique words in it.</p> <p>This is <strong>going to be a markov text generator</strong> that uses 2 linked lists.</p> <p>EDIT_1: So I fixed the infianite run time issue but Its still not checking if its unique or not.</p> <p>Updated Code:</p> <pre><code>public Boolean createSuperList(String newKey) { SuperLink newSuperLink = new SuperLink(newKey); SuperLink current = first; boolean i; if(isEmpty()){ incertLast(newSuperLink.toString()); } while(current != newSuperLink &amp;&amp; current != null){ if(current.equals(newSuperLink)){ System.out.println("Not unique Item"); i = false; } else { System.out.println("Unique Item"); i = true; } current = current.next; } if(i = true){ return true; }else{ return false; } } </code></pre> <p>EDIT_2:</p> <p>Okay so now its a nullpointerexception. The NPE is at the while loop. Specifically its current.keyWord. Im not sure how to change this so that It will work. Im not sure why its throwing an error here....</p> <p>Code:</p> <pre><code>public Boolean createSuperList(String newKey) { SuperLink newSuperLink2 = new SuperLink(newKey); SuperLink current = first; boolean i = false; if (isEmpty()) { incertLast(newKey); } while (!current.keyWord.equals(newSuperLink2.keyWord) &amp;&amp; current != null) { if (current.keyWord.equals(newSuperLink2.keyWord)) { System.out.println("Not unique Item"); i = false; break; } else { System.out.println("Unique Item"); i = true; } current = current.next; } if (i = true) { return i; } else { return i; } } </code></pre>
<p>You can solve your problem in a few lines:</p> <ul> <li>read values into a <code>LinkedHashSet</code> (set preserving the order of insertion)</li> <li>convert the result <code>new LinkedList&lt;&gt;(linkedHashSet)</code></li> </ul>
WPF Listbox memory leak <p>Here's my xaml:</p> <pre><code>&lt;ListBox Grid.Row="4" HorizontalAlignment="Stretch" Margin="10,132,10,10" ScrollViewer.VerticalScrollBarVisibility="Disabled" Name="lbStatus" VerticalAlignment="Stretch" VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling"/&gt; </code></pre> <p>and my C# code:</p> <pre><code> public void DisplayStatusMessage(string msg) { if (lbStatus.Dispatcher.CheckAccess()) { AddMessage(msg, Brushes.Black); } else { this.Dispatcher.BeginInvoke((Action)(() =&gt; { AddMessage(msg, Brushes.Black); })); } } private void AddMessage(string msg) { ListBoxItem status = new ListBoxItem(); status.Content = DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss:fff ") + msg; lbStatus.Items.Add(status); lbStatus.ScrollIntoView(status); status = null; } </code></pre> <p>I am calling DisplayStatusMessage within while (true) loop to display status on the listbox. My application grows considerably in size overnight, which seems to indicate a memory leak on the listbox. Is there an alternative to the listbox to display infinite status ? I thought setting the Virtualization to recycling would prevent from leaking ?</p>
<p>This isn't a 'leak' per se. If you are continually adding entries to a <code>ListBox</code>, overnight even, you're likely going to have thousands of entries, which will of course require memory to store.</p> <p>To avoid this, you could remove old entries as you add new ones:</p> <pre><code>if (listbox.Items.Count &gt; 100) listbox.Items.RemoveAt(0); // 0 or 99, whichever is your oldest listbox.Items.Add(status); listbox.ScrollIntoView(status); </code></pre>
readHTMLTable and rvest not working for HTML Table scraping <p>I've been attempting to scrape the data from a HTML table with issues.</p> <pre><code>url &lt;- "http://www.njweather.org/data/daily" Precip &lt;- url %&gt;% html() %&gt;% html_nodes(xpath='//*[@id="dataout"]') %&gt;% html_table() </code></pre> <p>this returns: </p> <blockquote> <pre><code>Warning message: 'html' is deprecated. Use 'read_html' instead. See help("Deprecated") </code></pre> </blockquote> <p>and a Precip List with no values in it.</p> <p>I also attempted to use the <code>readHTMLTable()</code> function:</p> <pre><code>readHTMLTable("http://www.njweather.org/data/daily", header = TRUE, stringAsFactors = FALSE) </code></pre> <p>this returns another empty list.</p>
<p>Unfortunately, that "Save to CSV" is a shockwave/flash control that just extracts the JSON content from the page, so there's no way to call that directly (via URL) but it would be clickable in a Firefox RSelenium web drive context (but…ugh!).</p> <p>Rather than use RSelenium or the newer webdriver packages, might I suggest some <code>gsub()</code> node content surgery that then uses <code>V8</code> to evaluate the content:</p> <pre><code>library(dplyr) library(rvest) library(readr) library(V8) ctx &lt;- v8() pg &lt;- read_html("http://www.njweather.org/data/daily") html_nodes(pg, xpath=".//script[contains(., '#dtable')]") %&gt;% html_text() %&gt;% gsub("^.*var json", "var json", .) %&gt;% gsub("var dTable.*", "", .) %&gt;% JS() %&gt;% ctx$eval() ctx$get("json")$aaData %&gt;% type_convert() %&gt;% glimpse() ## Observations: 66 ## Variables: 16 ## $ city &lt;chr&gt; "Berkeley Twp.", "High Point Monument", "Pequest", "Haworth", "Sicklerville", "Howell"... ## $ state &lt;chr&gt; "NJ", "NJ", "NJ", "NJ", "NJ", "NJ", "NJ", "NJ", "NJ", "NJ", "NJ", "NJ", "NJ", "NJ", "N... ## $ date &lt;date&gt; 2016-10-19, 2016-10-19, 2016-10-19, 2016-10-19, 2016-10-19, 2016-10-19, 2016-10-19, 2... ## $ source &lt;chr&gt; "Mesonet", "SafetyNet", "Mesonet", "Mesonet", "Mesonet", "Mesonet", "Mesonet", "Mesone... ## $ DT_RowId &lt;int&gt; 1032, 1030, 1029, 1033, 1034, 3397, 1101, 471, 454, 314, 299, 315, 316, 450, 317, 3398... ## $ temperaturemax_daily &lt;int&gt; 84, 73, 84, 85, 86, 85, 87, 81, 83, 83, 83, 83, 80, 81, 84, 86, 84, 72, 85, 85, 85, 84... ## $ temperaturemin_daily &lt;int&gt; 65, 63, 56, 65, 63, 66, 66, 64, 63, 66, 62, 64, 66, 62, 62, 65, 66, 67, 62, 64, 65, 62... ## $ dewpointmax_daily &lt;int&gt; 68, NA, 65, 67, 68, 68, 68, 65, NA, NA, NA, NA, NA, NA, 69, 68, 69, 68, 69, 70, 67, 67... ## $ dewpointmin_daily &lt;int&gt; 63, NA, 56, 60, 62, 63, 61, 55, NA, NA, NA, NA, NA, NA, 62, 62, 61, 65, 61, 63, 62, 61... ## $ relhumidmax_daily &lt;int&gt; 94, NA, 99, 94, 96, 91, 92, 90, NA, NA, NA, NA, NA, NA, 102, 93, 88, 94, 99, 94, 94, 9... ## $ relhumidmin_daily &lt;int&gt; 50, NA, 39, 45, 48, 51, 43, 41, NA, NA, NA, NA, NA, NA, 51, 46, 49, 83, 51, 51, 48, 48... ## $ pressuremax_daily &lt;dbl&gt; 29.97, NA, 29.97, 29.96, 30.02, 30.03, 29.99, 30.04, NA, NA, 30.01, 30.04, NA, 30.00, ... ## $ pressuremin_daily &lt;dbl&gt; 29.86, NA, 29.86, 29.84, 29.91, 29.90, 29.88, 29.90, NA, NA, 29.91, 29.95, NA, 29.88, ... ## $ precip_daily &lt;dbl&gt; 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... ## $ windspmax_daily &lt;int&gt; 17, 32, 16, 12, 8, 13, 15, 21, 13, 12, 10, 14, 19, NA, 13, 10, 11, 15, 15, 10, 13, 13,... ## $ windspmaxdir_daily &lt;chr&gt; "SW", NA, "WSW", "NW", "W", "WSW", "WSW", "W", "S", NA, NA, NA, NA, NA, "SSW", "SSW", ... </code></pre> <p>Also, read up on the changes to <code>rvest</code> and <code>xml2</code>. Switching to <code>read_html()</code> should be something you get into muscle memory (<code>html()</code> will go away at some point).</p>
display a hidden input field when enter value on a particuloar input filed <p>anyone could help me out on how i could achieve this with either javascript or jquery maybe to get the following as mentioned below</p> <p>say i have this field1</p> <pre><code>&lt;input type="text" name="field1" value=""&gt; </code></pre> <p>and then i have this field2 </p> <pre><code>&lt;input type="hidden" name="field2" value=""&gt; </code></pre> <p>what i mean to say the field2 should be hidden but if someone enters some value in field1 then field2 shows but if no value on field1 then it disappears?</p> <p>thanks in advance and appreciate your time and help</p>
<p>You'd get the first field, check if it has a value, and toggle the second field based on that, but you should not be using a hidden input, but instead hide it with CSS</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>$('[name="field1"]').on('input', function() { var el = $('[name="field2"]').toggle( this.value !== "" ); if (this.value === "") el.val(""); });</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; &lt;input type="text" name="field1" value="" placeholder="type something"&gt; &lt;br&gt;&lt;br&gt; &lt;input type="text" name="field2" value="" style="display:none"&gt;</code></pre> </div> </div> </p>
Sort function for array of structures <p>I have a structure called rain. It is defines like this</p> <pre><code> struct Rain{ string month; string year; double rainfall; } </code></pre> <p>I have an array of these (rain [240]) and I would like to sort using the sort algorithm. This is what I tried:</p> <pre><code>sort(rain.rainfall, rain.rainfall + 240); </code></pre> <p>but I get: </p> <pre><code>member reference base type 'Rainfall_data [240]' is not a structure or union sort(rain.rainfall, rain.rainfall + 240); ~~~~^~~~~~~~~ </code></pre> <p>I am just wondering if it is possible to use the sort algorithm this way, and if so what have I done wrong that it is not working?</p> <p>Thank you for your help.</p>
<p>Often it's most convenient to embed the function into the class/struct:</p> <pre><code>struct Rain { string month; string year; double rainfall; bool operator &lt; (const Rain&amp; r1) const { return (rainfall &lt; r1.rainfall); } }; </code></pre> <p>Now they can be sorted like the basic types:</p> <pre><code>std::sort(rain, rain + 240); </code></pre>
Processing file with large amount of data on one line (in Python) <p>I've inherited a 593 MB txt file in which all the data was written to <em>one</em> line. </p> <p>What's the best way to process it (preferably in Python)?</p>
<pre><code>CHUNKSIZE=1024 # read 1024 bytes at a time while True: chunk = f.read(CHUNKSIZE) if not chunk: break # end of file ... process(chunk) </code></pre> <p>is one way... alternatively 593MB is not all that huge... you can probably just load it all in at once without much difficulty (again it depends what you mean by "how do i process it?")</p>
Reading information from a file in C language <p>So I have the txt file from which I need to read the number of students written in that file, and because every student is in separate line, it means that I need to read the number of lines in that document. So I need to:</p> <ol> <li><p>Print all lines from that document</p></li> <li><p>Write the number of lines from that document.</p></li> </ol> <p>So, I write this:</p> <pre><code>#include "stdafx.h" #include &lt;stdio.h&gt; int _tmain(int argc, _TCHAR* Argo[]){ FILE *student; char brst[255]; student = fopen("student.txt", "r"); while(what kind of condition to put here?) { fgetc(brst, 255, (FILE*)student); printf("%s\n", brst); } return 0; } </code></pre> <p>Ok, I understand that I can use the same loop for printing and calculating the number of lines, but I can't find any working rule to end the loop. Every rule I tried caused an endless loop. I tried <code>brst != EOF</code>, <code>brst != \0</code>. So, it works fine and print all elements of the document fine, and then it start printing the last line of document without end. So any suggestions? I need to do this homework in C language, and I am using <code>VS 2012 C++</code> compiler.</p>
<p>OP's code is close but needs to use <code>fgets()</code> rather than <code>fgetc()</code> and use the return value of <code>fgets()</code> to detect when to quit, it will be <code>NULL</code> <a href="http://stackoverflow.com/questions/40139500/reading-information-from-a-file-in-c-language/40140587#comment67549285_40139500">@Weather Vane</a>. Also add a line counter.</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { FILE *student = fopen("student.txt", "r"); unsigned line_count = 0; if (student) { char brst[255]; // fgetc(brst, 255, (FILE*)student); while (fgets(brst, sizeof brst, student)) { line_count++; printf("%u %s", line_count, brst); } fclose(student); } printf("Line Count %u\n", line_count); return 0; } </code></pre>
Wordpress Plugin error. Backup Buddy <p>I am having a error when using <code>BackupBuddy</code> plugin for wordpress. I can not find the error anywhere online.</p> <blockquote> <p>Error #82389: A javascript error occured which may prevent the backup from continuing. Check your browser error console for details. This is most often caused by another plugin or theme containing broken javascript. See details below for clues or try temporarily disabling all other plugins.</p> <p>Details: 'Access is denied. '.</p> <p>URL: 'http:// (OUR URL)/wp-content/plugins/backupbuddy/js/backupPreform.js?ver=7.2.0.2'.</p> <p>Line:'22'.</p> </blockquote>
<p>I can't give you the exact fix for the problem, but I can point you in the right direction and seeing that nobody has answered in 1 hour, I hope it helps. The issue is that there are 2 libraries that need to load; one for backupbuddy and one for another plugin or theme(I'm pretty sure its your theme). The library for backupbuddy is not loading and causing the error. Usually one library- like Jquery - can be used by multiple plugins but its not working in this case.</p> <p>You might already know this, but I'll mention it anyways, if you set WP_DEBUG to true in your wp-config.php file, it might show you the location of where the conflict is happening in the other file. Another thing I would try is removing and re-installing the current theme you are using to ensure that all files are updated. </p>
Load a SOAP XML message into two different C# objects <p>I have a Java backend es a C# Silverlight UI which are communicating with each other via SOAP XML messages. The message contains a large object which contains lots of smaller objects which contains lots of even smaller objects and so on. My aim is to have two instance of this object on C# side, one that is the original and another one that user can edit. I can achieve it by deep-copying the object on C# side, but is a bit complicated to implement and slow. I can send two same objects in the SOAP XML Message, but it would waste the resources.</p> <p>Could I load the content of the same SOAP XML messages into two different C# objects which don't point to the same refernce.</p> <p>Thanks in advance</p>
<p>Sure you can...</p> <pre><code>var myFirstInstance = MyDeserializeMethod(incomingXML); var mySecondInstance = MyDeserializeMethod(incomingXML); </code></pre> <p>Since it is being deserialized first, it is not a direct reference to incomingXML - you are assigning the object which is returned from MyDeserializeMethod, which is a different object every time you run it.</p>
Setting Image background for a line plot in matplotlib <p>I am trying to set a background image to a line plot that I have done in matplotlib. While importing the image and using zorder argument also, I am getting two seperate images, in place of a single combined image. Please suggest me a way out. My code is -- </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>import quandl import pandas as pd import sys, os import matplotlib.pyplot as plt import seaborn as sns import numpy as np import itertools def flip(items, ncol): return itertools.chain(*[items[i::ncol] for i in range(ncol)]) df = pd.read_pickle('neer.pickle') rows = list(df.index) countries = ['USA','CHN','JPN','DEU','GBR','FRA','IND','ITA','BRA','CAN','RUS'] x = range(len(rows)) df = df.pct_change() fig, ax = plt.subplots(1) for country in countries: ax.plot(x, df[country], label=country) plt.xticks(x, rows, size='small', rotation=75) #legend = ax.legend(loc='upper left', shadow=True) plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.show(1) plt.figure(2) im = plt.imread('world.png') ax1 = plt.imshow(im, zorder=1) ax1 = df.iloc[:,:].plot(zorder=2) handles, labels = ax1.get_legend_handles_labels() plt.legend(flip(handles, 2), flip(labels, 2), loc=9, ncol=12) plt.show()</code></pre> </div> </div> </p> <p>So in the figure(2) I am facing problem and getting two separate plots</p>
<p>You're creating two separate figures in your code. The first one with <code>fig, ax = plt.subplots(1)</code> and the second with <code>plt.figure(2)</code></p> <p>If you delete that second figure, you should be getting closer to your goal</p>
How to expand first div in accordion? <p>My current accordion container works. <a href="https://jsfiddle.net/c9bwogte/" rel="nofollow">https://jsfiddle.net/c9bwogte/</a></p> <p>Im using a query to group the head and body, it works good. How do I get it to expand the first head by default? The first head would end up being the current year.</p> <pre><code>$(document).ready(function () { //toggle the component with class accordion_body $(".accordion_head").click(function () { if ($('.accordion_body').is(':visible')) { $(".accordion_body").slideUp(200); $(".plusminus").text('+'); } if ($(this).next(".accordion_body").is(':visible')) { $(this).next(".accordion_body").slideUp(200); $(this).children(".plusminus").text('+'); } else { $(this).next(".accordion_body").slideDown(200); $(this).children(".plusminus").text('-'); } }); }); </code></pre>
<p>You can add <code>.click()</code> at the end to trigger the accordion:</p> <pre><code>$(".accordion_head").click(function () { if ($('.accordion_body').is(':visible')) { $(".accordion_body").slideUp(200); $(".plusminus").text('+'); } if ($(this).next(".accordion_body").is(':visible')) { $(this).next(".accordion_body").slideUp(200); $(this).children(".plusminus").text('+'); } else { $(this).next(".accordion_body").slideDown(200); $(this).children(".plusminus").text('-'); } }).click(); </code></pre> <p><strong><a href="https://jsfiddle.net/j08691/eydyg8tb/" rel="nofollow">jsFiddle example</a></strong></p>
SQL - Duplicates when Querying 3 Tables <p>I have a pretty simple query that pulls data from 3 tables. I decided to use From and Where Clauses to Select what I want instead of Join but when I run the query it pulls duplicate data. DISTINCT was tried as well but it still pulled duplicate data.</p> <p>Here is the Query - </p> <pre><code>SELECT IV00101.ITEMNMBR, IV00101.ITEMDESC, ItmPrice.STNDCOST, ItmPrice.DS_Margin, IV00101.CURRCOST, IV00102.LSORDQTY, IV00102.LSRCPTDT, ItmPrice.MODIFDT, ItmPrice.MDFUSRID FROM DSLLC.dbo.IV00101 IV00101, DSLLC.dbo.IV00102 IV00102, DSLLC.dbo.ItmPrice ItmPrice WHERE IV00101.ITEMNMBR = IV00102.ITEMNMBR AND IV00101.ITEMNMBR = ItmPrice.ITEMNMBR AND IV00102.ITEMNMBR = ItmPrice.ITEMNMBR ORDER BY IV00101.ITEMNMBR </code></pre> <p>A small sample of the result can be seen <a href="https://i.stack.imgur.com/UthtN.png" rel="nofollow"><strong>here</strong></a>.</p>
<p>Try this : WHERE IV00101.ITEMNMBR = IV00102.ITEMNMBR AND IV00102.ITEMNMBR = ItmPrice.ITEMNMBR group by IV00101.ITEMNMBR ORDER BY IV00101.ITEMNMBR</p>
Trying to send random string in C# Discord <p>I am trying to make a bot in Discord. I now am working on making a random url. And to make this url, I first want to be sure the random generator works good. The random generated chars will be outputted as an array, but I want it as a string but I do not know how. I want the bot to send "LinkString" whenever I type +meme. Here is my code: </p> <pre><code> { commands.CreateCommand("meme") .Do(async (e) =&gt; { await e.Channel.SendMessage(LinkString); }); } discord.ExecuteAndWait(async () =&gt; { }); } private string LinkString(int Size) { string input = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var chars = Enumerable.Range(0, Size) .Select(x =&gt; input[random.Next(0, input.Length)]); return new string(chars.ToArray()); } </code></pre>
<p>You need to give your <code>LinkString()</code> method a parameter, an <code>int</code> as you've specified. Change it to this:</p> <pre><code> await e.Channel.SendMessage(LinkString(5)); </code></pre>
Find & Replace across entire workbook in specific row <pre><code> Dim sht As Worksheet Dim fnd As Variant Dim rplc As Variant fnd = "April" rplc = "May" For Each sht In ActiveWorkbook.Worksheets   sht.Cells.Replace what:=fnd, Replacement:=rplc, _     LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _     SearchFormat:=False, ReplaceFormat:=False Next sht End Sub </code></pre> <p>I have the follow code, I need it to find and replace across the entireworkbook but only in the row 30. How would I edit the code to do this?</p>
<p>Two things.</p> <p>First, don't use variants for fnd and rplc; use Strings.</p> <p>Second, specify the range you want to do the replace on, rather than just using "Cells".</p> <pre><code>Sub Replacer() Const csFnd As String = "April" Const csRpl As String = "May" Const csRow As String = "A30" Dim sht As Worksheet For Each sht In ActiveWorkbook.Worksheets sht.Range(csRow).EntireRow.Replace _ what:=csFnd, _ Replacement:=csRpl Next sht End Sub </code></pre> <p>It's also good practice to use constants at the top of your code to hold unchanging text, rather than putting <code>variable = "String"</code> in the body of the code. It's easier to maintain with the constants at the top.</p>
Iterating through one variable in a vector of struct with lower/upper bound <p>I have 2 structs, one simply has 2 values:</p> <pre><code>struct combo { int output; int input; }; </code></pre> <p>And another that sorts the input element based on the index of the output element:</p> <pre><code>struct organize { bool operator()(combo const &amp;a, combo const &amp;b) { return a.input &lt; b.input; } }; </code></pre> <p>Using this:</p> <pre><code>sort(myVector.begin(), myVector.end(), organize()); </code></pre> <p>What I'm trying to do with this, is iterate through the input varlable, and check if each element is equal to another input 'in'.</p> <p>If it is equal, I want to insert the value at the same index it was found to be equal at for input, but from output into another temp vector.</p> <p>I originally went with a more simple solution (when I wasn't using a structs and simply had 2 vectors, one input and one output) and had this in a function called copy:</p> <pre><code>for(int i = 0; i &lt; input.size(); ++i){ if(input == in){ temp.push_back(output[i]); } } </code></pre> <p>Now this code did work exactly how I needed it, the only issue is it is simply too slow. It can handle 10 integer inputs, or 100 inputs but around 1000 it begins to slow down taking an extra 5 seconds or so, then at 10,000 it takes minutes, and you can forget about 100,000 or 1,000,000+ inputs. </p> <p>So, I asked how to speed it up on here (just the function iterator) and somebody suggested sorting the input vector which I did, implemented their suggestion of using upper/lower bound, changing my iterator to this:</p> <pre><code>std::vector&lt;int&gt;::iterator it = input.begin(); auto lowerIt = std::lower_bound(input.begin(), input.end(), in); auto upperIt = std::upper_bound(input.begin(), input.end(), in); for (auto it = lowerIt; it != upperIt; ++it) { temp.push_back(output[it - input.begin()]); } </code></pre> <p>And it worked, it made it much faster, I still would like it to be able to handle 1,000,000+ inputs in seconds but I'm not sure how to do that yet. </p> <p>I then realized that I can't have the input vector sorted, what if the inputs are something like:</p> <pre><code>input.push_back(10); input.push_back(-1); output.push_back(1); output.push_back(2); </code></pre> <p>Well then we have 10 in input corresponding to 1 in output, and -1 corresponding to 2. Obviously 10 doesn't come before -1 so sorting it smallest to largest doesn't really work here.</p> <p>So I found a way to sort the input based on the output. So no matter how you organize input, the indexes match each other based on what order they were added.</p> <p>My issue is, I have no clue how to iterate through just input with the same upper/lower bound iterator above. I can't seem to call upon just the input variable of myVector, I've tried something like:</p> <pre><code>std::vector&lt;combo&gt;::iterator it = myVector.input.begin(); </code></pre> <p>But I get an error saying there is no member 'input'.</p> <p>How can I iterate through just input so I can apply the upper/lower bound iterator to this new way with the structs?</p> <p>Also I explained everything so everyone could get the best idea of what I have and what I'm trying to do, also maybe somebody could point me in a completely different direction that is fast enough to handle those millions of inputs. Keep in mind I'd prefer to stick with vectors because not doing so would involve me changing 2 other files to work with things that aren't vectors or lists.</p> <p>Thank you!</p>
<p>I think that if you sort it in smallest to largest (x is an integer after all) that you should be able to use <a href="http://en.cppreference.com/w/cpp/algorithm/adjacent_find" rel="nofollow">std::adjacent_find</a> to find duplicates in the array, and process them properly. For the performance issues, you might consider using <a href="http://www.cplusplus.com/reference/vector/vector/reserve/" rel="nofollow">reserve</a> to preallocate space for your large vector, so that your push back operations don't have to reallocate memory as often.</p>
Hash function issue - adding functionality <p>I tried adding functionality to the djb2 hash function, but it doesn't appear to like the changes. Specifically, I'm trying to include a loop that converts words (strings) to lower case. It throws the following two errors: </p> <ol> <li>Incompatible integer to pointer conversion assigning to <code>char *</code> from <code>int</code></li> <li>Cannot increment value of type <code>char *[45]</code></li> </ol> <p>Note that in the original code <code>*str++</code> appeared in the <code>while</code> loop. This is my first hash table, and I'm rather shaky on pointers. Any insight on where I've gone wrong would be appreciated. </p> <pre><code>// djb2 by Dan Bernstein -- slightly modified; unsigned int hash_function(const char* str) { unsigned int hash = 5381; int c; char* string[45]; for (int i = 0; str[i] != '\0'; i++) { string[i] = (tolower(str[i])); } while (c == *string++) hash = ((hash &lt;&lt; 5) + hash) + c; /* hash * 33 + c */ return (hash % LISTS); } </code></pre>
<p>This:</p> <pre><code>char* string[45]; </code></pre> <p>means "array of 45 character pointers", you should drop the asterisk.</p> <p>And you can't iterate over an array by incrementing the variable, the array variable cannot be changed. You can use a separate pointer:</p> <pre><code>const char *s = string; while (c = *s++) </code></pre> <p>Note that assignment is spelled <code>=</code>, while <code>==</code> is comparison for equality which is not what you mean.</p>
Y-axis ticks' labels visible partially <p>Which parameter should I manipulate to have whole labels visible here? As you see, hundreds are displayed as "00", "20" and so on:</p> <p><a href="https://i.stack.imgur.com/24dBR.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/24dBR.jpg" alt="enter image description here"></a></p>
<p>There is a related question linked here: <a href="http://stackoverflow.com/questions/25322535/how-to-increase-tick-label-width-in-d3-js-axis?rq=1">How to increase tick label width in d3.js axis</a></p> <p>Eventually it lead me to this piece of code (<code>padding</code> was already defined in my script):</p> <pre><code>var padding = 25; var margin = {top: 20, right: 40, bottom: 30, left: 60}, width = 560 - margin.left - margin.right, height = 300 - margin.top - margin.bottom; </code></pre> <p>Manipulating these values (margins and padding) finally gave me the result I wanted: the Y-axis labels are visible:</p> <p><a href="https://i.stack.imgur.com/H5doi.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/H5doi.jpg" alt="Solved"></a></p>
Inheriting from Db class - Two databases connection | PHP <p>In my app I used one database only, and I created class to provide some common methods. Now I need to implement additional database. </p> <p>So instead of creating separate Db class to do same things, I want to call that Db class with db related parameters.</p> <p>Problem is, when I try to extend Db class with a class where I provide methods to app, database connection isn't established - it is null.</p> <p>Both Main and User are using different databases.</p> <p>Class Main extends Db; Class User extends Db;</p> <p>Why something like this doesn't work?</p> <pre><code>class Db { protected $link; private $host; private $user; private $pass; private $dbName; public function __construct($host, $user, $pass, $db) { $this-&gt;host = $host; $this-&gt;user = $user; $this-&gt;pass = $pass; $this-&gt;dbName = $db; $this-&gt;connect(); } public function connect() { try { $this-&gt;link = new PDO("mysql:host=" . $this-&gt;host . ";dbname=" . $this-&gt;dbName . ";charset=utf8mb4", $this-&gt;user, $this-&gt;pass ); $this-&gt;link-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this-&gt;link-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } catch (PDOException $exc) { $this-&gt;setMessage($exc-&gt;getMessage()); } } } $db = new Db(HOST, USER,PASS,DB) class Main extends DB { public function __construct() { } /** App methods bellow*/ } $db2 = new Db(HOST2,USER2,PASS2,DB2); class User extends DB { public function __construct() { } /** App methods bellow*/ } </code></pre> <p>What would be easiest solution to implement two different database connections?</p> <p>Thanks!</p> <h1>Edit:</h1> <p>After updating my code as suggested, I have issues with accessing connection property of DB, so I am not able to do queries in Main and User class.</p> <p>What really confuses me, is the reason why that property it isn't visible to Main class?</p> <p>Main class methods are depending heavily on db link, and I am not sure how to fix this..</p> <p>Updated code:</p> <pre><code>class Main { protected $db; public function __construct($db) { $this-&gt;db = $db; } public function showFreeSlotsPerPlan() { try { $SQL = "some query"; $stmt = $this-&gt;db-&gt;prepare($SQL); /** Prepared statements bellow **/ } } class Db { protected $link; private $host; private $user; private $pass; private $dbName; public function __construct($host, $user, $pass, $db) { $this-&gt;host = $host; $this-&gt;user = $user; $this-&gt;pass = $pass; $this-&gt;dbName = $db; $this-&gt;connect(); } } </code></pre> <p>And calling it as suggested:</p> <pre><code>$db = new Db(HOST, USER, PASS, DB); $main = new Main($db); </code></pre> <p>And if I try to call a method f.e. showFreeSlotsPerPlan()</p> <pre><code>Fatal error: Call to undefined method Db::prepare() in /var/www/html/Master/class/Main.class.php </code></pre> <p>Then when I debug instance of Main I get the following:</p> <pre><code>Main Object ( [db:protected] =&gt; Db Object ( [link:protected] =&gt; PDO Object ( ) [host:Db:private] =&gt; localhost [user:Db:private] =&gt; root [pass:Db:private] =&gt; password [dbName:Db:private] =&gt; dbname ) ) </code></pre> <p>Edit2: Workaround is adding <code>prepare</code> method to the <code>DB.php</code>, and I was able to execute query successfully.</p> <p>Still I am not sure is this best aproach. I admit that my design is not good at all :(</p> <pre><code>public function prepare($sqlQuery) { return $this-&gt;link-&gt;prepare($sqlQuery); } </code></pre>
<p>@u_mulder described the technical issue you are facing correctly. The parent <code>Db</code> constructor is not automatically called from a child constructor. You could try to get around this by calling the parent constructor explicitly:</p> <pre><code>class Main extends DB { public function __construct() { parent::__construct(); } // ... } </code></pre> <p>The problem is that your parent (<code>DB</code>) requires parameters to it's constructor, so you would have to also pass those in to your child:</p> <pre><code>class Main extends DB { public function __construct($host, $user, $pass, $db) { parent::__construct($host, $user, $pass, $db); } // ... } </code></pre> <p>But this makes no sense. Your biggest problem is the design. Instead, you should <a href="https://en.wikipedia.org/wiki/Composition_over_inheritance" rel="nofollow">favor composition of objects over inheritance</a>, especially in this case. Try restructuring your class like this:</p> <pre><code>class Main { protected $db; public function __construct($db) { $this-&gt;db = $db; } // ... } $mainDb = new Db(HOST, USER,PASS,DB) $main = new Main($mainDb); </code></pre> <p>And do the same for your <code>User</code> class. When you do this, your <code>protected $link</code> property will no longer be visible inside of your <code>Main</code> class. This is Okay, because, really, your <code>Main</code> and <code>User</code> classes <em>should not</em> have visibility of that property because what is the point of having a <code>Db</code> class, anyway? You can get around this by adding some public methods to your <code>Db</code> class (e.g. <code>public function query($sql, $parameters)</code>) that are then called from your <code>Main</code> and <code>User</code> classes.</p> <p>Once you get that working, I would suggest that you look into the <a href="https://en.wikipedia.org/wiki/Active_record_pattern" rel="nofollow">Active Record Pattern</a>, or look into scrapping your approach altogether in favor of incorporating one of the many <a href="http://stackoverflow.com/q/108699/697370">open source ORMs</a> that are already available.</p>
SQL Case Statement in a Function <p>I am trying to write a function that takes two parameters and returns a calculated result based on a case statement (please see below). I keep getting a syntax error: </p> <blockquote> <p>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 'CASE when (medToConvert) = "Codeine" then MME = doseToConver' at line 13</p> </blockquote> <p>This is what I've tried so far:</p> <pre><code> /* Function that takes two parameters as input: Dosage of an opioid Name of the opioid Returns the morphine equivalent dosage */ CREATE FUNCTION convertToMorphineEquiv (doseToConvert INT, medToConvert VARCHAR(20)) RETURNS INT BEGIN DECLARE MME INT CASE when (medToConvert) = "Codeine" then MME = doseToConvert * 0.15 -- Fentanyl Transdermal (in mcg/hr) when (medToConvert) = "Fentanyl" then MME = doseToConvert * 2.4 when (medToConvert) = "Hydrocodone" then MME = doseToConvert * 1 when (medToConvert) = "Hydromorphone" then MME = doseToConvert * 4 when (medToConvert) = "Methadone" AND doseToConvert BETWEEN 1 AND 20 then MME = doseToConvert * 4 when (medToConvert) = "Methadone" AND doseToConvert BETWEEN 21 AND 40 then MME = doseToConvert * 8 when (medToConvert) = "Methadone" AND doseToConvert BETWEEN 41 AND 60 then MME = doseToConvert * 10 when (medToConvert) = "Methadone" AND doseToConvert &gt;=60 then MME = doseToConvert * 12 when (medToConvert) = "Morphine" then MME = doseToConvert * 1 when (medToConvert) = "Oxycodone" then MME = doseToConvert * 1.5 when (medToConvert) = "Oxymorphone" then MME = doseToConvert * 3 when (medToConvert) = "Tapentadol" then MME = doseToConvert * 0.4 else "Conversion for this opioid is not available" END RETURN MME END </code></pre>
<p>Create a table instead, and join to it. You will get much faster performance using a CROSS APPLY operation, as scalar-valued user-defined functions suffer from RBAR (Row By Agonizing Row) performance penalties</p>
How to stop SIGTERM and SIGKILL? <p>I need to run a huge process which will run for like 10+ minutes. I maxed the <code>max_execution_time</code>, but in my error logs I get a SIGTERM and then a SIGKILL. </p> <p>I read a little about SIGTERM and SIGKILL that they come from the daemon, but i Didn't figure out how to stop it from happening. I just need to disable it for one night. </p>
<p>Rather than trying to ignore signals, you need to find who sends them and why. If you're starting php from the command line, no one will send that signal and your script time will have <em>all the time</em>.</p> <p>But if you're actually starting this process as a response to an http request, it's probably the web server of FastCGI manager that limits the amount of time it waits for the script to finish. It also may simply kill the script because client connection (between user's browser and http server) has been terminated.</p> <p>So the important question you should ask yourself - what's the source of that signal and how this timeout can be increased. Please also provide all details about how you start this script and what platform you're running.</p>
How to replace symbols by their value in a R function body <p>This code reveals that <code>f</code> doesn't yet look up <code>q</code> before it's called.</p> <pre><code>q &lt;- 2 f &lt;- function(x) q + x f </code></pre> <p>I want to tell R which symbols in the body to look up right away (in this case <code>list("q")</code>) and have it modify <code>f</code> accordingly. How can it be done?</p>
<p>In Common Lisp this would look like:</p> <pre><code>CL-USER&gt; (defparameter q 4) Q CL-USER&gt; (let ((bar q)) (defmacro f (x) `(+ ,bar ,x))) F CL-USER&gt; (macroexpand-1 `(f 4)) (+ 4 4) T </code></pre> <p>In R this could look like:</p> <pre><code>&gt; q = 2 &gt; f = eval(bquote(function(x) .(q) + x)) &gt; f function (x) 2 + x &gt; </code></pre> <p>Since R is interpreted, eval is par for the course there. With Common Lisp, if you do not want to use eval, you can go with a compile-time macro that carries along with it a hard-coded value for 'q, so that every time it is used in code at that point on it refers to the value of 'q at creation time of the macro.</p>
Print random line from txt file? <p>I'm using random.randint to generate a random number, and then assigning that number to a variable. Then I want to print the line with the number I assigned to the variable, but I keep getting the error:</p> <blockquote> <p>list index out of range</p> </blockquote> <p>Here's what I tried:</p> <pre><code>f = open(filename. txt) lines = f.readlines() rand_line = random. randint(1,10) print lines[rand_line] </code></pre>
<p>You want to use <code>random.choice</code></p> <pre><code>import random with open(filename) as f: lines = f.readlines() print(random.choice(lines)) </code></pre>
Reading the code declarations and definitions in order to get the result of the expression without using GHCi <pre><code>data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf a myorder :: (a -&gt; c) -&gt; (b -&gt; c) -&gt; Tree a b -&gt; [c] myorder p q (Leaf x) = [p x] myorder p q (Branch x l r) = myorder p q l ++ [q x] ++ myorder p q r tree1 = Branch "Hi" (Branch "All" (Leaf (1::Int)) (Leaf (2::Int))) (Leaf (3::Int)) </code></pre> <p>Question asked: What is the result of the following expression?</p> <pre><code>&gt; myorder id length tree1 </code></pre> <p>I'm studying for an exam, and I want to get a better understanding of getting the outputs without the GHCi, since of course we have to do it by hand, and I really want to see how do I go by doing it. The answer was [1,3,2,2,3] If anyone can guide me through it, that would be great.<br> I also drew out the tree1 like so:</p> <pre><code> "Hi" / \ "All" 3 / \ 1 2 </code></pre>
<p>We need to evaluate</p> <pre><code>myorder id length (Branch "Hi" (Branch "All" (Leaf (1::Int)) (Leaf (2::Int))) (Leaf (3::Int))) </code></pre> <p>Try to apply the equations in order from top to bottom.</p> <pre><code>myorder p q (Leaf x) = [p x] </code></pre> <p>This equation does not apply since the argument <code>Branch "Hi" ... ...</code> is not of the form <code>Leaf x</code>.</p> <pre><code>myorder p q (Branch x l r) = myorder p q l ++ [q x] ++ myorder p q r </code></pre> <p>This equation does apply. We have <code>p = id</code>, <code>q = length</code>, <code>x = "Hi"</code>,</p> <pre><code>l = Branch "All" (Leaf (1::Int)) (Leaf (2::Int)), r = Leaf (3::Int). </code></pre> <p>So substituting these in the right hand side, the expression becomes</p> <pre><code> myorder id length (Branch "All" (Leaf (1::Int)) (Leaf (2::Int))) ++ [length "Hi"] ++ myorder id length (Leaf (3::Int)). </code></pre> <p>Now continue.</p>
Adding int and int? in Kotlin <p>I ran into a problem, which seems so simple that everyone should have ran into it at some point or another, yet failed to find a solution anywhere.</p> <p>Copied from the REPL:</p> <pre><code>var a : Int = 1 var c : Int? = 3 a + if (c != null) {c} else {0} ERROR: None of the following functions can be called with supplied argument (followed by the various implementations of kotlin.int.plus()) </code></pre> <p>So what I'm trying to do is add together an Int and an Int? and I'd like the result to be an Int. Very simple. I'm of course aware of the <code>!!</code> operator, however I want to avoid using this whenever possible, as it is not change-safe†. </p> <pre><code>a + if (c != null) {c!!} else {0} 4 </code></pre> <p>I am aware of the following solution, which handles null-safety and avoids the use of the <code>!!</code> operator.</p> <pre><code>a + (c ?: 0) 4 </code></pre> <p>My question is the following: Is there a way to do addition with the use of an if-else block and/or a when block, which does not require the use of the <code>!!</code> operator. My reason for preferring the use of if-else and not the Elvis operator is intelligibility for people from languages without an Elvis operator. So I'd like to get as close to <code>a + if (c != null) {c} else {0}</code> as possible.</p> <p>Thank you, if my problem or motivation is unclear or contrary to the design or intent of Kotlin, please let me know.</p> <p>† Sure, I may be able to assert that some variable is safe at the time when it's added, but this assertion will remain there even as code around it changes, possibly making the assertion invalid, thus negating one of Kotlin's points: null safety.</p>
<p>The problem is that kotlin can only assume a variable is never null after a null check if there is no way that variable can change value between operations.</p> <p>I don't exactly know how the REPL is implemented but my guess is that variables are inserted as members into a context class. This means the compiler cannot assume no changes can happen since another thread might change the value between operations.</p> <p>So it looks like this feature does not work in the REPL, but the elvis operator is a pretty clean alternative.</p>
How do I get a JSON object from a function? <p>I have the following component and I'm trying to retrieve a list of movies from an API. However, the variable <code>movies</code> does not contain the expected result.</p> <p>What am I doing wrong?</p> <p>Here's the code:</p> <pre><code>import React, { Component, } from 'react' import { View } from 'react-native' import { List, ListItem, Text, } from 'native-base'; class Test extends Component { render() { var movies = this.getMoviesFromApi(); for(var movie in movies) { console.warn(movie); } return ( &lt;List dataArray={movies} renderRow={(movie) =&gt; &lt;ListItem&gt; &lt;Text&gt;{movie}&lt;/Text&gt; &lt;/ListItem&gt;} /&gt; ); } async getMoviesFromApi() { try { let response = await fetch('https://facebook.github.io/react-native/movies.json'); let responseJson = await response.json(); return responseJson.movies; } catch(error) { console.error(error); } } } export default Test; </code></pre>
<p>In your fetch call, you should return the response with a <code>then()</code> call. Here's an example from an app I wrote:</p> <pre><code>// inside Utils/api.js getAllSchools(accessToken){ var url = `${baseUrl}/schools` return fetch(url).then((res) =&gt; res.json()) .catch((e) =&gt; { console.log('an error occurred getting schools', e) api.logError(e.message); }) }, </code></pre> <p>Then, wherever you're calling your function, set movies to that response:</p> <pre><code>api.getAllSchools("klsafj").then((res) =&gt; { var movies = res.data // then do whatever else you want to do with movies // or you could set movies to a state and use elsewhere }) </code></pre> <p>Hope this helps.</p>
Combine selectableItemBackground with shape for final background <p>I have a simple RecyclerView in which each row displays a line of text. Each row is selectable and so I want to use </p> <pre><code>android:background="?attr/selectableItemBackground" </code></pre> <p>The problem is that RecyclerViews do not allow for dividers; whereas I want dividers. Hence I need a background as below (called <code>bottom_line.xml</code>)</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;layer-list xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;item android:bottom="1dp" android:left="-2dp" android:right="-2dp" android:top="-2dp"&gt; &lt;shape android:shape="rectangle" &gt; &lt;stroke android:width="1dp" android:color="#FF000000" /&gt; &lt;solid android:color="#00FFFFFF" /&gt; &lt;padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp" /&gt; &lt;/shape&gt; &lt;/item&gt; &lt;/layer-list&gt; </code></pre> <p>My question is how do I combine my <code>bottom_line.xml</code> with <code>?attr/selectableItemBackground</code> to create a final drawable with ripples? (I am trying to avoid using a TextView inside a LinearLayout)</p>
<p>You can add dividers in several ways.</p> <p>One way is that your cell layout can have a divider in it, which is just a View with 1dp height and gray background. So you don't have to worry about combining background drawables.</p>
How do I get the 'initials' of a contact's middle name outlook vba <p><a href="https://i.stack.imgur.com/rErXE.png" rel="nofollow">Image</a></p> <p>From the image linked, I want to get the exchange user's middle name initials</p> <pre><code>Function getFullName(exchangeUser As ExchangeUser) As String Dim firstName, middleName, lastName, As String firstName = exchangeUser.GetExchangeUser.firstName middleName = exchangeUser.GetExchangeUser.{somehow retrieve middle name} lastName = exchangeUser.GetExchangeUser.lastName getFullName = firstName &amp; " " &amp; middleName &amp; " " &amp; lastName End Function </code></pre> <p>I tried GetExchangeUser.fullName but that does not return the middle initials</p> <p>---------------------------------------------------------EDIT--------------------------------------------------------------------</p> <p>I dont know how comments work so I am adding my code here</p> <p>I tried:</p> <pre><code>Function getFullName(exchangeUser As ExchangeUser) As String Dim firstName, middleName, lastName, As String Dim propName As String propName = "http://schemas.microsoft.com/mapi/proptag/0x3A44001F" firstName = exchangeUser.GetExchangeUser.firstName middleName = exchangeUser.GetExchangeUser.PropertyAccessor.GetProperty(propName) lastName = exchangeUser.GetExchangeUser.lastName getFullName = firstName &amp; " " &amp; middleName &amp; " " &amp; lastName End Function </code></pre> <p>Now I am getting an error that the property is not found</p>
<p>Retrieve the <code>PR_MIDDLE_NAME</code> MAPI property using AddressEntry.PropertyAccessor.GetProperty. The DALS property name is <code>http://schemas.microsoft.com/mapi/proptag/0x3A44001F</code> </p>
autoplay the contents within a div with jquery <p>I have some contents within different divs that i will like to display without clicking on any tab. I have been able to toggle the visibility of these contents by clicking, but I will really prefer it to be display automatically in a loop by using jquery. Below are my codes</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>$(document).ready(function(){ $('#advantages').click(function(){ $('#featureContent').fadeOut(400).addClass('hidden'); $('#advantageContent').fadeIn(400).removeClass('hidden'); $('#benefitsContent').fadeOut(400).addClass('hidden'); }); $('#benefits').click(function(){ $('#featureContent').fadeOut(400).addClass('hidden'); $('#advantageContent').fadeOut(400).addClass('hidden'); $('#benefitsContent').fadeIn(400).removeClass('hidden'); }); $('#features').click(function(){ $('#featureContent').fadeIn(400).removeClass('hidden'); $('#advantageContent').fadeOut(400).addClass('hidden'); $('#benefitsContent').fadeOut(400).addClass('hidden'); }); });</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; &lt;div id="featureLinks" class="col-lg-6 col-md-6 col-sm-6"&gt; &lt;ul class="text-center"&gt; &lt;li id="features"&gt; Smart travel &lt;/li&gt; &lt;li id="advantages"&gt; Smart route &lt;/li&gt; &lt;li id="benefits"&gt; Smart payment &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id="featureContent" class="col-lg-6 col-md-6 col-sm-6"&gt; &lt;h2 class="text-center"&gt; Smart travel &lt;/h2&gt; &lt;ul&gt; &lt;li&gt;All your favourite transit service providers like Uber, KLM, Great Western Rail and Blue Star Ferries on one integrated app! &lt;/li&gt; &lt;li&gt;Compare the availability, price and ETA for taxis/buses, flights, metro andferries, anytime and anywhere. &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id="advantageContent" class="col-lg-6 col-md-6 col-sm-6 hidden"&gt; &lt;h2 class="text-center"&gt; Smart Route &lt;/h2&gt; &lt;ul&gt; &lt;li&gt; Big data is finally at your service&lt;/li&gt; &lt;li&gt;Go where you&amp;#39;ve never gone before with integrated Satellite navigation system.&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id="benefitsContent" class="col-lg-6 col-md-6 col-sm-6 hidden"&gt; &lt;h2 class="text-center"&gt; Smart Payment &lt;/h2&gt; &lt;ul&gt; &lt;li&gt; Experience the ease and security of paying via the app. &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
<p>@Yemmy here is a quick example this will loop over these animations 10 times until i = 10. You'll need to edit the delays so it displays as you like it.</p> <pre><code>$(document).ready(function(){ var i = 0; while (i &lt; 10){ $('#featureContent').fadeOut(400).addClass('hidden').delay(400); $('#advantageContent').fadeIn(400).removeClass('hidden').delay(400); $('#benefitsContent').fadeOut(400).addClass('hidden').delay(400); $('#featureContent').fadeOut(400).addClass('hidden').delay(400); $('#advantageContent').fadeOut(400).addClass('hidden').delay(400); $('#benefitsContent').fadeIn(400).removeClass('hidden').delay(400); $('#featureContent').fadeIn(400).removeClass('hidden').delay(400); $('#advantageContent').fadeOut(400).addClass('hidden').delay(400); $('#benefitsContent').fadeOut(400).addClass('hidden').delay(400); i++ }; }); </code></pre> <p>fiddle: <a href="https://jsfiddle.net/nn4hgrv2/#&amp;togetherjs=kcgRhDRIGb" rel="nofollow">https://jsfiddle.net/nn4hgrv2/#&amp;togetherjs=kcgRhDRIGb</a></p>
HTML select options from a python list <p>I'm writing a python cgi script to setup a Hadoop cluster. I want to create an HTML select dropdown where the options are taken from a python list. Is this possible?? I've looked around a lot. Couldn't find any proper answer to this.</p> <p>This is what i've found so far on another thread...</p> <pre><code>def makeSelect(name,values): SEL = '&lt;select name="{0}"&gt;\n{1}&lt;/select&gt;\n' OPT = '&lt;option value="{0}"&gt;{0}&lt;/option&gt;\n' return SEL.format(name, ''.join(OPT.format(v) for v in values)) </code></pre> <p>I really need some help. Please. Thanks.</p>
<p>You need to generate a list of "option"s and pass them over to your javascript to make the list</p> <pre><code>values = {"A": "One", "B": "Two", "C": "Three"} options = [] for value in sorted(values.keys()): options.append("&lt;option value='" + value + "'&gt;" + values[value] + "&lt;/option&gt;") </code></pre> <p>Then inject "options" into your html. Say, in your "template.html" there is a line:</p> <pre><code>var options = $python_list; </code></pre> <p>Then at the end of your python script:</p> <pre><code>####open the html template file, read it into 'content' html_file = "template.html" f = open(html_file, 'r') content = f.read() f.close() ####replace the place holder with your python-generated list content = content.replace("$python_list", json.dumps(options)) ####write content into the final html output_html_file = "index.html" f = open(output_html_file, 'w') f.write(temp_content) f.close() </code></pre> <p>In your "index.html", you should have one line after "var options = ..." that takes the list and generate the dropdown.</p> <pre><code>$('#my_dropdown').append(options.join("")).selectmenu(); </code></pre> <p>Alternatively, I suggest that you use your python to generate a json file (with json.dumps()), a file called "config.json" maybe. And your html javascript file should read this json file to render the final page. So in your json file, there should be something like:</p> <p>{ ... "options": ["One", "Two", "Three"] ...}</p> <p>And in your html section, you could read the option values</p> <pre><code>d3.json("config.json", function(data)) { var options = []; for (var i= 0; i &lt; data.options.length; i++) { options.push("&lt;option value='" + data.options[i] + "'&gt;" + data.options[i] + "&lt;/option&gt;"); } $('#my_dropdown').append(options.join("")).selectmenu(); } </code></pre>
Simple Flatbuffers over ZeroMQ C example - Copy struct to flatbuffer over zmq and back to a struct again <p>Posting my work for posterity. Realized after finishing my last example in C++ that I actually needed to do it in C all along (awesome, right?). Both iterations took me considerable effort as a Java programmer and I think a lot of the sample code out there leaves far too many holes - <em>especially</em> when it comes to building which is considerably more difficult from the command line for someone who is used to using, say Eclipse, to build a project and handle dependencies.</p> <p>How to install dependencies for OSX with brew:</p> <p><code>brew install flatcc</code><br> <code>brew install zeromq</code></p> <p>You'll need all the standard builder binaries installed as well. I used gcc to compile with:</p> <p><code>gcc publisher.c -o bin/zmq_pub -lzmq -lflatcc</code><br> <code>gcc subscriber.c -o bin/zmq_sub -lzmq</code></p> <p>This assumes you've installed the zmq and flatcc libraries which should get symlinked to your /usr/local/include after brew finishes installing them. Like this:</p> <p><code> zmq_cpub $ls -la /usr/local/include lrwxr-xr-x 1 user group 37 Oct 18 18:43 flatcc -&gt; ../Cellar/flatcc/0.3.4/include/flatcc </code></p> <p>You'll get compilation errors such as: <code>Undefined symbols for architecture x86_64:</code> if you don't have the libraries correctly installed / linked. The compiler / linker will rename functions and prefix them with _ and potentially confuse the hell out of you. Like <code>Undefined symbols for architecture x86_64 _flatcc_builder_init</code> even though there never is supposed to be an <code>_flatcc_builder_init</code>. </p> <p>That's because linking libraries in C / C++ is fundamentally different than in Java. Instead of a specific project build path that you add JARs too there are known locations where external C / C++ libraries can install to. <code>/usr/local/include</code>, <code>/usr/local/lib</code>, <code>/usr/lib</code>, and <code>/usr/include</code>.</p> <p>And don't forget to generate the header files to use in your local project after installing the flatcc binary to your path:</p> <p><code>flatcc -a Car.fbs</code></p> <p>That should be pretty much every obstacle I faced on my trip down C lane. Hope it helps someone out there. </p>
<p>Car.fbs</p> <pre><code>namespace Test; table Car { name: string; model: string; year: int; } root_type Car; </code></pre> <p>Subscriber.c (listens for incoming structs)</p> <pre><code>// Hello World client #include "flatbuffers/Car_builder.h" // Generated by `flatcc`. #include "flatbuffers/flatbuffers_common_builder.h" #include &lt;zmq.h&gt; #undef ns #define ns(x) FLATBUFFERS_WRAP_NAMESPACE(Test, x) // Specified in the schema struct Car { char* name; char* model; int year; }; int main (void) { printf ("Connecting to car world server...\n"); void *context = zmq_ctx_new (); void *requester = zmq_socket (context, ZMQ_REQ); zmq_connect (requester, "tcp://localhost:5555"); int request_nbr; for (request_nbr = 0; request_nbr != 10; request_nbr++) { char buffer [1024]; printf ("Sending ready signal %d...\n", request_nbr); zmq_send (requester, "Hello", 5, 0); zmq_recv (requester, buffer, 1024, 0); printf ("Received car %d\n", request_nbr); ns(Car_table_t) car = ns(Car_as_root(buffer)); int year = ns(Car_year(car)); flatbuffers_string_t model = ns(Car_model(car)); flatbuffers_string_t name = ns(Car_name(car)); struct Car nextCar; // no need to double up on memory!! // strcpy(nextCar.model, model); // strcpy(nextCar.name, name); nextCar.model = model; nextCar.name = name; nextCar.year = year; printf("Year: %d\n", nextCar.year); printf("Name: %s\n", nextCar.name); printf("Model: %s\n", nextCar.model); } zmq_close (requester); zmq_ctx_destroy (context); return 0; } </code></pre> <p>Publisher.c (sends structs over zmq socket):</p> <pre><code>// Hello World server #include "flatbuffers/Car_builder.h" // Generated by `flatcc`. #include "flatbuffers/flatbuffers_common_builder.h" #include &lt;zmq.h&gt; #include &lt;unistd.h&gt; #include &lt;time.h&gt; #undef ns #define ns(x) FLATBUFFERS_WRAP_NAMESPACE(Test, x) // specified in the schema struct Car { char name[10]; char model[10]; int year; }; struct Car getRandomCar() { struct Car randomCar; int a = rand(); if ((a % 2) == 0) { strcpy(randomCar.name, "Ford"); strcpy(randomCar.model, "Focus"); } else { strcpy(randomCar.name, "Dodge"); strcpy(randomCar.model, "Charger"); } randomCar.year = rand(); return randomCar; } int main (void) { srand(time(NULL)); // Socket to talk to clients void *context = zmq_ctx_new (); void *responder = zmq_socket (context, ZMQ_REP); int rc = zmq_bind (responder, "tcp://*:5555"); assert (rc == 0); int counter = 0; while (1) { struct Car c = getRandomCar(); flatcc_builder_t builder, *B; B = &amp;builder; // Initialize the builder object. flatcc_builder_init(B); uint8_t *buf; // raw buffer used by flatbuffer size_t size; // the size of the flatbuffer // Convert the char arrays to strings flatbuffers_string_ref_t name = flatbuffers_string_create_str(B, c.name); flatbuffers_string_ref_t model = flatbuffers_string_create_str(B, c.model); ns(Car_start_as_root(B)); ns(Car_name_add(B, name)); ns(Car_model_add(B, model)); ns(Car_year_add(B, c.year)); ns(Car_end_as_root(B)); buf = flatcc_builder_finalize_buffer(B, &amp;size); char receiveBuffer [10]; zmq_recv (responder, receiveBuffer, 10, 0); printf ("Received ready signal. Sending car %d.\n", counter); sleep (1); // Do some 'work' zmq_send (responder, buf, size, 0); counter++; free(buf); } return 0; } </code></pre>
Why can't node can't find the static directory? <p>I set up node so that it serves my public folder. Now I am trying to access the files in the public/data/event folder structure but it can't find it.</p> <pre><code>Here is my file structure public/ data/ event/ src/ scripts/eventController.js webserver.js </code></pre> <p>This my eventsController.js file. This file tries to access files in the public/data/event/ folder structure but can't find them.</p> <pre><code>'use strict'; let fs = require('fs'); module.exports.get = function(req, res) { let event = fs.readFileSync('../public/data/event/' + req.params.id + '.json', 'utf8'); res.setHeader('Content-Type', 'application/json'); res.send(event); }; module.exports.save = function(req, res) { let event = req.body; fs.writeFileSync('../public/data/event/' + req.params.id + '.json', JSON.stringify(event)); res.send(event); }; module.exports.getAll = function(req, res) { let path = '../public/data/event/'; let files = []; try { files = fs.readdirSync(path); } catch (e) { console.log(e); res.send('[]'); res.end(); } let results = '['; for (let idx = 0; idx &lt; files.length; idx++) { if (files[idx].indexOf('.json') === files[idx].length - 5) { results += fs.readFileSync(path + '/' + files[idx]) + ','; } } results = results.substr(0, results.length - 1); results += ']'; res.setHeader('Content-Type', 'application/json'); res.send(results); res.end(); }; </code></pre> <p>This is the webserver file, where I server the public folder</p> <pre><code>'use strict'; let express = require('express'); let port = process.env.PORT || 5000; let path = require('path'); let app = express(); let events = require('./scripts/eventsController'); let rootPath = path.normalize(__dirname + '/../'); let bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.use(express.static(rootPath + '/public')); app.use('/bower_components', express.static(__dirname + '/../public/lib/')); app.use("/public", express.static(path.join(__dirname, 'public'))); app.get('/data/event/:id', events.get); app.get('/data/event', events.getAll); app.post('/data/event/:id', events.save); app.get('*', function(req, res) { res.sendFile(rootPath + '/public/index.html'); }); app.listen(port, function(err) { if (err) { console.log('There was an error creating the system'); } console.log('running server on port ' + port); }); </code></pre> <p>This is the error that I get from the terminal.<a href="https://i.stack.imgur.com/hU0n8.png" rel="nofollow"><img src="https://i.stack.imgur.com/hU0n8.png" alt="enter image description here"></a></p>
<p>It's because fs.readFile('public/data/event/') from src/scripts/eventController.js looks for the stuff in 'src/scripts/public/data/event/', not 'public/data/event'. You should go with fs.readFile('../../public/data/event'). Or better yet, always use absolute paths.</p>
selenium run chrome on raspberry pi <p>If your seeing this I guess you are looking to run chromium on a raspberry pi with selenium.</p> <p>like this <code>Driver = webdriver.Chrome("path/to/chomedriver")</code> or like this <code>webdriver.Chrome()</code></p>
<p>I have concluded that after hours and a hole night of debugging that you can't because there is no chromedriver compatible with a raspberry pi processor. Even if you download the linux 32bit. You can confirm this by running this in a terminal window <code>path/to/chromedriver</code> it will give you this error </p> <blockquote> <p>cannot execute binary file: Exec format error</p> </blockquote> <p>hope this helps anyone that wanted to do this :)</p>
jq - How to select objects based on a 'blacklist' of property values <p>Similar to the question answered here: <a href="http://stackoverflow.com/questions/34878915/jq-how-to-select-objects-based-on-a-whitelist-of-property-values" title="jq - How to select objects based on a &#39;whitelist&#39; of property values">jq - How to select objects based on a 'whitelist' of property values</a>, I'd like to select objects based on a blacklist of property values...</p> <p>The following works fine as a whitelist: <code>curl -s 'https://api.github.com/repos/stedolan/jq/commits?per_page=10' | jq --argjson whitelist '["stedolan", "dtolnay"]' '.[] | select(.author.login == $whitelist[]) | {author: .author.login, message: .commit.message}'</code></p> <pre><code>{ "author": "dtolnay", "message": "Remove David from maintainers" } { "author": "stedolan", "message": "Make jv_sort stable regardless of qsort details." } { "author": "stedolan", "message": "Add AppVeyor badge to README.md\n\nThanks @JanSchulz, @nicowilliams!" } </code></pre> <p>The problem is, I want to negate that and only show commits from authors besides 'stedolan' and 'dtolnay'; however, if I use <code>!=</code> or <code>not</code>, I seem to get the same wrong result:</p> <pre><code>nhenry@BONHENRY:~⟫ curl -s 'https://api.github.com/repos/stedolan/jq/commits?per_page=10' | jq --argjson blacklist '["stedolan", "dtolnay"]' '.[] | select(.author.login == $blacklist[] | not) | .author.login' | sort | uniq -c | sort -nr 14 "nicowilliams" 2 "stedolan" 1 "dtolnay" nhenry@BONHENRY:~⟫ curl -s 'https://api.github.com/repos/stedolan/jq/commits?per_page=10' | jq --argjson blacklist '["stedolan", "dtolnay"]' '.[] | select(.author.login != $blacklist[]) | .author.login' | sort | uniq -c | sort -nr 14 "nicowilliams" 2 "stedolan" 1 "dtolnay" </code></pre> <p>Any suggestions?</p>
<p>One solution would simply be to use <code>index</code> with <code>not</code>:</p> <pre><code>.[] | .author.login | select( . as $i | $blacklist | index($i) | not) </code></pre> <p>However, assuming your jq has <code>all/2</code>, there is something to be said for using it:</p> <pre><code>.[] | .author.login | select( . as $i | all($blacklist[]; $i != .)) </code></pre> <p>If your jq does not have it, then there is still something to be said for using this solution, with <code>all/2</code> defined as follows:</p> <pre><code>def all(s; condition): reduce s as $i (true; . and ($i | condition)); </code></pre>
Have a user create files with 777 permission in linux <p>I have an application. The processes for the application have cacheusr as user. When I create files in the application I get the following ownership and permission:</p> <pre><code>aless80&gt; ls -FGlAhpa test.xml -rwxrw-r-- 1 cacheusr 1.6K Oct 19 16:41 test.xml </code></pre> <p>My question is: how to make sure the created files have permission 777 by default? I just added aless80 to the cacheusr group, but that does not help.</p> <pre><code>aless80&gt; groups aless80 aless80 : aless80 adm cdrom sudo dip plugdev staff lpadmin sambashare cacheusr vboxusers aless80&gt; id aless80 uid=1000(aless80) gid=1000(aless80) groups=1000(aless80),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),50(staff),108(lpadmin),110(sambashare),1001(cacheusr),999(vboxusers) aless80&gt; groups cacheusr cacheusr : cacheusr root aless80&gt; id cacheusr uid=1001(cacheusr) gid=1001(cacheusr) groups=1001(cacheusr),0(root) </code></pre>
<p>you can control the permissions of newly created files with the <code>umask</code> command:</p> <pre><code>$ umask u+rwx,g+rwx,o+rwx $ touch foo; mkdir bar $ ls -ld foo bar -rw-rw-rw- 1 user user 0 Oct 20 00:00 foo drwxrwxrwx 2 user user 1024 Oct 20 00:00 bar $ </code></pre>
Google Compute Engine canceling execution (Linux - execute on background) <p>[Solved] - It was actually a Linux question</p> <p>I have an instance on Google Compute Engine that I want to execute 50000 iterations of a Genetic Algorithm. The thing is everytime I lose the SSH connection, it cancels the execution and I don't want it to happen.</p> <p>I've searched the options and for similar problems on the internet but I couldn't find any help.</p> <p>Is there any way to keep the execution on the Google Cloud instance even if I'm not connected via SSH?</p>
<p>This is a Linux question, not specific to GCE. Just use the <code>nohup &lt;command&gt; &amp;</code> pattern. For example, the following command will start a HTTP server on port 8080, even if you disconnect from SSH, it remains running in the background:</p> <pre><code>nohup python -m SimpleHTTPServer 8080 &amp; </code></pre>
Easier way to check if a string contains only one type of letter in python <p>I have a string <code>'829383&amp;&amp;*&amp;@&lt;&lt;&lt;&lt;&gt;&gt;&lt;&gt;GG'</code>. I want a way to measure if a string has only one type of letter. For example the string above would return True, because it only has two Gs, but this string, <code>'829383&amp;&amp;*&amp;@&lt;&lt;&lt;&lt;&gt;&gt;&lt;&gt;GGAa'</code> would not. I've been iteratively going through the string having made it into an array. I was hoping someone knew an easier way. </p>
<p>use <code>filter</code> with <code>str.isalpha</code> function to create a sublist containing only letters, then create a set. Final length must be one or your condition isn't met.</p> <pre><code>v="829383&amp;&amp;&amp;@&lt;&lt;&lt;&lt;&gt;&gt;&lt;&gt;GG" print(len(set(filter(str.isalpha,v)))==1) </code></pre>
Using the OVER clause in T-SQL to SELECT DISTINCT on all columns except one <p>I have a table with colA, colB, colC, colD. I need to SELECT DISTINCT on all columns except for colA. I've found some examples that demonstrate the use of the OVER clause in T-SQL to achieve this; however, they have been pretty specific, and as such, difficult to apply to my situation. Any insight anyone can will be so greatly appreciated.</p>
<p>You can use DENSE_RANK twice, one with ASC order, the other with DESC order, than add them up and subtract 1. That way, you got the SELECT DISTINCT with the OVER clause.</p>
C++ - Assignment of raw pointers to unique_ptr nodes in a Linked List <p>I'm trying to figure out how to update my tail raw pointer to a new tail after removing a node in my linked list. (is homework)</p> <p>I've defined the head and tail as</p> <pre><code> std::unique_ptr&lt;Node&gt; head ; Node* tail ; </code></pre> <p>and in my function for removing a node from the back I have the following implementation. </p> <pre><code>int Deque::remove_back(){ if (empty()) {throw std::runtime_error(std::string("Empty"));}; std::unique_ptr&lt;Node&gt; old; Node* p = head.get(); int return_value = tail-&gt;val; while (p-&gt;next != tail) {p = p-&gt;next)} old = move(tail); tail = p; return return_value; } </code></pre> <p>So tail is a raw pointer of type Node. P is a raw pointer of type Node. </p> <p>Head is a unique pointer of type Node. </p> <p>I'm setting p = head.get()</p> <p>so now p points to the head</p> <p>p = p->next should be iterating down my nodes.</p> <p>The problem is that <code>p-&gt;next != tail</code> </p> <p>p->next is a pointer to the next node following whatever p is. </p> <p>I'm trying to set a pointer to a node to be equal to a raw pointer of type node (tail).</p> <p>Its telling me I can't do this. </p> <p>I believe its due to p->next not changing into an owning pointer instead of the observing one I declared it to be. </p> <p>Errors: </p> <pre><code>Deque.cpp|68|error: no match for 'operator!=' (operand types are 'std::unique_ptr&lt;Node&gt;' and 'Node*')| Deque.cpp|69|error: cannot convert 'std::unique_ptr&lt;Node&gt;' to 'Node*' in assignment| Deque.cpp|71|error: no match for 'operator=' (operand types are 'std::unique_ptr&lt;Node&gt;' and 'std::remove_reference&lt;Node*&amp;&gt;::type {aka Node*}')| </code></pre>
<p>The error messages imply that <code>Node::next</code> is a <code>std::unique_ptr&lt;Node&gt;</code>. You cannot compare/assign a <code>std::unique_ptr</code> directly to a raw pointer. You need to use the <code>std::unique_ptr::get()</code> method instead:</p> <pre><code>while (p-&gt;next.get() != tail) { p = p-&gt;next.get(); } </code></pre> <p>Also, your loop is not taking into account when the list has only 1 node in it (<code>head == tail</code>). <code>p-&gt;next</code> will be <code>nullptr</code> on the second iteration and crash. And since you would be removing the last node in the list, you would need to reset <code>head</code> to <code>nullptr</code>. Either way, when assigning <code>p</code> as the new <code>tail</code>, you need to reset <code>p-&gt;next</code> to <code>nullptr</code> so it will no longer be pointing at the old node.</p> <p>Try this:</p> <pre><code>int Deque::remove_back(){ if (empty()) { throw std::runtime_error("Empty"); } int return_value = tail-&gt;val; if (!head-&gt;next) { head = nullptr; // or: head.reset(); tail = nullptr; } else { Node* p = head.get(); Node *prev = p; while (p-&gt;next-&gt;next) { p = p-&gt;next.get(); prev = p; } tail = prev; tail-&gt;next = nullptr; // or: tail-&gt;next.reset(); } return return_value; } </code></pre> <p>That being said, it can be tricky using <code>std::unique_ptr</code> in a linked-list implementation. If you want automatic destruction of nodes, you could just use raw pointers and wrap the list inside of a class that destroys the nodes when itself is destroyed, and then <code>remove_back()</code> can destroy the node being removed.</p> <p>The STL already has such classes available: <code>std::list</code> (double linked) and <code>std::forward_list</code> (single linked). You should be using them instead of a manual list implementation.</p>
gettext.tostring method cannot resolved <p>I am trying to send data to firebase. I want to call the time and date in a method and then the method that is responsible for sending data to fire base. When I try to call time and date it gives me an error.</p> <p>Here is my code.</p> <pre><code>public class Room1 extends AppCompatActivity { boolean hasSetTime = false; boolean hasSetDate = false; boolean hasSetTime1 = false; @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.room1); final Calendar c = Calendar.getInstance(); final int year = c.get(Calendar.YEAR); final int month = c.get(Calendar.MONTH); final int day = c.get(Calendar.DAY_OF_MONTH); final int hour = c.get(Calendar.HOUR_OF_DAY); final int minute1 = c.get(Calendar.MINUTE); final Calendar v = Calendar.getInstance(); final int hour2 = v.get(Calendar.HOUR_OF_DAY); final int minute2 = v.get(Calendar.MINUTE); final String date; final EditText ft1; final EditText fd1; final EditText e1; ft1 = (EditText) findViewById(R.id.ft1); fd1 = (EditText) findViewById(R.id.fd1); e1 = (EditText) findViewById(R.id.e1); fd1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DatePickerDialog datepick = new DatePickerDialog(Room1.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { fd1.setText(dayOfMonth + "/" + month + "/" + year); SimpleDateFormat dateFormatter; Date d; String entered_dob; d = new Date(year, month, day); dateFormatter = new SimpleDateFormat("MM-dd-yyyy"); entered_dob = dateFormatter.format(fd1.getText()); hasSetDate = true; sendDataToFireBase(); } }, year, month, day); datepick.setTitle("select date"); datepick.show(); } }); e1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TimePickerDialog timepickend = new TimePickerDialog(Room1.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { e1.setText(hourOfDay + ":" + minute); hasSetTime = true; sendDataToFireBase(); } }, hour2, minute2, true ); timepickend.setTitle("select time"); timepickend.show(); } }); ft1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TimePickerDialog timepick = new TimePickerDialog(Room1.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay2, int minute2) { ft1.setText(hourOfDay2 + ":" + minute2); hasSetTime1=true; sendDataToFireBase(); } }, hour, minute1, true ); timepick.setTitle("select time"); timepick.show(); } } ); } public void sendDataToFireBase() { if (hasSetTime == true &amp;&amp; hasSetDate==true&amp;&amp;hasSetTime1==true) { FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("Date"); myRef.setValue(ft1.getText().toString()); DatabaseReference myRef2 = database.getReference("Time"); myRef2.setValue(e1.getText().toString()); DatabaseReference myRef3 = database.getReference("Timereserved"); myRef2.setValue(fd1.getText().toString()); } } } </code></pre>
<pre><code>public void sendDataToFireBase() { ft1 // &lt;-----get rid of this if </code></pre>
Yes or No answer from user with Validation and restart option? <p>(py) At the moment, the code below does not validate/output error messages when the user inputs something other than the two choices "y" and "n" because it's in a while loop. </p> <pre><code>again2=input("Would you like to calculate another GTIN-8 code? Type 'y' for Yes and 'n' for No. ").lower() #** while again2 == "y": print("\nOK! Thanks for using this GTIN-8 calculator!\n\n") restart2() break #Break ends the while loop restart2() </code></pre> <p>I'm struggling to think of ways that will allow me to respond with an output when they input neither of the choices given. For example:</p> <pre><code>if again2 != "y" or "n" print("Not a valid choice, try again") #Here would be a statement that sends the program back to the line labelled with a ** </code></pre> <p>So, when the user's input is not equal to "y" or "n" the program would return to the initial statement and ask the user to input again. Any ideas that still supports an efficient code with as little lines as possible? Thanks!</p>
<pre><code>def get_choice(prompt="Enter y/n?",choices=["Y","y","n","N"],error="Invalid choice"): while True: result = input(prompt) if result in choices: return result print(error) </code></pre> <p>is probably a nice generic way to approach this problem</p> <pre><code>result = get_choice("Enter A,B, or C:",choices=list("ABCabc"),error="Thats not A or B or C") </code></pre> <p>you could of coarse make it not case sensitive... or add other types of criteria (e.g. must be an integer between 26 and 88) </p>
C# DataTable - How to set a column to value without for loop? <p>I have a DataTable called dataTable that has two columns Col1 and Col2 and it contains five rows all initialized to null. How would I set the values in Col1 and Col2 to "1" and "2" respectively without using a for loop or foreach loop for each DataRow?</p>
<p>Use 10 assignment statements. No loop required.</p>
Ng-submit called twice with Routeprovider <p>I use the same <code>form</code> to create and update users in database. I can update properly, but when I create one user, submit send twice and create two same users in database.</p> <p>I have this in <code>RouteProvider</code>.</p> <pre><code> .config(function($routeProvider) { $routeProvider .when("/users", { controller: "MainControlador", templateUrl: "templates/users.html" }) .when("/user/:id", { controller: "UserControlador", templateUrl: "templates/user.html" }) .when("/users/edit/:id", { controller: "UserControlador", templateUrl: "templates/form.html" }) .when("/users/new", { controller: "NewUserControlador", templateUrl: "templates/form.html" }) .when("/", { templateUrl: "templates/main.html" }) .otherwise("/"); }) </code></pre> <p>This is my <code>form</code> </p> <pre><code>&lt;div&gt; &lt;form ng-submit="saveUser()"&gt; &lt;input ng-model="user.name" type="text" required&gt; &lt;input ng-model="user.surname" type="text" required&gt; &lt;input ng-model="user.phone" type="text"required&gt; &lt;input ng-model="user.email"type="text" required&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>And finally i use this <code>controller</code></p> <pre><code>//Controller Update .controller("UserControlador", function($scope, $routeParams, UserAPI) { $scope.title = "Edit user"; UserAPI.getOne($routeParams.id).success(function(data) { //Get Array First Element $scope.user = data[0]; }) $scope.saveUser = function() { var data = ({ id: $routeParams.id, name: $scope.user.name, surname: $scope.user.surname, phone: $scope.user.phone, email: $scope.user.email }); UserAPI.update(data).success(function(data) { $scope.user = data; }) } }) //Controller Create .controller("NewUserControlador", function($scope, UserAPI) { $scope.title = "Add user"; $scope.saveUser = function() { var data = ({ name: $scope.user.name, surname: $scope.user.surname, phone: $scope.user.phone, email: $scope.user.email, }); UserAPI.create(data).success(function(data) { console.log(data); $scope.user = data; }) } }) </code></pre> <p>¿Any idea what happen here? I tried to use console.log but apparently all works fine. I tried to use too Angular batarang to debug angular calls but don´t work.</p>
<p>You have declared two controllers, one for saving the user (<em>NewUserControlador</em>) and one for updating <em>(UserControlador)</em>. Both methods are called saveUser() and they are declared on the $scope. </p> <p>There might be a conflict because of the same name. Why don't you use one Controller for those operations? They are all CRUD operations for the same Entity (User) after all. </p> <p>If you still want to use two different controllers, you could use some logging to find out what is happening or a greater idea would be to rename the update method in the UserControlador.</p> <p>More information about scopes can be found <a href="https://docs.angularjs.org/guide/scope" rel="nofollow">here</a></p>
Windows - Where can I find a system() list of parameters? <p>This is my first question here in StackOverflow, so if this question has already been made or is in the wrong topic, please excuse me.</p> <p>I'm studying C using Windows and I'm looking for a list/book/manual of usable parameters for the system() function. Stuff like system("pause"), system("cls"), system("color 1f"), etc...</p> <p>Thanks for the help in advance.</p>
<p>The purpose of system() API is to execute an external command, the parameters are the arguments of the command that you are trying to execute, just like if you were typed in shell prompt, there is not anything special to pass, just put into the string.</p>
writing data into mysql with mysqli_real_escape_string() but without & <p>iam using this code below, but the character "&amp;" will not be inserted into the db, also when i copy/paste some text from other pages and put it into the db the text ends for example in the middle of the text, dont know why, i tried also addslashes() and htmlspecialchars() or htmlentities().</p> <p>i read mysqli_real_escape_string() is againt SQL injection attacks and htmlspecialchars() against XSS attachs, should i also combine them ?</p> <pre><code>$beschreibung = mysqli_real_escape_string($db, $_POST['beschreibung']); </code></pre>
<p>SQL Injection is merely just improperly formatted queries. What you're doing is not enough, stop now. Get into the practice of using prepared statements.. </p> <pre><code>$Connection = new mysqli("server","user","password","db"); $Query = $Connection-&gt;prepare("SELECT Email FROM test_tbl WHERE username=?"); $Query-&gt;bind_param('s',$_POST['ObjectContainingUsernameFromPost']); $Query-&gt;execute(); $Query-&gt;bind_result($Email); $Query-&gt;fetch(); $Query-&gt;close(); </code></pre> <p>Above is a very basic example of using prepared statements. It will quickly and easily format your query.</p> <p>My best guess to what is happening, I'm assuming you're just using the standard:</p> <pre><code>$Query = mysqli_query("SELECT * FROM test_tbl WHERE Username=".$_POST['User']); </code></pre> <p>As this query is not properly formatted you may have the quotes in your chunk of text which close the query string. PHP will then interpret everything as a command to send to the SQL server</p>
Bootstrap multiple root modules each with different providers (provided from outside) <p>My application is not a SPA but I use Angular 2 for some parts of the page. I have created multiple root modules that I bootstrap with injectable providers which contain informations from the outside world:</p> <p>Root module 1:</p> <pre><code>let serviceOne = new ServiceOne("SuperImportantInfoFromSomewhere"); let providers: any = [{ provide: ServiceOne, useValue: serviceOne }]; platformBrowserDynamic(MyFirstRootModule, providers); </code></pre> <p>Root module 2, somewhere at the bottom of the page:</p> <pre><code>let serviceTwo = new ServiceTwo(42); let providers: any = [{ provide: ServiceTwo, useValue: serviceTwo }]; platformBrowserDynamic(MySecondRootModule, providers); </code></pre> <p>Sadly, this does not work. When I want <code>ServiceTwo</code> to get injected into a component, it fails. It only works if I provide both services at the first bootstrap (in this case <code>MyFirstRootModule</code>). It must be something related to the new DI system I don't fully understand.</p> <p>Since I work within a CMS I do not know all providers at the first bootstrap; the two modules do not even know each other.</p> <p>Is there a way to completely separate those two modules or somehow provide the second service to the DI system after the first root module has been bootstraped?</p>
<p>I came up with a very dirty workaround. Before bootstraping the module I add the provider directly to the annotations of the class using the Reflect API:</p> <pre><code>import "reflect-metadata"; import { MySecondRootModule } from "MySecondRootModule"; import { ServiceTwo } from "ServiceTwo"; export class MySecondRootApplication { constructor() { let serviceTwo = new ServiceTwo(42); let annotations: Array&lt;any&gt; = (Reflect as any).getMetadata("annotations", MySecondRootModule); if (annotations[0].providers != undefined) { annotations[0].providers.push({ provide: ServiceTwo, useValue: serviceTwo }); } else { annotations[0].providers = [{ provide: ServiceTwo, useValue: serviceTwo }]; } (Reflect as any).defineMetadata("annotations", annotations, type); // Perform what ever else needs to be done platformBrowserDynamic(MySecondRootModule); } } </code></pre> <p>I know, it's bad. But it works. By the way: Using this method also provides the ability to alter the templateUrl, for example if you want to use an ASP.NET MVC partial view result.</p>
Passing string from spinner to second activity <p>I'm building an app in which the first activity contains a spinner with strings "Red", "Yellow", "Blue" and "Green". When the user selects a spinner item, the second activity's background will be that color. I'm having issues with passing that value from the MainActivity class to the Display class. </p>
<p>In case you wonder how to retrieve the spinner value : </p> <pre><code>String pickedColor = yourSpinner.getSelectedItem().toString(); </code></pre> <p>In your first Activity, when building intent do something like : </p> <pre><code>Intent intent = new Intent(MainActivity.this, DisplayActivity.class); intent.putExtra("COLOR_KEY", pickedColor); startActivity(intent); </code></pre> <p>Then in your second activity : </p> <pre><code>String color = getIntent().getStringExtra("COLOR_KEY"); </code></pre> <p>Then do whatever you need :)</p>
InputStream reading file and counting lines/words <p>I'm working on a project and I'm trying to count </p> <p>1) The number of words. 2) The number of lines in a text file. </p> <p>My problem is that I can't figure out how to detect when the file goes to the next line so I can increment lines correctly. Basically if next is not a space increment words and if next is a new line, increment lines. How would I do this? Thanks!</p> <pre><code>public static void readFile(Scanner f) { int words = 0; int lines = 0; while (f.hasNext()) { if (f.next().equals("\n")) { lines++; } else if (!(f.next().equals(" "))) { words++; } } System.out.println("Total number of words: " + words); System.out.println("Total number of lines: " + lines); } </code></pre>
<p>Do you have to use InputStream? (Yes) It is better to use a BufferedReader with an InputStreamReader passed in so you can read the file line by line and increment while doing so.</p> <pre><code>numLines = 0; try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = br.readLine()) != null) { numLines++; // process the line. } } </code></pre> <p>Then to count the words just split the string using a regular expression that finds whitespaces. <code>myStringArray = MyString.Split(MyRegexPattern);</code> will then return a <code>String[]</code> of all the words. Then all you do is <code>numWords += myStringArray.length();</code></p>
How to get the Original Row and the Modified Row of DataRowView using DataRowViewVersion <p>I have a datatable that is filled from a database. I load a bindingsource with that table.</p> <pre><code>Sub LoadData() Dim bsTemp As BindingSource = New BindingSource bsTemp.DataSource = dtTemp End Sub </code></pre> <p>I then have other code programmatically editing the values in the datatable. I NEVER call AcceptChanges() ..let me be clear NEVER.</p> <p>I do call bsTem.EndEdit() and I also call that on my dtTemp.Row(x).EndEdit() Whenever I make a change to it.</p> <p>So now all I want to do is compare the two rows (I know I can do this with a for each column but I am not wanting to do that.) </p> <p>I would like to know how to make this work:</p> <pre><code>Dim modview As New DataView(dtTemp.Copy, "", "Id", DataViewRowState.ModifiedCurrent) Dim origView As New DataView(dtTemp.Copy, "", "Id", DataViewRowState.ModifiedOriginal) </code></pre> <p>So I can then perform something like this:</p> <pre><code> Dim rowComparer As DataRowComparer(Of DataRow) = DataRowComparer.Default IsEqual = rowComparer.Equals(origRow.Row, modRow.Row) </code></pre> <p>When I do this both views show the Modified data, one of them should only show me the Original unmodified Row. </p> <p>I know I can do this [C# version]:</p> <pre><code>SomeDataRow[0, DataRowVersion.Original] //by index SomeDataRow["ColumnName", DataRowVersion.Original] </code></pre> <p>But again tis works on a column by column basis - me being the iterator - and I see no reason to do that when the DataView supposedly has this built in . So what could I be doing wrong that I do not see the original version .</p>
<p>The <code>New DataView(..)</code> does not determine which rows to copy, it only says what the state of the rows after they are in the view will have. Your first parameter says which rows <code>dtTemp.Copy</code>.</p> <p>Since the <code>copy</code> method of a datatable is a copy of all rows, you might want to use something like the <code>select</code> method, which allows you to filter based on state.</p> <pre><code>dtTemp.Select("","",ModifiedOriginal) </code></pre> <p>EDIT:</p> <p>There must be an issue with getting it that way. According to the example given from <a href="https://msdn.microsoft.com/en-us/library/system.data.dataviewrowstate.aspx" rel="nofollow">MSDN</a>, it should work if you use the <code>DataView.RowStateFilter</code>. I tested it and it did work. I think the key is that the <code>DataView</code> controls what you see. If you look at the raw data through the <code>DataRow</code>, it is always current.</p>
How to convert a txt stream web request containing json to a jObject? <p>Trying to use a query Google has available, but they return an attached txt file containing the JSON results. I'm a newbie programmer, so I can't figure out why any of the shots I took aren't working.</p> <pre><code> public async Task&lt;YouTubeSearchResult&gt; SearchYouTubeAsync(string query) { var result = new YouTubeSearchResult(); string errorMessage = ""; try { string encodedName = WebUtility.UrlEncode(query); Uri url = new Uri($"http://suggestqueries.google.com/complete/search?client=firefox&amp;ds=yt&amp;q={encodedName}"); HttpClient client = new HttpClient(); Stream streamResult = await client.GetStreamAsync(url); StreamReader reader = new StreamReader(streamResult); errorMessage = JsonConvert.SerializeObject(reader.ReadToEnd()); JObject jsonResults = JObject.Parse(JsonConvert.SerializeObject(reader.ReadToEnd())); result.Success = true; result.Message = "Success getting search results"; result.SearchResults = jsonResults; } catch (Exception ex) { result.Success = false; result.Message = $"Server error getting search results: {errorMessage} | {ex}"; result.SearchResults = null; } return result; } } </code></pre> <p>This is the response along with the error code I get.</p> <pre><code>{ "success": false, "message": "Server error getting search results: \"[\"search\",[\"search\",\"search and destroy\",\"searching for my baby bobby moore\",\"search engine optimization\",\"search and discard\",\"search for the worst\",\"search youtube\",\"searching\",\"search history\",\"search party sam bruno\"]]\" | Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 2.\r\n at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader, JsonLoadSettings settings)\r\n at Newtonsoft.Json.Linq.JObject.Parse(String json, JsonLoadSettings settings)\r\n at OdsCode.Services.YouTubeSearchService.&lt;SearchYouTubeAsync&gt;d__3.MoveNext()", "searchResults": null } </code></pre> <p>Adding the error and current results separately to clarify.</p> <blockquote> <p>| Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 2.\r\n at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader, JsonLoadSettings settings)\r\n at Newtonsoft.Json.Linq.JObject.Parse(String json, JsonLoadSettings settings)\r\n at OdsCode.Services.YouTubeSearchService.d__3.MoveNext()",</p> <p>"Server error getting search results: \"[\"search\",[\"search\",\"search and destroy\",\"searching for my baby bobby moore\",\"search and discard\",\"search for the worst\",\"search youtube\",\"search engine optimization\",\"searching\",\"search history\",\"search party sam bruno\"]]\" |</p> </blockquote> <p>Below is the response I get from google in postman</p> <pre><code>http://suggestqueries.google.com/complete/search?client=firefox&amp;ds=yt&amp;q=search Cache-Control →no-cache, must-revalidate Content-Disposition →attachment; filename="f.txt" Content-Encoding →gzip Content-Length →136 Content-Type →text/javascript; charset=UTF-8 Date →Wed, 19 Oct 2016 20:10:17 GMT Expires →-1 Pragma →no-cache Server →gws X-Frame-O ptions →SAMEORIGIN X-XSS-Protection →1; mode=block [ "search", [ "search", "search and destroy", "searching for my baby bobby moore", "search engine optimization", "search and discard", "search for the worst", "search youtube", "searching", "search history", "search party sam bruno" ] ] </code></pre> <p>Help me I been at it for days now... No food until I figure this out!!!!!</p>
<p>Problem one - you use <code>reader.ReadToEnd()</code> twice. First when you attempt to read errorMessage, Then on the next line you use it again. By the second time you have already read everything. Delete the line:</p> <pre><code>errorMessage = JsonConvert.SerializeObject(reader.ReadToEnd()); </code></pre> <p>Problem two - looks like the data you are receiving is an array so in order to read it you will need to use </p> <pre><code>JArray jsonResults = JArray.Parse(reader.ReadToEnd()); </code></pre>
c# outlook addin xml dynamic menu not populating <p>I am using ribbon xml to make a dynamic context menu and the menu appears, but is showing up inside the menu itself. I see "Dynamic Menu" and hover over the context menu button, but there are no contents.</p> <p>My xml:</p> <pre><code>&lt;contextMenus&gt; &lt;contextMenu idMso='ContextMenuCalendarItem'&gt; &lt;dynamicMenu id='MyDynamicMenu' label ='Dynamic Menu'getContent='GetMenuContent' /&gt; &lt;/contextMenu &gt; &lt;/contextMenus&gt; </code></pre> <p>and my GetMenuContent method:</p> <pre><code>public string GetMenuContent(Office.IRibbonUI ribbonUI) { string xmlString = "&lt;menu xmlns='http://schemas.microsoft.com/office/2009/07/customui'&gt;"; for (int i = 0; i &lt; AddInDefs.thisProjectList.Count; i++) { xmlString = xmlString + "&lt;button id='proj" + i + "' label='" + AddInDefs.thisProjectList[i].name.ToString() + "' onAction='displayMsg'/&gt;"; } xmlString = xmlString + "&lt;/menu&gt;"; return xmlString; } </code></pre> <p>I am thinking there is something wrong with the way I am making the GetMenuContent method. Thanks for the help in advance!</p>
<p>fixed by using:</p> <pre><code>StringBuilder xmlString = new StringBuilder(@"&lt;menu xmlns=""http://schemas.microsoft.com/office/2009/07/customui"" &gt;"); for (int i = 0; i &lt; AddInDefs.thisProjectList.Count; i++) { xmlString.Append(@"&lt;button id='proj" + i.ToString() + "' label='" + AddInDefs.thisProjectList[i].name.ToString() + "' onAction='displayMsg'/&gt;"); } xmlString.Append(@"&lt;/menu&gt;"); return xmlString.ToString(); </code></pre> <p>and changing <code>Office.IRibbonUI ribbonUI</code> to <code>Office.IRibbonControl control</code></p>
Angular 1.5 directive loop issue repeating the first element <p>referring to this plunker: <a href="https://plnkr.co/edit/kBoDTXmm2XbxXjpDA4M9?p=preview" rel="nofollow">https://plnkr.co/edit/kBoDTXmm2XbxXjpDA4M9?p=preview</a></p> <p>I am trying to create a directive that takes an array of json objects, syntax highlights them and its that syntax highlighted element in the page.</p> <p>I have had mixed results with different watching methods, but what I cant figure out in this one is why the same id:1 is showing all the way down the list, why not id:1, id:2, id:2, id:3 etc.</p> <pre><code>angular.module("ngjsonview",[]).directive('ngjsoncollection',['$sce', function(){ 'use strict'; return { transclude: false ,restrict:'E' ,scope:{ d:'=',o:"=" } ,templateUrl: "./template.htm" ,controller:function($scope,$sce){ var fnPretty = function(objData){ if (typeof objData != 'string') { var strOut = JSON.stringify(objData, undefined, 2); } strOut = strOut.replace(/&amp;/g, '&amp;amp;') .replace(/&lt;/g, '&amp;lt;') .replace(/&gt;/g, '&amp;gt;'); return strOut.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) { var cls = 'number'; if (/^"/.test(match)) { if (/:$/.test(match)) { cls = 'key';} else { cls = 'string'; } } else if (/true|false/.test(match)) { cls = 'boolean';} else if (/null/.test(match)) {cls = 'null'; } return '&lt;span class="' + cls + '"&gt;' + match + '&lt;/span&gt;'; }); }; $scope.html=$sce.trustAsHtml(fnPretty($scope.d)); $scope.$watchCollection('d',function(arrData){ $scope.arrHTML=[]; for (var i = 0, len = arrData.length; i &lt; len; i++) { $scope.arrHTML.unshift($sce.trustAsHtml(fnPretty(arrData[i]))); } }); } }; }]); </code></pre>
<p>moving the timeout into a function helped with the specific problem I had</p> <pre><code>$scope.arrData=[]; function addIt(x) { $timeout(function(){ $scope.arrData.push({id:x}); }, 100); } for(var i=0; i &lt; 100; i++){ addIt(i) } </code></pre>
Is it idiomatic in go to handle all returned errors? <p>Many functions in go return errors to fit an interface, but these errors are always nil. Should these errors still be checked?</p> <p>An example for this is the <a href="https://golang.org/src/crypto/sha1/sha1.go?s=1064:1418" rel="nofollow">crypto/sha1 Write() function</a>, which does not set the err value. So the code does not need to be:</p> <pre><code>_, err = sha1Hasher.Write(buffer) if err != nil { log.Printf("sha1 could not be calculated (%s)", err) } </code></pre> <p>but only:</p> <pre><code>sha1Hasher.Write(buffer) </code></pre> <p>The second option is shorter and cleaner and go is a lot about simple code but it is suggested to handle all errors:</p> <blockquote> <p>But remember: Whatever you do, always check your errors!</p> </blockquote> <p><a href="https://blog.golang.org/errors-are-values" rel="nofollow">https://blog.golang.org/errors-are-values</a></p> <blockquote> <p>Clearly, we must handle any errors; we can't just ignore them.</p> </blockquote> <p><a href="http://stackoverflow.com/a/16126516/4944254">http://stackoverflow.com/a/16126516/4944254</a></p> <p>Which is the best way to go?</p>
<p>In situation that you described, you will probably be fine with not checking error, same as not checking errors when using <code>fmt.Println</code>. </p> <p>However, when you use <code>fmt.Println</code> you know which concrete implementations are being used. When you are using <code>Writer</code> interface (which <code>os.Stdout</code> implements) - you can not assume if implementation will return any errors. In that case, IMHO, you should always check errors.</p> <p>Btw, writing to <code>os.Stdout</code>, which <code>fmt.Print</code> uses, can fail (one might be able to replace value of <code>os.Stdout</code> to something else).</p>
permission issue with docker under windows <p>I'm using this scheme : </p> <p>1/ I'm working on windows 7</p> <p>2/ I'm using vagrant to mount a "ubuntu/trusty64" box</p> <p>3/ I apt-get install ansible</p> <p>4/ I install docker and docker-compose with ansibe</p> <p>5/ I create a docker image with this dockerfile : </p> <pre><code>FROM php:7-apache MAINTAINER Bruno DA SILVA "bruno.dasilva@foo.com" COPY containers-dirs-and-files/var/www/html/ /var/www/html/ WORKDIR /var/www/html </code></pre> <p>6/ I run it :</p> <pre><code>sudo docker build -t 10.100.200.200:5000/pimp-hello-world . sudo docker run -p 80:80 -d --name test-php 10.100.200.200:5000/pimp-hello-world </code></pre> <p>7/ apache can't display the page, I have to add :</p> <pre><code>RUN chmod -R 755 /var/www/html </code></pre> <p>to the dockerfile in order to have it visible.</p> <p>so here is my question : can I handle files permission while working on windows (and how)? Or do I have to move under linux?</p>
<p>This happens also in Linux. Docker copies the files and put root as owner. The only way I have found to overcome this without chmod, is archiving the files in a tar file and then use</p> <pre><code>ADD content.tgz /var/www/html </code></pre> <p>I will expand it automatically </p> <p>Regards </p>
What does the "e" flag mean in fopen <p>I saw a code snippet using <code>fopen(file_name, "r+e")</code>. What does the <code>e</code> flag mean in fopen? I couldn't find any information from the linux man page.</p>
<p>It's documented in the man page on my system (release 3.54 of the Linux man-pages project).</p> <blockquote> <p><strong>e</strong> (since glibc 2.7)<br> Open the file with the <code>O_CLOEXEC</code> flag. See <code>open(2)</code> for more information. This flag is ignored for <code>fdopen()</code>.</p> </blockquote> <p>Scroll down; it's under "Glibc notes". This is a non-standard extension.</p> <p>An online copy of the man page is <a href="https://linux.die.net/man/3/fdopen" rel="nofollow">here</a>.</p>
Setting up Derby on MacOS Sierra <p>I am following Java: How To Program - Chapter 24. The chapter deals with database implementation in Java. I followed the steps to setup "Derby", but I get the error <code>java.sql.SQLException: Database 'books' not found.</code>. </p> <p>I checked $PATH to make sure it includes $DERBY_HOME. $DERBY_HOME points to the correct folder(<code>/Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home/db</code>).</p> <p>I checked $JAVA_HOME and it was also setup correctly(<code>/Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home</code>).</p> <p>I can use the tool <code>ij</code> and it shows me the database that is setup. I added <code>derby.jar</code> to the package in eclipse. The following is the code from the book, but when I compile it I get the error <code>java.sql.SQLException: Database 'books' not found.</code></p> <p>I looked it up online, and there were recommendations that I add <code>//localhost:1527/books</code>. But if I add that I get the <code>java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/books</code> error. </p> <p>There was also suggestions that I use <code>Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();</code>, that didn't solve the problem either. </p> <p>I have copy/pasted the <code>books.sql</code> database in the same package as the one that contains the source code.</p> <p>Does anybody know how to solve the problem? I am running MacOS Sierra.</p> <pre><code>public class DisplayAuthors { public static void main(String [] args) { final String DATABASE_URL = "jdbc:derby:books"; final String SELECT_QUERY = "Select authorID, firstName, lastName from authors"; try( Connection connection = DriverManager.getConnection( DATABASE_URL, "deitel", "deitel"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(SELECT_QUERY)){ ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfCols = metaData.getColumnCount(); System.out.printf("Authors of table of Books databse:%n%n"); for(int i = 0; i &lt; numberOfCols; i++) System.out.printf("%-8s\t",metaData.getColumnName(i)); System.out.println(); while(resultSet.next()){ for (int i = 1; i &lt;= numberOfCols; i++) System.out.printf("%-8s\t",resultSet.getObject(i)); System.out.println(); } }catch(SQLException ex){ ex.printStackTrace(); } } } </code></pre>
<p>I figured the problem was. When the creating the database via <code>ij</code> I had to be in the same directory that the source file is. Now under eclipse I thought that this would mean I need to be under package folder(JAVAProject/src/package), but that was wrong. I had to be under (JAVAProject). </p>
Get multiple cursors (carets) at each find result in Intellij Idea editors? <p>I want to select all the string resource keys that contain the word key at the same time. I had a hard time figuring this out so I figured I'd post this for others. The <a href="https://www.jetbrains.com/help/idea/2016.2/multicursor.html" rel="nofollow">multicursor documentation</a> doesn't address this question.</p> <p>An excerpt of the file I wanted to select from.</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;!-- User Preferences --&gt; &lt;string name="preference_key_pedigree_enable_offline_mode"&gt;Pref.OfflineMode&lt;/string&gt; &lt;string name="preference_title_pedigree_enable_offline_mode"&gt;Offline Mode&lt;/string&gt; &lt;string name="preference_summary_on_pedigree_enable_offline_mode"&gt;Scans work without an internet connection, don\'t require a VIN and can\'t be saved.&lt;/string&gt; &lt;string name="preference_summary_off_pedigree_enable_offline_mode"&gt;Scan results will be sent to the server.&lt;/string&gt; &lt;string name="preference_default_pedigree_enable_offline_mode"&gt;false&lt;/string&gt; &lt;string name="preference_key_pedigree_hide_cleared_dtcs"&gt;pref_pedigree_hide_cleared_dtcs&lt;/string&gt; &lt;string name="preference_title_pedigree_hide_cleared_dtcs"&gt;Hide Cleared DTCs&lt;/string&gt; &lt;string name="preference_summary_on_pedigree_hide_cleared_dtcs"&gt;DTC\'s are hidden after they\'ve been cleared&lt;/string&gt; &lt;string name="preference_summary_off_pedigree_hide_cleared_dtcs"&gt;DTC\'s are still shown after they\'ve been cleared&lt;/string&gt; &lt;string name="preference_default_pedigree_hide_cleared_dtcs"&gt;true&lt;/string&gt; &lt;string name="preference_key_analytics_global_opt_out"&gt;pref_analytics_global_opt_out&lt;/string&gt; &lt;string name="preference_title_analytics_global_opt_out"&gt;Analytics Opt-Out&lt;/string&gt; &lt;string name="preference_summary_on_analytics_global_opt_out"&gt;Analytics switched off.&lt;/string&gt; &lt;string name="preference_summary_off_analytics_global_opt_out"&gt;Crash reports and usage statistics are being used to improve this app.&lt;/string&gt; &lt;string name="preference_default_analytics_global_opt_out"&gt;false&lt;/string&gt; &lt;/resources&gt; </code></pre>
<p>Intellij Idea calls this <a href="https://www.jetbrains.com/help/idea/2016.2/selecting-text-in-the-editor.html#d1743632e270" rel="nofollow"><em>multiselection</em></a>.</p> <p>Select the term to search for with your cursor. In my example, the word <em>key</em><br> <a href="https://i.stack.imgur.com/Rb6R3.png" rel="nofollow"><img src="https://i.stack.imgur.com/Rb6R3.png" alt="enter image description here"></a><br> Next, <em>select all occurrences</em>:</p> <ul> <li>press <kbd>ctrl</kbd>+<kbd>alt</kbd>+<kbd>shift</kbd>+<kbd>J</kbd></li> <li>use the <a href="https://www.jetbrains.com/help/idea/2016.2/navigating-to-action.html?search=ctrl%20shift%20a" rel="nofollow">find action menu</a> <kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>A</kbd> <a href="https://i.stack.imgur.com/DVL5L.png" rel="nofollow"><img src="https://i.stack.imgur.com/DVL5L.png" alt="action search screenshot"></a></li> </ul> <p><a href="https://i.stack.imgur.com/WfbHN.png" rel="nofollow"><img src="https://i.stack.imgur.com/WfbHN.png" alt="screenshot of selection"></a></p> <p>Now you can expand your selection (<kbd>ctrl</kbd>+<kbd>W</kbd>) to the entire keys, and then copy and past elsewhere.</p>
Cannot find module `dist/bin/x.js` when trying to use the command that comes with the package after npm global install <p>You did <code>npm install -g aVeryCoolPackage</code> and when you want to use <code>aVeryCoolPackage</code>'s command in your shell you get an error like this:</p> <pre><code>Error: Cannot find module '/usr/local/lib/node_modules/aVeryCoolPackage/dist/bin/cli.js' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at loadAVeryCoolPackage (/usr/local/lib/node_modules/aVeryCoolPackage/bin/aVeryCoolPackage.js:30:3) at /usr/local/lib/node_modules/aVeryCoolPackage/bin/aVeryCoolPackage.js:44:5 at LOOP (fs.js:1758:14) at _combinedTickCallback (internal/process/next_tick.js:67:7) at process._tickCallback (internal/process/next_tick.js:98:9) </code></pre> <p>After you cd into <code>/usr/local/lib/node_modules/thePackage</code> to your surprise you see that the folder <code>dist</code> does not exist at all. This is strange. You tried <code>npm uninstall -g aVeryCoolPackage</code> and then <code>npm install -g aVeryCoolPackage</code> again but you run into the same problem when trying to use its command. Everyone else on github is not running into this problem. What is going on?</p>
<p>In my case I had cloned the repo from github. And I did <code>npm install -g aVeryCoolPackage</code> at the same directory as where the repo is, so it actually installed my local copy of it where it has <code>.gitignore</code> the <code>dist</code> folder. As a result I didn't have <code>dist</code> in <code>/usr/local/lib/node_modules/aVeryCoolPackage/</code> and it threw the Cannot find module error every time it tried to <code>require</code> files in it.</p> <p>Fun fact: You would have no idea how the error arises if you <code>npm uninstall -g aVeryCoolPackage</code> and <code>npm install -g aVeryCoolPackage</code> at a different directory where the clone of the repo is not there and getting it fixed as a result. It would become one of those mysteries in node development where sometimes you get strange errors and then you stop seeing them. </p>
How to split files according to a field and edit content <p>I am not sure if I can do this using unix commands or I need a more complicated code, like python.</p> <p>I have a big input file with 3 columns - id, different sequences (second column) grouped in different groups (3rd column).</p> <pre><code>Seq1 MVRWNARGQPVKEASQVFVSYIGVINCREVPISMEN Group1 Seq2 PSLFIAGWLFVSTGLRPNEYFTESRQGIPLITDRFDSLEQLDEFSRSF Group1 Seq3 HQAPAPAPTVISPPAPPTDTTLNLNGAPSNHLQGGNIWTTIGFAITVFLAVTGYSF Group20 </code></pre> <p>I would like: split this file according the group id, and create separate files for each group; edit the info in each file, adding a ">" sign in the beginning of the id; and then create a new row for the sequence</p> <pre><code>Group1.txt file &gt;Seq1 MVRWNARGQPVKEASQVFVSYIGVINCREVPISMEN &gt;Seq2 PSLFIAGWLFVSTGLRPNEYFTESRQGIPLITDRFDSLEQLDEFSRSF Group20.txt file &gt;Seq3 HQAPAPAPTVISPPAPPTDTTLNLNGAPSNHLQGGNIWTTIGFAITVFLAVTGYSF </code></pre> <p>How can I do that? </p>
<p>This shell script should do the trick:</p> <pre><code>#!/usr/bin/env bash filename="data.txt" while read line; do id=$(echo "${line}" | awk '{print $1}') sequence=$(echo "${line}" | awk '{print $2}') group=$(echo "${line}" | awk '{print $3}') printf "&gt;${id}\n${sequence}\n" &gt;&gt; "${group}.txt" done &lt; "${filename}" </code></pre> <p>where <code>data.txt</code> is the name of the file containing the original data.</p> <p>Importantly, the Group-files should not exist prior to running the script.</p>
C# thread report found items <p>Lets say I want to make a program that finds primes and shows them in a list as soon as one is found. I could make a thread that finds the primes, but how can I report them to the GUI thread? I was thinking about an event that raises when a prime is found, but now the event is on another thread than my GUI. How can I push an answer from one thread to another?</p> <p>Regards, Bas</p>
<p>The <a href="https://msdn.microsoft.com/en-us/library/hh242985(v=vs.103).aspx" rel="nofollow">Reactive Extensions</a> framework is designed for creating and observing asynchronous sequences.</p>
d3 chart and google font not visible on github page <p>I uploaded a page onto Github and the HTML, CSS and Jquery and Jquery UI run very well. However, the d3 chart does not run. (PS: the chart is hidden, and becomes visible once the card on the middle is clicked. The data on the d3 chart was entered manually, it was not linked to an external data file.)</p> <p>You can see in on <a href="http://uxxo-wireframes.tumblr.com/Company_One" rel="nofollow">the original page</a> when you click on the middle (black) card.</p> <p>On <a href="https://popbijoux.github.io/" rel="nofollow">the github page</a>, if you click on the middle card, the collapsed css container appears, but no chart:(. On the Github page, in addition to the d3 issue, I see that the Google font I used (Lato) did not upload either.</p> <p>I am new to Github there may be something obvious I am missing. I uploaded the whole thing as an html file (as opposed to separate folders for the css and the js scripts.</p>
<p>you've got a <code>https</code> issue (trying to load <code>http</code> assets on a <code>https</code> site).</p> <p>Instead of defining the protocol as <code>http://</code> or <code>https://</code> that you reference your assets from, try using the protocol agnostic <code>//</code></p>
Left join in MySQL doesn't give me expected result <p>I have the following SQL:</p> <pre><code>SELECT t.teilnehmer_id, t.familienname, t.vorname, t.ort, t.ortsteil, t.kontrolle_ertrag, t.kontrolle_1j, t.kontrolle_brache, SUM(fe.nutzflaeche) AS nutzflaeche_ertrag, GROUP_CONCAT(fe.nutzflaeche) AS einzelfl_ertrag, SUM(fp.nutzflaeche) AS nutzflaeche_pflanzj, GROUP_CONCAT(fp.nutzflaeche) AS einzelfl_pflanzj, SUM(fb.nutzflaeche) AS nutzflaeche_brache, GROUP_CONCAT(fb.nutzflaeche) AS einzelfl_brache, SUM(fn.nutzflaeche) AS nutzflaeche_nicht_aush, GROUP_CONCAT(fn.nutzflaeche) AS einzelfl_nicht_aush FROM teilnehmer t LEFT JOIN anrede a ON (t.anrede_id = a.anrede_id) LEFT JOIN antragsform af ON (t.antragsform_id = af.antragsform_id) LEFT JOIN bank b ON (t.bank_id = b.bank_id) LEFT JOIN flurverzeichnis fe ON (t.teilnehmer_id = fe.teilnehmer_id AND fe.kulturbez = 'E') LEFT JOIN flurverzeichnis fp ON (t.teilnehmer_id = fp.teilnehmer_id AND fp.kulturbez = 'P') LEFT JOIN flurverzeichnis fb ON (t.teilnehmer_id = fb.teilnehmer_id AND fb.kulturbez = 'B') LEFT JOIN flurverzeichnis fn ON (t.teilnehmer_id = fn.teilnehmer_id AND fn.kulturbez = 'N') WHERE 1 = 1 GROUP BY t.teilnehmer_id ORDER BY familienname, vorname </code></pre> <p>The sum doesn't reflect the correct areas if there is a match in more than one kulturbez. E.g. if I have 5 rows with kulturbez 'E' and 2 rows with kulturbez 'N', each 'E' row shows up twice and each 'N' row shows up 5 times. Any suggestions on how to redo the SQL to only sum each row with the matching kulturbez once? Thanks,</p> <p>Gunter</p>
<p>As indicated in my comment, unavoidable 1:N joins usually need subqueries to calculate aggregate values appropriately; but it looks like your need can be solved with conditional aggregation, like so:</p> <pre><code>SELECT t.teilnehmer_id, t.familienname, t.vorname, t.ort, t.ortsteil, t.kontrolle_ertrag, t.kontrolle_1j, t.kontrolle_brache , SUM(CASE WHEN f.kulturbez = 'E' THEN f.nutzflaeche ELSE NULL END) AS nutzflaeche_ertrag , GROUP_CONCAT(CASE WHEN f.kulturbez = 'E' THEN f.nutzflaeche ELSE NULL END) AS einzelfl_ertrag , SUM(CASE WHEN f.kulturbez = 'P' THEN f.nutzflaeche ELSE NULL END) AS nutzflaeche_pflanzj , GROUP_CONCAT(CASE WHEN f.kulturbez = 'P' THEN f.nutzflaeche ELSE NULL END) AS einzelfl_pflanzj , SUM(CASE WHEN f.kulturbez = 'B' THEN f.nutzflaeche ELSE NULL END) AS nutzflaeche_brache , GROUP_CONCAT(CASE WHEN f.kulturbez = 'B' THEN f.nutzflaeche ELSE NULL END) AS einzelfl_brache , SUM(CASE WHEN f.kulturbez = 'N' THEN f.nutzflaeche ELSE NULL END) AS nutzflaeche_nicht_aush , GROUP_CONCAT(CASE WHEN f.kulturbez = 'N' THEN f.nutzflaeche ELSE NULL END) AS einzelfl_nicht_aush FROM teilnehmer t LEFT JOIN anrede a ON (t.anrede_id = a.anrede_id) LEFT JOIN antragsform af ON (t.antragsform_id = af.antragsform_id) LEFT JOIN bank b ON (t.bank_id = b.bank_id) LEFT JOIN flurverzeichnis f ON (t.teilnehmer_id = fe.teilnehmer_id) WHERE 1 = 1 GROUP BY t.teilnehmer_id ORDER BY familienname, vorname </code></pre> <p>Aggregate functions ignore NULL values for the most part. <em>(Also, technically <code>ELSE NULL</code> is optional, as it is the assumed value if <code>ELSE</code> is not specified; but is good practice to make your intent clear.)</em></p>
Get object initialization syntax from C# list <p>I have a List of type employee. </p> <pre><code>public class Employee { public string Name { get; set; } public int Id { get; set; } public string Level { get; set; } } List&lt;Employee&gt; empList = new List&lt;Employee&gt;(); </code></pre> <p>Assume if this list has 10 items, from this list, I want to generate object initialization code. So basically I should get a string like this:</p> <pre><code> "Employee e = new Employee{Name: "A", Id:1, Level:1}; Employee e = new Employee{Name: "B", Id:2, Level:2}; Employee e = new Employee{Name: "C", Id:3, Level:1}; Employee e = new Employee{Name: "D", Id:4, Level:6}; Employee e = new Employee{Name: "E", Id:5, Level:2}; Employee e = new Employee{Name: "F", Id:6, Level:5} Employee e = new Employee{Name: "G", Id:7, Level:4}; Employee e = new Employee{Name: "H", Id:8, Level:3}; Employee e = new Employee{Name: "I", Id:9, Level:1}; Employee e = new Employee{Name: "J", Id:10, Level:1}"; </code></pre> <p>The reason I am doing this is, I am getting list of records from database but it does not have a sort order (another property). I need to manually add the sort order to each item (hard code). So if I don't automate this, the only other option I will have would require me to create the object manually(instead of getting the values from database) and add SortOrder property to each object. </p>
<p>I don't understand how having this code will help you, but here it is:</p> <pre><code>String.Join( Environment.NewLine, empList.Select(x =&gt; $"Employee e = new Employee() {{ Name = \"{x.Name}\", Id = {x.Id}, Level = \"{x.Level}\" }};")); </code></pre> <p>I'm going to suggest that a better option would be for you to create a sorting dictionary, to create the manual sort order, and then use this to sort your list that you load from the database.</p> <p>Do something like this:</p> <pre><code>var sorter = new Dictionary&lt;int, string&gt;() { { 1, "c" }, { 2, "a" }, { 3, "b" }, { 4, "c" }, { 5, "c" }, { 6, "a" }, { 7, "a" }, { 8, "b" }, { 9, "d" }, { 10, "c" }, }; empList = empList .OrderBy(e =&gt; sorter.ContainsKey(e.Id) ? sorter[e.Id] : "z") .ToList(); </code></pre>
Adding large data in Excel <p>I have around 200,000 data in excel which is separated in per 15min for each day for two years. Now, I want to add for each day(including all the 15mins data at once) eg. 01/01/2014 to 12/31/2016. I did it using a basic formula (=sum(range)) but it is very time consuming. Can anyone help me find a easy way to resolve this problem?</p>
<p>It's faster and more reliable to work with big data sets using <a href="https://support.office.com/en-us/article/Introduction-to-Microsoft-Power-Query-for-Excel-6e92e2f4-2079-4e1f-bad5-89f6269cd605?ui=en-US&amp;rs=en-US&amp;ad=US" rel="nofollow">Ms Power Query</a> in which you can perform data analitics and process with single queries, or using <a href="https://www.youtube.com/watch?v=Rg37CyqUklY" rel="nofollow">Power View</a> of the dataset loaded into the datamodel that really works really fast.</p>
LinkedIN Encounter error: Your application has not been authorized for the scope "r_basicprofile" <p>I was able to connect to the LinkedIn API for about two months and everything was correct. Was wondering if there has been any change to the API lately to block my app like so? </p> <p>The app was in development stage and mostly 5 hits a day against their API. </p>
<p>It's not you, it's LinkedIn. See others complaining about the same issue: <a href="https://twitter.com/search?q=linkedin%20oauth" rel="nofollow">https://twitter.com/search?q=linkedin%20oauth</a></p>
Validation for must_be_below_user_limit allowing users to exceed user limit Rails 4 <p>So I Am building a multi-tenant app in Rails 4 with Apartment, Devise and Devise_Invitable. </p> <p>I Want to Limit the number of users in each account based on the plan type. </p> <p>When I create a user the validation should look to see that the user count is below the plan limit and if it is equal to the plan limit:</p> <p>A) Not Allow the user to be created B) show a flash message that tells the owner / admin they need to upgrade their account. </p> <p>As it sits now the validation is not throwing an error on create, but its also not preventing the user from being created either. </p> <p><strong>Here is the User Model:</strong> </p> <pre><code>class User &lt; ApplicationRecord # Constants &amp; Enums USER_LIMITS = ActiveSupport::HashWithIndifferentAccess.new( #Plan Name #Auth Users responder: 6, first_responder: 12, patrol_pro: 30, guardian: 60 ) # Before Actions # Devise Modules devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :invitable, :lockable, :timeoutable # Relationships belongs_to :account, optional: true # Validations validates :f_name, presence: true validates :l_name, presence: true validates :date_of_birth, presence: true validate :must_be_below_user_limit, on: [:create] # Custom Methods def full_name l_name.upcase + ", " + f_name end def user_limit USER_LIMITS[account.plan.plan_type] end def must_be_below_user_limit if account.present? &amp;&amp; persisted? &amp;&amp; account.users.size &gt; user_limit errors[:user_limit] = "can not have more than #{user_limit} users" end end end </code></pre> <p><strong>Here is the Plan model:</strong> </p> <pre><code>class Plan &lt; ApplicationRecord # Enum &amp; Constants enum plan_type: [:responder, :first_responder, :patrol_pro, :guardian] USER_LIMITS = ActiveSupport::HashWithIndifferentAccess.new( #Plan Name #Auth Users responder: 6, first_responder: 12, patrol_pro: 30, guardian: 60 ) # Before Actions # Relationships belongs_to :account, optional: true # Validations end </code></pre> <p><strong>and here is the Account model:</strong></p> <pre><code>class Account &lt; ApplicationRecord include ImageUploader[:image] # Constants RESTRICTED_SUBDOMAINS = %w(www patrolvault admin test type taurenapplabs taurenmaterialservices) # Before Actions before_validation :downcase_subdomain # Relationships belongs_to :owner, class_name: 'User', optional: true accepts_nested_attributes_for :owner has_many :users # Validations validates :owner, presence: true validates :subdomain, presence: true, uniqueness: { case_sensitive: false }, format: { with: /\A[\w\-]+\Z/i, message: 'Contains invalid characters.' }, exclusion: { in: RESTRICTED_SUBDOMAINS, message: 'Restricted domain name'} has_one :plan accepts_nested_attributes_for :plan private def downcase_subdomain self.subdomain = self.subdomain.downcase end end </code></pre> <p>Like I said, its not that the validation is erroring out.. but its also not preventing the user from being created. Any help here would be greatly appreciated. </p>
<p>Try add <code>retrun false</code> in the <code>must_be_below_user_limit</code> method.</p> <pre><code>def must_be_below_user_limit if account.present? &amp;&amp; persisted? &amp;&amp; account.users.count &gt; user_limit errors[:user_limit] = "can not have more than #{user_limit} users" return false end end </code></pre>
Drawing an iscosceles triangle of asteriks on C++ <p>I am learning c++ and I'm trying draw an iscosceles triangle using asteriks. My code looks like:</p> <pre><code>int main(){ for(int i=1;i&lt;11;i++){ for(int j=0;j&lt;i;j++) { cout &lt;&lt; "*"; } cout &lt;&lt; endl; } return 0; } </code></pre> <p>The top half therefore comes out but how can I start decrementing immediately after reaching j==10 so that i get the bottom half. Please assist. </p>
<p>Alternative to @space_voyager this code support dynamic size so you can have as large as you can define with the size. </p> <p>The algorithm here is</p> <ol> <li>Check if current index or iteration is in the middle (in this case, 11. Programmatically is 10).</li> <li>If true, iterate j from 0 to current index of I.</li> <li>If false (that means that the current index is greater than the middle), iterate j from size - I in decreasing order.</li> </ol> <h1>How size - I works?<br></h1> <p>At the first iteration where it is true (I > 10, therefore when I = 11) size - I = 21-11. You get 10, hence the output will print 10 times. Second time I = 12. You'll get decreasing result as you go.</p> <p><br></p> <pre><code>int main(){ int size = 21; for(int i=1;i&lt;size;i++){ if(i &lt;=size/2) { for(int j=0;j&lt;i;j++) { cout &lt;&lt; "*"; } cout &lt;&lt; endl; } else if (i &gt; size/2) { for(int j=size-i; j&gt;0;j--) { cout &lt;&lt; "*"; } cout &lt;&lt; endl; } } return 0; } </code></pre> <p>Output</p> <blockquote> <pre><code>* ** *** **** ***** ****** ******* ******** ********* ********** ********** ********* ******** ******* ****** ***** **** *** ** * </code></pre> </blockquote> <h1>Edit</h1> <p>As per space_voyager said, having copy pasted code is not the best practice. Here's the updated code (similar to his, I only added the dynamic part. Change the value of size, you change everything)</p> <pre><code>int main(){ int size = 20; for(int i=1;i&lt;size;i++){ int k; if(i &lt;=size/2) { k = i; } else if (i &gt; size/2) { k = size-i; } for(int j=0; j&lt;k; j++) { cout &lt;&lt; "*"; } cout &lt;&lt; endl; } return 0; } </code></pre>
How to execute multiline python code from a bash script? <p>I need to extend a shell script (bash). As I am much more familiar with python I want to do this by writing some lines of python code which depends on variables from the shell script. Adding an extra python file is not an option.</p> <pre><code>result=`python -c "import stuff; print('all $code in one very long line')"` </code></pre> <p>is not very readable.</p> <p>I would prefer to specify my python code as a multiline string and then execute it.</p>
<p>Use a here-doc:</p> <pre><code>result=$(python &lt;&lt;EOF import stuff print('all $code in one very long line') EOF ) </code></pre>