title
stringlengths
10
150
body
stringlengths
17
64.2k
label
int64
0
3
Setting up pythonpath in OS X
<p>A new PHP developer here trying to learn Python/Django using the "Tango With Django" tutorial.</p> <p>I'm up to section 2.2.2 where I have to set up the pythonpath and I'm having the following problem:</p> <p>When I type the following in the terminal: <code>echo $pythonpath</code> I get a blank line instead of the correct path.</p> <p>I followed the troubleshooting steps and found where the site-packages directory is: <code>Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages</code></p> <p>Per their instructions I updated my <code>.bashrc</code> file so it looks like this now:</p> <pre><code>PATH=$PATH:$HOME/.rvm/bin # Add RVM to PATH for scripting ### Added by the Heroku Toolbelt export PATH="/usr/local/heroku/bin:$PATH" export PYTHONPATH=$PYTHONPATH:/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages </code></pre> <p>For a reason I don't understand I'm still getting a blank line when I <code>echo $pythonpath</code>.</p> <p>Because I was having difficulty getting the <code>pythonpath</code> set up I skipped it, but then had problems installing Setuptools, Pip, and Django.</p> <p>Can anyone tell me what I'm doing wrong? Any resources I can look at beside Tango with Django?</p>
0
Compare Two Pivot Tables
<p>I have two pivot tables, one in Column A, one in Column B, and they are formatted the same way.</p> <p>The pivot tables have a list of Users, and under each User a list of IDs.</p> <p>Is there a way I can compare the two pivot tables against each other? I want to match Users in both tables and see which Users have duplicate IDs.</p> <p>To help visualize, the tables look something like this:</p> <p>Table 1 </p> <pre><code>------------------------- | DAVE | asgh4 | lshg8 | | MATT | 39f8 | 2352 | ------------------------- </code></pre> <p>Table 2</p> <pre><code>------------------------- | PETER | dgghn | lkasj| | DAVE | asgh4 | 38gfj| ------------------------- </code></pre> <p>I want to see matches like "DAVE" and "asgh4" because the user matches and the ID matches. Is there a way to accomplish this? Thanks!</p>
0
How can I count white spaces using substr_count() in PHP
<p>how can I count the number of white spaces in a file using PHP?</p> <p>I have tried the substr function but it isn't working.</p>
0
Free Calendar/Schedular Control in WPF
<p>Is there any free WPF calendar/Schedular /appointment control available , I have searched on google but couldn't find one.</p>
0
iterating through java collection using jQuery
<p>I am starting with this object,</p> <pre><code>public class myTO { private String id; private String name; } </code></pre> <p>Which is used in this object</p> <pre><code>public myCombiTO { private myTO myTO; private List&lt;String&gt; valueList; private List&lt;String&gt; displayList; } </code></pre> <p>I create a list of these objects</p> <pre><code>List&lt;myCombiTO&gt; myCombiTOList = getMyCombiTOList(); </code></pre> <p>I use this list to set a jsp page attribute</p> <pre><code>request.setAttribute("myAttrList", myCombiTOList); </code></pre> <p>And forward to the jsp page. I then use jquery and jstl to populate a drop down from this list</p> <pre><code>&lt;select name="mYSelect" id="mySelect"&gt; &lt;c:forEach var="myVar" items="${myAttrList}"&gt; &lt;option value="${myVar.myTO.id}" &gt; &lt;c:out value="${myVar.myTO.name}" /&gt; &lt;/option&gt; &lt;/c:forEach&gt; &lt;/select&gt; </code></pre> <p>My problem is I want to populate a second drop down using jquery with the values from mycombiTO.getValueList(). so far I have this</p> <pre><code>$("#mySelect").change(function(){ var myJSList = ${myAttrList}; var chosenGroup = $("#mySelect").val(); var valueArray = myJSList.get(chosenGroup).valueList; var displayArray = myJSList.get(chosenGroup).displayList; var items = {'display':[displayArray], 'value':[valueArray]}; //now populate drop downs $.populateSelect($('#myselect').get(0), items); }); jQuery.populateSelect = function(element,items) { $.each(items, function() { element.options[element.options.length] = new Option(this.display,this.value); }); }; </code></pre> <p>However its not working please help. I am having trouble creating the javascript object based on two arrays. Hwoever ideally I would want to reference a java map from jquery using key/value pairs. Is this possible ?</p> <p>Thanks in advance.</p>
0
How do I do modulus in C++?
<p>How do I perform a mod operation between two integers in C++?</p>
0
Java vs. C++ for building a GUI which has a C++ backend
<p>I currently have a C++ backend that I need to connect with a GUI, and since I've never built a GUI before, I was confused on where to start. </p> <p>I'm comfortable writing code in C++ and Java, so I'd prefer my GUI to be in one of those languages. Also, the GUI has to be reasonably OS independent over Windows and Linux (and hopefully, hence Macs).</p> <p>Now I understand that if I use Java to do it, I'll need some wrappers to do it - but I've also heard (strictly second hand) that writing a GUI in C++ is a pain. </p> <p>I don't want to rewrite too much of my backend code in Java (who does??) and I was hoping for input on:</p> <ul> <li>Does either language offer serious advantages/disadvantages compared to the other? </li> <li>How serious is the wrapping issue, and how much rewriting would come in if I used Java. </li> <li>Are there any specific resources I should look at that people think would be relevant?</li> </ul> <p>Thanks and Cheers All :)</p>
0
Is is possible to make a method execute only once?
<p>I have a for loop and structure like this:</p> <pre><code>for(....) .... .... if(isTrue) ... do something.. .. method to be executed once (doTrick) is declared outside for loop. ....endif endfor public void doTrick() ... ... ..end </code></pre> <p>Is it possible for a method in for loop to be executed only once?</p>
0
download files using bash script using wget
<p>I've been trying to create a simple script that will take a list of file to be downloaded from a .txt file, then using a loop it will read the .txt what files needs to be downloaded with the help of the other separated .txt file where in the address of the files where it will be downloaded. But my problem is I don't know how to do this. I've tried many times but I always failed.</p> <pre><code>file.txt 1.jpg 2.jpg 3.jpg 4.mp3 5.mp4 </code></pre> <p>=====================================</p> <pre><code>url.txt url = https://google.com.ph/ </code></pre> <p>=====================================</p> <pre><code>download.sh #!/bin/sh url=$(awk -F = '{print $2}' url.txt) for i in $(cat file.txt); do wget $url done </code></pre> <p>Your help is greatly appreciated. </p>
0
How to add two figures side by side, and insert captions to each of them?
<p>In Word, I can add two figures side by side, however, when I insert captions to each of them, the figure number doesn't change, both of them have the same figure number. How can I solve this problem?</p>
0
C# MemoryStream - Timeouts are not supported on this stream
<p>I'm trying to create a csv file dynamially and output the stream to the browser.</p> <p>Here is my api end point:</p> <pre><code> [System.Web.Http.HttpGet] [System.Web.Http.Route("export-to-csv")] public FileStreamResult ExportDeposits([FromUri(Name = "")]DepositSearchParamsVM depositSearchParamsVM) { if (depositSearchParamsVM == null) { depositSearchParamsVM = new DepositSearchParamsVM(); } var records = _DepositsService.SearchDeposits(depositSearchParamsVM); var result = _DepositsService.WriteCsvToMemory(records); var memoryStream = new MemoryStream(result); return new FileStreamResult(memoryStream, "text/csv") { FileDownloadName = "export.csv" }; } </code></pre> <p>Here is my service method:</p> <pre><code>public byte[] WriteCsvToMemory(IEnumerable&lt;DepositSummaryVM&gt; records) { using (var stream = new MemoryStream()) using (var reader = new StreamReader(stream)) using (var writer = new StreamWriter(stream)) using (var csv = new CsvWriter(writer)) { csv.WriteRecords(records); writer.Flush(); stream.Position = 0; var text = reader.ReadToEnd(); return stream.ToArray(); </code></pre> <p>}</p> <pre><code> } </code></pre> <p>Here is the error message:</p> <blockquote> <p>{ "message": "An error has occurred.", "exceptionMessage": "Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.",<br> "exceptionType": "Newtonsoft.Json.JsonSerializationException",<br> "stackTrace": " at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract&amp; memberContract, Object&amp; memberValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Owin.HttpMessageHandlerAdapter.d__13.MoveNext()", "innerException": { "message": "An error has occurred.", "exceptionMessage": "Timeouts are not supported on this stream.", "exceptionType": "System.InvalidOperationException", "stackTrace": " at System.IO.Stream.get_ReadTimeout()\r\n at GetReadTimeout(Object )\r\n at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)" } }</p> </blockquote>
0
Change color of matInput
<p>How do I change matInput to a custom color. I want to change the placeholder and underline color.</p> <p>I have read through most of the posts and could not find a solution to change the underline.</p> <pre><code> &lt;mat-form-field class="example-full-width"&gt; &lt;input matInput placeholder="Favorite food" value="Sushi"&gt; &lt;/mat-form-field&gt; </code></pre> <p><a href="https://stackblitz.com/angular/yglxbxybndq/" rel="noreferrer">Stackblitz example</a></p> <p><a href="https://i.stack.imgur.com/ln3UE.jpg" rel="noreferrer">Image example</a></p>
0
How to Test React Hooks useEffect, useCallBack
<p>I'm trying to write unit test cases using Jest, Enzyme for useEffect, and useCallback for React hooks but I'm unable to succeed. Can you someone help me to write a test case for the below code.</p> <p>ModalComponent.jsx</p> <pre><code> const ModalComponent = ({ closeModal }) =&gt; { const handleModal = useCallback((event) =&gt; { if (event.keyCode === 27) { closeModal(false); } } useEffect(() =&gt; { document.addEventListener('keydown', handleModal); return () =&gt; document.removeEventListener('keydown', handleModal); }, []); return ( &lt;Modal&gt; &lt;Header onClose={closeModal} /&gt; &lt;Body /&gt; &lt;Footer /&gt; &lt;/Modal&gt; ); } </code></pre> <p>ModalComponent.spec.jsx</p> <pre><code> describe('Modal Component', () =&gt; { let props; beforeEach(() =&gt; { props = { closeModal: jest.fn(), }; }; it('should handle useEffect', () =&gt; { jest.spyOn(React, 'useEffect').mockImplementation(f =&gt; f()); document.addEventListener('keydown', handleModal); document.removeEventListener('keydown', handleModal); const component = shallow(&lt;ModalComponent /&gt;); }); }); </code></pre> <p>It is unable to cover these lines <code>document.addEventListener('keydown', handleModal);</code>,<code>document.removeEventListener('keydown', handleModal);</code>, <code>if(event.keyCode === 27)</code>, <code>closeModal(false)</code>. How can I cover the test cases?</p>
0
How to switch on\off frontend form validation for some fields in yii2?
<p>I have got difficult form in yii2 view, where some fields show or hide. It decide from user field choises, select options in the form. I write this frontend logic with custom jquery file. All is ok. But when I submit form - hidden fields stay without validation and nothing is happend.How I can kill ofrontend validation, when fields are hiiden and switch on it, when fields are visible?</p>
0
how to calculate line height from psd file? (leading+ font size)
<p>I have this psd and trying to convert it to html css. </p> <p>But I can't calculate the line height in css from the psd.</p> <p>How can i calculate the line height from the leading + font size?</p> <p>thanks</p>
0
Calling RESTful Web Services from PostgreSQL procedure/function
<p>I have been provided RESTful web services to push data into a remote DB of another application. I need to call these services to push data from PostgreSQL DB by sending data in JSON format as GET/POST parameters to the web service. Is it possible to call these web services from the PostgreSQL functions (periodically) which push data into my database in the first place, or write JAVA code to call these web services that run queries on PostgreSQL database and call web services to pass them to the remote DB.</p>
0
Increment Cell Values in a Range by 1 with VBA Excel
<p>Im currently trying to implement an insert new row value and a automatic checkbox inserter.</p> <p>I currently have the following code spread over different buttons and therefore different Subs. I have boldened the key information that i will need to increment by 1 cell. This will occur after clicking the "InsertNewBill" button.:</p> <pre><code>Private Sub InsertNewBill_Click() 'I AM USING i TO STORE THE CELL INCREMENT, IT CURRENTLY DOES NOTHING** Dim i As Integer '**range("A30:AC30").Select** '**range("AC30").Activate** Selection.Copy Selection.Insert Shift:=xlDown End Sub Private Sub DeleteTickBoxes_Click() 'Variables Dim c As CheckBox Dim CellRange As Range Dim cel As Range Set CellRange = ActiveSheet.Range("E7:**F30**") 'Delete Checkboxes within the specified range above on the ActiveSheet Only For Each c In ActiveSheet.CheckBoxes If Not Intersect(c.TopLeftCell, CellRange) Is Nothing Then c.Delete End If Next 'Insert New Checkboxes and Assign to a specified link cell using the offset For Each cel In CellRange 'you can adjust left, top, height, width to your needs Set c = ActiveSheet.CheckBoxes.Add(cel.Left, cel.Top, 30, 6) With c 'Clears the textbox so it has no text .Caption = "" 'Offset works by offsetting (Row offset, Column Offset) and accepts 'positive for down/right and negative for left/up, 'keep in not that the linked cells will automatically populate with true/false .LinkedCell = cel.Offset(0, -4).Address End With Next Call CentreCheckbox_Click End Sub </code></pre> <p>I need all boldened values to increase by one. I.e from F30 to F31 and A30:AC30 to A31:AC31. This value also needs to be carried across from the InsertNewBill_Click sub to the DeleteTickBoxes_Click sub.</p> <p>I assume i will need to remove the Private sub and possibly have a public integer variable? Im just not sure how to implement increasing only the number by 1 after each button click.</p> <p>All your help is appreciated</p>
0
Flutter : Textfield in ListView.builder
<p>Hi everyone i have some data at Cloud Firestore and a ListView.builder to load the data in it. In this ListView.builder i have Network.Image, ListTile to show the title and subtitle and another ListTile which has a Textfield to add some comment and an iconbutton. My goal is to get the text of the textfield and show as a alertDialog when the button clicked. Until now i added a controller to the textfield but whenever i type anything in the textfield it changes all the textfields. I have tried creating a List to specify a unique controller so i can stop the all of the changes in textfields but i have failed. Is there any way i can do this. All this textfields and iconbuttons must be unique so when i clicked the iconbutton i need to see the text of the typed textfield.</p>
0
Python use timeout for subprocess with Popen
<p>Im running the following script with popen </p> <pre><code>process = subprocess.Popen(['python', 'solver.py', 'newsudoku.csp', '-i', 'arc'], stdout=subprocess.PIPE) out, err = process.communicate() </code></pre> <p>I need to process the output that is being stored in the out variable</p> <p>thing is this script varies in the time of its execution, and I need to kill it if it goes past 60 seconds. I know that python 3 has timeout for check_call, but the other script im running is in python 2.7</p> <p>So how could I count 60 seconds and then kill the subprocess? ideally doing something else as well if this happens (adding 1 to a counter)</p>
0
How to update Xcode with a new Apple ID?
<p>I've recently changed apple ID and I've downloaded xCode on mac with another apple ID.</p> <p>Not the mac store informs me there is a new version for xCode but I need to insert password of the older Apple ID, and I can't just use the new one. It seems the app is associated with the old apple ID.</p> <p>I can't even download a new xCode using the new apple id, because it only gives me the option to update it with the old Apple ID.</p>
0
The entity or complex type ... cannot be constructed in a LINQ to Entities query
<p>Why does one method work but not the other, when it seems they are both doing the same thing, i.e. constructing an entity. My question then, is there a way to construct the entity in a L2E query instead of having to use just Linq or indeed both?</p> <p>This works fine...</p> <pre><code>var queryToList = (from ac in ctx.AuthorisationChecks where wedNumbers.Contains(ac.WedNo) orderby ac.WedNo, ac.ExpAuthDate, ac.ActAuthDate select new AuthorisationCheck { Blah = ac.Blah }).ToList(); model.AuthorisationChecks = queryToList.Select(x =&gt; new AuthorisationCheck { Blah = x.Blah }).ToList(); </code></pre> <p>However, if i change...</p> <pre><code>var queryToList </code></pre> <p>to</p> <pre><code>model.AuthorisationChecks queryToList // Of type List&lt;AuthorisationCheck&gt; </code></pre> <p>i get the error in the Title...</p> <pre><code>The entity or complex type 'Model.AuthorisationCheck' cannot be constructed in a LINQ to Entities query. </code></pre> <p><strong>EDIT:</strong> In the model it is simply, nothing fancy here.</p> <pre><code>public List&lt;AuthorisationCheck&gt; AuthorisationChecks { get; set; } </code></pre> <p><strong>EDIT2:</strong> Tidied this up a little to be (which works fine)...</p> <pre><code>model.AuthorisationChecks = (from ac in ctx.AuthorisationChecks where wedNumbers.Contains(ac.WedNo) orderby ac.WedNo, ac.ExpAuthDate, ac.ActAuthDate select ac).ToList() .Select(x =&gt; new AuthorisationCheck { Blah = x.Blah }).ToList(); </code></pre> <p><strong>EDIT2: My Solution</strong> I wasn't happy with the anonymous type method and so went ahead and created a simple model containing only the properties I required to be used in the viewmodel.</p> <p>Changed the type of model.AuthorisationChecks</p> <p>from </p> <pre><code>List&lt;AuthorisationCheck&gt; // List of Entities </code></pre> <p>to</p> <pre><code>List&lt;AuthorisationCheckModel&gt; // List of models </code></pre> <p>which allows the following code to work, and without profiling it seems a lot quicker than using an anonymous type (and of course I don't cast to a list twice!).</p> <pre><code>model.AuthorisationChecks = (from ac in ctx.AuthorisationChecks where wedNumbers.Contains(ac.WedNo) orderby ac.WedNo, ac.ExpAuthDate, ac.ActAuthDate select new AuthorisationCheckModel { Blah = x.Blah }).ToList(); </code></pre> <p>P.S. I was once warned by a coworker (who used to work for Microsoft) that it isn't a good idea to directly use Entities in this manner, maybe this was one of the reasons he was thinking of, I've also noticed some odd behavior using Entities directly in other cases (mainly corruptions).</p>
0
Sorting an array of strings in C
<p>I have an assignment I've been working on for a few hours now, and I can't seem to get it quite right. The assignment is to take a random number of names (from stdin), sort them, and then output them in alphabetical order. I can't find any sites online that handle this kind of sorting specifically, and have had no luck trying to implement qsort() into my code. </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; int stringcmp(const void *a, const void *b) { const char **ia = (const char **)a; const char **ib = (const char **)b; return strcmp(*ia, *ib); } void main(int argc, char *argv[]) { char *input[] = {" "}; char temp[20][20]; int i = 0; int num = 0; int place = 0; int stringlen = sizeof(temp) / sizeof(char); printf("How many names would you like to enter? "); scanf("%d", &amp;num); while (place &lt; num) { printf("Please input a name(first only): "); scanf("%s", input[place]); printf("The name you entered is: "); printf("%s\n", input[place]); place++; } //qsort(temp, stringlen, sizeof(char *), stringcmp); &lt;-- just an idea I was messing with qsort(input, stringlen, sizeof(char *), stringcmp); printf("Names:\n"); for(i=0; i&lt;place; i++) printf("%s\n", input[i]); system("PAUSE"); return(EXIT_SUCCESS); } </code></pre> <p>The main problem is, when I go to output my code, I cannot use the char *input variable because of how its declared. The temp[] will display, but will not be sorted by qsort because it is not declared as a pointer. Any ideas?</p>
0
ClassNotFoundException: Didn't find class "com.google.android.gms.ads.AdView"
<p>I did a lot of research and this seems to be a common error for many users but for very different reasons. None of which I found worked for me.</p> <p>I'm getting</p> <pre><code>java.lang.RuntimeException: Unable to start activity ComponentInfo{ [...]/[...].activities.StartActivity}: android.view.InflateException: Binary XML file line #173: Error inflating class [...].BannerAd [...] Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class com.google.android.gms.ads.AdView [...] Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.ads.AdView" on path: DexPathList[[zip file "/data/app/[...]-1.apk"],nativeLibraryDirectories=[/data/app-lib/[...]-1, /vendor/lib, /system/lib]] </code></pre> <p>I'm having the newest versions of ADT and SDK packages installed. I copied google-play-services_lib to my workspace and imported it as a Android project. I added it as a library to my app project. I checked everything under "Order and Export".</p> <p>I'm having a banner_ad.xml:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal|top" android:orientation="vertical" &gt; &lt;com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto" android:id="@+id/adView" android:layout_width="match_parent" android:layout_height="wrap_content" ads:adSize="BANNER" ads:adUnitId="[...]" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>And a BannerAd.java which I am using:</p> <pre><code>package [...]; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.LinearLayout; import [...].R; import [...].general.Settings; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; public class BannerAd extends LinearLayout { public BannerAd(Context context, AttributeSet attrs) { super(context, attrs); if (!Settings.PRO) { LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mInflater.inflate(R.layout.banner_ad, this, true); AdView adView = (AdView) this.findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest); } } } </code></pre> <p>Could it have something to do with proguard? I have no idea, this is my proguard-project.txt file, however:</p> <pre><code># To enable ProGuard in your project, edit project.properties # to define the proguard.config property as described in that file. # # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in ${sdk.dir}/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the ProGuard # include property in project.properties. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} -keep class * extends java.util.ListResourceBundle { protected Object[][] getContents(); } -keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable { public static final *** NULL; } -keepnames @com.google.android.gms.common.annotation.KeepName class * -keepclassmembernames class * { @com.google.android.gms.common.annotation.KeepName *; } -keepnames class * implements android.os.Parcelable { public static final ** CREATOR; } </code></pre> <p>Any ideas what I could try to fix this?</p> <p>Edit: Sometimes, I also get such output in the console (but not every time I compile, only sometimes):</p> <pre><code>[2014-07-24 12:49:05 - [...]] Dx trouble processing: [2014-07-24 12:49:05 - [...]] Dx bad class file magic (cafebabe) or version (0033.0000) ...while parsing com/google/android/gms/internal/mb.class ...while processing com/google/android/gms/internal/mb.class [2014-07-24 12:49:05 - [...]] Dx trouble processing: [2014-07-24 12:49:05 - [...]] Dx bad class file magic (cafebabe) or version (0033.0000) ...while parsing com/google/android/gms/internal/mc.class ...while processing com/google/android/gms/internal/mc.class [2014-07-24 12:49:05 - [...]] Dx [...] [Lots of similar warnings here] [...] trouble processing: [2014-07-24 12:49:25 - [...]] Dx bad class file magic (cafebabe) or version (0033.0000) ...while parsing com/google/ads/mediation/customevent/CustomEventAdapter$a.class ...while processing com/google/ads/mediation/customevent/CustomEventAdapter$a.class [2014-07-24 12:49:25 - [...]] Dx trouble processing: [2014-07-24 12:49:25 - [...]] Dx bad class file magic (cafebabe) or version (0033.0000) ...while parsing com/google/ads/mediation/customevent/CustomEventServerParameters.class ...while processing com/google/ads/mediation/customevent/CustomEventServerParameters.class [2014-07-24 12:49:25 - [...]] Dx 2786 warnings </code></pre>
0
Use Google Apps Script to loop through the whole column
<p>I am trying to loop through the whole row in my google sheet and copy some of the data from one sheet to another. The list will get longer over time.</p> <p>More specifically: If input in column B equals "blue", than copy the values from column A and C into another sheet. Do this for all columns till the end of the column.</p> <p>Link to my spreadsheet: <a href="https://docs.google.com/spreadsheets/d/1xnLygpuJnpDfnF6LdR41gN74gWy8mxhVnQJ7i3hv1NA/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1xnLygpuJnpDfnF6LdR41gN74gWy8mxhVnQJ7i3hv1NA/edit?usp=sharing</a></p> <ul> <li>The loop stops when the colour does not equal blue. Why?</li> <li>As you can see I used a for loop. Is that even the way to go?</li> <li>Can I do anything about the speed of the code execution?</li> </ul> <p>Any comments, hints or help are highly appreciated.</p> <p>Regards!</p>
0
Avoid animation of UICollectionView after reloadItemsAtIndexPaths
<p>UICollectionView animate items after reloadItemsAtIndexPaths is called (fade animation).</p> <p>Is there a way to avoid this animation? </p> <p>iOS 6</p>
0
Usage of 'pull' command in Jgit
<p>I'm a new user of git and am using <a href="http://wiki.eclipse.org/JGit" rel="noreferrer">JGit</a> to interact with a remote git repository. In JGit, I used <code>CloneCommand</code> to initially to clone a repo, and it worked without a issue. However, when I try to use <code>PullCommand</code>, which is the equivalent of SVN update AFAIK, the local repo contents are not updated. </p> <p>This is the code that I used:</p> <pre><code>private String localPath; private Repository localRepo; private Git git; localPath = "/home/test/git_repo_test"; remotePath = "https://github.com/test/repo_1.git"; try { localRepo = new FileRepository(localPath + "/.git"); } catch (IOException e) { e.printStackTrace(); } git = new Git(localRepo); PullCommand pullCmd = git.pull(); try { pullCmd.call(); } catch (GitAPIException e) { e.printStackTrace(); } </code></pre> <p>This doesn't update the local repository for new files which I have pushed to the remote repository using the command line. However, if I delete the local repository and take a clone again, all the changes are reflected. </p> <p>Please let me know what is the correct approach of using <code>PullCommand</code> in JGit.</p> <p>EDIT:</p> <p>The structure of the remote repository:</p> <pre><code>root ____ file_1 |______ directory_1 |__________ file_2 |__________ file_3 </code></pre> <p>directory_1 and the two files are pushed from the commandline after the initial cloning and I tried this code so that it will get reflected in the local repository, which is not happening.</p> <p>The code used to clone the repository:</p> <pre><code>File file = new File(localPath); CloneCommand cloneCmd = git.cloneRepository(); try { cloneCmd.setURI(remotePath) .setDirectory(file) .call(); } catch (GitAPIException e) { e.printStackTrace(); } </code></pre> <p>Here, <code>git</code>, <code>localPath</code> and <code>remotePath</code> are the same variable as above.</p>
0
Weird exception: Cannot cast String to Boolean when using getBoolean
<p>I'm getting a very weird error. I have 2 activities. On both I'm getting the <code>SharedPreferences</code> using <code>MODE_PRIVATE</code> (if it matters) by <code>sp = getPreferences(MODE_PRIVATE);</code> on each activity's <code>onCreate()</code> I'm calling <code>sp.getBoolean(IntroActivity.SHOW_INTRO, true)</code></p> <p>On the <code>IntroActivity</code> this works fine. But when I'm trying in the main activity, I'm getting this</p> <pre><code>10-12 04:55:23.208: E/AndroidRuntime(11668): FATAL EXCEPTION: main 10-12 04:55:23.208: E/AndroidRuntime(11668): java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.app.SharedPreferencesImpl.getBoolean(SharedPreferencesImpl.java:242) 10-12 04:55:23.208: E/AndroidRuntime(11668): at com.lablabla.parkme.ParkMeActivity$2.onClick(ParkMeActivity.java:194) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.view.View.performClick(View.java:4084) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.view.View$PerformClick.run(View.java:16966) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Handler.handleCallback(Handler.java:615) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Handler.dispatchMessage(Handler.java:92) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Looper.loop(Looper.java:137) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.app.ActivityThread.main(ActivityThread.java:4745) 10-12 04:55:23.208: E/AndroidRuntime(11668): at java.lang.reflect.Method.invokeNative(Native Method) 10-12 04:55:23.208: E/AndroidRuntime(11668): at java.lang.reflect.Method.invoke(Method.java:511) 10-12 04:55:23.208: E/AndroidRuntime(11668): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 10-12 04:55:23.208: E/AndroidRuntime(11668): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 10-12 04:55:23.208: E/AndroidRuntime(11668): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>I made sure that I'm not putting a <code>String</code> somewhere in the middle with that same key</p> <p>Any ideas?</p> <p>Thanks!</p> <p>EDIT: some code:</p> <pre><code>//onCreate() sp = getPreferences(MODE_PRIVATE); // other method boolean showIntro = sp.getBoolean(IntroActivity.SHOW_INTRO, true); // Exception is here showIntroCheckBox.setChecked(showIntro); </code></pre> <p>If it matters, the code which throws the exception is inside a button's <code>onClick</code></p>
0
Connecting to a remote mongoDB server
<p>I have a remote machine which I connect to using SSH, I installed mongoDB on it, and I wish to use it remotely, how do I connect to it using nodejs and mongoDB compass? the localhost is the IP ?</p> <pre><code>const db = "mongodb://what do I write here?"; const connectDB = async () =&gt; { try { await mongoose.connect(db, { useNewUrlParser: true, useCreateIndex: true }); console.log("MongoDB Connected..."); } catch (err) { console.error(err.message); process.exit(1); } }; connectDB(); </code></pre>
0
How do I detect a mobile browser in a .NET MVC3 application
<p>I'm developing a .NET MVC3 application. </p> <p>Is there a good way to detect if the user is using a mobile browser in the view (using RAZOR). I'm wanting to differ the display logic if it's a mobile browser.</p> <p>Thanks!</p>
0
Search ABAddressbook iOS SDK
<p>I want to search the iPhone address book for a specific phone number, and then retrieve the contact name. I am currently looping through all contacts and extracting the multivalue properties and comparing against the value. This is taking way too much time. I have read the Apple addressbook guide, and they say:</p> <blockquote> <p>"accomplish other kinds of searches, use the function ABAddressBookCopyArrayOfAllPeople and then filter the results using the NSArray method filteredArrayUsingPredicate:."</p> </blockquote> <p>Can anyone give me an example on how to exactly do that?</p> <p>Thanks.</p>
0
how to add searchbar in uitableview?
<p>I have an <code>NSMutableArray</code> displayed in a <code>UITableView</code>, and I have added some elements there.</p> <p>For example, element names are First, FirstTwo, Second, SecondTwo, Third, ThirdTwo.</p> <p>Now I want to add a search bar in the screen. In that search bar when I type F, the table should only show First and FirstTwo.</p> <p>How should I do this?</p>
0
Which .NET collection is faster: enumerating foreach Dictionary<>.Values or List<>?
<p>Are one of these enumerations faster than the other or about the same? (example in C#)</p> <p>Case 1:</p> <pre><code>Dictionary&lt;string, object&gt; valuesDict; // valuesDict loaded with thousands of objects foreach (object value in valuesDict.Values) { /* process */ } </code></pre> <p>Case 2:</p> <pre><code>List&lt;object&gt; valuesList; // valuesList loaded with thousands of objects foreach (object value in valuesList) { /* process */ } </code></pre> <p>UPDATE:</p> <p>Background:</p> <p>The dictionary would be beneficial for keyed search elsewhere (as opposed to iterating through a list), but the benefit would be diminished if iterating through the dictionary is much slower than going through the list.</p> <p>UPDATE: Taking the advice of many, I've done my own testing.</p> <p>First, these are the results. Following is the program.</p> <p>Iterate whole collection Dict: 78 Keyd: 131 List: 76</p> <p>Keyed search collection Dict: 178 Keyd: 194 List: 142800</p> <pre><code>using System; using System.Linq; namespace IterateCollections { public class Data { public string Id; public string Text; } public class KeyedData : System.Collections.ObjectModel.KeyedCollection&lt;string, Data&gt; { protected override string GetKeyForItem(Data item) { return item.Id; } } class Program { static void Main(string[] args) { var dict = new System.Collections.Generic.Dictionary&lt;string, Data&gt;(); var list = new System.Collections.Generic.List&lt;Data&gt;(); var keyd = new KeyedData(); for (int i = 0; i &lt; 10000; i++) { string s = i.ToString(); var d = new Data { Id = s, Text = s }; dict.Add(d.Id, d); list.Add(d); keyd.Add(d); } var sw = new System.Diagnostics.Stopwatch(); sw.Start(); for (int r = 0; r &lt; 1000; r++) { foreach (Data d in dict.Values) { if (null == d) throw new ApplicationException(); } } sw.Stop(); var dictTime = sw.ElapsedMilliseconds; sw.Reset(); sw.Start(); for (int r = 0; r &lt; 1000; r++) { foreach (Data d in keyd) { if (null == d) throw new ApplicationException(); } } sw.Stop(); var keydTime = sw.ElapsedMilliseconds; sw.Reset(); sw.Start(); for (int r = 0; r &lt; 1000; r++) { foreach (Data d in list) { if (null == d) throw new ApplicationException(); } } sw.Stop(); var listTime = sw.ElapsedMilliseconds; Console.WriteLine("Iterate whole collection"); Console.WriteLine("Dict: " + dictTime); Console.WriteLine("Keyd: " + keydTime); Console.WriteLine("List: " + listTime); sw.Reset(); sw.Start(); for (int r = 0; r &lt; 1000; r++) { for (int i = 0; i &lt; 10000; i += 10) { string s = i.ToString(); Data d = dict[s]; if (null == d) throw new ApplicationException(); } } sw.Stop(); dictTime = sw.ElapsedMilliseconds; sw.Reset(); sw.Start(); for (int r = 0; r &lt; 1000; r++) { for (int i = 0; i &lt; 10000; i += 10) { string s = i.ToString(); Data d = keyd[s]; if (null == d) throw new ApplicationException(); } } sw.Stop(); keydTime = sw.ElapsedMilliseconds; sw.Reset(); sw.Start(); for (int r = 0; r &lt; 10; r++) { for (int i = 0; i &lt; 10000; i += 10) { string s = i.ToString(); Data d = list.FirstOrDefault(item =&gt; item.Id == s); if (null == d) throw new ApplicationException(); } } sw.Stop(); listTime = sw.ElapsedMilliseconds * 100; Console.WriteLine("Keyed search collection"); Console.WriteLine("Dict: " + dictTime); Console.WriteLine("Keyd: " + keydTime); Console.WriteLine("List: " + listTime); } } </code></pre> <p>}</p> <p>UPDATE:</p> <p>Comparison of Dictionary with KeyedCollection as suggested by @Blam.</p> <p>The fastest method is iterating over an Array of KeyedCollection Items.</p> <p>Note, however, that iterating over the dictionary values is faster than over the KeyedCollection without converting to an array.</p> <p>Note that iterating over the dictionary values is much, much faster than over the dictionary collection.</p> <pre><code> Iterate 1,000 times over collection of 10,000 items Dictionary Pair: 519 ms Dictionary Values: 95 ms Dict Val ToArray: 92 ms KeyedCollection: 141 ms KeyedC. ToArray: 17 ms </code></pre> <p>Timings are from a Windows console application (Release build). Here is the source code:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace IterateCollections { public class GUIDkeyCollection : System.Collections.ObjectModel.KeyedCollection&lt;Guid, GUIDkey&gt; { // This parameterless constructor calls the base class constructor // that specifies a dictionary threshold of 0, so that the internal // dictionary is created as soon as an item is added to the // collection. // public GUIDkeyCollection() : base() { } // This is the only method that absolutely must be overridden, // because without it the KeyedCollection cannot extract the // keys from the items. // protected override Guid GetKeyForItem(GUIDkey item) { // In this example, the key is the part number. return item.Key; } public GUIDkey[] ToArray() { return Items.ToArray(); } //[Obsolete("Iterate using .ToArray()", true)] //public new IEnumerator GetEnumerator() //{ // throw new NotImplementedException("Iterate using .ToArray()"); //} } public class GUIDkey : Object { private Guid key; public Guid Key { get { return key; } } public override bool Equals(Object obj) { //Check for null and compare run-time types. if (obj == null || !(obj is GUIDkey)) return false; GUIDkey item = (GUIDkey)obj; return (Key == item.Key); } public override int GetHashCode() { return Key.GetHashCode(); } public GUIDkey(Guid guid) { key = guid; } } class Program { static void Main(string[] args) { const int itemCount = 10000; const int repetitions = 1000; const string resultFormat = "{0,18}: {1,5:D} ms"; Console.WriteLine("Iterate {0:N0} times over collection of {1:N0} items", repetitions, itemCount); var dict = new Dictionary&lt;Guid, GUIDkey&gt;(); var keyd = new GUIDkeyCollection(); for (int i = 0; i &lt; itemCount; i++) { var d = new GUIDkey(Guid.NewGuid()); dict.Add(d.Key, d); keyd.Add(d); } var sw = new System.Diagnostics.Stopwatch(); long time; sw.Reset(); sw.Start(); for (int r = 0; r &lt; repetitions; r++) { foreach (KeyValuePair&lt;Guid, GUIDkey&gt; w in dict) { if (null == w.Value) throw new ApplicationException(); } } sw.Stop(); time = sw.ElapsedMilliseconds; Console.WriteLine(resultFormat, "Dictionary Pair", time); sw.Reset(); sw.Start(); for (int r = 0; r &lt; repetitions; r++) { foreach (GUIDkey d in dict.Values) { if (null == d) throw new ApplicationException(); } } sw.Stop(); time = sw.ElapsedMilliseconds; Console.WriteLine(resultFormat, "Dictionary Values", time); sw.Reset(); sw.Start(); for (int r = 0; r &lt; repetitions; r++) { foreach (GUIDkey d in dict.Values.ToArray()) { if (null == d) throw new ApplicationException(); } } sw.Stop(); time = sw.ElapsedMilliseconds; Console.WriteLine(resultFormat, "Dict Val ToArray", time); sw.Reset(); sw.Start(); for (int r = 0; r &lt; repetitions; r++) { foreach (GUIDkey d in keyd) { if (null == d) throw new ApplicationException(); } } sw.Stop(); time = sw.ElapsedMilliseconds; Console.WriteLine(resultFormat, "KeyedCollection", time); sw.Reset(); sw.Start(); for (int r = 0; r &lt; repetitions; r++) { foreach (GUIDkey d in keyd.ToArray()) { if (null == d) throw new ApplicationException(); } } sw.Stop(); time = sw.ElapsedMilliseconds; Console.WriteLine(resultFormat, "KeyedC. ToArray", time); } } } </code></pre>
0
Spring Boot Microservice cant connect to Eureka Server
<p>I try to connect my service (auth-service) to the Eureka Server for the service registry. The Eureka server is running, but when I try to connect the auth-service nothing happens.</p> <p>I added the configurations to application.yaml and application.properties, but nothing helped.</p> <p>application.yaml from auth-service:</p> <pre><code>eureka: client: fetchRegistry: true registryFetchIntervalSeconds: 5 serviceUrl: defaultZone: http://localhost:8761/eureka instance: preferIpAddress: true </code></pre> <p>URL of Eureka server: <a href="http://localhost:8761/" rel="nofollow noreferrer">http://localhost:8761/</a></p> <p>DS Replicas: localhost</p> <p>Message when I start auth-service:</p> <pre><code>2019-05-24 16:58:11.457 INFO [auth-service,,,] 14704 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2019-05-24 16:58:13.293 INFO [auth-service,,,] 14704 --- [ main] o.s.cloud.commons.util.InetUtils : Cannot determine local hostname 2019-05-24 16:58:14.521 INFO [auth-service,,,] 14704 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2019-05-24 16:58:14.524 INFO [auth-service,,,] 14704 --- [ main] d.h.authservice.AuthServiceApplication : Started AuthServiceApplication in 11.448 seconds (JVM running for 12.63) </code></pre> <p>The Eureka Server is annotated with @EnableEurekaServer and the Client is annotated with @EnableDiscoveryClient</p> <p>auth-service pom:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.1.4.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;groupId&gt;de.hspf&lt;/groupId&gt; &lt;artifactId&gt;auth-service&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;auth-service&lt;/name&gt; &lt;description&gt;Demo project for Spring Boot&lt;/description&gt; &lt;properties&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;spring-cloud.version&gt;Greenwich.RELEASE&lt;/spring-cloud.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.postgresql&lt;/groupId&gt; &lt;artifactId&gt;postgresql&lt;/artifactId&gt; &lt;version&gt;42.2.5&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate.javax.persistence&lt;/groupId&gt; &lt;artifactId&gt;hibernate-jpa-2.0-api&lt;/artifactId&gt; &lt;version&gt;1.0.1.Final&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.security&lt;/groupId&gt; &lt;artifactId&gt;spring-security-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sendgrid&lt;/groupId&gt; &lt;artifactId&gt;sendgrid-java&lt;/artifactId&gt; &lt;version&gt;4.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt; &lt;artifactId&gt;jjwt&lt;/artifactId&gt; &lt;version&gt;0.9.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.modelmapper&lt;/groupId&gt; &lt;artifactId&gt;modelmapper&lt;/artifactId&gt; &lt;version&gt;1.1.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.thymeleaf&lt;/groupId&gt; &lt;artifactId&gt;thymeleaf-spring3&lt;/artifactId&gt; &lt;version&gt;3.0.8.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.xmlunit&lt;/groupId&gt; &lt;artifactId&gt;xmlunit-core&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-sleuth-zipkin&lt;/artifactId&gt; &lt;version&gt;2.1.1.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-netflix-eureka-client&lt;/artifactId&gt; &lt;version&gt;2.0.1.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-starter&lt;/artifactId&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt; &lt;version&gt;Finchley.M9&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p></p> <p>Discovery Service pom</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.example&lt;/groupId&gt; &lt;artifactId&gt;discovery-server&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;name&gt;discovery-server&lt;/name&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.1.2.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;spring-cloud.version&gt;Greenwich.RELEASE&lt;/spring-cloud.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-server&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt; &lt;version&gt;Finchley.M9&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;spring-milestones&lt;/id&gt; &lt;name&gt;Spring Milestones&lt;/name&gt; &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt; &lt;snapshots&gt; &lt;enabled&gt;false&lt;/enabled&gt; &lt;/snapshots&gt; &lt;/repository&gt; &lt;/repositories&gt; </code></pre> <p></p>
0
Conflict in merging
<p>I have some troubles in my project angular. Who can help me ?</p> <blockquote> <p>ERROR in src/app/app-routing.module.ts(5,1): error TS1185: Merge conflict marker encountered.</p> </blockquote>
0
True + True = 2. Elegantly perform boolean arithmetic?
<p>I have nested lists of truth values representing SAT forumlas, like this:</p> <pre><code>[[[0, True, False], [0, True, False], [0, True, 1]], [[0, True, True], [2, True, True], [3, False, True]], [[1, False, False], [1, False, False], [3, False, True]]] </code></pre> <p>representing</p> <pre><code>([x0=0] + [x0=0] + [x0=1]) * ([x0=1] + [x1=1] + [-x2=1]) * ([-x3=0] + [-x3=0] + [-x2=1]) </code></pre> <p>I would like to calculate the truth value of the whole formula. First step would be adding up the truth values of the literals in each clause.</p> <p>like this:</p> <pre><code>clause_truth_value = None for literal in clause: # multiply polarity of literal with its value # sum over all literals clause_truth_value += literal[1]*literal[2] </code></pre> <p>if <code>clause_truth_value</code> is <code>True</code> after the summation, the clause is true as a whole.</p> <p>But I am not getting what I expected:</p> <p><code>True + True = 2</code> that's not as expected</p> <p><code>True * True = 1</code> that's as expected</p> <p><code>False + False = 0</code> that's as expected </p> <p><code>False * False = 0</code> that's as expected</p> <p>so... True is simply 1 and False is 0... that sucks, I expected the arithmetic operators to be overloaded for the boolean algebra. Is there an elegant way to do do boolean arithmetic with boolean variables?</p>
0
SVN Mergeinfo properties on paths other than the working copy root
<p>I have an SVN repository where I have trunk and a branch.</p> <p>I intend to merge the trunk into the branch at regular intervals, however, when I do this I see many property status changes, in addition to actual file content changes.</p> <p>On further investigation the property changes are mergeinfo properties. I wouldn't expect this because we <em>always</em> branch and merge from the top root level.</p> <p>I used the <code>svn propdel</code> command and removed all mergeinfo properties from the branch WC (then reverted the change on the root) before merging trunk in, and the problem went away.</p> <p>So the question is, how did my branch get all these mergeinfo changes in it at sub-directory levels?</p>
0
Update multiple values in a single statement
<p>I have a master / detail table and want to update some summary values in the master table against the detail table. I know I can update them like this:</p> <pre><code>update MasterTbl set TotalX = (select sum(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID) update MasterTbl set TotalY = (select sum(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID) update MasterTbl set TotalZ = (select sum(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID) </code></pre> <p>But, I'd like to do it in a single statement, something like this:</p> <pre><code>update MasterTbl set TotalX = sum(DetailTbl.X), TotalY = sum(DetailTbl.Y), TotalZ = sum(DetailTbl.Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID group by MasterID </code></pre> <p>but that doesn't work. I've also tried versions that omit the "group by" clause. I'm not sure whether I'm bumping up against the limits of my particular database (Advantage), or the limits of my SQL. Probably the latter. Can anyone help?</p>
0
SELECT * FROM in MySQLi
<p>My site is rather extensive, and I just recently made the switch to PHP5 (call me a late bloomer).</p> <p>All of my MySQL query's before were built as such:</p> <pre><code>"SELECT * FROM tablename WHERE field1 = 'value' &amp;&amp; field2 = 'value2'"; </code></pre> <p>This made it very easy, simple and friendly.</p> <p>I am now trying to make the switch to mysqli for obvious security reasons, and I am having a hard time figuring out how to implement the same <code>SELECT * FROM</code> queries when the <code>bind_param</code> requires specific arguments.</p> <p>Is this statement a thing of the past?</p> <p>If it is, how do I handle a query with tons of columns involved? Do I really need to type them all out every time?</p>
0
Reverse a list without using built-in functions
<p>I'm using Python 3.5. </p> <p>As part of a problem, I'm trying to design a function that takes a list as input and reverts it. So if <code>x = [a, b, c]</code> the function would make <code>x = [c, b, a]</code>.</p> <p>The problem is, I'm not allowed to use any built-in functions, and it has got me stuck. My initial thought was the following loop inside a function:</p> <pre><code>for revert in range(1, len(x) + 1): y.append(x[-revert]) </code></pre> <p>And it works. But the problem is I'm using <code>len(x)</code>, which I believe is a built-in function, correct? </p> <p>So I searched around and have made the following very simple code:</p> <pre><code>y = x[::-1] </code></pre> <p>Which does exactly what I wanted, but it just seems almost too simple/easy and I'm not sure whether <code>"::"</code> counts as a function. </p> <p>So I was wondering if anyone had any hints/ideas how to manually design said function? It just seems really hard when you can't use any built-in functions and it has me stuck for quite some time now.</p>
0
How to insert a string inside another string using Go lang
<p>Most programming languages have a function that allows us to insert one string into another string. For example, I can take the string Green and the string HI, and perform an operation Green.insert(HI,2) to get the resulatant string GrHIeen. But such a function does not come with the standard GO lang library.</p> <p>Is there any Golang function which I can use to insert a string inside an string?</p> <p>For example</p> <pre><code>string = "&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;" // I want Following Output string = "&lt;/table&gt;&lt;pagebreak /&gt;&lt;/body&gt;&lt;/html&gt;" </code></pre>
0
What is the use of bag tag in Hibernate?
<p>I need to know how to use the bag tag and what is the purpose of it?</p>
0
Namespace & Class Conflict
<p>I'm facing a problem with a conflict between the DateTime class and a namespace for some unknown reason was also called DateTime.</p> <p>Assembly <strong>CompanyDateTime</strong> has namespace <strong>Company.DateTime</strong></p> <p>My Application is in the namespace: <strong>Company</strong></p> <p>the problem is that everytime I need to use <strong>DateTime</strong> class, I have to explicitely say <strong>System.DateTime</strong> is their any way of getting around this?</p> <p>Is is possible to say <strong>SomeRandomStuff = Company.DateTime</strong> and have <strong>DateTime</strong> always be <strong>System.DateTime</strong> </p> <p>Note: </p> <ol> <li>I need to reference this Assembly in my application eventhough I do not use it because some Assembly that I need actually uses this class.</li> <li>I can use an entry on the app.config file to identify a dependent assembly but I cannot do that since company policy is against it and all referenced assembly needs to be in the output folder.</li> <li>Deployment goes through a build server</li> </ol> <p>Possible Resolution? Is is possible for <strong>CompanyDateTime</strong> to get automatically deployed to the output folder without adding it in the reference? </p>
0
What's the difference between String(value) vs value.toString()
<p>Javascript has lot's of "tricks" around types and type conversions so I'm wondering if these 2 methods are the same or if there is some corner case that makes them different?</p>
0
To open a popup window on clicking link button in grid view
<p>In the below code i have a grid view inside grid view i have a link button when i click the link button it should open a popup window .pls help me to do this.</p> <pre><code>&lt;asp:TemplateField HeaderText="Edit" itemstyle-width="150px"&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton ID="btnEdit" runat="server" CommandName="Edit" Text="Edit" CausesValidation="false"/&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre> <p>Codebehind:</p> <pre><code>if (e.CommandName.Equals("Edit")) { LinkButton btnView = (LinkButton)e.CommandSource; Response.Redirect("NewDocument.aspx?DID=" + lblDocumentID.Text.ToString(), true); } </code></pre>
0
Isotope not working with imagesLoaded?
<p>I'm using jQuery Isotope to create a horizontal layout, aligning DIVs with 100% height next to each other and center images inside each DIV vertically. So for, I'm calling Isotope like this and everything works fine in Chrome (locally):</p> <pre><code>$(function(){ var $container = $('#container'); $container.isotope({ itemSelector : '.itemwrap', layoutMode: 'horizontal', horizontal: { verticalAlignment: 0.5 } }); }); </code></pre> <p>As the images take time to load, they tend to mess up the Isotope layout, so I'm trying to work with the imagesLoaded fix: <a href="http://isotope.metafizzy.co/appendix.html" rel="noreferrer">http://isotope.metafizzy.co/appendix.html</a></p> <p>I implemented this fix like this:</p> <pre><code>$(function(){ var $container = $('#container'); $container.imagesLoaded( function(){ $container.isotope({ itemSelector : '.itemwrap', layoutMode: 'horizontal', horizontal: { verticalAlignment: 0.5 } }); }); }); </code></pre> <p>With this imagesLoaded, the Isotope does not load at all anymore. Removing imagesLoaded, Isotope kicks in again (but with the messed up layouts). Does anyone know, where the mistake lies?</p> <p>Thanks!</p>
0
What is the longest regular expression you have seen
<p>I just found an extremely long regular expression (6000+ characters) for a WordPress email validation. That got me thinking, what is the longest one you have ever actually seen that is being used in a production environment.</p>
0
R group by year
<p>I read a csv into R and now I have a list of data. </p> <pre><code>head(data) Date Open High Low Close Volume 1 31-Dec-14 223.09 225.68 222.25 222.41 2402097 2 30-Dec-14 223.99 225.65 221.40 222.23 2903242 3 29-Dec-14 226.90 227.91 224.02 225.71 2811828 4 26-Dec-14 221.51 228.50 221.50 227.82 3327016 5 24-Dec-14 219.77 222.50 219.25 222.26 1333518 6 23-Dec-14 223.81 224.32 219.52 220.97 4513321 tail(data) Date Open High Low Close Volume 499 9-Jan-13 34.01 34.19 33.40 33.64 697979 500 8-Jan-13 34.50 34.50 33.11 33.68 1283985 501 7-Jan-13 34.80 34.80 33.90 34.34 441909 502 4-Jan-13 34.80 34.80 33.92 34.40 673993 503 3-Jan-13 35.18 35.45 34.75 34.77 741941 504 2-Jan-13 35.00 35.45 34.70 35.36 1194710 </code></pre> <p>This is the stock price of a stock foreach day over a 2 year period from January 1st 2013 - December 31st 2014. For now I just want to be able to group by year, for any function or formula.</p> <p>So, let's say I want: <code>median(data$Close)</code></p> <p>returns: 177.515 </p> <p>Is there a way to tell R to return these numbers for each of the two years as opposed to just all data?</p> <p>e.g. combining R with a familiar SQL statement:</p> <pre><code>median(data$Close) GROUP BY YEAR(Date); </code></pre> <p>I'm hoping to get something returned like:</p> <pre><code>2013 167.5 2014 175 </code></pre>
0
Aliases in .bash_profile not working properly
<p>I have been trying to alter the .bash_profile that is in my root directory, but have been running into some problems. I am on OS X, Yosemite, on a Macbook Pro. As I understand it, the .bash_profile file contains the script that is called automatically whenever the Terminal app is opened and the bash shell starts. This is what I currently have written in that file: </p> <pre><code>PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}" export PATH </code></pre> <p>This works perfectly fine. However, I want to add an alias (right underneath the above two lines) as follows:</p> <pre><code>alias test='cd ..' </code></pre> <p>However, when I save this and start up the Terminal, I get the following message:</p> <pre><code>-bash: alias: ..": not found </code></pre> <p>Replacing the single quotes with double quotes doesn't help, nor does taking them away altogether. Curiously however, the following alias works:</p> <pre><code>alias c=clear </code></pre> <p>When I type c into the terminal, it clear the screen, as you would expect. However, if I instead entered this line with quotes in the bash profile as:</p> <pre><code>alias c='clear' </code></pre> <p>Then I will get the following whenever I enter c into the Terminal:</p> <pre><code>-bash: 'clear': command not found </code></pre> <p>Note that I do not get an error message on startup for this alias.</p> <p>What am I doing wrong? Is there a setting I need to change somewhere to get aliases to work properly? I have seen previous examples of aliases and they simply do not work for me.</p>
0
Copy a file to another directory, in which the file does not exist! PHP
<p>I'm trying to copy my file from one directory to another directory( destination in which the file does not exist)</p> <p>As far as I understood copy function just works if you want to rename and the file already exists in the destination directory; what should I do if the file does not exist in the destination directory?</p> <p>My attempt:</p> <pre><code>public function addSlidesToPath() { $myAddr=$this-&gt;input-&gt;post('addr'); $src=realpath(BASEPATH.'../uploaded_images').'/'.$myAddr[0]; $dest="C:\\Slides"; return copy( $src , $dest. basename($src )); } </code></pre> <p>Please let me know if you need more clarification; my code works fine if a file with the same name exists in the destination but if no file with the name, it is not working!</p> <pre><code>ADDED Here you can see my different attempts: 1)for **copy** without basename the error is "The second argument of copy() function cannot be a directory" 2)for **copy** with basename the error is "The second argument of copy() function cannot be a directory" as well 3)for **move_uploaded_file** with basename there is no error but the result is false! 4)for **move_uploaded_file** without basename there is no error but the result is false! </code></pre> <p>Thanks</p>
0
write numpy array to CSV with row indices and header
<p>I have a numpy array.</p> <pre><code>values = np.array([14, 21, 13, 56, 12]) </code></pre> <p>I want to write <code>values</code> in one column of a CSV file, the row indices in another column, and a header. I found this function:</p> <pre><code>numpy.savetxt("foo.csv", values, header="Id,Values", delimiter=",") </code></pre> <p>I'm not sure how to add the indices <code>(1, 2, 3, 4, 5)</code>. Also, my header turns out to be <code># Id,Values</code>. I'm not sure where the <code>#</code> came from. This is what I get:</p> <pre><code># Id,Values 14 21 13 56 12 </code></pre> <p>I want something like this:</p> <pre><code>Id,Values 1,14 2,21 3,13 4,56 5,12 </code></pre>
0
django - import error: no module named views
<p>I've been racking my brains and can't figure out why there should be an import error when 'views' is imported. I get the following message when I visit my index page:</p> <pre><code>" Request Method: GET Request URL: http://127.0.0.1:8000/moments/ Django Version: 1.6.1 Exception Type: ImportError Exception Value: No module named views Exception Location: C:\Python27\lib\site-packages\django\utils\importlib.py in import_module, line 40 " </code></pre> <p>Here is my urls.py</p> <pre><code>from django.conf.urls import patterns, url from moments_app import views urlpatterns = patterns('', url(r'^$', "views.index", name='index'), url(r'^$', "views.choose_dataset", name='choose'), url(r'^get_moments/', "views.get_moments", name='get_moments'), url(r'^learn/$', "views.learn", name='learn'), url(r'^(?P&lt;moment_id&gt;\d+)/$', "views.detail", name='detail'), ) </code></pre> <p>I clearly have a module named views in my moments_app folder. Also, moments_app is in my path. Does anyone have any ideas as to what might be causing this? </p>
0
Find Connected Components Networkx
<p>I need to find the connected nodes in the undirected and weighted graph. I did look up for some suggestions here but no one happens to answer that is related to my problem. These node pairs who also happen to connect with neighbors and every pair while connected spends some time in seconds connected.I am trying to find the connected components and the number of time the same comments connect and for how long (time) do they connect. </p> <p>Eg: </p> <pre><code>Node Node time A B 34 A B 56 A C 09 A D 5464 A C 456 C B 36 C A 345 B C 346 </code></pre> <p>So Over all <code>A B C</code> are connected two time </p> <pre><code>Nodes connected time [A B C] 1 34+09+36 = 79 [A B C] 1 56+345+346 = 747 </code></pre> <p>Expected output is </p> <pre><code>Nodes connected time [A B C] 2 826 And Node connected time [A B] 2 90 [B C] 2 382 [A C] 2 354 </code></pre> <p>Code:</p> <pre><code>import networkx as nx import numpy as np from collections import defaultdict count = defaultdict(int) time = defaultdict(float) data = np.loadtxt('USC_Test.txt') for line in data: edge_list = [(line[0], line[1])] G= nx.Graph() G.add_edges_from(edge_list) components = nx.connected_components(G) count['components'] += 1 time['components'] += float(line[2]) print components, count['components'], time['components'] </code></pre> <p>Input:</p> <pre><code>5454 5070 2755.0 5070 4391 2935.0 1158 305 1.0 5045 3140 48767.0 4921 3140 58405.0 5372 2684 460.0 1885 1158 351.0 1349 1174 6375.0 1980 1174 650.0 1980 1349 650.0 4821 2684 469.0 4821 937 459.0 2684 937 318.0 1980 606 390.0 1349 606 750.0 1174 606 750.0 5045 3545 8133.0 4921 3545 8133.0 3545 3140 8133.0 5045 4243 14863.0 4921 4243 14863.0 4243 3545 8013.0 4243 3140 14863.0 4821 4376 5471.0 4376 937 136.0 2613 968 435.0 5372 937 83.0 </code></pre> <p>Wrong Output</p> <p>The output i get is wrong </p> <pre><code>Last_node_pair total_count_of_line total_time of Entire input data </code></pre> <p>Where as i am supposed to get </p> <pre><code>[5045 3140 4921] [number_of_times_same_components_connected] [total_time_components_connected] </code></pre>
0
Rails: redirect_to :controller=>'tips', :action => 'show', :id => @tip.permalink
<p>I tried to redirect rails to show action by passing controller, action, and params. However, rails ignores the name of action totally!</p> <p>what I got is <a href="http://mysite/controllername/paramId" rel="noreferrer">http://mysite/controllername/paramId</a></p> <p>so i have error message....</p> <p>here is the action code I used:</p> <pre><code>def update @tip = current_user.tips.find(params[:id]) @tip.attributes = params[:tip] @tip.category_ids = params[:categories] @tip.tag_with(params[:tags]) if params[:tags] if @tip.save flash[:notice] = 'Tip was successfully updated.' redirect_to :controller=&gt;'tips', :action =&gt; 'show', :id =&gt; @tip.permalink else render :action =&gt; 'edit' end end </code></pre>
0
Can open source code hosted at github be closed-source?
<p>Can the owner of an open source Github repository later decide to close it? What about other people's contribution to that project?</p> <p><strong>Edit</strong> - several people focused only on the legal aspects. Besides them there exists the technical question: Is it technically possible to take a public repository I own on Github, and turn it private at a later date? Assuming nobody created a public forked from it, will this in effect hide the source code for this project?</p>
0
UTL_FILE.FOPEN() procedure not accepting path for directory?
<p>I am trying to write in a file stored in c:\ drive named vin1.txt and getting this error .Please suggest!</p> <pre><code>&gt; ERROR at line 1: ORA-29280: invalid &gt; directory path ORA-06512: at &gt; "SYS.UTL_FILE", line 18 ORA-06512: at &gt; "SYS.UTL_FILE", line 424 ORA-06512: at &gt; "SCOTT.SAL_STATUS", line 12 ORA-06512: &gt; at line 1 </code></pre> <p>HERE is the code</p> <pre><code> create or replace procedure sal_status ( p_file_dir IN varchar2, p_filename IN varchar2) IS v_filehandle utl_file.file_type; cursor emp Is select * from employees order by department_id; v_dep_no departments.department_id%TYPE; begin v_filehandle :=utl_file.fopen(p_file_dir,p_filename,'w');--Opening a file utl_file.putf(v_filehandle,'SALARY REPORT :GENERATED ON %s\n',SYSDATE); utl_file.new_line(v_filehandle); for v_emp_rec IN emp LOOP v_dep_no :=v_emp_rec.department_id; utl_file.putf(v_filehandle,'employee %s earns:s\n',v_emp_rec.last_name,v_emp_rec.salary); end loop; utl_file.put_line(v_filehandle,'***END OF REPORT***'); UTL_FILE.fclose(v_filehandle); end sal_status; execute sal_status('C:\','vin1.txt');--Executing </code></pre>
0
How to generate and add privacy policy on Google Play?
<p>I have to create and add a privacy policy to my Android app. My app accesses background geolocation data, so whatever policy I add has to include info about how location data is used. Two questions:</p> <ol> <li><p>Is there a standard approach to creating a privacy policy? For example, is there a template that people usually use, that I would be able to add an extra geolocation clause to?</p> </li> <li><p>Where in the Google Play console do you add the privacy policy? I went to <code>Store Presence -&gt; Main Store Listing</code> and didn't see any place to add a privacy policy.</p> </li> </ol>
0
Python Django Admin Clean() Method not overiding values
<p>Maybe I am missing something here, but according to the django docs, I should be able to overide values sent from an admin form from within the clean() method. From django docs</p> <pre><code>def clean(self): from django.core.exceptions import ValidationError # Don't allow draft entries to have a pub_date. if self.status == 'draft' and self.pub_date is not None: raise ValidationError('Draft entries may not have a publication date.') # Set the pub_date for published items if it hasn't been set already. if self.status == 'published' and self.pub_date is None: self.pub_date = datetime.date.today() </code></pre> <p>I have stripped down my code and am just trying a basic example here from within the admin</p> <p>Models.py</p> <pre><code>class Test(models.Model): name = models.CharField(max_length=255,) def clean(self): self.name = 'Robin Hood' return self </code></pre> <p>So when I try and add a new Test record, if I leave the name field empty, it should grab the value from the clean method and save.</p> <p>What happens though, is that the form doesnt validate, and the field remains empty.</p> <p>Am I missing something blantantly obvious here?</p>
0
Pandas - Replace values based on index
<p>If I create a dataframe like so:</p> <pre><code>import pandas as pd, numpy as np df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=list('AB')) </code></pre> <p>How would I change the entry in column A to be the number 16 from row 0 -15, for example? In other words, how do I replace cells based purely on index?</p>
0
Remove validators from form control Angular 6
<p>I have a form with a lot of form controls and Validators for some of the controls, like:</p> <pre><code>title = new FormControl("", Validators.compose([ Validators.required ])); description = new FormControl("", [ Validators.required, Validators.minLength(1), Validators.maxLength(2000) ]); </code></pre> <p>How do I add a save as draft button that does not validate the controls? Or remove them?</p> <p>I have tried a lot of examples such as:</p> <pre><code>saveDraft() { this.addProjectForm.controls.title.clearValidators(); this.addProjectForm.controls.title.setErrors(null); this.addProjectForm.controls.title.setValidators(null); } </code></pre> <p>or</p> <pre><code>saveDraft() { this.addProjectForm.controls['title'].clearValidators(); this.addProjectForm.controls['title'].setErrors(null); this.addProjectForm.controls['title'].setValidators(null); } </code></pre> <p>but nothing works..</p>
0
Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation
<p>Even though I manually configured JDK project structure <a href="https://i.stack.imgur.com/VxQ2W.jpg" rel="noreferrer">file/Project structure</a> it still shows this error FAILURE: Build failed with an exception.</p> <p>`What went wrong: Execution failed for task ':sample:compileReleaseJavaWithJavac'.</p> <blockquote> <p>Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation.`</p> </blockquote> <p>I'm confused why it is still looking for C:\Program Files\Java\jre1.8.0_151 instead of JDK</p>
0
Debugging on Moto 360
<p>I am trying to get debugging over Bluetooth working on my Moto 360. I am following these <a href="https://developer.android.com/training/wearables/apps/bt-debugging.html" rel="noreferrer">instructions</a> but when I put in <code>adb forward tcp:4444 localabstract:/adb-hub; adb connect localhost:4444</code> all that happens is adb runs through its list of available commands again.</p> <p>In the wear companion app <code>Debugging over Bluetooth</code> is enabled, Host says Disconnected and Target says connected.</p> <p>On the watch itself ADB debugging is enabled and Debug over Bluetooth is enabled</p> <p>I also references this <a href="http://blog.timmattison.com/archives/2014/07/16/common-android-wear-tasks-for-developers/" rel="noreferrer">article</a> which has a little more information but still nothing</p> <p>adb see's my phone just never the watch</p> <p>What am I missing?</p>
0
Spring MVC Restful service response
<p>Any idea why I get a "HTTP/1.1 200 OK" when I set </p> <pre><code>Response.status(Response.Status.NOT_FOUND) </code></pre> <p>I can see that this has been set correctly in the response body?</p> <pre><code>curl -v http://my_host/api/v1/user/99999999 </code></pre> <p><strong><em>HTTP/1.1 200 OK</em></strong></p> <p>Access-Control-Allow-Origin: *</p> <p>Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE</p> <p>....</p> <p>{"statusType":"NOT_FOUND","entity":"Unable to retrieve product with id:99999999","entityType":"java.lang.String","status":404,"metadata":{}}</p> <pre><code>@RequestMapping(value="/product/{id}", method=RequestMethod.GET) @ResponseBody public Response getProduct(@PathVariable String id) { Product product = null; //productService.getProduct(id); if (product == null) { // I KNOW I GET HERE !!! return Response.status(Response.Status.NOT_FOUND).entity("Unable to retrieve product with id:"+id). build(); } // AS EXPECTED I DO NOT GET HERE Map&lt;String, Object&gt; json = productRenderer.renderProduct(....); return Response.ok(json, MediaType.APPLICATION_JSON).type("application/json").build(); } </code></pre> <p>BTW am using Spring version 3.2.10</p>
0
How to get the screen width and height in iOS?
<p>How can one get the dimensions of the screen in iOS?</p> <p>Currently, I use:</p> <pre><code>lCurrentWidth = self.view.frame.size.width; lCurrentHeight = self.view.frame.size.height; </code></pre> <p>in <code>viewWillAppear:</code> and <code>willAnimateRotationToInterfaceOrientation:duration:</code></p> <p>The first time I get the entire screen size. The second time i get the screen minus the nav bar.</p>
0
What is the difference between Postgres DISTINCT vs DISTINCT ON?
<p>I have a Postgres table created with the following statement. This table is filled by as dump of data from another service.</p> <pre><code>CREATE TABLE data_table ( date date DEFAULT NULL, dimension1 varchar(64) DEFAULT NULL, dimension2 varchar(128) DEFAULT NULL ) TABLESPACE pg_default; </code></pre> <p>One of the steps in a ETL I'm building is extracting the unique values of <code>dimension1</code> and inserting them in another intermediary table. However, during some tests I found out that the 2 commands below do not return the same results. I would expect for both to return the same sum. The first command returns more results compared with the second (1466 rows vs. 1504.</p> <pre><code>-- command 1 SELECT DISTINCT count(dimension1) FROM data_table; -- command 2 SELECT count(*) FROM (SELECT DISTINCT ON (dimension1) dimension1 FROM data_table GROUP BY dimension1) AS tmp_table; </code></pre> <p>Any obvious explanations for this? Alternatively to an explanation, is there any suggestion of any check on the data I should do?</p> <p>EDIT: The following queries both return 1504 (same as the "simple" <code>DISTINCT</code>)</p> <pre><code>SELECT count(*) FROM data_table WHERE dimension1 IS NOT NULL; SELECT count(dimension1) FROM data_table; </code></pre> <p>Thank you!</p>
0
Python pandas groupby aggregate on multiple columns, then pivot
<p>In Python, I have a pandas DataFrame similar to the following:</p> <pre><code>Item | shop1 | shop2 | shop3 | Category ------------------------------------ Shoes| 45 | 50 | 53 | Clothes TV | 200 | 300 | 250 | Technology Book | 20 | 17 | 21 | Books phone| 300 | 350 | 400 | Technology </code></pre> <p>Where shop1, shop2 and shop3 are the costs of every item in different shops. Now, I need to return a DataFrame, after some data cleaning, like this one:</p> <pre><code>Category (index)| size| sum| mean | std ---------------------------------------- </code></pre> <p>where size is the number of items in each Category and sum, mean and std are related to the same functions applied to the 3 shops. How can I do these operations with the split-apply-combine pattern (groupby, aggregate, apply,...) ?</p> <p>Can someone help me out? I'm going crazy with this one...thank you!</p>
0
Django template: check for empty query set
<p>Is there a way to check for an empty query set in the Django template? In the example below, I only want the NOTES header to be displayed if there are notes. </p> <p>If I put an {% empty %} inside the "for" then it does display whatever is inside the empty tag, so it knows it's empty.</p> <p>I'm hoping for something that does not involve running the query twice.</p> <pre><code>{% if notes - want something here that works %} NOTES: {% for note in notes %} {{note.text}} {% endfor %} {% endif %} </code></pre> <p>Clarification: the above example "if notes" does not work - it still displays the header even with an empty query set.</p> <p>Here's a simplified version of the view</p> <pre><code>sql = "select * from app_notes, app_trips where" notes = trip_notes.objects.raw(sql,(user_id,)) return render_to_response(template, {"notes":notes},context_instance=RequestContext(request)) </code></pre> <p>Edit: the view select selects from multiple tables.</p>
0
How to set linker flags for OpenMP in CMake's try_compile function
<p>I would like to verify that the current compiler can build with openmp support. The application has do deploy across a wide variety of unix systems, some of which might have old versions of OpenMP, and I would like to test for important OpenMP functionality. So, I want to build a test source file that incorporates some of the OpenMP calls.</p> <p>Thus, I created a very simple test file, and attempted to use the try_compile function from CMake. Ufortunately, it doesn't seem to apply the -fopenmp linker flag correctly. Does anyone know how to either force the linker flag or to see if the linker flag is being applied anywhere?</p> <p>from CMakeLists.txt</p> <pre><code>try_compile( HAVE_OPENMP ${APBS_ROOT}/src/config ${APBS_ROOT}/src/config/omp_test.c CMAKE_FLAGS "-DCMAKE_C_FLAGS=-fopenmp -DCMAKE_EXE_LINKER_FLAGS=-fopenmp" OUTPUT_VARIABLE TRY_COMPILE_OUTPUT ) </code></pre> <p>from omp_test.c</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;omp.h&gt; int main() { int i; int threadID = 0; #pragma omp parallel for private(i, threadID) for(i = 0; i &lt; 16; i++ ) { threadID = omp_get_thread_num(); #pragma omp critical { printf("Thread %d reporting\n", threadID); } } return 0; } </code></pre> <p>The resulting output is</p> <pre><code>Change Dir: src/config/CMakeFiles/CMakeTmp Run Build Command:/usr/bin/make "cmTryCompileExec/fast" /usr/bin/make -f CMakeFiles/cmTryCompileExec.dir/build.make CMakeFiles/cmTryCompileExec.dir/build make[1]: Entering directory `src/config/CMakeFiles/CMakeTmp' /usr/bin/cmake -E cmake_progress_report /data/work/source/apbs/src/config/CMakeFiles/CMakeTmp/CMakeFiles 1 Building C object CMakeFiles/cmTryCompileExec.dir/omp_test.c.o /usr/bin/gcc -o CMakeFiles/cmTryCompileExec.dir/omp_test.c.o -c /data/work/source/apbs/src/config/omp_test.c Linking C executable cmTryCompileExec /usr/bin/cmake -E cmake_link_script CMakeFiles/cmTryCompileExec.dir/link.txt --verbose=1 /usr/bin/gcc CMakeFiles/cmTryCompileExec.dir/omp_test.c.o -o cmTryCompileExec -rdynamic CMakeFiles/cmTryCompileExec.dir/omp_test.c.o: In function `main': omp_test.c:(.text+0x19): undefined reference to `omp_get_thread_num' collect2: ld returned 1 exit status make[1]: *** [cmTryCompileExec] Error 1 make[1]: Leaving directory `src/config/CMakeFiles/CMakeTmp' make: *** [cmTryCompileExec/fast] Error 2 CMake Error at CMakeLists.txt:688 (message): Test OpenMP program would not build. OpenMP disabled </code></pre> <p>When I try to compile the test program on the command line, it works fine</p> <pre><code>src/config$ gcc -fopenmp omp_test.c -o omp_test &amp;&amp; ./omp_test Thread 1 reporting Thread 4 reporting Thread 7 reporting Thread 11 reporting Thread 9 reporting Thread 12 reporting Thread 6 reporting Thread 8 reporting Thread 15 reporting Thread 13 reporting Thread 10 reporting Thread 0 reporting Thread 3 reporting Thread 2 reporting Thread 5 reporting Thread 14 reporting </code></pre>
0
Node.js + Express: Routes vs controller
<p>New to Node.js and Express, I am trying to understand the two seems overlapping concepts, routes vs controller.</p> <p>I have seen examples that simple does app.js + routes/*, this seems to be sufficient to route various requests needed. </p> <p>However, I also see people talking about using controllers, and some that implies a more formal MVC model (???).</p> <p>Would be great if someone can help me clear this mystery, and if you have a good example for setting up controller in Node.js + Express framework that will be great!</p> <p>Thanks,</p>
0
Eclipse/Android: can't install Google APIs targets
<p>To use a MapView in my android application, I need to to run it in a "Google APIs (Google Inc.)" <a href="http://code.google.com/android/add-ons/google-apis/maps-overview.html#avdsetup" rel="nofollow">target</a>. However, I can't figure out how to download one. </p> <p>In Eclipse, Android SDK and AVD Manager -> Third party add-ons -> Google Inc. -> No packages found</p> <p>Although I can see that they are a bunch of packages available when looking at the <a href="https://dl-ssl.google.com/android/repository/addon.xml" rel="nofollow">url</a></p> <p>Same issue as <a href="http://code.google.com/p/processing/issues/detail?id=879" rel="nofollow">here</a>.</p> <p>Here help would be appreciated!</p>
0
how to create a multi select box with out selected options codeigniter
<p>hi i am using <code>codeigniter</code> , i want to add a <code>multi select box</code> to my page , </p> <p>i saw the codeigniter user guide example , but what it is doing is set the values in multi select . </p> <p>like this </p> <pre><code>$options = array( 'small' =&gt; 'Small Shirt', 'med' =&gt; 'Medium Shirt', 'large' =&gt; 'Large Shirt', 'xlarge' =&gt; 'Extra Large Shirt', ); $shirts_on_sale = array('small', 'large'); echo form_dropdown('shirts', $options, $shirts_on_sale); </code></pre> <p>in this multi select box created like this </p> <pre><code>&lt;select name="shirts" multiple="multiple"&gt; &lt;option value="small" selected="selected"&gt;Small Shirt&lt;/option&gt; &lt;option value="med"&gt;Medium Shirt&lt;/option&gt; &lt;option value="large" selected="selected"&gt;Large Shirt&lt;/option&gt; &lt;option value="xlarge"&gt;Extra Large Shirt&lt;/option&gt; &lt;/select&gt; </code></pre> <p>it have to give the options to be selected in <code>$shirts_on_sale</code> array , but in my case i want to create a multi select but <code>dont want selected options</code> i tried to pass an empty array . but it is not working </p> <p>like this </p> <pre><code>$array = array(); echo form_dropdown('shirts', $substore_details, $array); </code></pre> <p>how to create a multi select with no selected items . please help..............</p>
0
C/C++ sockets and a non-blocking recv()
<p>I'm having a problem where calling recv() system call does not block. I have a client-server structure setup at the moment, and the problem I am having is I send the server one message, while the server is set up so that it's something like:</p> <pre><code>while (1) { char buf[1024]; recv(fd, buf, sizeof(buf), flags); processMsg(buf); } </code></pre> <p>It receives the first message correctly, but the recv() does not block and "receives" trash data which is not what is desired. I'd like to react to messages only when they are sent. Can anyone advise? </p>
0
Advantages of node.js in comparison with other web technologies
<p>As I understand, <code>node.js</code> is useful for Java Script programmers, who can now develop in server-side. Besides, some Java Script code can be ported from client-side to server-side.</p> <p>Are there any other advantages for <code>node.js</code> in comparison with other server-side technologies (Java web frameworks, <code>RoR</code>, <code>Django</code>, etc.) ?</p>
0
System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred
<p>I have the same web app working in three others servers. Anyone have any idea why is not working in the 4th server? See the error and stacktrace:</p> <blockquote> <p><em>An operations error occurred.</em></p> <p><em>Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</em></p> <p><em>Exception Details:<br> System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred.</em></p> <p><em>Source Error:</em></p> <p><em>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</em></p> <p><em>Stack Trace:</em></p> <p><em>[DirectoryServicesCOMException (0x80072020): An operations error occurred. ] System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +454 System.DirectoryServices.DirectoryEntry.Bind() +36 System.DirectoryServices.DirectoryEntry.get_AdsObject() +31 System.DirectoryServices.PropertyValueCollection.PopulateList() +22<br> System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName) +96<br> System.DirectoryServices.PropertyCollection.get_Item(String propertyName) +142 System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer() +1134 System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit() +37 System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() +124 System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx() +31 System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable'1 identityType, String identityValue, DateTime refDate) +14<br> System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, String identityValue) +73<br> System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue) +25<br> Infraero.TINE3.STTEnterprise.Web.Common.Seguranca.ServicoAutenticacao.EfetuarLogin(AcessoUsuario acessoUsuario, String senha) in D:\SVN\STT\trunk\4-0_CodigoFonte_Enterprise\4-4_SRC\Infraero.TINE3.STTEnterprise.Web\Common\Seguranca\ServicoAutenticacao.cs:34 Infraero.TINE3.STTEnterprise.Web.Controllers.LoginController.ValidarUsuarioAD(String matricula, String senha, AcessoUsuario acessoUsuario) in D:\SVN\STT\trunk\4-0_CodigoFonte_Enterprise\4-4_SRC\Infraero.TINE3.STTEnterprise.Web\Controllers\LoginController.cs:92 Infraero.TINE3.STTEnterprise.Web.Controllers.LoginController.ValidarUsuario(String matricula, String senha) in D:\SVN\STT\trunk\4-0_CodigoFonte_Enterprise\4-4_SRC\Infraero.TINE3.STTEnterprise.Web\Controllers\LoginController.cs:80 Infraero.TINE3.STTEnterprise.Web.Controllers.LoginController.Index(LoginViewModel loginViewModel) in D:\SVN\STT\trunk\4-0_CodigoFonte_Enterprise\4-4_SRC\Infraero.TINE3.STTEnterprise.Web\Controllers\LoginController.cs:54 lambda_method(Closure , ControllerBase , Object[] ) +108<br> System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17<br> System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary'2 parameters) +208<br> System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary'2 parameters) +27<br> System.Web.Mvc.&lt;>c__DisplayClass15.b__12() +55 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func'1 continuation) +263<br> System.Web.Mvc.&lt;>c__DisplayClass17.b__14() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList'1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191<br> System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343<br> System.Web.Mvc.Controller.ExecuteCore() +116<br> System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10<br> System.Web.Mvc.&lt;>c__DisplayClassb.b__5() +37<br> System.Web.Mvc.Async.&lt;>c__DisplayClass1.b__0() +21<br> System.Web.Mvc.Async.&lt;>c__DisplayClass8'1.b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult'1.End() +62 System.Web.Mvc.&lt;>c__DisplayClasse.b__d() +50<br> System.Web.Mvc.SecurityUtil.b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60<br> System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9<br> System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963149 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +184</em></p> </blockquote> <p>EfetuarLogin Method:</p> <pre><code>public static bool EfetuarLogin(User user, string password) { bool isValid = false; if (user != null) { PrincipalContext context = new PrincipalContext(ContextType.Domain); using (context) { isValid = context.ValidateCredentials(user.Login, password); if (isValid) { UserPrincipal userAD = UserPrincipal.FindByIdentity(context, user.Login); MySession.CurrentUser = new MyUserSession() { Id = user.Id, ProfileId = user.ProfileId , Login = user.Login , Name = userAD.Name }; } } } return isValid; } </code></pre>
0
how to fit image inside TD of HTML table
<p>I am displaying an image inside TD using:</p> <p> </p> <p>But image seems to be taking larger width than the width defined for the TD.</p> <p>Please provide me some solution.</p>
0
Fast pseudorandom number generator for cryptography in C
<p>I was using the following code to generate sequence of pseudo-random numbers that was used for cryptographic purposes, but then I read somewhere that it may not be very secure. Can someone give me C implementation of a better generator -- the main goal is for this method to be fast. For instance, I did some research and came across <a href="http://en.wikipedia.org/wiki/Blum_Blum_Shub" rel="noreferrer">Blum Blum Shub</a> method, which would totally kill performance by doing pow(N) calculations.</p> <p>PS. And please don't quote Wikipedia articles w/o C/C++ code. I'm looking for C or C++ code sample of what I'm showing below.</p> <pre><code>#define ROL(v, shift) ((((v) &gt;&gt; ((sizeof(v) * 8) - (shift))) | ((v) &lt;&lt; (shift)))) ULONGLONG uiPSN = doSeed(); //64-bit unsigned integer for(int i = 0; i &lt; sizeOfArray; i++) { uiPSN = uiPSN * 214013L + 2531011L; uiPSN = ROL(uiPSN, 16); //Apply 'uiPSN' } </code></pre>
0
VB.net - insert/retrieve picture from mysql Database directly to/from a Picturebox
<p>I'm am having a heck of a time finding a code snippet that works for this. I have got to the point where it appears the picture is stored as a blob (perhaps incorrectly) by using this code.</p> <pre class="lang-vb prettyprint-override"><code>Dim filename As String = txtName.Text + ".jpg" Dim FileSize As UInt32 Dim ImageStream As System.IO.MemoryStream ImageStream = New System.IO.MemoryStream PbPicture.Image.Save(ImageStream, System.Drawing.Imaging.ImageFormat.Jpeg) ReDim rawdata(CInt(ImageStream.Length - 1)) ImageStream.Position = 0 ImageStream.Read(rawdata, 0, CInt(ImageStream.Length)) FileSize = ImageStream.Length Dim query As String = ("insert into actors (actor_pic, filename, filesize) VALUES (?File, ?FileName, ?FileSize)") cmd = New MySqlCommand(query, conn) cmd.Parameters.AddWithValue("?FileName", filename) cmd.Parameters.AddWithValue("?FileSize", FileSize) cmd.Parameters.AddWithValue("?File", rawData) cmd.ExecuteNonQuery() MessageBox.Show("File Inserted into database successfully!", _ "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk) </code></pre> <p>but on retrieving to the picturebox using the following code:</p> <pre class="lang-vb prettyprint-override"><code>Private Sub GetPicture() 'This retrieves the pictures from a mysql DB and buffers the rawdata into a memorystream Dim FileSize As UInt32 Dim rawData() As Byte Dim conn As New MySqlConnection(connStr) conn.Open() conn.ChangeDatabase("psdb") Dim cmd As New MySqlCommand("SELECT actor_pic, filesize, filename FROM actors WHERE actor_name = ?autoid", conn) Cmd.Parameters.AddWithValue("?autoid", Actor1Box.Text) Reader = cmd.ExecuteReader Reader.Read() 'data is in memory FileSize = Reader.GetUInt32(Reader.GetOrdinal("filesize")) rawData = New Byte(FileSize) {} 'get the bytes and filesize Reader.GetBytes(Reader.GetOrdinal("actor_pic"), 0, rawData, 0, FileSize) Dim ad As New System.IO.MemoryStream(100000) ' Dim bm As New Bitmap ad.Write(rawData, 0, FileSize) Dim im As Image = Image.FromStream(ad) * "error occurs here" (see below) Actor1Pic.Image = im Reader.Close() conn.Close() conn.Dispose() ad.Dispose() </code></pre> <p>I get the error "parameter not valid" in the area noted. FYI If anyone even has some better (working) code examples than this that I can plug in versus debugging this mess that would be great too.</p>
0
Is Orchard or Umbraco MVC?
<p>I'm much happier with the quality of output I can get with MVC over webforms: hand crafted HTML that isn't full of additional machine generated gubbins (polite term). I realize of course that MVC is about a lot more than this, but concentrating on just that "view" part...</p> <p>I'm looking at Orchard or Umbraco for a project. I see both support Razor syntax (Umbraco just about) - but with my strong leaning to MVC Views rather than webforms, does that rule out Umbraco?</p> <p>All the Umbraco reading I've found so far is about the XSLT engine, as the razor syntax is brand new, which scares me :-)</p>
0
How to create an empty dataFrame in Spark
<p>I have a set of Avro based hive tables and I need to read data from them. As Spark-SQL uses hive serdes to read the data from HDFS, it is much slower than reading HDFS directly. So I have used data bricks Spark-Avro jar to read the Avro files from underlying HDFS dir. </p> <p>Everything works fine except when the table is empty. I have managed to get the schema from the .avsc file of hive table using the following command but I am getting an error "<strong>No Avro files found</strong>" </p> <pre><code>val schemaFile = FileSystem.get(sc.hadoopConfiguration).open(new Path("hdfs://myfile.avsc")); val schema = new Schema.Parser().parse(schemaFile); spark.read.format("com.databricks.spark.avro").option("avroSchema", schema.toString).load("/tmp/myoutput.avro").show() </code></pre> <p>Workarounds: </p> <p>I have placed an empty file in that directory and the same thing works fine. </p> <p>Are there any other ways to achieve the same? like conf setting or something? </p>
0
What is the best way to determine if a date is today in JavaScript?
<p>I have a date object in JavaScript and I want to figure out if that date is today. What is the fastest way of doing this?</p> <p>My concern was around comparing date object as one might have a different time than another but any time on today's date should return <code>true</code>.</p>
0
Count 'white' pixels in opencv binary image (efficiently)
<p>I am trying to count all the white pixels in an OpenCV binary image. My current code is as follows:</p> <pre><code> whitePixels = 0; for (int i = 0; i &lt; height; ++i) for (int j = 0; j &lt; width; ++j) if (binary.at&lt;int&gt;(i, j) != 0) ++whitePixels; </code></pre> <p>However, after profiling with gprof I've found that this is a very slow piece of code, and a large bottleneck in the program. </p> <p>Is there a method which can compute the same value faster?</p>
0
PHP Insert into MySQL syntax error
<p>I'm having trouble submitting some data to MySQL via php, i get the following error:</p> <p><strong>"Error: 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 ''student' (UID, FirstName, LastName, DOB, EmergencyContact, Address, City, State' at line 1"</strong></p> <p>I'm not sure where i've gone wrong, any help would be great.</p> <pre><code>&lt;?php $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $dob = $_POST['dob']; $emergencycontact = $_POST['emergencycontactperson']; $address = $_POST['addressline1']; $city = $_POST['city']; $state = $_POST['state']; $zip = $_POST['zip']; $homephone = $_POST['homephone']; $cellphone = $_POST['cellphone']; $guardian = $_POST['guardian']; $inneighborhood = 0; if ($zip == "49503") $inneighborhood = 1; $con = mysqli_connect("localhost", "cookarts_root", "password", "cookarts_database"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql = "INSERT INTO 'student' (FirstName, LastName, DOB, EmergencyContact, Address, City, State, ZIP, CellPhone, HomePhone, Guardian, InNeighborhood) VALUES ($firstname', '$lastname', '$dob', '$emergencycontact', '$address', '$city', '$state', '$zip', '$cellphone', '$homephone', '$guardian', '$inneighborhood')"; if ($con-&gt;query($sql) === TRUE) { echo 'users entry saved successfully'; } else { echo 'Error: '. $con-&gt;error; } mysqli_close($con); ?&gt; </code></pre> <p><img src="https://i.stack.imgur.com/9yEVe.png" alt="enter image description here"></p> <p>If you need more info i'd be happy to provide it, thanks again for the help.</p>
0
How do I vertically align an input in a DIV
<p>I'm creating a website, and I have a login-field that contains two inputs. I want to vertically align those items inside the DIV.</p> <p>Here's my HTML:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Instagram tweaks&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;p&gt;INSTATWEAKS&lt;/p&gt; &lt;/header&gt; &lt;div class="loginbar"&gt; &lt;input type="text" name="username" id="username" class="input"&gt; &lt;input type="password" name="password" id="password" class="input"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And the CSS:</p> <pre><code>.loginbar { width: 800px; height: 400px; box-sizing: border-box; margin: auto auto; display: block; box-shadow: 0 0 10px black; color: orange; margin-top: 200px; } header { width: 100%; height: 50px; text-align: center; background-color: #111; position: absolute; top: 0; } body { margin: 0; padding: 0; } .input { font-size: 22px; vertical-align: text-top; text-align: center; } p { font-size: 30px; color: lightblue; margin-top: 10px; font-weight: bold; } </code></pre> <p>I want the inputs inside the div with the class 'loginbar' to be vertically centered</p>
0
How to support "AddType x-mapp-php5 .php" on my development machine
<p>My ISP requires me to put the following in my .htaccess files:</p> <pre><code>AddType x-mapp-php5 .php </code></pre> <p>But that breaks my development machine.</p> <p>I don't really understand what that directive is for, but I'm sick of commenting it out for dev, and uncommenting it whenever I need to upload a new version.</p> <p>Is there some way of supporting it in dev?</p>
0
java.util.logging.Logger doesn't respect java.util.logging.Level?
<p>In plain Java SE 6 environment:</p> <pre><code>Logger l = Logger.getLogger("nameless"); l.setLevel(Level.ALL); l.fine("somemessage"); </code></pre> <p>Nothing shows up in Eclipse console. <em>l.info("")</em> and above works just fine, but anything below <em>fine</em> just doesn't seem to work. What's could be wrong? TIA.</p>
0
Pass a string by reference in Javascript
<p>I want to create a string and pass it by reference such that I can change a single variable and have that propagate to any other object that references it.</p> <p>Take this example:</p> <pre><code>function Report(a, b) { this.ShowMe = function() { alert(a + " of " + b); } } var metric = new String("count"); var a = new Report(metric, "a"); var b = new Report(metric, "b"); var c = new Report(metric, "c"); a.ShowMe(); // outputs: "count of a"; b.ShowMe(); // outputs: "count of b"; c.ShowMe(); // outputs: "count of c"; </code></pre> <p>I want to be able to have this happen:</p> <pre><code>var metric = new String("count"); var a = new Report(metric, "a"); var b = new Report(metric, "b"); var c = new Report(metric, "c"); a.ShowMe(); // outputs: "count of a"; metric = new String("avg"); b.ShowMe(); // outputs: "avg of b"; c.ShowMe(); // outputs: "avg of c"; </code></pre> <p>Why doesn't this work?</p> <p>The <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String" rel="noreferrer">MDC reference on strings</a> says metric is an object.</p> <p>I've tried this, which is not what I want, but is very close:</p> <pre><code>var metric = {toString:function(){ return "count";}}; var a = new Report(metric, "a"); var b = new Report(metric, "b"); var c = new Report(metric, "c"); a.ShowMe(); // outputs: "count of a"; metric.toString = function(){ return "avg";}; // notice I had to change the function b.ShowMe(); // outputs: "avg of b"; c.ShowMe(); // outputs: "avg of c"; alert(String(metric).charAt(1)); // notice I had to use the String constructor // I want to be able to call this: // metric.charAt(1) </code></pre> <p>The important points here:</p> <ol> <li>I want to be able to use <strong>metric</strong> like it's a normal string object</li> <li>I want each report to reference the same object.</li> </ol>
0
Calculate text diffs in PHP
<p>Are there any libraries (3rd party or built-in) in <code>PHP</code> to calculate text diffs?</p>
0
The element is obscured(Server did not provide stack information) automation in edge browser with selenium
<p>org.openqa.selenium.WebDriverException: Element is obscured (WARNING: The server did not provide any stacktrace information). This code is working fine for chrome and firefox but not with edge browser.</p> <pre><code> `public class Login { public WebDriver driver; By userName = By.id("ctl14_UserName"); By password = By.id("ctl14_Password"); By login = By.id("ctl14_LoginButton"); public Login(WebDriver driver) { this.driver = driver; } // Set password in username textbox public void setUserName(String strUserName) { driver.findElement(userName).sendKeys(strUserName); } // Set password in password textbox public void setPassword(String strPassword) { driver.findElement(password).sendKeys(strPassword); } public void clickMyaccount(){ driver.findElement(myAccount).click(); } // Click on login button public void clickLogin() { driver.findElement(login).click(); } } //Test class public class AdminLogin extends BaseForDifferentLogins { Login objLoginAdmin; @Test(priority=0) public void login() throws InterruptedException{ objLoginAdmin=new Login(driver); objLoginAdmin.clickMyaccount(); Thread.sleep(3000); objLoginAdmin.setUserName("superuser1"); objLoginAdmin.setPassword("superuser1"); Thread.sleep(3000); objLoginAdmin.clickLogin(); Thread.sleep(3000); } }` </code></pre>
0
nginx configuration for Laravel 4
<p>I am trying to setup my Laravel 4 project using nginx . Here is my nginx server block for laravel :</p> <pre><code>server { listen 80; root /home/prism/www/laravel/public; index index.php index.html index.htm; server_name example.com; location / { try_files $uri $uri/ /index.php$is_args$args; } location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } </code></pre> <p>But my problem is , Its showing "404 not found" error for all other routes except the default one , that comes with default installation . </p>
0
How can I fake request.POST and GET params for unit testing in Flask?
<p>I would like to fake request parameters for unit testing. How can I achieve this in Flask?</p>
0
"Command /usr/sbin/chown failed with exit code 1" when Archiving
<p>I am trying to archive my first iOS 4.3 Application for iPhone and I always encounter this error:</p> <pre><code>Command /usr/sbin/chown failed with exit code 1 </code></pre> <p>I have searched through various forums, trying solutions such as changing the Alternate Install Group (which I don't know what to change to), and turning on 'Skip Install'.</p>
0
How do I remove elements at a set of indices in a vector in MATLAB?
<p>I have a vector with 100 elements. I have another vector with index positions of elements I want to remove from this vector.</p> <p>How do I do this?</p>
0
iPhone - testing if a notification exists
<p>At some point in a code one may add something like</p> <pre><code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething) name:@"Hello" object:nil]; </code></pre> <p>How do I test if this notification is already active on the queue or has been removed, to prevent adding a duplicate?</p> <p>thanks.</p>
0
Can't connect to MongoDB through PHP
<p>I just wanted to take a look at Mongo-DB. But i just don't get it running. I've installed it with PECL and my <code>phpinfo()</code> tells me that the extension is loaded, but when i try to get a connection with</p> <p><code>$mongo = new Mongo();</code></p> <p>I get this:</p> <blockquote> <p>Fatal error: Uncaught exception 'MongoConnectionException' with message ': Transport endpoint is not connected'</p> </blockquote> <p>Anybody have the same Problem? ... Or any Idea on this?</p>
0
Pipe Ipython magic output to a variable?
<p>I want to run a bash script in my ipython Notebook and save the output as a string in a python variable for further manipulation. Basically I want to pipe the output of the bash magic to a variable, For example the output of something like this:</p> <pre><code>%%bash some_command [options] foo bar </code></pre>
0
std::array incomplete type error with an array of std::tuple
<p>I am getting some strange behaviour with a C++11 <code>std::array</code>. When I try to compile with <code>std::array&lt;std::tuple&lt;int, float&gt;, 6&gt; myTuples;</code> as a member variable, I get these errors:</p> <p><code>mingw32\4.7.2\include\c++\array:-1: In instantiation of 'struct std::array&lt;std::tuple&lt;int, float&gt;, 6u&gt;':</code><br> <code>mingw32\4.7.2\include\c++\array:77: error: 'std::array&lt;_Tp, _Nm&gt;::_M_instance' has incomplete type</code></p> <p>I'm not sure if any of this changes anything but the class it is in is a template class derived from another template class. The template parameter is an <code>unsigned int</code> an determines the size of a protected <code>std::array</code> in the base class, which I reference in the derived class <code>using Base&lt;param&gt;::m_array;</code>. The derived class has various <code>glm::vec3/dmat4/quat</code> types, and uses OpenGL fixed function <code>glBegin(GL_QUADS);</code> stuff. I'm using SDL-1.2.15 to create an OpenGL context. I think most of that was irrelevant, but maybe not. I could paste code, but everything is interconnected, so it can only be compiled as a whole (which distributed between sources is around a thousand or so lines).</p> <p>However, when I include this same line in <a href="http://ideone.com/O7TCMe" rel="noreferrer" title="Ideone.com example">this ideone example</a>, in very similar circumstances, it compiles perfectly fine. I checked that it wasn't just my compiler (MinGW g++ version 4.7.2) by compiling the same on my compiler with command line <code>g++ -Wall -std=c++11</code></p> <p>Does anyone know why I might get these errors? I had some problems before with the compiler crashing while parsing <code>std::array</code> assignment (using <code>array = {{a,b,c}};</code> for a default parameter), but this time its a compiler error not crash.</p>
0
Start WSL Ubuntu in specific or current folder on Windows
<p>When installing Subsystem for Linux and Ubuntu from store on his development machine I can switch (or start) to Ubuntu shell by simply</p> <p><a href="https://i.stack.imgur.com/RgSmf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RgSmf.png" alt="enter image description here"></a></p> <p>But the Ubuntu shell start in <code>/home/techsupp</code> folder by default. Is it possible to force it to start in same folder than the one I use my <code>Ubuntu</code> command?</p> <p>So in my example I should be in </p> <pre><code>/mnt/h </code></pre> <p>Thank you.</p> <p><strong>What I already tried:</strong></p> <pre><code>H:\&gt;ubuntu help Launches or configures a linux distribution. Usage: &lt;no args&gt; - Launches the distro's default behavior. By default, this launches your default shell. run &lt;command line&gt; - Run the given command line in that distro, using the default configuration. - Everything after `run ` is passed to the linux LaunchProcess call. config [setting [value]] - Configure certain settings for this distro. - Settings are any of the following (by default) - `--default-user &lt;username&gt;`: Set the default user for this distro to &lt;username&gt; clean - Uninstalls the distro. The appx remains on your machine. This can be useful for "factory resetting" your instance. This removes the linux filesystem from the disk, but not the app from your PC, so you don't need to redownload the entire tar.gz again. help - Print this usage message. </code></pre> <p>I also discover this request on uservoice: <a href="https://wpdev.uservoice.com/forums/266908-command-prompt-console-windows-subsystem-for-l/suggestions/13421103-let-us-right-click-open-bash-here-from-explorer?tracking_code=8a8bc624c72a8336565fcd6d5737d712" rel="noreferrer">https://wpdev.uservoice.com/forums/266908-command-prompt-console-windows-subsystem-for-l/suggestions/13421103-let-us-right-click-open-bash-here-from-explorer?tracking_code=8a8bc624c72a8336565fcd6d5737d712</a></p> <p>Please vote for it.</p>
0
i dont understand what is 0x7fffffff mean. is there any other way to code getHashValue method?
<pre><code>public int getHashValue(K key){ return (key.hashCode() &amp; 0x7fffffff) % size; } </code></pre> <p>i dont understand what is 0x7fffffff mean. is there any other way to code getHasValue method? </p>
0
Twitter Bootstrap Modal data-dismiss
<p>I am trying to get modal data-dismiss action working to close the modal on click. There seems to be an issue that I cannot find documented and hopefully someone here can shed some light on it. Here is the code </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset='UTF-8'/&gt; &lt;title&gt; Modal test &lt;/title&gt; &lt;link href='themes/default/bootstrap/css/bootstrap.css' rel='stylesheet'/&gt; &lt;link href='themes/default/bootstrap/css/bootstrap-responsive.css' rel="stylesheet"/&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="modal" id="myModal"&gt; &lt;div class="modal-header"&gt; &lt;button class="close" data-dismiss="modal"&gt;×&lt;/button&gt; &lt;h3&gt;Modal header&lt;/h3&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;One fine body…&lt;/p&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;a href="#" class="btn"&gt;Close&lt;/a&gt; &lt;a href="#" class="btn btn-primary"&gt;Save changes&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="alert alert-block"&gt; &lt;a class="close" data-dismiss="alert" href="#"&gt;x&lt;/a&gt; &lt;h4 class="alert-heading"&gt;Warning!&lt;/h4&gt; Best check yo self, you're not... &lt;/div&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="themes/default/bootstrap/js/bootstrap.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p> is the full suite of bootstrap including bootstrap-modal.js</p> <p>I put in the <code>&lt;div class="alert alert-block"&gt;</code> for testing the action, it seems to work in the alert but not the modal!</p>
0
Change Select List Option background colour on hover
<p>Is it possible to change the default background color of a select list option on hover?</p> <p>HTML:</p> <pre><code>&lt;select id="select"&gt; &lt;option value="1"&gt;One&lt;/option&gt; &lt;option value="2"&gt;Two&lt;/option&gt; &lt;option value="3"&gt;Three&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I have tried <code>option:hover { background-color: red; }</code>, but it is of no use. Does anybody know how to do this?</p>
0
How to reach bottom of listview, load more items
<p>When I reach the bottom of my ListView (Scroll down until the end), how do I load more items? Here is my class (maybe it will help) </p> <pre><code>public class ListFood extends Activity { int userid; String cat; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_food); ListView lv = (ListView) findViewById(R.id.ListView01); TextView tv = (TextView) findViewById(R.id.TextView01); Webservice ws = new Webservice(); List&lt;Afood&gt; list = new ArrayList&lt;Afood&gt;(); int i; Bundle bundle = getIntent().getExtras(); userid = bundle.getInt("userid"); cat = bundle.getString("cat"); list = ws.getFoodFromCat(cat); String [] food = new String [list.size()]; for(i=0;i&lt;list.size();i++) { food[i] = list.get(i).name; } if(cat.equalsIgnoreCase("FastFood")) tv.setText("Fast Food"); else tv.setText(cat); lv.setAdapter(new ArrayAdapter&lt;String&gt;(this, R.layout.list, food)); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { // When clicked, show a toast with the TextView text Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show(); } }); } } </code></pre>
0