_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d8501
train
There are serveral ways to do that. Since you seems to be new to javascript, you can start with callback: function load(url, callback){ var xhr = new XMLHttpRequest(); xhr.onloadend = function(e){ callback(xhr); }; xhr.open('GET', url); xhr.send(); } load('/', function (data) { console.log(data); }); In this example, callback is a function, and we pass xhr as a parameter to that function while calling. A: My advice is to make use of the Promise and fetch APIs. function ajax(options) { return new Promise(function (resolve, reject) { fetch(options.url, { method: options.method, headers: options.headers, body: options.body }).then(function (response) { response.json().then(function (json) { resolve(json); }).catch(err => reject(err)); }).catch(err => reject(err)); }); } You can use it like so: const ajaxResponse = await ajax({url: '/some/api/call', method: 'get'}); In case you don't already know, await can only be used inside async functions. If you don't want to use async functions, do the following: ajax({url: '/some/api/call', method: 'get'}).then(data => { // process data here }); Explanation: JavaScript is a single-threaded language. This means everything runs in a blocking manner. If your Ajax call takes 3 seconds, then JavaScript will pause for 3 seconds. Luckily, the XMLHttpRequest and fetch APIs combat this issue by using asynchronous functions, meaning code can continue running while the Ajax call is awaiting a response. In your code, you're not getting a response from your function because the Ajax call doesn't stop the execution, meaning by the time the call has been made, there's nothing to return yet and by the time the call is finished, the function's call is long in the past too. You can tell JavaScript however to keep track of this asynchronous task through Promises. When your task is finished, the Promise's then function is called with the data from the Ajax call. JavaScript also provides syntactic sugar to make reading asynchronous code easier. When we use an async function, what we're actually doing is creating a regular function, whose body is wrapped in a Promise. This also means that when you want to wait for the result of a previous Promise, you can prepend await in front of the Promise reference and await the completion of the Promise. So you may have code that looks like this: const call = await ajax({ ... }); console.log(call); which actually translates to the following: ajax({ ... }).then(call => { console.log(call); });
unknown
d8502
train
A clean way is using pysolr import pysolr # Create a client instance. The timeout and authentication options are not required. solr = pysolr.Solr('http://localhost:8983/solr/') # Do a health check. ping = solr.ping() resp = json.loads(ping) if resp.get('status') == 'OK': print('success') A: if the code below error(connection refused), solr is not working. gettingstarted is an example collective name in the link. from urllib.request import * connection = urlopen('http://localhost:8983/solr/gettingstarted/select?q=mebus&wt=python') response = eval(connection.read())
unknown
d8503
train
Could use the following (assumes your words are all matched by \w) "Crazy Fredrick bought many very exquisite opal jewels.".replace(/(\w+) (\w+)/g, '$1'); -> "Crazy bought very opal." Replacing $1 with $2 gives you: "Fredrick many exquisite jewels." A: Not sure if RegEx is the right tool, but you could split the string by space into an array and then use filter to remove the odd or even elements: var s = "Crazy Fredrick brought many very exquisite opal jewels"; s.split(/\s+/) .filter(function (_, index) { return index % 2 !== 0; // only want "odd" words }).join(" "); // yields "Fredrick many exquisite jewels" A: Not the best solution, but you can try using these regexes: \b\S+\b\s?(?=((\b\S+\b\s?){2})*\.?$) \b\S+\b\s?(?=\b\S+\b\s?((\b\S+\b\s?){2})*\.?$) Explanation and demonstration here: http://regex101.com/r/kR3hS5
unknown
d8504
train
I found the solution, i was overriding ondestroy view on one of my fragment and added requireActivity.finish() in the overridden method
unknown
d8505
train
I finally found what was going on. The view controller that was not being dealloc was created through a class method, for example : + (instancetype) createMyViewController. This kind of methods return autorelease objects. My only guess is that the autorelease pool is drained way too late in my case. Adding an @autoreleasepool {} block around the appropriate code fixed everything. A: Check out these view controller lifecycle methods. One of them is probably the right place for the code you have in dealloc, and you can count on them being called at the times stated. Dealloc should only be used for memory cleanup, e.g. free. - (void)viewWillDisappear:(BOOL)animated - (void)viewDidDisappear:(BOOL)animated
unknown
d8506
train
I managed to find the solution. Thanks to this post: DOMDocument append already fixed html from string I did: private function appendChildNode($dom_output, $cit_node, $nodeName, $nodeText) { if ($nodeText != null && $nodeText != "" ) { $node = $dom_output->createElement($nodeName); $fragment = $dom_output->createDocumentFragment(); $fragment->appendXML( $nodeText); $node->appendChild($fragment); $cit_node->appendChild($node); return $node; } }
unknown
d8507
train
Programmatically add MouseClick even handlers to all your PictureBoxes in Form_Load. The event handler will parse the sender (PictureBox) and find the CheckBox based on the fact that the corresponding controls' names end in the same index. Remove the handlers when the form closes. Private pictureBoxPrefix As String = "PictureBox" Private checkBoxPrefix As String = "CheckBox" Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix)) AddHandler pb.MouseClick, AddressOf PictureBox_MouseClick Next End Sub Private Sub PictureBox_MouseClick(sender As Object, e As MouseEventArgs) Dim index = Integer.Parse(pb.Name.Replace(pictureBoxPrefix, "")) Dim pb = CType(sender, PictureBox) Dim cb = CType(Me.Controls.Find($"{checkBoxPrefix}{index}", True).First(), CheckBox) pb.BackColor = Color.Green cb.Checked = True End Sub Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix)) RemoveHandler pb.MouseClick, AddressOf PictureBox_MouseClick Next End Sub A: In the Load() event of your form, use Controls.Find() to get a reference to both the PictureBoxes and CheckBoxes. Store the CheckBox reference in the Tag() property of each PictureBox. Wire up the Click() event of you PB. In that event, change the color of the PB, then retrieve the CheckBox from the Tag() property and check the box as well: Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load For i As Integer = 1 To 28 Dim PB As PictureBox = Me.Controls.Find("PictureBox" & i, True).FirstOrDefault Dim CB As CheckBox = Me.Controls.Find("CheckBox" & i, True).FirstOrDefault If Not IsNothing(PB) AndAlso Not IsNothing(CB) Then PB.Tag = CB CB.Tag = PB AddHandler PB.Click, AddressOf PB_Click AddHandler CB.CheckedChanged, AddressOf CB_CheckedChanged End If Next End Sub Private Sub PB_Click(sender As Object, e As EventArgs) Dim pb As PictureBox = DirectCast(sender, PictureBox) Dim cb As CheckBox = DirectCast(pb.Tag, CheckBox) If pb.BackColor.Equals(Color.Green) Then pb.BackColor = Color.Empty cb.Checked = False Else pb.BackColor = Color.Green cb.Checked = True End If End Sub Private Sub CB_CheckedChanged(sender As Object, e As EventArgs) Dim cb As CheckBox = DirectCast(sender, CheckBox) Dim pb As PictureBox = DirectCast(cb.Tag, PictureBox) pb.BackColor = If(cb.Checked, Color.Green, Color.Empty) End Sub
unknown
d8508
train
I ended up reverting to css-loader version 1.0.1 to fix the problem.
unknown
d8509
train
This should get you on the right track. //your javascript $('#myDropdown').on('change', function(){ var data = {someData : someDataValue, someMoreData : someMoreDatavalue}; $.post('myControllerName/UpdateProduct', data, function(responseData){ //callback function }); }); //in your controller [HttpPost] public ActionResult UpdateProduct(int someData, string someMoreData) { //do something with your data } A: Try this @Html.DropDownList("id", (SelectList)ViewBag.Values, new { onchange = string.Format("UpdateProductsDB(this, {0})", item.id) }) And your UpdateProductsDB function will now accept id as well. function UpdateProductsDB(categorySelected, productId) { ... } Also depending on the type of your id, if it is an integer than you can just use: string.Format("UpdateProductsDB(this, {0})", item.id) But if it is a GUID or a string you will have to put single quotes around: string.Format("UpdateProductsDB(this, '{0}')", item.id) A: Turns out I didn't need jQuery or AJAX at all, just these 3 lines. When an item is selected in the drop down, this "posts back" or runs immediately : @using (Html.BeginForm("UpdateProduct", "GiftList")) { @Html.Hidden("prodID", item.Id) @Html.DropDownList("catID", (SelectList)ViewBag.Values, new { onchange = "this.form.submit();" }) }
unknown
d8510
train
The response is surrounded by [ ]. This indicates it's an array. So you need to reference into that array to get to the data. msg.payload[0].price_usd
unknown
d8511
train
You forgot to receive the result of zeroPad. The function uses realloc(), so the passed pointer may be invalidated. The function returns the new pointer, so you have to assign that to x. This means that the line in the main() function zeroPad(5,x,10); should be x = zeroPad(5,x,10);
unknown
d8512
train
Let me guess, you get a System.FormatException here dateEdit.Text = (string.Format("{yyyy-MM-dd}", rdr["data"])); That is because you can't use String.Format in that way, a format string must have an index or the index must be preceeded like here: dateEdit.Text = string.Format("{0:yyyy-MM-dd}", rdr["data"]); or without String.Format but DateTime.ToString: int columndIndex = rdr.GetOrdinal("data"); DateTime dt = rdr.GetDateTime(columndIndex); dateEdit.Text = dt.ToString("yyyy-MM-dd");
unknown
d8513
train
This depends on what you mean by, 'test a string'. Do you want to check if the entire string matches your pattern, or if the pattern just happens to occur in your string, e.g. 'ESZ6' vs. "I've got an ESZ6 burning a hole in my pocket'. Can other characters abut your target, eg. '123ESZ6ARE'? Assuming we're just testing individual tokens like 'ESZ6' and 'ESSP6', then here are some code ideas: import re items = ('ESZ6', 'ESSP6') prog = re.compile(r"[A-Z]+[FGHJKMNQUVXZ]\d$") matches = [item for item in items if prog.match(item)] Use .match() instead of .search() unless you want an unanchored search. Drop the final '$' if you want the end unanchored. (If using Python 3.4 or later, and want an anchored search, you can probably drop the '$' and use .fullmatch instead of .match) Pattern match operators only match one character sans repetition operators so you don't need the {1} indications. Use raw strings, r"\d", when dealing with patterns to keep Python from messing with your back slashes. Your description and your examples don't match exactly so I'm making some assumptions here.
unknown
d8514
train
The suppressed exception (RuntimeException-A) was added to the IOException caught in the catch and lost from the stack trace printout as it was not passed as the cause of the RuntimeException-C. So when the RuntimeException-C is printed from the main it has no mention of the IOException or the suppressed RuntimeException-A. And therefore the book's answer is correct because the only exception that is propagated from the main method is RuntimeException-C without cause (IOException), and without any suppressed exceptions (as it was on IOException).
unknown
d8515
train
Why does using cast, cast to CastList<dynamic, Type> and not the original Type? From the docs, myList.cast<MyType> returns a List<MyType>. In your case you're calling resp.cast<List<Questionnaire>>, so the return will be List<List<Questionnaire>>, which is not what you want. If you're asking about CastList<dynamic, Type>, it's a subclass of List<Type>, see the source code. It's useful because CastList doesn't need to create a new list, it's just a wrapper around the original list where each element is cast with as Type before being returned. What changes do I do to get my data? The problem is you're calling resp.cast<Type> where resp is not a list that constains Type. Here's a working sample based on the code you provided: import 'dart:convert'; final sampleJson = """[ { "questionId": 1, "displayQuestions": [ { "question": "how old are you", "answers": [ "1", "2", "3", "4" ] } ] } ] """; class DisplayQuestion { String question; List<String> answers; DisplayQuestion.fromJson(Map<String, dynamic> json) : question = json["question"], answers = json["answers"].cast<String>(); String toString() => 'question: $question | answers: $answers'; } class Questionnaire { int questionnaireId; List<DisplayQuestion> displayQuestions; Questionnaire.fromJson(Map<String, dynamic> json) : questionnaireId = json['questionnaireId'], displayQuestions = (json['displayQuestions'] as List<dynamic>) .map((questionJson) => DisplayQuestion.fromJson(questionJson)) .toList(); String toString() => '$displayQuestions'; } List<Questionnaire> parseQuestionnaires() { List<Questionnaire> questionnaires = (json.decode(sampleJson) as List<dynamic>) .map((questionnaireJson) => Questionnaire.fromJson(questionnaireJson)) .toList(); return questionnaires; } void main() { print(parseQuestionnaires()); // => [[question: how old are you | answers: [1, 2, 3, 4]]] }
unknown
d8516
train
I wanted to disable this because of the sitelinks searchbox and the fact that I don't have a search function that works globally, just on the blog. Having the search box enabled for me would have undesirable effects. The easier option may just be to prevent Google using the sitelinks searchbox without having to touch the functions files. You can prevent Google using sitelinks searchbox on your site by using the following meta: <meta name="google" content="nositelinkssearchbox" /> If you want to disable Yoast's JSON-LD all together then here's a snippet from my blog and the code I use on my site: SOURCE How to disable Yoast SEO Schema JSON-LD completely function bybe_remove_yoast_json($data){ $data = array(); return $data; } add_filter('wpseo_json_ld_output', 'bybe_remove_yoast_json', 10, 1); Login to your WordPress dashboard and head over to the editor within the tab menu appearance, find your functions file (normally named functions.php) and add the code below just before the PHP tag is closed at the bottom. A: Simplest way to completely disable the Yoast SEO schema JSON-LD Add this line to functions.php file: add_filter( 'wpseo_json_ld_output', '__return_empty_array' ); Source A: If you want to disable just Organization or just Website, add this to your theme's functions.php file: function bybe_remove_yoast_json($data){ if ( (isset($data['@type'])) && ($data['@type'] == 'Organization') ) { $data = array(); } return $data; } add_filter('wpseo_json_ld_output', 'bybe_remove_yoast_json', 10, 1); A: Unless the data Yoast produces is wrong, there is no harm in having it. Quite the contrary, having more structured data is better than having less. If having it is "unnecessary" depends on your definition of what is necessary. Some consumers might be interested in it, others not. My guess is that Yoast adds a WebSite entity because of Google’s sitelinks searchbox rich snippet result, which allows Google users to search your site directly from the Google search result.
unknown
d8517
train
I'm not sure if this is the reason, but each time, you're resetting the contentview. This should only be called once in onCreate, otherwise just remove the elements and use an inflater to add new ones. I think every time it resets the contentview, it will reset the textboxes. A: I think, i got your problem . sundayDialog.setContentView(R.layout.sunday_dialog); this is View you are setting for your custom Dialog. this is fine. And after sunday click button again you are resetting your Layout which again creates all views and you are getting everything reset. final Dialog sundayDialog = new Dialog(this); sundayDialog.setContentView(R.layout.sunday_dialog); Button sundaySubmitBtn = (Button) sundayDialog .findViewById(R.id.sundayDialogSubmitBtn); Button sundayCancelBtn = (Button) sundayDialog .findViewById(R.id.sundayDialogCancelBtn); sundaySubmitBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Submit Button // Here i have removed setContent View.... final EditText etAmountBought = (EditText) findViewById(R.id.amountBoughtET); final EditText etCost = (EditText) findViewById(R.id.pricePaidET); String amountBought = etAmountBought.getText().toString(); String cost = etCost.getText().toString(); if (amountBought.isEmpty() || cost.isEmpty()) { //sundayDialog.dismiss(); emptyETDialogCall(); } else { try { mAmountBought = Integer.parseInt(amountBought); mPricePaid = Integer.parseInt(cost); } catch (NullPointerException e) { Log.e(TAG, "Error in sunday dialog in try/catch"); } } if (mPricePaid >= 250) { costTooHighDialogCall(); mPricePaid = 0; } // textBlockDisplay(); // Update the text block with input. } }); sundayCancelBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Cancel Button sundayDialog.dismiss(); sundayCancelDialog(); } }); sundayDialog.show(); }
unknown
d8518
train
Try this: "Change (.*?) to value (.*?)\." https://regex101.com/r/gG5sK3/2 Where the first and the second group are your desired values!
unknown
d8519
train
It's actually a std::ptrdiff_t, which has to be a signed integer. It has to be signed because it can be used as the difference between two iterators, and that can of course be negative.
unknown
d8520
train
Are you calling the method on viewDidLoad: method? Somethimes calling a modal view controller within viewDidLoad: gives this kind of problem. You can solve this problem calling it from the viewDidAppear: method.
unknown
d8521
train
Socket is now supported since 1.7.2 by signing up trusted tester
unknown
d8522
train
Yep, what they said. Also, if you want to assign more than one class, use a space to separate them, like so: <div class="ts visible">. Edit: Also, use spaces to separate the "padding" values, like this: padding: 0 0 0 20px;, or just use padding-left: 20px;. A: You can use it like this: <div class="ts">... </div> But I strongly recommend you take a look at css here, it's not that hard. A: Just give that <div> a class attribute, like this: <div class="ts"></div> If you want it to have both classes, use a space between like this: <div class="ts visible"></div> A: You'd simply do: <div class="ts">Contents of div</div> That said, I very much suspect that's not the answer you're looking for. :-)
unknown
d8523
train
You would need to add the logic to a template that matched the 'Proposal' element <xsl:template match="*[local-name() = 'Proposal']"> Then, you would just write an xsl:if statement, like so: <xsl:if test="not(*[local-name() = 'ApplicationData'])"> <oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006"> <oneapp:TreesHedgesWales/> <oneapp:OtherLowCarbonEnergy/> </oneapp:ApplicationData> </xsl:if> You would need to wrap this in an xsl:copy if you wanted to retain the Proposal element. If you didn't already have an existing template matching Proposal in your XSLT, you could add the test to template match itself <xsl:template match="*[local-name() = 'Proposal'][not(*[local-name() = 'ApplicationData'])]"> <xsl:copy> <oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006"> <oneapp:TreesHedgesWales/> <oneapp:OtherLowCarbonEnergy/> </oneapp:ApplicationData> </xsl:copy> </xsl:template> As michael.hor257k mentioned in comments, it would be much cleaner if you declared your namespaces in your XSLT, and used namespace prefixes in the matching.... <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006"> <xsl:template match="oneapp:Proposal[not(oneapp:ApplicationData)]"> <xsl:copy> <oneapp:ApplicationData> <oneapp:TreesHedgesWales/> <oneapp:OtherLowCarbonEnergy/> </oneapp:ApplicationData> </xsl:copy> </xsl:template>
unknown
d8524
train
They didn't need to explicitly write implements Set<E>. They did it for readability. A: There is another reason; consider the following java program:- package example; import java.io.Serializable; import java.util.Arrays; public class Test { public static interface MyInterface { void foo(); } public static class BaseClass implements MyInterface, Cloneable, Serializable { @Override public void foo() { System.out.println("BaseClass.foo"); } } public static class Class1 extends BaseClass { @Override public void foo() { super.foo(); System.out.println("Class1.foo"); } } static class Class2 extends BaseClass implements MyInterface, Cloneable, Serializable { @Override public void foo() { super.foo(); System.out.println("Class2.foo"); } } public static void main(String[] args) { showInterfacesFor(BaseClass.class); showInterfacesFor(Class1.class); showInterfacesFor(Class2.class); } private static void showInterfacesFor(Class<?> clazz) { System.out.printf("%s --> %s\n", clazz, Arrays.toString(clazz .getInterfaces())); } } Which outputs the following text (java 6u16): class example.Test$BaseClass --> [interface example.Test$MyInterface, interface java.lang.Cloneable, interface java.io.Serializable] class example.Test$Class1 --> [] class example.Test$Class2 --> [interface example.Test$MyInterface, interface java.lang.Cloneable, interface java.io.Serializable] Notice how Class1 does not have explicit interfaces defined, so the Class#getInterfaces() does not include those interfaces, whereas Class2 does. The use of this only becomes clear in this program:- package example; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import example.Test.BaseClass; import example.Test.Class1; import example.Test.Class2; public class Test2 extends Test { public static void main(String[] args) { MyInterface c1 = new Class1(); MyInterface c2 = new Class2(); // Note the order... MyInterface proxy2 = createProxy(c2); proxy2.foo(); // This fails with an unchecked exception MyInterface proxy1 = createProxy(c1); proxy1.foo(); } private static <T> T createProxy(final T obj) { final InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.printf("About to call %s() on %s\n", method .getName(), obj); return method.invoke(obj, args); } }; return (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj .getClass().getInterfaces(), handler); } } Which outputs:- About to call foo() on example.Test$Class2@578ceb BaseClass.foo Class2.foo Exception in thread "main" java.lang.ClassCastException: $Proxy1 cannot be cast to example.Test$MyInterface at example.Test2.main(Test2.java:23) While Class1 does implicitly implement MyInterface, but the created proxy does not. Hence if we wanted to create a dynamic proxy which implements all interfaces for an object which has implicit interface inheritance then the only way to do it generically would be to walk the superclasses all the way back to java.lang.Object, as well as walking all the implemented interfaces and their superclasses (remember Java supports multiple interface inheritance), which doesn't sound very efficient, while it is much easier (and faster) to explicitly name interfaces as I suppose they are set in at compile time. So what uses reflection & proxies? RMI for one... Therefore, yes it is a convenience, but no it is certainly not redundant: remember that these classes were carefully designed and implemented by Josh Bloch, so I suspect that they were explicitly programmed this way so that proxied network stubs and skeletons work as they do. A: I've asked Josh Bloch, and he informs me that it was a mistake. He used to think, long ago, that there was some value in it, but he since "saw the light". Clearly JDK maintainers haven't considered this to be worth backing out later. A: Good catch, they did not need to put java.io.Serializable either. A: It's redundant. You could do without the implements Set<E>. A: Perhaps it has something to do with the way javadoc gets generated. You know how Java API tells you all concrete classes that impement an interface or inherit from other classes? While I agree that at runtime its redundant, I can see how this might ease the automatic generation of javadoc. This is just a wild guess of course.
unknown
d8525
train
The purpose of web container like tomcat is to able to run applications independently so they can be started and stopped without affecting each other. In case you think there can be multiple future applications will also require the same service, you can make a separate application and expose an API for the operations.
unknown
d8526
train
Right now, you don't do anything with the result of your service method. You have to assign the returned item to your variable: .subscribe(result => { this.myVar = result; console.log(this.myVar); });
unknown
d8527
train
For me it worked as soon as I have set-up the printRect like: NSRect printRect = NSZeroRect; printRect.size.width = (printInfo.paperSize.width - printInfo.leftMargin - printInfo.rightMargin) * printInfo.scalingFactor; printRect.size.height = (printInfo.paperSize.height - printInfo.topMargin - printInfo.bottomMargin) * printInfo.scalingFactor; self.hostingView.printRect = printRect; op = [NSPrintOperation printOperationWithView:self.hostingView printInfo:printInfo]; Note self.hostingViewrefers to the CorePlot hostingView.
unknown
d8528
train
Instead of returning null you could return -1 and then check for the value you return being -1. if (valueReturned == -1) { return null; } else { //continue with method } The samePosition() method should return always an integer: private int samePosition(String macD, int routeD, float latD, float longD) { int size = latLongList.size(); if (size > 1) { ArrayList<Double> array = new ArrayList<>(); for (int i = 0; i < latLongList.size() - 1; i++) { LatLong last = latLongList.get(latLongList.size() - 1); double distance = haversineDistance(latLongList.get(i), last); array.add(distance); } ArrayList<Double> distanceRange = new ArrayList<>(); for (int j = 0; j < array.size(); j++) { // Store request in the circumcircle of 4 meter into ArrayList. if (array.get(j) < 4) { distanceRange.add(array.get(j)); } } if (distanceRange.size() == 0) { processData(macD, routeD, latD, longD); return 0; } else { return -1; } } else { processData(macD, routeD, latD, longD); return 0; } } A: Check the below and modify as needed. Instead of returning 201 as response in all the cases I preferred to return different status code based on whether you processed the data or not. In your earlier code, the code segment you are trying to extract is returning null from one point and nothing from last else where you are calling processData(..). @POST @Consumes(MediaType.APPLICATION_JSON) public Response storeData(Data data) { .. int status = samePosition(..); return Response.status(status).build(); } private int samePosition(..) { int status = 201; if() { ... if (distanceRange.size() == 0) { processData(macD, routeD, latD, longD); } else { status = <Preferred HTTP status code to return for not processing>; } } else { } return status; }
unknown
d8529
train
You can do this by several ways e.g: watch : { itemSelection: function(val) { ... } } There is some examples. Check this fiddle
unknown
d8530
train
As mentioned in the error message, you should use .any(). like: if (key == 1).any(): print('Alert') As key == 1 will be an array with [False, True, True, False, ...] You might also want to detect ones that exceeds certain score, say 0.7: for key, score in zip( detections['detection_classes'], detections['detection_scores']): if score > 0.7 and key == 1: print('Alert') break
unknown
d8531
train
There's nothing built-in, everything is a simple consequence of the Monad instance you quoted (and, since this example uses do notation, how that desugars to uses of the >>= operator): allEvenOdds n = do evenValue <- [2,4 .. n] oddValue <- [1,3 .. n] return (evenValue,oddValue) -- desugaring the do notation allEvenOdds n = [2,4 .. n] >>= \evenValue -> [1,3 .. n] >>= \oddValue -> return (evenValue, oddValue) -- using the list instance of Monad to replace >>= and return allEvenOdds n = concatMap (\evenValue -> concatMap (\oddValue -> [(evenvalue, oddValue)]) [1,3 .. n] ) [2,4 .. n] which you can hopefully easily see "iterates over" both lists and results in a list of all pairs of (even, odd) with values taken from both lists. At a high level, we can say that the list monad results in iteration simply because concatMap, like map, executes the given function for each element of the list, so it implicitly iterates over the list. A: The list instance of the Monad typeclass models nondeterminism: you can see each var <- someList as a for loop like in Python. The do notation is desugared to [2,4 .. n] >>= (\evenValue -> [1, 3 .. n] >>= (\oddValue -> return (evenValue, oddValue))), so this is equivalent to something in Python like: result = [] for evenValue in range(2, n, 2): for oddValue in range(1, n, 2): result.append((evenValue, oddValue)) or with list comprehension: result = [ (evenValue, oddValue) for evenValue in range(2, n, 2) for oddValue in range(1, n, 2) ] This works since for instance Monad [], the expression [2,4 .. n] >>= (\evenValue -> [1, 3 .. n] >>= (\oddValue -> return (evenValue, oddValue))) is thus equivalent to: concatMap (\evenValue -> [1, 3 .. n] >>= (\oddValue -> return (evenValue, oddValue))) [2,4 .. n] and thus: concatMap (\evenValue -> concatMap (\oddValue -> [(evenValue, oddValue)]) [1, 3 .. n]) [2,4 .. n] But do notation is not "hardwired" to IO: IO is just an instance of Monad that is implemented in such way that one IO action will run before the second one. For lists, it thus is implemented in an equivalent way as spanning Python for loops.
unknown
d8532
train
Use the NSURL it must work. webalani.loadRequest(NSURLRequest(URL: NSURL(string: "aString")!)) And make sure your this line must be NSURL too if let aString = URL(string: "" + ("http://www.truebilisim.com/myiphone/true/mymagazaplus/barkod.php?barkod=\(scan.stringValue)")) {
unknown
d8533
train
There are at least two ways to accomplish what you want to do, but both are disabled by default. The first one is to enable server access logging on your bucket(s), and the second one is to use AWS CloudTrail. You might be out of luck if this already happened and you had no auditing set up, though.
unknown
d8534
train
From the reference: For an expression of the form & expr If the operand is an lvalue expression of some object or function type T, operator& creates and returns a prvalue of type T*, with the same cv qualification, that is pointing to the object or function designated by the operand. So, the type of the expression &i is an int*, where i is of type int. Note that for expressions of this form where expr is of class type, the address-of operator may be overloaded, and there are no constraints on the type that can be returned from this overloaded operator.
unknown
d8535
train
I would try separate out your development folders from your build folders as it can get a bit messy once you start running react build. A structure I use is: api build frontend run_build.sh The api folder contains my development for express server, the frontend contains my development for react and the build is created from the run_build.sh script, it looks something like this. #!/bin/bash rm -rf build/ # Build the front end cd frontend npm run build # Copy the API files cd .. rsync -av --progress api/ build/ --exclude node_modules # Copy the front end build code cp -a frontend/build/. build/client/ # Install dependencies cd build npm install # Start the server npm start Now in your build directory you should have subfolder client which contains the built version of your react code without any clutter. To tell express to use certain routes for react, in the express server.js file add the following. NOTE add your express api routes first before adding the react routes or it will not work. // API Routing files - Located in the routes directory // var indexRouter = require('./routes/index') var usersRouter = require('./routes/users'); var oAuthRouter = require('./routes/oauth'); var loginVerification = require('./routes/login_verification') // API Routes // app.use('/',indexRouter); app.use('/users', usersRouter); app.use('/oauth',oAuthRouter); app.use('/login_verification',loginVerification); // React routes - Located in the client directory // app.use(express.static(path.join(__dirname, 'client'))); // Serve react files app.use('/login',express.static(path.join(__dirname, 'client'))) app.use('/welcome',express.static(path.join(__dirname, 'client'))) The react App function in the App.js component file will look like the following defining the routes you have just added told express to use for react. function App() { return ( <Router> <div className="App"> <Switch> <Route exact path="/login" render={(props)=><Login/>}/> <Route exact path="/welcome" render={(props)=><Welcome/>}/> </Switch> </div> </Router> ); } Under the components folder there are components for login and welcome. Now navigating to http://MyWebsite/login will prompt express to use the react routes, while for example navigating to http://MyWebsite/login_verification will use the express API routes.
unknown
d8536
train
There are several ways you could accomplish this. First, you should add program.exe to the project. You would do this by right-clicking the project in Visual Studio, and selecting Add > Existing Item... Select program.exe, and it will appear in the project. Viewing its properties, you can set "Copy to Output Directory" to "Copy Always", and it will appear in your output directory beside your application. Another way to approach the problem is to embed it as a resource. After adding program.exe to your project, change the Build Action property of the item from Content to Embedded Resource. At runtime, you could extract the command-line executable using Assembly.GetManifestResourceStream and execute it. private static void ExtractApplication(string destinationPath) { // The resource name is defined in the properties of the embedded string resourceName = "program.exe"; Assembly executingAssembly = Assembly.GetExecutingAssembly(); Stream resourceStream = executingAssembly.GetManifestResourceStream(resourceName); FileStream outputStream = File.Create(destinationPath); byte[] buffer = new byte[1024]; int bytesRead = resourceStream.Read(buffer, 0, buffer.Length); while (bytesRead > 0) { outputStream.Write(buffer, 0, bytesRead); bytesRead = resourceStream.Read(buffer, 0, buffer.Length); } outputStream.Close(); resourceStream.Close(); } A: You might try something like: try { System.Diagnostics.Process foobar = Process.Start("foobar.exe"); } catch (Exception error) { // TODO: HANDLE error.Message } A: You can add any miscellaneous file to your project by rightclicking on the project and selecting add new
unknown
d8537
train
I found several sites explaining how to do this https://dl.dropboxusercontent.com/u/98433173/links.html
unknown
d8538
train
Try this: func didBegin(_ contact: SKPhysicsContact) { let collision: UInt32 = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask if collision == CollisionNum.swordNum.rawValue | CollisionNum.enemyNum.rawValue { enemy.removeFromParent() } } You were only testing if bodyA is equal to the enemy, however, bodyA may be equal to the sword instead. A: You do not want to remove "enemy" because "enemy" is always the last monster you added. You need to check which contactBody is the enemy so you can remove it. You can do that by guaranteeing which node you want to associate as A, and which you want to associate as B by looking at the categoryBitMask value: func didBegin(_ contact: SKPhysicsContact) { //This guarantees the lower categoryBitMask (Providing you are only using one) is in A let bodyA = contact.bodyA.categoryBitMask <= contact.bodyB.categoryBitMask ? contact.bodyA : contact.bodyB let bodyB = contact.bodyA.categoryBitMask <= contact.bodyB.categoryBitMask ? contact.bodyB : contact.bodyA if bodyA.categoryBitMask == CollisionNum.swordNum.rawValue && bodyB.categoryBitMask == CollisionNum.enemyNum.rawValue { bodyB.node.removeFromParent() } } Of course this will lead to problems with multiple collisions, so instead you may want to do: var removeNodes = SKNode() func didBegin(_ contact: SKPhysicsContact) { //This guarantees the lower categoryBitMask (Providing you are only using one) is in A let bodyA = contact.bodyA.categoryBitMask <= contact.bodyB.categoryBitMask ? contact.bodyA : contact.bodyB let bodyB = contact.bodyA.categoryBitMask > contact.bodyB.categoryBitMask ? contact.bodyB : contact.bodyA if bodyA.categoryBitMask == CollisionNum.swordNum.rawValue && bodyB.categoryBitMask == CollisionNum.enemyNum.rawValue { bodyB.node.moveToParent(removeNodes) } } func didFinishUpdate(){ removeNodes.removeAllChildren() }
unknown
d8539
train
The processor doesn't know. It is the responsibility of the programmer to keep track of which registers/memory locations contain signed numbers and which contain unsigned numbers. A 32-bit register can either store numbers in the range -2147483648 .. 2147483647 or in the range 0 .. 4294967295. The processor doesn't know which of these two ranges the programmer intends to use. The beauty of 2's complement arithmetic is that the processor can perform most operations without needing to know. Some of the operations where the processor does need to know are: division, multiplication where the result is twice the width of the operands, and comparison. For multiplication and division, there are separate opcodes for signed vs. unsigned. For comparison, the comparison opcode is the same, but the conditional branch opcodes used to check the result of the comparison are different depending on whether the programmer wants to treat the operands as signed or unsigned.
unknown
d8540
train
Thanks for the help from @jkiiski here is the full explanation and solution: * *SBCL uses extra modules (SB-SPROF, SB-POSIX and others) that are not always loaded into the image. These module reside in contrib directory located either where SBCL_HOME environment variable pointing (if it is set) or where the image resides (for example, in /usr/local/lib/sbcl/). *When an image is saved in another location and if SBCL_HOME is not set, SBCL won't be able to find contrib, hence the errors that I saw. *Setting SBCL_HOME to point to contrib location (or copying contrib to image location or new image to contrib location) solves the problem. *Finally, about roswell: roswell parameter -m searches for images in a specific location. For SBCL (sbcl-bin) it would be something like ~/.roswell/impls/x86-64/linux/sbcl-bin/1.3.7/dump/. Secondly, the image name for SBCL must have the form <name>.core. And to start it, use: ros -m <name> -L sbcl-bin run. (Quick edit: better use ros dump for saving images using roswell as it was pointed out to me) A: If you want to create executables, you could try the following: (sb-ext:save-lisp-and-die "core" :compression t ;; this is the main function: :toplevel (lambda () (print "hell world") 0) :executable t) With this you should be able to call QUICKLOAD as you wish. Maybe you want to checkout my extension to CL-PROJECT for creating executables: https://github.com/ritschmaster/cl-project
unknown
d8541
train
Change route group prefix to: $app->group(['prefix' => 'v1'
unknown
d8542
train
It's just a precedence issue. Your expression is being interpreted as n * (n #:: squares(n + 1)), which is clearly not well-typed (hence the error). You need to add parentheses: def squares(n: Int): Stream[Int] = (n * n) #:: squares(n + 1) Incidentally, this isn't an inference problem, because the types are known (i.e., n is known to be of type Int, so it need not be inferred).
unknown
d8543
train
I had this problem because of whitespace after the last semicolon in my schema. My java code was executing that whitespace as a separate query. On Froyo it complains, on Ice Cream Sandwich it doesn't cause a problem. A: My guess would that you are using a BOOLEAN & TINYINT type which are not supported. You need to use INTEGER instead
unknown
d8544
train
I'm assuming these all appear in your .bashrc file. You need to add them to .zshrc for zsh to define them.
unknown
d8545
train
It seems to me as though it would be preferable to keep a list of ingredients then reference those when you create your compositions, rather than entering the ingredient names each time. You could do it using a many to many relationship and a through table, like so: class Ingredient(models.Model): name = models.CharField(max_length=10) class Composition(models.Model): name = models.CharField(max_length=255) ingredients = models.ManyToManyField(Ingredient, through='CompositionIngredient') def save(...): #Validate ingredients add up to 100% and such class CompositionIngredient(models.Model): composition = models.ForeignKey(Composition) ingredient = models.ForeignKey(Ingredient) proportion = models.DecimalField() See the Django docs for more information. EDIT: Here's the documentation on how to deal with through tables in the admin interface.
unknown
d8546
train
You should first select the form that you want to use and then specify the element by id. It's called localpart in the webpage that you have referred to. Here's the sample code: import mechanize br = mechanize.Browser() response = br.open("https://reg.webmail.freenet.de/freenet/Registration") # Check response here # : # : form = -1 count = 0 for frm in br.forms(): if str(frm.attrs["id"])=="regForm": form = count break count += 1 # Check if form is not -1 # : # : br.select_form(nr=form) Or, if you know that there is only one form, you could have simply done br.select_form(nr=0) And then, finally: br.form["localpart"] = "[email protected]"
unknown
d8547
train
This is a list of one element (another list). [[u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur']] So if item is a list of lists, each with one element, then you can do new_list = [sublist[0] for sublist in item] If you had more than one element in each sublist, then you'll need another nested loop in that. Though, in reality, you shouldn't use lines = [f.read()]. The documentation uses a single string when you use tag_text, so start with this # Initialize one tagger tagger = treetaggerwrapper.TreeTagger(TAGLANG='en') # Loop over the files all_tags = [] for filename in sorted(glob.glob(os.path.join(input_directory, '*.txt'))): with codecs.open(filename, encoding='utf-8') as f: # Read the file content = f.read() # Tag it tags = tagger.tag_text(content) # add those tags to the master tag list all_tags.append(tags) print(all_tags)
unknown
d8548
train
Email [email protected] from the email address currently associated with the account. In the email, provide: * *Current Account Name: the name currently associated with the account *Extension ID(s): One or more IDs of extensions in the account *New Account Name: the desired name for the account [Disclosure: I am a Crossrider employee]
unknown
d8549
train
Did you define an autoload directive? You need to add this to your composer.json file: "autoload": { "psr-4": { "controllers\\": "controllers/" } } to point the autoloader in the right direction and then run composer update from the terminal in your project directory. Now the class will load without explicitly requiring its file. A: Make sure you run at least composer dump-autoload after making changes to your composer.json. composer install or composer update will also do it. From your question and the comments it seems like you didn't run the command after you added the autoloading definition for your own code.
unknown
d8550
train
Your app probably needs to request the WRITE_EXTERNAL_STORAGE permissions as described here, but you might also want to check your folder path. In future you should report any exceptions or logcat entries you see and more detail in general about HOW the operation fails. Also try other things such as creating folders in your private data space using Environment. getDataDirectory() A: You need to provide the permission to AndroidManifest.xml for STORAGE permissions. Go to AndroidManifest.xml-> permission tab -> click add -> uses permission Name:android.permission.WRITE_EXTERNAL_STORAGE and android.permission.READ_EXTERNAL_STORAGE if necessary.
unknown
d8551
train
If you have the DHCP server within the intranet under your control, you can specify a DNS server that everyone has to use. That DNS server can point to local IP addresses. Then, it will look like an ordinary website to visitors within your network. If you want to connect via HTTPS, you would have to use something like Let's Encrypt to get a certificate or you can self-sign a certificate, although modern browsers will throw up an error if you self-sign. Edit: For https, it shouldn't be too big of a deal to get a CA to sign you a cert. If you don't want any connections to the outside world (air-gapped or something), then you need to find a CA to sign a certificate for you (costs $$$). Https shouldn't be too big of a need for you because only people within your network could carry out an attack, and it seems like you have it locked down pretty well. The best option for you would be to self-sign and have all the browsers within the network trust your certificate. That would be free and easy to do with no need to connect to the outside world. For DNS, adding a DNS entry to point to your internal server will not affect other machines. All it will do is tell the other computers on your network that "www.example.se" exists at 192.168.1.1 (or whatever the internal ip of your server is). Do you have a DNS server on your network or are you communicating using IP addresses?
unknown
d8552
train
function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } from here A: use following code function numericFilter(txb) { txb.value = txb.value.replace(/[^\0-9]/ig, ""); } call it in on key up <input type="text" onKeyUp="numericFilter(this);" /> A: Here is a solution which blocks all non numeric input from being entered into the text-field. html <input type="text" id="numbersOnly" /> javascript var input = document.getElementById('numbersOnly'); input.onkeydown = function(e) { var k = e.which; /* numeric inputs can come from the keypad or the numeric row at the top */ if ( (k < 48 || k > 57) && (k < 96 || k > 105)) { e.preventDefault(); return false; } };​ A: Please note that, you should allow "system" key as well $(element).keydown(function (e) { var code = (e.keyCode ? e.keyCode : e.which), value; if (isSysKey(code) || code === 8 || code === 46) { return true; } if (e.shiftKey || e.altKey || e.ctrlKey) { return ; } if (code >= 48 && code <= 57) { return true; } if (code >= 96 && code <= 105) { return true; } return false; }); function isSysKey(code) { if (code === 40 || code === 38 || code === 13 || code === 39 || code === 27 || code === 35 || code === 36 || code === 37 || code === 38 || code === 16 || code === 17 || code === 18 || code === 20 || code === 37 || code === 9 || (code >= 112 && code <= 123)) { return true; } return false; } A: // Solution to enter only numeric value in text box $('#num_of_emp').keyup(function () { this.value = this.value.replace(/[^0-9.]/g,''); }); for an input box such as : <input type='text' name='number_of_employee' id='num_of_emp' /> A: @Shane, you could code break anytime, any user could press and hold any text key like (hhhhhhhhh) and your could should allow to leave that value intact. For safer side, use this: $("#testInput").keypress(function(event){ instead of: $("#testInput").keyup(function(event){ I hope this will help for someone. A: or function isNumber(n){ return (parseFloat(n) == n); } http://jsfiddle.net/Vj2Kk/2/ A: This code uses the event object's .keyCode property to check the characters typed into a given field. If the key pressed is a number, do nothing; otherwise, if it's a letter, alert "Error". If it is neither of these things, it returns false. HTML: <form> <input type="text" id="txt" /> </form> JS: (function(a) { a.onkeypress = function(e) { if (e.keyCode >= 49 && e.keyCode <= 57) {} else { if (e.keyCode >= 97 && e.keyCode <= 122) { alert('Error'); // return false; } else return false; } }; })($('txt')); function $(id) { return document.getElementById(id); } For a result: http://jsfiddle.net/uUc22/ Mind you that the .keyCode result for .onkeypress, .onkeydown, and .onkeyup differ from each other. A: Javascript For only numeric value in textbox :: <input type="text" id="textBox" runat="server" class="form-control" onkeydown="return onlyNos(event)" tabindex="0" /> <!--Only Numeric value in Textbox Script --> <script type="text/javascript"> function onlyNos(e, t) { try { if (window.event) { var charCode = window.event.keyCode; } else if (e) { var charCode = e.which; } else { return true; } if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } return true; } catch (err) { alert(err.Description); } } </script> <!--Only Numeric value in Textbox Script -->
unknown
d8553
train
to get what you want you must ignore SIGINT in the childs. see this What happens to a SIGINT (^C) when sent to a perl script containing children? In short Ctrl-C is send to all processes in the foreground group. That means your child processes get SIGINT too, they do not have a handler and get killed. signal( SIGINT, SIG_IGN ); add in the child code, near setting the other signal handler.
unknown
d8554
train
Here is what you want. SmartHttpSessionStrategy
unknown
d8555
train
Turns out the issue was in my client. For issuing requests, I was using RestTemplate which internally was using HttpClient. Well, HttpClient internally managing connections and by default it has ridiculously low limits configured - max 20 concurrent connections... I solved the issue by configuring PoolingHttpClientConnectionManager (which supposed to deliver better throughput in multi-threaded environment) and increased limits: HttpClientBuilder clientBuilder = HttpClientBuilder.create(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setMaxTotal(10000); connManager.setDefaultMaxPerRoute(10000); clientBuilder.setConnectionManager(connManager); HttpClient httpClient = clientBuilder.build(); After doing that, I greatly increased issued requests per second which made Tomcat to add new threads - as expected
unknown
d8556
train
If you only know offset (i.e. index of the starting column), size (i.e. how many data), cols (i.e. maximum number of colums), and you want to calculate how many rows your data will span, you can do int get_spanned_rows(int offset, int size, int cols) { int spanned_rows = (offset + size) / cols if ( ( (offset + size ) % cols) != 0 ) spanned_rows++ return spanned_rows } where % is the modulus (or reminder) operator A: int calc_rows(int start,int length){ int rows = 0; int x= 0; if (start != 0){ x = 6%start; rows+=1; } if ((start+length) % 6 != 0){ x +=(start+length) % 6; rows+=1; } rows+= (length - x)/6; return rows; } calculates number of rows by dividing by 6 but after subtracting partially filled rows count A: In case you only want the number of rows you can calculate num_rows = (offset + size + cols - 1) / cols which in this case is num_rows = (4 + 8 + 6 - 1) / 6 = 17 / 6 = 2
unknown
d8557
train
So you have a few options to choose from: * *Combine all your queries into a single query (Make a larger query, which will join together all the tables you need in your example) *Create a view (Create a view of these tables within the database, then query using the view) *Create a materialized view (Creating a materialized view has it's benefits, though the upkeep of it is a bit tougher. Since materialized views actually hold real data, it means they need to be synced with the tables. They are only intended to be used when you need data fast and the data does not change often. In your case it could actually work, if you sync the materialized view every 5 min.) - Warning: MySQL does not directly support materialized views. If you are trying to go for speed, then cache your results and only retrieve what was inserted after it.
unknown
d8558
train
The problem is your javascript syntax, it's const url = `/address/get-names/?search=${input}` instead of const url = "/address/get-names/?search=${input}"
unknown
d8559
train
In C# use Timer class and set that to 1 second. A: Problem solved just added RunOnUiThread within tmr_Elapsed void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { RunOnUiThread(() => { txtDays = FindViewById<TextView> (Resource.Id.txtDays); txtHours = FindViewById<TextView> (Resource.Id.txtHours); txtMins = FindViewById<TextView> (Resource.Id.txtMins); txtSec = FindViewById<TextView> (Resource.Id.txtSec); DateTime enteredDate = new DateTime(2013, 7, 25, 12 ,30 ,00); DateTime todaysDateTime = DateTime.Now; DateTime formattedDate = todaysDateTime.AddHours (2); TimeSpan span = enteredDate.Subtract(formattedDate); totalDays = span.TotalDays; totalHours = span.TotalHours; totalMins = span.TotalMinutes; totalSec = span.TotalSeconds; Console.WriteLine ("Days: " + String.Format("{0:0}", Math.Truncate(totalDays))); Console.WriteLine ("Hours: " + String.Format("{0:0}", Math.Truncate(totalHours))); Console.WriteLine ("Minutes: " + String.Format("{0:0}", Math.Truncate(totalMins))); Console.WriteLine ("Seconds: " + String.Format("{0:0}", Math.Truncate(totalSec))); txtHours.Text = String.Format ("{0:0}", Math.Truncate (totalHours)); txtHours.Text = String.Format ("{0:0}", Math.Truncate (totalHours)); txtMins.Text = String.Format ("{0:0}", Math.Truncate (totalMins)); txtSec.Text = String.Format ("{0:0}", Math.Truncate (totalSec)); }); }
unknown
d8560
train
Try adding <uses-permission android:name="android.permission.INTERNET" /> to your manifest. This allows your application network access. More can be found here. A: You have to use 10.0.2.2 to access local server.
unknown
d8561
train
When you use presentViewController, the viewController is not pushed onto the navigation stack. Normally, it is presented modally. So if you want to dismiss it, use [self dismissViewControllerAnimated:true completion:nil];
unknown
d8562
train
SQL server doesn't allow to have multiple cascade paths to the same table in the database. In your case there are two of them for Tools: * *Employee -> Handle -> Tool *Employee -> Attachment -> Tool All ways to fix the issue consist in setting DeleteBehavior.Restrict for one relationship or the other, for example: * *Setting DeleteBehavior.Restrict for Entity -> Handle relationship and handling this cascade path by a trigger (otherwise "restrict" won't allow to delete a record having references to it) *Setting DeleteBehavior.Restrict for Entity -> Handle relationship and handling this cascade path in application code (update/delete all related entities explicitly before deleting the main one) *Setting "restrict" behavior for both Entity relationships etc... A: You said: There is a table of employees, where each employee has any number of handles, attachments and jobs But your diagram establishes a direct link between an employee and a handle, one handle has many employees, and an employee has only one handle Your statement is in conflict with your diagram I think this modelling is wrong, from the database perspective. I think a job should have an employee. (If a job has multiple employees you'll need another table jobemployees that maps one job id to multiple employees.) A job has a tool, a tool has a handle and an attachment. I fail to see why deleting an employee should delete their jobs (if I fired someone the house he built while working for me still exists) but you can clean this up without using cascading constraints Ultimately you can see in the diagram the cycle you've created. If deleting something at a 1 end deletes everything at the * end then deleting anything in your diagram starts a chain that takes a split path that comes back together. Removing the employee entity does indeed break this up Ultimately an employee should not directly have a job, a handle or an attachment
unknown
d8563
train
One approach is to use load data infile (see here) with the set option to assign column values. Columns that are not being set will be given their default values, which is typically NULL. Personally, I would load the data into a staging table with two columns and then insert the data from the staging table into the final table. This makes it easier to validate the data before putting it into the "real" table.
unknown
d8564
train
Using WPI, we have plaintext begins with P=>(10110)(01111)(01000) Using j5a0edj2b we have the ciphertext C=>(01001)(11111)(00000)(11010)(00100)(00011)(01001)............ then by addition of P and C in mod 2, the key stream is S=>(11111)(10000)(01000).... we find the matrix from key stream s0=1,s1=1,s2=1,s3=1,s4=1,s5=1,s6=0,s7=0,s8=0,s9=0,s10=0,s11=1 etc For the matrix first line.... (s0,s1,s2,s3,s4,s5) second line....(s1,s2,s3,s4,s5,s6) third line.....(s2,s3,s4,s5,s6,s7) 4th (s3,s4,s5,s6,s7,s8) 5th (s4,s5,s6,s7,s8,s9) last line (s5,s6,s7,s8,s9,s10) this calulations are given in LFSRs in details
unknown
d8565
train
You need https://github.com/phonegap/phonegap-wp7 Please note that this is still not really production ready yet though. We're hoping that it will be there by the time Mango launches though. Note that this is targetting the Mango beta 2 refresh. I'd assume that you're not using that. The one you got from my site looks like a very old version. Get the latest version. I've updated my github profile so you can contact me through there now. A: For the record :) Use the latest lib of phonegap for WP7 from: https://github.com/callback/phonegap/tree/master/lib/windows
unknown
d8566
train
Cells of collection are dequeued dequeueReusableCell , you need to override prepareForReuse Or set a tag greenView.tag = 333 And inside cellForItemAt do this cellB.resultsView.subviews.forEach { if $0.tag == 333 { $0.removeFromSuperview() } } if receivedMessages[indexPath.row].pollResults != [] { for i in 0...receivedMessages[indexPath.row].pollResults.count - 1 { cellB.resultsView.addSubview(sq(pollSum: receivedMessages[indexPath.row].pollTotal!, pollResult: receivedMessages[indexPath.row].pollResults[i])) } }
unknown
d8567
train
I'm a bit biased (being a Googler and member of the App Engine team), but I think Endpoints is worth a try. With regards to the general disclaimer on using Endpoints in production, we have allowed some developers to launch in production as long as they have spoken to us first. I provided another answer to a related question on RESTful development here. The developer tried Endpoints and decided to use it over other options.
unknown
d8568
train
Swift arrays have built in functions for this exact functionality. I recommend checking out the official documentation for Collection Types from Apple for a starting point. Here is an example that follows your question: // With [Character] let vowels: [Character] = ["a", "e", "i", "o", "u"] let chars: [Character] = ["a", "b", "c", "d", "e"] let resultVowels = vowels.filter { chars.contains($0) } resultVowels.count // == 2 resultVowels.description // == "[a, e]" // With [String] let people = ["Bill", "Sam", "Suzy"] let peeps = ["Abe", "Bill", "Charlie"] let resultPeople = people.filter { peeps.contains($0) } resultPeople.count // == 1 resultPeople.description // == "[Bill]" The result will be the names (or numbers, characters, etc.) that are matching up. So you can not only get the count, but also the contents of the comparison in this procedure. So long as the types follow Equatable, this will work for you. If you want to return a Boolean, just simply: return filteredArray.count != 0 Now, if you want to compare say, a [Character] to a String then: let vowels: [Character] = ["a", "e", "i", "o", "u"] let someString = "abcde" let result = vowels.filter { someString.characters.contains($0) } result.count // == 2 result.description // == "[a, e]" The String.characters property is a new feature brought in to Swift 2. I hope I was able to assist you. A: 1 ) Common chars in 2 words You easily check the intersection of the common chars in 2 strings using the Set struct: let set0 = Set("abcde".characters) let set1 = Set("aeiou".characters) let intersection = set0.intersect(set1) // {"e", "a"} 2) Common words in 2 lists Similarly you can find the intersection of 2 arrays of strings: let set0 : Set = ["bill", "sam", "suzy"] let set1 : Set = ["abe", "bill", "charlie"] let intersection = set0.intersect(set1) // {"bill"} 3) Back to Array Please note that in both examples, the intersection constant is a Set. You can transform it into an Array writing: let list = Array(intersection) Hope this helps. P.S. This code is for Swift 2.0 Update More specifically if you want to find out whether an intersection exists you can simply write: !intersection.isEmpty
unknown
d8569
train
Try this: UIGraphicsBeginImageContext(targetSize); NSString *txt = @"my String"; UIColor *txtColor = [UIColor whiteColor]; UIFont *txtFont = [UIFont systemFontOfSize:30]; NSDictionary *attributes = @{NSFontAttributeName:txtFont, NSForegroundColorAttributeName:txtColor}; CGRect txtRect = [txt boundingRectWithSize:CGSizeZero options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil]; [txt drawAtPoint:CGPointMake(targetSize.width/2 - txtRect.size.width/2, targetSize.height/2 - txtRect.size.height/2) withAttributes:attributes]; UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); A: NSMutableParagraphStyle *styleCenter = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; styleCenter.alignment = NSCenterTextAlignment; NSDictionary *attributes = @{NSFontAttributeName:txtFont,NSForegroundColorAttributeName:txtColor,NSParagraphStyleAttributeName:styleCenter}; [txt drawInRect:rect withAttributes:attributes]; A: This category on NSString will draw the centered text in rect with given below font: @implementation NSString (Helpers) - (void)drawCentredInRect:(CGRect)rect withFont:(nullable UIFont *)font andForegroundColor:(nullable UIColor *)foregroundColor { NSMutableDictionary *attributes = [NSMutableDictionary new]; if (font) { attributes[NSFontAttributeName] = font; } if (foregroundColor) { attributes[NSForegroundColorAttributeName] = foregroundColor; } CGSize textSize = [self sizeWithAttributes:attributes]; CGPoint drawPoint = CGPointMake( CGRectGetMidX(rect) - (int) (textSize.width / 2), CGRectGetMidY(rect) - (int) (textSize.height / 2) ); [self drawAtPoint:drawPoint withAttributes:attributes]; } A: I tried the answer for your clever question,Now I got the solution +(UIImage*) drawText:(NSString*)text inImage:(UIImage*)image atPoint:(CGPoint)point { UIGraphicsBeginImageContextWithOptions(image.size, YES, 0.0f); [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)]; CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height); [[UIColor whiteColor] set]; if([text respondsToSelector:@selector(drawInRect:withAttributes:)]) { //iOS 7 or above iOS 7 NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; style.alignment = NSTextAlignmentCenter; NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName]; [text drawInRect:rect withAttributes:attr]; } UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } Please call the above method in where you pick the image like below - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *imagePicked = info[UIImagePickerControllerEditedImage]; picker.delegate = self; self.imageViewTextCenter.image = [ViewController drawText:@"WELCOME" inImage:imagePicked atPoint:CGPointMake(0, 0)];; [picker dismissViewControllerAnimated:YES completion:nil]; }
unknown
d8570
train
Really slow response, I know but once this gets out of beta phase it could work http://codebender.cc/ A: You can have Arduino IDE on android, but have some problem with the usb port http://arduino.cc/forum/index.php/topic,114141.0.html veckoff A: Not that I know of, but maybe you could build something like it with this? http://www.amarino-toolkit.net/ A: You can upload sketch, no root required: http://arduinocommander.blogspot.com/2013/03/upload-sketch.html A: Check out ArduinoDroid - full-featured Arduino IDE on android: https://play.google.com/store/apps/details?id=name.antonsmirnov.android.arduinodroid
unknown
d8571
train
To get a random element from array: function randChoice(array){ return array[Math.floor(Math.random()*array.length)]; }; There are 2 method to generate a mesh from random points that I know of: convex hull and alpha shape. Creating a mesh by repeating picking 3 random points would almost surely result in spaghetti. If you just want to generate terrain like in the picture, there is terrain generation from heightmap.
unknown
d8572
train
You can try this // attach a click event to the payment radio group $(".payment-item").click(function(){ var payment = $("input:radio[name='payment']:checked").val(), // check the current value isPaypal = payment !== "10", // a simple check to see what was selected delivery = $("#del-type-7"); // get the radio element with the pre-order option return delivery.prop({ // Disabled if `isPaypal` is true disabled: isPaypal, // Checked if `isPaypal` is true checked: !isPaypal }); }); Have a look at the demo http://jsfiddle.net/jasonnathan/3s3Nn/2/ A: jsBin demo All you need: var $delType7 = $("#del-type-7"); // Cache your elements $("[name='payment']").click(function(){ var PPal = $("[name='payment'][value='10']").is(':checked'); // Boolean $delType7.prop({checked:!PPal, disabled:PPal}); // boolean to toggle states }); Remove onclick from HTML http://api.jquery.com/checked-selector/ http://api.jquery.com/prop/
unknown
d8573
train
NOTE: While OAuth 2.0 also defines the token Response Type value for the Implicit Flow, OpenID Connect does not use this Response Type, since no ID Token would be returned. As OpenID Connect specification highlights, response_type=token is not a valid response type for OpenID Connect. So what you are observing is falling back to OAuth 2.0 and hence receiving an access token. I do not come from Spring background, but you should be able to define/configure the appropriate response_type values from your code. If this is not the case, you were merely lucky with Authorization code flow observation. Depending on authorization server configurations/preference it may send an id token. For example, Azure AD sends id token for OAuth 2.0 code grant
unknown
d8574
train
It's usually a good practice to call the base class constructor from your subclass constructor to ensure that the base class initializes itself before your subclass. You use the base keyword to call the base class constructor. Note that you can also call another constructor in your class using the this keyword. Here's an example on how to do it: public class BaseClass { private string something; public BaseClass() : this("default value") // Call the BaseClass(string) ctor { } public BaseClass(string something) { this.something = something; } // other ctors if needed } public class SubClass : BaseClass { public SubClass(string something) : base(something) // Call the base ctor with the arg { } // other ctors if needed } A: You can call the base class constructor like this: // Subclass constructor public Subclass() : base() { // do Subclass constructor stuff here... } You would call the base class if there is something that all child classes need to have setup. objects that need to be initialized, etc... Hope this helps.
unknown
d8575
train
What is the accepted way of dealing with this using BEM? Depends on what version of BEM you're using. I use a variant of the pre-spec concept of BEM, which means that you'll have different answers if you follow bem.info. Modifiers should be attached to the element they modify. Modifying a block, however, allows the modifier to be inherited by child elements: <div class="foo foo--example"> <div class="foo__bar foo--example__bar">...</div> <div> This gets messy when child elements have modifiers as well: <div class="foo foo--example"> <div class=" foo__bar foo--example__bar foo__bar--another-example foo--example__bar--another-example">...</div> <div> This form of BEM syntax is quite verbose. It's best used on generated code. I use LESS for CSS preprocessing, so my BEM code often looks like: .foo { ... &__bar { ... } } With modifiers it becomes: .foo { ... &__bar { ... } &--example { ... &__bar { ... } } } This enforces that the cascade is in the proper order and that all selectors continue to have exactly one class.
unknown
d8576
train
spidev checks for validity of the values in the input list via PyLong_Check, (see here), which sadly doesn't accept certain things that you might hope it would as valid values. Worse, the error message does not really tell you anything useful. I think your issue is that with count = spi.readbytes(1), count is being set to a list, not an integer. If you change to count = spi.readbytes(1)[0] I would expect your code to work!
unknown
d8577
train
You'll need to create your app in an html file and then embed it in an iframe element in a widget. https://help.rallydev.com/apps/2.1/doc/#!/guide/embedding_apps The burn down chart is accessible via the Standard Report component: https://help.rallydev.com/apps/2.1/doc/#!/api/Rally.ui.report.StandardReport
unknown
d8578
train
It's Konrad here. I'm Auth0 Community Engineer. Not an Angular expert but as I can see looking at our quickstart and your code snippet you're not invoking localAuthSetup methood anywhere you just have it defined as well as handleAuthCallback. Can you try calling both in the constructor as it's suggested in the quickstart? A: Login to your tenant, go to the spa app, settings. Find the Allowed Callback URLs and make sure you have something like this there` your_domain, your_domain/login """ PS "/login" is the same path of Application Login URI
unknown
d8579
train
Declare a BOOL instance variable and use it as a flag to indicate if the instructional view has been dismissed yet. Then, add a check inside your motionBegan method to see if it should do anything or not. Something like this: //.h BOOL instructionsDoneShowing; //.m //Wherever your instructions screen is dismissed instructionsDoneShowing = TRUE; //Inside your motionBegan method if (instructionsDoneShowing) { //Do your stuff here } A: After initiation of your view, say [yourView resignFirstResponder]; When user dismisses the instructions say - [yourView becomeFirstResponder];
unknown
d8580
train
Ok, try this. I added some comments. function submit () { var table = document.getElementById("info"); var td1 = document.createElement("td") var td2 = document.createElement("td"); td1.innerHTML = document.getElementById("p-name").value; td2.innerHTML = document.getElementById("p-id").value; // create a table row var row = document.createElement("tr"); row.appendChild(td1); row.appendChild(td2); // instead of your append // table.children[0].appendChild(row); // use this append table.appendChild(row); var bedit = document.createElement("BUTTON"); var bename = document.createTextNode("Edit"); bedit.appendChild(bename); bedit.onclick = edit_row.bind(null, bedit, td1); // createtd6 before because it is not known by your previous code // I use this td2 instead of td6 td2.appendChild(bedit); } function edit_row(bedit, td1) { bedit.style.display = "none"; // create bsave button before because it is not known by your previous code // bsave.style.display = "block"; var input = document.createElement("INPUT"); input.setAttribute("type", "text"); var string = td1.textContent; td1.innerHTML = ""; td1.appendChild(input); input.value = string; } submit(); <table id="info"></table> <hr/> <input id="p-name" type="text" value="name_value" /> <input id="p-id" type="text" value="id_value" />
unknown
d8581
train
You need to use attribute selector. Live Demo var res = $('[lang=english]') You can iterate through each item use each() $('[lang=english]').each(function () { alert($(this).text()); }); A: $('*[lang]').each(function () { //Your Code } A: You can do this via HTML5 data-* attribute. Set the attribute like this `` To fetch all elements with data-lang set to "english" use: document.querySelectorAll('[data-lang="english"]'); A: While you already have an (accepted) answer to this question, I thought I'd post an additional answer, to more completely answer the question as asked, also to cover the various issues I've raised in comments to those other answers. Each approach I discuss in my answer will be applied to the following HTML mark-up: <div class="langContainer"> <span lang="english">Some text in an English span</span> <span lang="french">Some text in an French span</span> <span lang="algerian">Some text in an Algerian span</span> <span lang="urdu">Some text in an Urdu span</span> </div> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> <ol> <li>List item one</li> <li>List item two</li> <li>List item three</li> <li>List item four</li> <li>List item five</li> <li>List item six</li> <li>List item seven</li> </ol> <ul class="langContainer"> <li><div lang="english">Some text in an English div</div></li> <li><div lang="french">Some text in an French div</div></li> <li><div lang="algerian">Some text in an Algerian div</div></li> <li><div lang="urdu">Some text in an Urdu div</div></li> </ul> The easiest way to style elements with a lang attribute is CSS, for example: :lang(english), :lang(french) { color: #f90; } JS Fiddle demo. The above will style all elements with a lang attribute equal to english or french. Of course, this being CSS, it's possible to modify the selector to apply to only specific elements with those attributes: span:lang(english), div:lang(french) { color: #f90; } JS Fiddle demo. This, as you would imagine, styles a span with a lang attribute equal to english and a div element with a lang attribute equal to french. Using the :lang() pseudo-class, without passing a value, does not, unfortunately, select elements that simply possess a lang attribute. However, using the CSS attribute-selector [lang] does: [lang] { color: #f90; } JS Fiddle demo. The absence of an element in that selector, of course, implies the universal selector so to select more accurately it might be wise to modify the selector to apply to either specific element-types (span[lang]) or to elements within a specific parent element (div.langContainer [lang]). However, for other purposes, such as modifying the content, or element-nodes themselves, using jQuery you have the same selectors available, for example. In the following examples I'll be assigning the element's original text to jQuery's data object (with the variable-name of original-text) and replacing the element's visible text (as a demonstration of passing an anonymous function to a method, to avoid having to iterate through the matched elements with each(), though you can do that if you want to), with that in mind I'll post only the selector: // selecting elements with lang equal to 'english': $(':lang(english)') JS Fiddle demo. // selecting all elements with the lang attribute: $('[lang]') JS Fiddle demo. // specifying the element-type: $('span[lang]') JS Fiddle demo. // specifying the element-type: $('div.langContainer [lang]') JS Fiddle demo. It seems, incidentally, from a jsPerf comparison of the jQuery approaches, that defining the element type (for example $('span[lang]')) is the fastest means by which to select (that said, of course, if you're only styling the content then CSS would be faster yet). A brief discussion of using each() versus an anonymous function passed to a method. Using this approach depends entirely on what you want to do, but if you want to, for example, modify the text of each matched-element, the two following approaches are equivalent: $('span[lang]').each(function(i){ $(this).text('matched element ' + i); }); JS Fiddle demo; $('span[lang]').text(function(i) { return 'matched element ' + i; }); JS Fiddle demo; There is, however, no significant difference between the time it takes to run either. A: Try this $('[lang="english"],[lang="anotherlanguage"]')
unknown
d8582
train
Put the enumeration in the class containing the PIMPL. A: Put the enumeration into its own type: struct FooEnum { enum Type { TYPE_A, TYPE_B, }; }; Then Foo and Bar can both access FooEnum::Type and Bar.h doesn't need to include Foo.h. A: I'd argue that enums are a bad idea to start with, but in general for constants/the many things like constants in C++ none of which are quite constants and all of which have issues. I like to put it into a struct then have the classes using it inherit from the struct. I'd also argue that the pimpl idiom is bad. Actually I am sure it's a poor way to do things. It's something that works but is awkward and a bit silly. It's also easy to avoid, and the only reason it comes about is due to people using yet other bad design choices. Usually someone just tacks on OOP stuff to a class they designed to be concrete. Then you get the mixed inheritance case and the plethora of issues it causes such as super slow compile time. Instead, consider pure virtual base classes, then writing your libs to that to avoid templates and avoid the forward declaration problem. Not for everything, but definitely for the cases where you are generating code for lots of classes.
unknown
d8583
train
Use GRANT to give execute privileges grant execute on PACKAGE_B to new_schema; Then, you need to ensure that any reference in package A includes the full path: PACKAGE_B.SOME_PROC It might be worth creating a public synonym in for the package, so that you can avoid referencing the schema too.
unknown
d8584
train
One method uses aggregation: select name from t group by name having min(classification) = max(classification) and min(classification) = 'manager'; A: Method with a subquery which should work well when there are not only 'Managers' and 'Workers' in the table: SELECT t1.name FROM t t1 WHERE t1.classification='Manager' AND NOT EXISTS ( SELECT 1 FROM t t2 WHERE t1.name=t2.name AND t2.classification='Worker' ) A: Count the number of titles. If they have a title of 'Manager' and there's only one title, select the individual: SELECT * FROM PEOPLE p INNER JOIN (SELECT NAME, COUNT(TITLE) AS TITLE_COUNT FROM PEOPLE GROUP BY NAME) c ON c.NAME = p.NAME WHERE p.TITLE = 'Manager' AND c.TITLE_COUNT = 1; dbfiddle here
unknown
d8585
train
Is this secure? No. Does this protect the users' password? No. It's vulnerable to rudimentary cryptanalysis. For example, with a simple SQL Injection the attacker could get both the "hash" and the prime number. From there, the attacker could simply divide the hash by the prime and get the sum of the characters. The interesting thing here is that while the original password is protected, collisions are not. So the attacker could generate a trivial collision and use it to log into your site. For example, let's say after dividing the "hash" was 532. We could get that same hash by a 7 character string of repeating > characters (">>>>>>>"). Good hash functions have 3 fundamental properties: * *Pre-image resistance (given h(m) it should be hard to find m) *Second-pre-image resistance (given m it should be hard to find n such that h(m) == h(n)) *Collision Resistance (it should be difficult to find a pair of messages such that h(m) == h(n). Your given function only possibly does the first, but only in that there are so many possible permutations (collisions) that it's impossible to tell what the original was... So definitely not. I recommend using approved and vetted crypto, and take the Coursera Cryptography Course.
unknown
d8586
train
I have a dozen builds of Perl on my system, and they all use ~/.cpan. I have never had a problems, but I cannot say that it is safe. It depends on the settings therein. Specifically, * *build_dir_reuse should (probably) be zero. *makepl_arg shouldn't contain INSTALL_BASE. *mbuildpl_arg shouldn't contain --install_base. "Install base" overrides where the modules are installed. If you start installing the modules for all your builds in one location, you will have problems due to incompatibilities between versions, releases and builds of Perl. If you want to share .cpan and have a local install directory, you can probably get away with using PREFIX=/home/username/perl5 LIB=/home/username/perl5/lib instead of INSTALL_BASE=/home/username/perl5. It uses a smarter directory structure. By the way, local::lib causes "install base" to be used, so you'll run into problems if you use local::lib with multiple installs of Perl.
unknown
d8587
train
I think you could use Paralel::ForkManager to do this. There is a good tutorial on PerlMonks about Paralel::ForkManager. It could be this simple: my $manager = Parallel::ForkManager->new( 6 ); foreach my $command (@commands) { $manager->start and next; system( $command ); $manager->finish; };
unknown
d8588
train
tldr; You don't need getPointResolution to create circle polygons. You can use geom.Polygon.circular to create the blue circle which has the correct radius. new ol.geom.Polygon.circular([lng, lat], radius); You will need to divide the radius by the resolution if you plan to create a circle (green) or create a polygon.fromCircle (red). https://codepen.io/dbauszus-glx/pen/LYmjZvP
unknown
d8589
train
Try processing path with path module, as below const path = require('path'); const dirPath = path.resolve(__dirname, './commands'); And then pass dirPath to readdirSyncfunction. path is an internal node.js module, so you don't need to install anything A: You are on Windows. The path delimeter for Windows is \, not /. Try making your program platform agnostic with something like this: const fs = require('fs'); const path = require("path"); const commandDir = path.join(__dirname, "commands"); const commandFiles = fs.readdirSync(commandDir).filter(file => file.endsWith('.js')); console.log(commandFiles); A: With RegEx const fs = require('fs'); let searchPath = "./mydirectory"; let searchFileName = ".*myfile.*"; let searchFoundFiles = fs .readdirSync(searchPath) .filter((f) => new RegExp(searchFileName).test(f)); if (searchFoundFiles.length) { console.log("File already exists"); }
unknown
d8590
train
IE7 supports :hover, at least in standards mode. It may not in quirks mode. A: IE has a history of bad CSS support. Originally only a tags supported :hover. And also you couldn't have something like a:hover span to indicate that only the span tag should change when hovering the parent a. If you want correct :hover functionality across all IE versions, you need to use javascript and onmouseover/onmouseout. It also helps if you use an xhtml doctype, to enable standards mode. A: IE 6 only supports the :hover pseudo class on links, but IE 7 supports it on most elements. As David mentioned, it might not work in quirks mode. The reason would then be that IE mostly reverts back to something closer to IE 4 in quirks mode, allowing a lot of IE specific features and removing several standards compliant features. If you want the :hover functionality on a block element and support back to IE 6, you can use a link element and make it a block element using CSS. Note that a link only can contain inline elements (e.g. no divs) so if you want block elements inside the link you would have to set that using CSS also: CSS: .hoverlink { display: block; } .hoverlink:hover { background: #eee; } .hoverlink .item { display: block; } HTML: <a href="..." class="hoverlink"> <span class="item">Line 1</span> <span class="item">Line 2</span> <span class="item">Line 3</span> </a> (You might want to consider the impact on search engines using the technique also. A link has better impact if it just contains the text describing what it links to.) A: :hover is not supported by every element e.g. it works on <a> but breaks on <div> afaik A: I've run into this a few times - have a look at the following link .. http://www.bernzilla.com/item.php?id=762 "if you want support for :hover on all elements and not just the <a> tag, make sure you're using a strict DOCTYPE so IE7 doesn't kick in to quirks mode."
unknown
d8591
train
The key size for RSA is not the size of the encoded public key. The key size for asymmetric algorithms is a value that is directly related to the security strength. For RSA that is the size of the modulus, as factorization of the modulus is how you can attack RSA. The public key consists of the modulus of 128 bytes and a public exponent, so by definition it is already larger than the key size (although the public exponent is commonly just set to 0x010001 or 65537, the fifth prime of Fermat. Add additional information for this proprietary Microsoft format and you get to 148 bytes. As 148 - 128 - 3 is 17, you expect 17 bytes of overhead. To decrypt you've got to use the private key. I don't know why that isn't clear and what this has to do with the other question.
unknown
d8592
train
I think the piece you are missing is the idea of using Perl's internal grep function, for searching a list of URL lines based on what you are calling your "differentiator". Slurp your URL lines into a Perl array (assuming there are a finite manageable number of them, so that memory is not clobbered): open URLS, theUrlFile.txt or die "Cannot open.\n"; my @urls = <URLS>; Then within the loop over your file containing "placeholders": while (my $key = /[a-z]+\s([a-z0-9]+)\.jpg/g) { my @matches = grep $key, @urls; if (@matches) { s/[a-z]+\s$key\.jpg/$matches[0]/; } } You may also want to insert error/warning messages if @matches != 1.
unknown
d8593
train
Check this Class public class CirculaireNetworkImageView extends NetworkImageView { private int borderWidth; private int canvasSize; private Bitmap image; private Paint paint; private Paint paintBorder; public CirculaireNetworkImageView(final Context context) { this(context, null); } public CirculaireNetworkImageView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.actionButtonStyle); } public CirculaireNetworkImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); paint = new Paint(); paint.setAntiAlias(true); paintBorder = new Paint(); paintBorder.setAntiAlias(true); } public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; this.requestLayout(); this.invalidate(); } public void setBorderColor(int borderColor) { if (paintBorder != null) paintBorder.setColor(borderColor); this.invalidate(); } public void addShadow() { setLayerType(LAYER_TYPE_SOFTWARE, paintBorder); paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK); } @SuppressLint("DrawAllocation") @Override public void onDraw(Canvas canvas) { // load the bitmap image = drawableToBitmap(getDrawable()); // init shader if (image != null) { canvasSize = canvas.getWidth(); if(canvas.getHeight()<canvasSize) canvasSize = canvas.getHeight(); BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); paint.setShader(shader); // circleCenter is the x or y of the view's center // radius is the radius in pixels of the cirle to be drawn // paint contains the shader that will texture the shape int circleCenter = (canvasSize - (borderWidth * 2)) / 2; canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) + borderWidth - 4.0f, paintBorder); canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) - 4.0f, paint); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = measureWidth(widthMeasureSpec); int height = measureHeight(heightMeasureSpec); setMeasuredDimension(width, height); } private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // The parent has determined an exact size for the child. result = specSize; } else if (specMode == MeasureSpec.AT_MOST) { // The child can be as large as it wants up to the specified size. result = specSize; } else { // The parent has not imposed any constraint on the child. result = canvasSize; } return result; } private int measureHeight(int measureSpecHeight) { int result = 0; int specMode = MeasureSpec.getMode(measureSpecHeight); int specSize = MeasureSpec.getSize(measureSpecHeight); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else if (specMode == MeasureSpec.AT_MOST) { // The child can be as large as it wants up to the specified size. result = specSize; } else { // Measure the text (beware: ascent is a negative number) result = canvasSize; } return (result + 2); } public Bitmap drawableToBitmap(Drawable drawable) { if (drawable == null) { return null; } else if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } } A: Check the source code of the NetworkImageView here. Modify it to extend your "CircleImageView" instead of the normal ImageView and you are done.
unknown
d8594
train
Thanks to ntr's suggestion, I changed the type def to use local storage. The Json TP then found all of the props and the actual call worked as expected. Thanks everyone.
unknown
d8595
train
From Generics: Type Parameters Type parameters specify and name a placeholder type, and are written immediately after the function’s name, between a pair of matching angle brackets (such as <T>). Naming Type Parameters In most cases, type parameters have descriptive names, such as Key and Value in Dictionary<Key, Value> and Element in Array<Element>, which tells the reader about the relationship between the type parameter and the generic type or function it’s used in. However, when there isn’t a meaningful relationship between them, it’s traditional to name them using single letters such as T, U, and V, such as T in the swapTwoValues(_:_:) function above. So func createArray<Element>(element: Element) -> [Element] { ... } func createArray<T>(element: T) -> [T] { ... } func createArray<Rumpelstilzchen>(element: Rumpelstilzchen) -> [Rumpelstilzchen] { ... } are identical functions. Here the placeholder type is the element type of the returned array, therefore Element is a suitable “descriptive name.” But it makes no difference otherwise, is it up to you to choose a name for the placeholder, balancing between readability and conciseness. A: T is not particularly traditional. In FP, Backus uses T, but ML, from around the same time, uses a. Haskell uses a, Scala uses A. There's a mix of choices. Swift, however, has strong reasons to use descriptive names. First, it's a quite descriptive language. Types are named with fully spelled-out words. Methods typically are literate in construction. Variables and properties are rarely abbreviated. There's no reason that type parameters should be uniquely obscure. It also matches well with associated types which are quite naturally verbose. What would you call Collection's index type besides Index? Why should its "element" type be specially abbreviated? And if Array implements Collection, why should it create a distinct name (T) that it would then have to associate with Collection's Element? Why would you special-case all this just to make the type name unintuitive? The deeper question would be, why wouldn't Array's element be called Element?
unknown
d8596
train
for does not do what you think it does; it is not an imperative loop. It is a list comprehension, or sequence-generator. Therefore, there is not a return or iterate call at its end, so you cannot place recur there. It would seem you probably do not need either loop or recur in this expression at all; the for is all you need to build a sequence, but it's not clear to me exactly what sequence you wish to build. A: Further to @JohnBaker's answer, any recur refers to the (nearest) enclosing loop or fn (which may be dressed as a letfn or a defn). There is no such thing in your snippet. So there is nothing for the recur to be in tail position to. But just replace the for with loop, and you get (loop [i 20] (loop [x 1] (if (zero? (rem i x)) i (recur (+ i 1))))) ... which evaluates to 20,no doubt what you intended. However, the outer loop is never recurred to, so might at well be a let: (let [i 20] (loop [x 1] (if (zero? (rem i x)) i (recur (+ i 1))))) The recur is in tail position because there is nothing left to do in that control path through the loop form: the recur form is the returned value. Both arms of an if have their own tail position. There are some other disguised ifs that have their own tail position: ors and ands are such.
unknown
d8597
train
For the given business objects, simplest way is to have lucene documents with the following fields: title, body, firstName, lastName, country, emailAddress, gender You might want to have title and user-related fields as STORED. Choice of analyzers depends on your search requirements (like do you want to support partial matches, suffix queries, stemming etc). Queries for the given use-cases: 1) title:india OR body:india OR country:india 2) title:yahoo OR body:yahoo OR emailAddress:yahoo 3) title:(Skeet OR Async) OR body:(Skeet OR Async) 4) title:asynchronous 5) lastName:skeet
unknown
d8598
train
Add a destroy method to the plugin prototype in jTinder.js: destroy: function(element){ $(element).unbind(); $(this.element).removeData(); } like so: init: function (element) { container = $(">ul", element); panes = $(">ul>li", element); pane_width = container.width(); pane_count = panes.length; current_pane = panes.length - 1; $that = this; $(element).bind('touchstart mousedown', this.handler); $(element).bind('touchmove mousemove', this.handler); $(element).bind('touchend mouseup', this.handler); }, destroy: function(element){ $(element).unbind(); $(this.element).removeData(); } showPane: function (index) { panes.eq(current_pane).hide(); current_pane = index; }, And then create a function, addcard() where you first fetch the data you want from a JSON source, add it to the main under the tinderslide, delete and then reinitialize the jTinder event. function addcard(){ $.getJSON("example.json",function(data){ //assign the data var elem="<li>"+data+"</li>"; //delete existing jTinder event $("#tinderslide").data('plugin_jTinder').destroy(); //reinitialize new jTinder event $("#tinderslide").jTinder({ onDislike:function(){ doSomething(); } onLike:function(){ doSomethingElse(); } }); }); } And call addcard() whenever you need to add a new card.
unknown
d8599
train
To start I would suggest heroku, they have a free option and some nice guides, depending on which server side language you use . This way you can get used to hosting some apps and doing deployments, seeing logs etc. The database doesn't have to be on the same hosting necessarily, you can use mongolab for example. For domain names it's a different thing, you will have to use the likes of godaddy A: Why not setup your own VPS (Virtual Private Server)? There are many providers.. A: Design the software application with portability and avoid vendor lock-in to cloud services. For file transfer, there are FTP/FXP, zip/gzip, & version control standards like Git, CVS, SVN, etc. Use phpMyAdmin for the database export & import process to change web hosts. Otherwise, build a staging subdomain or a local development environment with copies of the original web app & use those to transfer files+DB to a new host for production.
unknown
d8600
train
@Denis Pramme Please try this code and let me know: public class LoginActivity extends Activity { ..... private void SignInMethod() { new Thread(new Runnable() { public void run() { try { HttpPost postMethod = new HttpPost("*URL TO YOUR API SERVER*" + "Authenticate"); //_email and _password are String values from TextView: postMethod.setEntity(new StringEntity("grant_type=password&username=" + _email + "&password=" + _password)); postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded"); //here is the reponse, you can check it: response = httpClient.execute(postMethod, resonseHandler); } catch(Exception ex) { //Login to server failed... ex.printStackTrace(); } } }).start(); } } A: @DennisPramme, ok please change the line: String response = httpClient.execute(postMethod, resonseHandler); TO this line: (it will show status returned from server): HttpResponse responseFromServer = httpClient.execute(postMethod); int status = responseFromServer.getStatusLine().getStatusCode();
unknown