_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d11401
train
At the TCP socket level, the only things that are known are the source and destination IP addresses (and ports) of the connection. How the IP address was resolved via DNS is not possible to know at this layer. Even though HTTP works on top of TCP, HTTP servers have to look at the HTTP headers from the client to know which domain they are making a request to. (That's how the HTTP_HOST value gets filled in.) One possible solution is to configure your server to have an additional IP address. This can be by assigning an additional IP address to the NIC or adding an additional NIC. Then have each domain use a different IP address. Otherwise, this is not possible and you may want to consider your application protocol on top of TCP to convey this information.
unknown
d11402
train
* *Yes, Serverless VPC access guaranty a static IP address is you perform the correct set up (use a Cloud Nat and a router for routing the Serverless VPC Access IP-Range through Cloud Nat and use a static IP in Cloud Nat) *You aren't able to reach MongoDB via serverless VPC connector because your routes aren't well defined, and because of the point 3 *You can perform a peering between MongoDB Atlas and your VPC. For this, follow this page. If you peering is in pending state, I think that is because the GCP part has not been performed. Then define correctly your route and be sure that your firewall allow communication, and that should work!
unknown
d11403
train
Make sure you set the configuration right default_text_search_config (string) Selects the text search configuration that is used by those variants of the text search functions that do not have an explicit argument specifying the configuration. See Chapter 12 for further information. The built-in default is pg_catalog.simple, but initdb will initialize the configuration file with a setting that corresponds to the chosen lc_ctype locale, if a configuration matching that locale can be identified. You can see the current value with SHOW default_text_search_config; or SELECT get_current_ts_config(); You can change it for the session with SET default_text_search_config = newconfiguration; Or, you can use ALTER DATABASE <db> SET default_text_search_config = newconfiguration From Chapter 12. Full Text Search During installation an appropriate configuration is selected and default_text_search_config is set accordingly in postgresql.conf. If you are using the same text search configuration for the entire cluster you can use the value in postgresql.conf. To use different configurations throughout the cluster but the same configuration within any one database, use ALTER DATABASE ... SET. Otherwise, you can set default_text_search_config in each session. Each text search function that depends on a configuration has an optional regconfig argument, so that the configuration to use can be specified explicitly. default_text_search_config is used only when this argument is omitted. You can use \dF to see the text search configurations you have installed. So what you want, is something like this where to_tsvector('newconfig', title) @@ to_tsquery('newconfig', '你') No idea what language the query is in to answer this question, or what configuration will properly stem that language.
unknown
d11404
train
You should probably check if the actual field is empty - since submitting a form will still have an array: if(!empty($this->data['Epin']['e_pin'])) { Within your for() loop, you should be using create() and don't set id: for($i=0;$i<$limit;$i++) { $this->Epin->create(); $random = substr(number_format(time() * rand(),0,'',''),0,11)."<br/>"; $this->data['Epin']['e_pin'] = $random; //... Your redirect should be lowercase: $this->redirect(... It's quite difficult to understand what you're actually asking, but if you're trying to redirect if the form was submitted empty, the redirect should be one more level out: } $this->Session->setFlash("Epin has been added"); $this->Redirect(array('action'=>'admin_manage_epin')); }
unknown
d11405
train
Try this, $data = array(); foreach ($_POST['id_kuitansi'] as $id_kuitansi){ $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi); $i = $this->input; $data[] .= array( 'id' => $id_kuitansi, 'qty' => '1', 'price' => $detail_kuitansi['nilai'], 'name' => $detail_kuitansi['no_kuitansi'] ); print_r($data); //$this->cart->insert($data); } You were simply reassigned the values to $data each while you need to append the array value to the $data array A: Problem solved with this code : foreach ($_POST['id_kuitansi'] as $id_kuitansi) { $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi); $i = $this->input; $data[] = array( 'id' => $id_kuitansi, 'qty' => '1', 'price' => $detail_kuitansi['nilai'], 'name' => $detail_kuitansi['no_kuitansi'] ); } //print_r($data); $this->cart->insert($data); Thanks Mohammad... A: whenever we need to insert multiple data in single query, then we can user batch for inserting data. such as, $data = $arrInsert = array(); foreach ($_POST['id_kuitansi'] as $id_kuitansi){ $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi); $i = $this->input; $data = array( 'id' => $id_kuitansi, 'qty' => '1', 'price' => $detail_kuitansi['nilai'], 'name' => $detail_kuitansi['no_kuitansi'] ); //print_r($data); $arrInsert[] = $data; //$this->cart->insert($data); } $this->db->insert_batch('tableName', $arrInsert); In insert batch you can replace tableName with your table name.
unknown
d11406
train
TypeScript is just a superset of JavaScript. This means that you can write ES5 or ES6 code, it will be perfectly compiled by tsc. In TypeScript, even if you do not use type checking, it is OK: function myFunction () { // Your code... } var myFunction = function () { // Your code... }; let myFunction = function () { // Your code... }; const myFunction = () => { // Your code... }; // etc.
unknown
d11407
train
Currently, the app object only lives on for 60 seconds after the context has been deselected.
unknown
d11408
train
The main problem with your directive is that you can't use mustache binding in ngModel and ngOptions directive because they are evaluated directly. You can directly bind to the scoped property (ngModel and alloptionsModel): directive('dimension', function() { return { restrict: 'E', scope: { ngModel: '=', alloptionsModel: '=' }, template: '<div>' + '<label ng-transclude></label>' + '<fieldset>' + '<div class="form-group">' + '<select ng-model="ngModel" ng-options="x for x in alloptionsModel" multiple class="form-control"></select>' + '</div>' + '</fieldset>' + '</div>', replace: true, transclude: true }; }); See this plunkr for a working example. Edit As for the compile route, there is nothing wrong with it. It is useful when you need to dynamically create a template which will clearly be your case when you will get to the select's item template. compile: function(tElement, tAttrs) { var select = tElement.find('select'), value = tAttrs.value ? 'x.' + tAttrs.value : 'x', label = tAttrs.label ? 'x.' + tAttrs.label : 'x', ngOptions = value + ' as ' + label + ' for x in alloptionsModel'; select.attr('ng-options', ngOptions); } // In the HTML file <dimension ng-model="inputs.users" alloptions-model="allusers" label="name"> Users </dimension> I've updated the plunkr with the compile function.
unknown
d11409
train
That is the expected outcome with push. It looks like you want to use concat. push will append whatever the argument is to a new element at the end of the array. If you add a string it will add the string. If you add an array it will add an array...as the last element. It will not flatten the resultant array. On the other hand concat will concat the two arrays and return a new array. The original array will be unchanged though. A: var a = [1] console.log(a.length) // 0 var b = [2] var c = a.push(b) console.log(c) // [1, [2]] console.log(c.length) // 2 Try using concat(): var a = [1] console.log(a.length) // 1 var b = [2] var c = a.concat(b) console.log(c) // [1, 2] <<< Desired behaviour console.log(c.length) // 2
unknown
d11410
train
Well, I figured out how to fix it. * *The Oracle Instant Client version I had should be instantclient-basic-nt-11.2.0.4.0.zip *Oracle Home is not needed at all *When mentioning the path of instant client in the path variable, it should be the last if any other oracle client is already available in the machine. Once I fixed these, it just worked like a charm!
unknown
d11411
train
Error is pretty self-explanatory. You can only run explain on ActiveRecord::Relation objects. But find_by_sql gives you an Array instead, on which explain cannot be called. You have two ways to work around this: * *Convert your query with ActiveRecord methods (which return Relation) *Use explain inside your find_by_sql string.
unknown
d11412
train
see the API docs ...the response will deliver a currency symbol. and the example on Github explains how to set the destination: $rqData = new \hotelbeds\hotel_api_sdk\helpers\Availability(); $rqData->destination = new Destination("PMI");
unknown
d11413
train
If I understand your question correctly that you placed a push button in a button group, the answer is it would not work because button group is supposed to be composed of only toggle button and radio button. When I tried putting a push button in a button group, nothing would happen, just as you described.
unknown
d11414
train
You are passing the return value of the GetRandom() method of your single RandomGenerator instance to each of the threads. You need to pass a reference to the RandomGenerator to each of the threads instead, so GetRandom() can be called each time. Thread T1 = new Thread(delegate () { p.EnqueueNumber(numberQueue, rg); }); If you create a RandomGenerator per thread you can also stop using locks which are overkill for this use case. Finally if you insist on concurrent multi-write to, single-read from the same queue, you should also look at ConcurrentQueue rather than Queue as it is thread-safe.
unknown
d11415
train
With xslt version=1.0 you can use a extension "not-set". <xsl:call-template name="findString"> <xsl:with-param name="content1" select="exsl:node-set($nodelist)"></xsl:with-param> </xsl:call-template> To make it woke you have to add following lines. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" extension-element-prefixes="exsl" version="1.0"> Update: Based on solution from Mads Hansen <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:exsl="http://exslt.org/common" extension-element-prefixes="exsl"> <xsl:template name="doo"> <xsl:variable name="nodelist"> <root> <a size="12" number="11"> <sex>male</sex> Hulk </a> <a size="12" number="11"> <sex>male</sex> Steven XXXXXXXXXXX </a> </root> </xsl:variable> aaa <xsl:call-template name="findString"> <xsl:with-param name="content1" select="exsl:node-set($nodelist)"></xsl:with-param> </xsl:call-template> </xsl:template> <xsl:template match="/"> <xsl:call-template name="doo" /> </xsl:template> <xsl:template name="findString"> <xsl:param name="content1" select="."></xsl:param> <!-- here i need to search the text() XXXXXXXXXXX from $content1 and replace them--> <xsl:apply-templates mode="mytext" select="$content1"/> </xsl:template> <!--Identity template will copy all matched nodes and apply-templates--> <xsl:template match="@*|node()" mode="mytext"> <xsl:copy> <xsl:apply-templates select="@*|node()" mode="mytext"/> </xsl:copy> </xsl:template> <!--Specialized template to match on text nodes that contain the "findString" value--> <xsl:template match="text()[contains(.,'XXXXXXXXXXX')]" mode="mytext"> <xsl:variable name="findString" select="'XXXXXXXXXXX'"/> <xsl:variable name="replaceString" select="'YYYYYYYYYYYY'"/> <xsl:value-of select="concat(substring-before(., $findString), $replaceString, substring-after(., $findString))"/> </xsl:template> </xsl:stylesheet>
unknown
d11416
train
Working Fiddle HTML <p id="points">Total points: <span id="total-points"></span></p> <div id="box"></div> Remove this Javascript $('#points').innerHTML += points.toString(); Replace with this $('#total-points').text(points); A: $(document).ready(function () { var totPoints="Total points: "; // define a variable with this string value Animate(); div.on('mousedown', function () { points += 1; $('#points').html( totPoints+ points.toString()); // concatenate and add the html alert("Points" + points.toString());// Wrote this to prove that points score IS being incremented }); }); A: Insted of using innerHtml u can direcly use $('#points').html( "Total points: "+ +points.toString()); Working jsFiddle A: Try using $("#points").html(points); this will work. using .innerHTML with jquery will give problems as jquery uses this in a different manner to pure js.
unknown
d11417
train
Simple enough, if the list has one element, return it, else, multiply the first element by the base to the power of the list length minus 1 and add the output of the recursive call on the rest of the list. NB. I imagine you meant base 10, base 1 doesn't really make sense ;) def listIntoNumber(lst, base): assert len(lst) > 0 if len(lst) == 1: return lst[0] return lst[0]*base**(len(lst)-1) + listIntoNumber(lst[1:], base) print(listIntoNumber([1,2,3,2,9], 10)) # 12329 print(listIntoNumber([1,0,0,1,0], 2)) # 18 A: I assume base is the current number def listIntoNumber(lst,base): if len(lst)==0: return base base=base+lst[0]*(10**(len(lst)-1)) print(base) lst.pop(0) return listIntoNumber(lst,base) print(listIntoNumber([1,2,3,2,9],0))
unknown
d11418
train
You need to check your sys.path and find the source of anomalies, if any. See Debugging modifications of sys.path for a way to track changes to sys.path and Can I zip all the python standard libs and the python still able to import it? for how it's constructed. venv is implemented via Py3's stock site.py: If a file named "pyvenv.cfg" exists one directory above sys.executable, sys.prefix and sys.exec_prefix are set to that directory and it is also checked for site-packages (sys.base_prefix and sys.base_exec_prefix will always be the "real" prefixes of the Python installation). If "pyvenv.cfg" (a bootstrap configuration file) contains the key "include-system-site-packages" set to anything other than "false" (case-insensitive), the system-level prefixes will still also be searched for site-packages; otherwise they won't. When creating a venv, python and a number of other files are copied into <venv>/bin (<venv\Scripts in Windows), and a pyvenv.cfg is placed into <venv> for site.py to find upon Python startup. activate prepends <venv>/bin to PATH so that the local executable is started instead of the system one when you type "python". Ultimately, this results in a sys.path that combines system-wide standard library with venv-specific 3rd-party modules. It would look something like this: >>> sys.path ['', '<venv>/bin/python36.zip', <system Python platlib>, <system Python purelib>, '<venv>', '<venv>/lib/site-packages'] So, normally, there shouldn't be folders from another venv in sys.path resulting directly from venv logic. They may result from PYTHONPATH, or from some .pth files, or even from your own code. The above diagnostics should show where they come from.
unknown
d11419
train
jjones64. I have to say that Access DB is not supported as a sink dataset in the ADF,please see this support list: My advice is you could transfer to sql db data into on-prem csv file with copy activity, then load csv file into Access DB following this tutorial:https://blog.ip2location.com/knowledge-base/how-to-import-csv-into-microsoft-access-database/
unknown
d11420
train
When you create datamigration don't forget to use --freeze argument for all apps you somehow use in this migration, in my case it's auth: python manage.py datamigration my_app --freeze auth Then use orm['auth.User'].objects.all() instead of User.objects.all(). A: I am using user model as from django.contrib.auth.models import AbstractUser class MyProjectUser(AbstractUser): ... and i create migration for add new permissions to some groups of users: # -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.db import models permissions_codenames = ( 'can_action_1', ... 'can_action_10', ) class Migration(DataMigration): def forwards(self, orm): "Write your forwards methods here." permissions = orm['auth.Permission'].objects.filter(codename__in=permissions_codenames) for user in orm.MyProjectUser.objects.filter(groups__name__in=('GroupName1', 'GroupName2')): user.user_permissions.add(*permissions) def backwards(self, orm): "Write your backwards methods here." permissions = orm['auth.Permission'].objects.filter(codename__in=permissions_codenames) for user in orm.MyProjectUser.objects.filter(groups__name__in=('GroupName1', 'GroupName2')): user.user_permissions.remove(*permissions) models = { ... } complete_apps = ['users'] symmetrical = True in complete_apps = ['users'] 'users' is app name, where located MyProjectUser class.
unknown
d11421
train
dim datedue as date, lastdate as date datedue = Dateadd("d", 30, lastdate) If datedue < Date() then 'do stuff End if This is basic syntax for checking dates. Since you didnt try anythin on your own, this is all you get. Have fun :) A: You don't "type functions into a cell", you set the ControlSource of a textbox. And Access has dozens of date functions. However, you could start with a query: Select *, DateAdd("d", [CleaningFrequency], [LastCleaned]) As NextCleaning, IIf(DateDiff("d", [LastCleaned], Date()) > [CleaningFrequency], "Overdue", Null) As [Status], IIf(DateDiff("d", [LastCleaned], Date()) = [CleaningFrequency], "Yes", Null) As [Clean Today] From YourTable Of course, replace field and table names with those of yours.
unknown
d11422
train
Somebody could get access to a resource via a misconfigured IAM role for example. This is especially relevant for S3, where public access might sometimes be configured inadvertently. If you have encryption via KMS, access to the key would also have to be granted, which provides an additional layer of security, and something you can monitor and alert on easily. This also applies to your own components, some of which will be granted access to the KMS key, but others (like a frontend server) might not, because they don't need it, and you want to implement the least privilege principle to limit the impact of a potential breach. Of course you will not only rely on key access to implement access control to your resources, but it provides a single point where rules and actual access can easily be enforced and audited. Also think about backups and disposed media. Maybe more usual to consider this when you host stuff yourself, but it is still relevant for public clouds. You probably trust AWS to manage backups and disposed media securely, but while they're pretty good at it, they might not be perfect, and you have zero control. If you store your data encrypted, there is no way for it to be recovered from a dumpster.
unknown
d11423
train
When you create your action type, you need to use the profile object type (aka connected object type). Here I created my verb to "high five" a person: The object type will be configured automatically because profile is a built-in, FB-provided object type. So you don't have to configure the object type, unless there's an advanced setting you need. Then create an aggregation: Your og meta tags for the object then need to use the type profile (filepath for this example is /og/profile2.html): <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# high_fiver: http://ogp.me/ns/fb/high_fiver#"> <meta property="fb:app_id" content="27877347222" /> <meta property="og:url" content="http://www.rottentomatoes.com/celebrity/tom_hanks/" /> <meta property="og:type" content="profile" /> <meta property="og:title" content="Tom Hanks" /> <meta property="og:description" content="Tom Hanks profile on RT" /> <meta property="og:image" content="http://content6.flixster.com/rtactor/40/37/40376_pro.jpg" /> Notice that you can point to any profile, not just a FB profile. Above, I am using Tom Hanks' profile on Rotten Tomatoes, which uses Open Graph and has og:type profile. And I publish actions like so: <script type="text/javascript"> function postAction() { FB.api( '/me/high_fiver:high_five' + '?profile=http://www.plooza.com/og/profile2.html', 'post', function(response) { if (!response || response.error) { alert('Error occured'); console.log(response.error); } else { alert('Post was successful! Action ID: ' + response.id); } } ); } </script> Finally, a user of my app will publish the OG story on his/her timeline (in a "timeline unit"): When you click the link "Tom Hanks" in the story unit, it loads the Rotten Tomatoes profile. You can try this demo app here: http://plooza.com/og/profile2.html A: So “friend” is your own object type? How exactly is it defined? I think for what you’re planning to do here, the built-in object type Profile might suit your needs better – because that already creates a tie to a Facebook profile that is recognizable as such by the Open Graph.
unknown
d11424
train
I guess the key event of sdl is not firing every frame so you shouldn't change the camera position directly from there because camera wont update every frame. I would create a boolean variable MOVE_FORWARD that will represent if the forward key is pushed or not * *In the key event you update the MOVE_FORWARD variable. while (SDL_PollEvent(&e)) { .......... case SDL_KEYDOWN: switch (e.key.keysym.sym) { case SDLK_w: MOVE_FORWARD=true; break; *In every frame you update the position of the camera if (MOVE_FORWARD){pos+=0.3} This way the camera updates its position every frame and not only when the key event fires You could also avoid creating key state variables using SDL_GetKeyboardState(NULL) instead of SDL_PollEvent(&e): Uint8* keystate = SDL_GetKeyState(NULL); if(keystate[SDL_SCANCODE_W]) { pos+=0.3; }
unknown
d11425
train
After a very long wait I finally got some time over to finish this. Very sorry for the extremely long wait. I don't know if it's fully what you're looking for, but it will make the train and station classes work more together. As you have so many collections (as they're even within your classes) it's hard to update them all. I'd recommend you to use a Dictionary(Of TKey, TValue) and just having Boolean properties in your train classes. Your Dictionary would look like this: Dictionary(Of station, List(Of train)). First we'll need some extensions methods to later help us find and iterate through the stations and trains. We'll start with a function that will find a station by specifying it's name. Create a new Module and add this code within: ''' <summary> ''' Finds a station by it's name. ''' </summary> ''' <param name="StationCollection">The dictionary to look for the station in.</param> ''' <param name="Name">The name of the station to find.</param> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function FindStationByName(ByRef StationCollection As Dictionary(Of station, List(Of train)), ByVal Name As String) As station Name = Name.ToLower() 'ToLower() provides case-insensitive checking. 'Iterating through a Dictionary requires iterating through it's keys, as it's not index based. For Each k As station In StationCollection.Keys If k.name_t.ToLower() = Name Then Return k End If Next Return Nothing End Function Then we need extension methods for finding a train by it's id or it's name. We also an extension for finding all trains linked to a specific station. In the same module as above add: ''' <summary> ''' Finds a train by it's ID. ''' </summary> ''' <param name="TrainCollection">The list to look for the train in.</param> ''' <param name="Id">The ID of the train to find.</param> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function FindTrainById(ByRef TrainCollection As List(Of train), ByVal Id As Integer) As train For Each t As train In TrainCollection If t.id = Id Then Return t End If Next Return Nothing End Function ''' <summary> ''' Finds a train by it's name. ''' </summary> ''' <param name="TrainCollection">The list to look for the train in.</param> ''' <param name="TrainName">The name of the train to find.</param> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function FindTrainByName(ByRef TrainCollection As List(Of train), ByVal TrainName As String) As train TrainName = TrainName.ToLower() For Each t As train In TrainCollection If t.name_t = TrainName Then Return t End If Next Return Nothing End Function ''' <summary> ''' Finds all trains linked to the specified station. ''' </summary> ''' <param name="StationCollection">The dictionary to look for the station in.</param> ''' <param name="StationName">The name of the station which's trains to find.</param> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function FindTrainsByStation(ByRef StationCollection As Dictionary(Of station, List(Of train)), ByVal StationName As String) As List(Of train) StationName = StationName.ToLower() For Each k As station In StationCollection.Keys If k.name_t.ToLower() = StationName Then Return StationCollection(k) End If Next Return Nothing End Function Finally we'll need an extension method to remove a train from all the stations. This extension method will be used by the RemoveAll() and RemoveAllByName() methods in the train class later. ''' <summary> ''' Removes a trains link from all stations. ''' </summary> ''' <param name="StationCollection">The dictionary of stations which's links to this train to remove.</param> ''' <param name="train">The train to remove.</param> ''' <param name="MatchName">If true, match by the train's name instead of it's ID.</param> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Sub RemoveTrainFromAllStations(ByVal StationCollection As Dictionary(Of station, List(Of train)), ByVal train As train, ByVal MatchName As Boolean) For Each k As station In StationCollection.Keys For i = 0 To StationCollection(k).Count - 1 Dim t As train = StationCollection(k)(i) If MatchName = False Then 'Wether to match against the train's name or id. If t.id = train.id Then t.Remove() End If Else If t.name_t = train.name_t Then t.Remove() End If End If Next Next End Sub Now onto your classes. Passing the Dictionary reference to your station and train classes can also help you create functions for checking which train belongs to which station, etc. By doing this you have the classes working together with the Dictionary, you can even make another wrapper class around this to reduce "messieness" even more. You will also need to override the Equals and GetHashCode methods in order for dictionaries and hash tables to be able to lookup your key correctly. This is just example code, so I haven't included your properties here: Public Class train Private StationCollection As Dictionary(Of station, List(Of train)) 'Storing the main dictionary. Private _parent As station ''' <summary> ''' Wether this train is departing or arriving. ''' </summary> ''' <remarks></remarks> Public Property Departing As Boolean = False ''' <summary> ''' The station that owns this train (multiple stations can own trains with the same names and IDs). ''' This is mainly used for internal functions. ''' </summary> ''' <remarks></remarks> Public ReadOnly Property ParentStation As station Get Return _parent End Get End Property ''' <summary> ''' Initializes a new instance of the train class. ''' </summary> ''' <param name="StationCollection">The main dictionary containing this train and it's station.</param> ''' <param name="ParentStation">The station that owns this train (multiple stations can own trains with the same names and IDs).</param> ''' <remarks></remarks> Public Sub New(ByRef StationCollection As Dictionary(Of station, List(Of train)), ByVal ParentStation As station) Me.StationCollection = StationCollection Me._parent = ParentStation End Sub ''' <summary> ''' Removes this train from it's station. ''' </summary> ''' <remarks></remarks> Public Sub Remove() Me.StationCollection(ParentStation).Remove(Me) End Sub ''' <summary> ''' Removes this, and all other trains having the same ID as this, from all stations in the main dictionary. ''' </summary> ''' <remarks></remarks> Public Sub RemoveAll() Me.StationCollection.RemoveTrainFromAllStations(Me, False) End Sub ''' <summary> ''' Removes this, and all other trains having the same name as this, from all stations in the main dictionary. ''' </summary> ''' <remarks></remarks> Public Sub RemoveAllByName() Me.StationCollection.RemoveTrainFromAllStations(Me, True) End Sub 'the rest of your code... 'Overriding Equals() and GetHashCode(), comparison will be performed by comparing two trains' id's. Public Overrides Function Equals(obj As Object) As Boolean Return obj IsNot Nothing AndAlso obj.GetType() Is GetType(train) AndAlso DirectCast(obj, train).id = Me.id End Function Public Overrides Function GetHashCode() As Integer Return Me.id.GetHashCode() End Function End Class And the station class: Public Class station Private StationCollection As Dictionary(Of station, List(Of train)) 'Linking this station to the main Dictionary. ''' <summary> ''' Gets a list of trains arriving at this station. Modifying the returned list will NOT affect the main dictionary or it's stations. ''' </summary> ''' <remarks></remarks> Public ReadOnly Property ArrivingTrains As List(Of train) Get Return Me.GetTrainsByType(False) End Get End Property ''' <summary> ''' Gets a list of trains departing from this station. Modifying the returned list will NOT affect the main dictionary or it's stations. ''' </summary> ''' <remarks></remarks> Public ReadOnly Property DepartingTrains As List(Of train) Get Return Me.GetTrainsByType(True) End Get End Property ''' <summary> ''' Gets all trains of the specified type that are linked to this station. ''' </summary> ''' <param name="Departing">Wether to get all departing trains or all arriving trains.</param> ''' <remarks></remarks> Private Function GetTrainsByType(ByVal Departing As Boolean) As List(Of train) Dim TrainList As List(Of train) = StationCollection(Me) 'Getting all trains for this station. Dim ReturnList As New List(Of train) For Each t As train In TrainList If t.Departing = Departing Then ReturnList.Add(t) End If Next Return ReturnList End Function ''' <summary> ''' Removes this station and all links to trains arriving or departing from it. ''' </summary> ''' <remarks></remarks> Public Sub Remove() For Each t As train In StationCollection(Me) 'Iterate though all the trains for this station. GetType(train).GetField("_parent", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic).SetValue(t, Nothing) 'Use reflection to set the train's parent to Nothing. Next StationCollection.Remove(Me) End Sub ''' <summary> ''' Initializes a new instance of the station class. ''' </summary> ''' <param name="StationCollection">The main dictionary containing this train and it's station.</param> ''' <remarks></remarks> Public Sub New(ByRef StationCollection As Dictionary(Of station, List(Of train))) Me.StationCollection = StationCollection End Sub 'the rest of your code... 'Overriding Equals() and GetHashCode(), comparison will be performed by comparing two stations' names. Public Overrides Function Equals(obj As Object) As Boolean Return obj IsNot Nothing AndAlso obj.GetType() Is GetType(station) AndAlso DirectCast(obj, station).name_t = Me.name_t End Function Public Overrides Function GetHashCode() As Integer Return Me.name_t.GetHashCode() End Function End Class Adding new stations/trains When adding items to the dictionary you would first have to initialize a new station class, then you create new train classes where you point the ParentStation parameter to the station you just created. For example: Dim MainDictionary As New Dictionary(Of station, List(Of train)) 'Create the dictionary (only do this once, unless you need multiple of course). Dim new_station As New station(MainDictionary) 'Create a new station. new_station.name = "Station 1" MainDictionary.Add(new_station, New List(Of train)) Dim new_train As New train(MainDictionary, new_station) 'Create a new train. new_train.id = 3 new_train.name_t = "Train 1" new_train.Departing = True 'This train is leaving from the station. MainDictionary(new_station).Add(new_train) 'Add the train to the station. Extension methods The extension methods are used when... * *You want to find a specific station by it's name. For example: Dim st As station = MainDictionary.FindStationByName("Station 1") *You want to find a train by it's id or name. For example: Dim t As train = MainDictionary.FindStationByName("Station 1").ArrivingTrains.FindTrainById(3) Dim t2 As train = MainDictionary.FindStationByName("Station 1").ArrivingTrains.FindTrainByName("Train 1") *Or when you want to get all trains from a specific station (by it's name). For example: Dim trains As List(Of train) = MainDictionary.FindTrainsByStation("Station 1") Overview of the methods, fields and properties: - The train class - StationCollection * *A private field holding the reference to your main dictionary of all stations. _parent * *A private field holding the station this train is "linked" to. Departing * *A public property indicating if this train is departing (leaving) or arriving (coming) ParentStation * *A public read-only property returning the value of _parent. Remove() * *Removes this train from the station it's linked to. RemoveAll() * *Removes this train, and all other trains having the same ID as this, from all stations in the main dictionary. RemoveAllByName() * *Same as RemoveAll(), but matches against the trains' names instead of their IDs. - The station class - StationCollection * *Same as in the train class. ArrivingTrains * *A read-only property returning all trains arriving at (coming to) this station. DepartingTrains * *A read-only property returning all trains departing (leaving) from this station. GetTrainsByType() * *A private method for getting arriving/departing trains. Used by the above properties. Remove() * *Removes this station and all links to arriving or departing trains (by nullifying their _parent field) that are in the main dictionary. Hope this helps! And sorry again for taking so long.
unknown
d11426
train
I pinned down the issue to privileges changes since Docker Desktop 4.15.0 for Mac. What fixed the issue on my end was to downgrade to 4.14.1: * *Uninstall Docker completely. This can be done by opening Docker Desktop UI, clicking the Bug icon and clicking "Uninstall". Then, the application can be moved to the bin. *Install Docker Desktop 4.14.1 I encountered this issue on a company Mac where I suspect the Privileges app I need to use to elevate permissions doesn't work well with the privileges changes Docker made starting from 4.15.0. Extract from their 4.15.0 changelog: Docker Desktop for Mac no longer needs to install the privileged helper process com.docker.vmnetd on install or on the first run. For more information see Permission requirements for Mac.
unknown
d11427
train
It seems, that Gson failed here: "pods":[{"id": ^ This [ is unexpected because in your model PodModel pods field is plain field, not an array. May be you have to change pods to by an array, and in this case you will be able to parse such json. UPD: Just change pods definition to this one: private List<ItemPod> pods; * *change according way getter and setter. This solution should work (tested).
unknown
d11428
train
Look at the response body: array(2) { ["id"]=> string(29) "urn:ngsi-ld:Building:store005" ["type"]=> string(8) "Building" } That isn't JSON. It looks like a var_dump(). Check the endpoint you call!
unknown
d11429
train
Your query looks completely correct. I loaded your data and used your queries verbatim and got just what you would expect. Ascending: select * from cbcallers where calls_completed is not null order by calls_completed asc [ Item 8uda23sd7 icon: myimgicon.jpg name: john smith calls_completed: 0000002, Item 8uda5asd3 icon: myimgicon2.jpg name: john smarts calls_completed: 0000015, Item 8udassad8 icon: myimgicon3.jpg name: john smoogie calls_completed: 0000550] Descending: select * from cbcallers where calls_completed is not null order by calls_completed desc [ Item 8udassad8 icon: myimgicon3.jpg name: john smoogie calls_completed: 0000550, Item 8uda5asd3 icon: myimgicon2.jpg name: john smarts calls_completed: 0000015, Item 8uda23sd7 icon: myimgicon.jpg name: john smith calls_completed: 0000002] Maybe it is an issue with your SimpleDB client, which one are you using, do you know if it is using the latest SimpleDB API version ("2009-04-15")?
unknown
d11430
train
After trying and trying - created another RDS DB, copying existing one, created another VPC to try it out there are few things that need to be considered (obviously, they are all documented, but it's not an easy task to find all the information, since - at least in my case - it wasn't documented in one place: * *If you want your DB instance in the VPC to be publicly accessible, you must enable the VPC attributes DNS hostnames and DNS resolution (existing VPC can be changed too). *Check the VPC security group and enable the DB access port (in case of the standard MS SQL deployment - 1433) - since starting the 2013, VPC security groups have replaced the RDS security group. *Check thoroughly the RDS DB information for Security Groups, port and other info that can be misidentified. *Somehow not obvious (at least for me at first), but when using SQL Management Studio to access the RDS DB - do not use the ":1433" or other port identifier at the end of DB instance name. *If nothing of the above works, ask the question here and keep googling... :) Most of the info found here: http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.RDSVPC.html
unknown
d11431
train
I tried to reproduce the issue which you have described, but it seems that everything works fine. Demo: https://jsfiddle.net/BlackLabel/hw6kt2cv/ Highcharts.chart('container', { tooltip: { useHTML: true, headerFormat: '<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/dog_cool_summer_slideshow/1800x1200_dog_cool_summer_other.jpg" width="150"/><br />► Listing {point.x}<br />', pointFormat: '<span style="color:{series.color}">► {series.name} : </span> {point.y:, .0f} <br />', split: false, shared: true }, series: [{ data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175] }] }); Maybe some other options have an impact on your chart? Could you share a sample which will show the issue? According to the comments - using the tooltip.outside should fix the described issue. Demo: https://jsfiddle.net/BlackLabel/1xshj85w/ API: https://api.highcharts.com/highcharts/tooltip.outside
unknown
d11432
train
You add the textArea to a JScrollPane, and then never do anything with the pane. jScrollPane1 = new JScrollPane(tfFIXMsg); You need add(jScrollPane1);
unknown
d11433
train
There are no closed form solutions for logistic regression, but there are many iterative methods to learn its parameters. One of the simplest ones is steepest descent method, which simply iteratively moves in the opposite direction to the gradient. For 1D logistic regression it would be: beta1_t+1 = beta1_t - alpha * SUM_(x, y) x * (s(beta1_t*x + beta0_t) - y) beta0_t+1 = beta0_t - alpha * SUM_(x, y) (s(beta1_t*x + beta0_t) - y) where: s(x) = 1 / (1 + exp(-x)) and * *alpha is learning rate, something small enough, like 0.01 *your model's prediction is s(beta1 * x + beta0) *your data is of form {(x1, y1), ..., (xK, yK)}) and each yi is either 0 or 1 This is literally saying beta_t+1 = beta_t - alpha * GRAD_theta J(beta_t) where J is logistic loss
unknown
d11434
train
May be you need to change scheme for saving your bitmaps? For example, you can store bitmaps in inner app's directory and saving path to this image in database. Also, you can try to change your select query like this: SELECT * FROM your_table; I think, you can receive only 20 bytes because you select word, not a column (I mean 'claimattachmentimage' in your query)
unknown
d11435
train
You are correct. You can read from your Model objects and ObservableCollections on a worker thread without having a cross-thread violation. Getting or setting the value of a property on a UI element (more specifically, an object that derives from DispatcherObject) must be done on the UI thread (more specifically, the thread on which the DispatcherObject subclass instance was created). For more info about this, see here.
unknown
d11436
train
The .rda file contains the model object in a R-specific serialization data format. You should be able to de-serialize it using the readRDS(rds_path) method, and then invoke the r2pmml(model, pmml_path) method. Training a model, and serializing it into a RDS file: library("randomForest") rf = randomForest(Species ~ ., data = iris) saveRDS(rf, "rf.rds") De-serializing the model from the RDS file, and exporting it into a PMML file: library("r2pmml") rf_clone = readRDS("rf.rds") r2pmml(rf_clone, "rf.pmml")
unknown
d11437
train
You are definitely overthinking this. Use a simple ConcurrentHashMap, and ConcurrentSkipListSet/CopyOnWriteArraySet depending on your concurrency characteristics (mainly if iteration needs to take into account on-the-fly modifications of the data). Use something like the following snippet as the getSet method: private Set<V> getSet(K key) { Set<V> rv = map.get(key); if (rv != null) { return rv; } map.putIfAbsent(key, new Set<V>()); return map.get(key); } This will ensure proper lockless concurrency when adding/removing objects, for the iteration you will need to determine whether missing updates is an issue in your problem domain. if it's not an issue to miss a new object when it's added during the iteration, use the CopyOnWriteArraySet. On the third hand, you want to take a deep look into what kind of granularity you can use w.r.t. concurrency, what your requirements are, what the proper behavior is in edge cases, and most of all, what performance and concurrency characteristics your code must cover - if it's something that happens twice on startup, I'd just make all methods synchronized and be done with it. A: If you are going to be adding to the 'set' often, CopyOnWriteArrayList and CopyOnWriteArraySet are not going to be viable - They use far too many resources for add operations. However, If you are adding rarely, and iterating over the 'set' often, than they are your best bet. The Java ConcurrentHashMap puts every single map into a bucket per se - your put if absent operation will lock the list when it searches for the key, and then, release the lock and put in the key. Definitely use the ConcurrentHashMap instead of the map. Your getSet method could will be inherently slow, especially when synchronized - perhaps, you could preload all of the keys and the sets sooner than later. I suggest you follow in line with what Louis Wasserman says, and see if your performance is decent with the Guava implementation.
unknown
d11438
train
For me works with the function CKEDITOR.editor.getData. https://ckeditor.com/docs/ckeditor4/latest/guide/dev_savedata.html Your code can be changed to below <EditForm Model="@postObject" OnValidSubmit="SaveObject"> <div class="form-group"> <DataAnnotationsValidator /> <ValidationSummary /> <InputTextArea id="editor" @bind-Value="@PostObject.Content" Class="form-control" /> </div> <button type="submit" class="btn btn-primary">Save</button> </EditForm> @code { PostObject postObject= new PostObject(); string contentFromEditor = string.Empty; protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) await jsRuntime.InvokeAsync<string>("RTF", "editor"); await base.OnAfterRenderAsync(firstRender); } private async Task SaveObject() { contentFromEditor = await JSRuntime.InvokeAsync<string>("CKEDITOR.instances.editor.getData"); } }
unknown
d11439
train
You should use quantifiers to load the great layout depending on your screen size and orientation. For example, activity_main.xml from layout-large-land and layout folders wont react the same. The first one will only be loaded if you are on a tablet and landscape oriented. The second one will be the default layout. You will need to use small, large, landscape (land) and portrait (default) quantifiers. About loading datas, you can use saveInstanceState bundle. Note that views with an id will automatically handle it.
unknown
d11440
train
I found that the DataTable’s ImportRow works well for this. If you set the grids SelectionMode to FullRowSelect then you should be able to loop through the grids SelectedRows collection and “import” the selected row(s) into the other DataTable. Below is a simple example. dt and dt2 are two DataTables with similar schemas. dt is a data source for datagridview1 and dt2 is a data source to datagridview2. Initially, dt is filled with some data and dt2 is empty. Once the user selects one or more rows, a button's click event initiates moving the selected rows from dt to dt2. To start, a simple loop through the selected rows. A check if the “new row” is selected which we do not want to copy, therefore we ignore it. Next, get the “data bound” row from the data table in the form of a DataRowView object. Then we “import” that row into dt2, and finally removing the copied row from dt. I did not do a lot of testing on this however it appears to work as expected. private void button1_Click(object sender, EventArgs e) { DataRowView drv; foreach (DataGridViewRow row in dataGridView1.SelectedRows) { if (!row.IsNewRow) { drv = (DataRowView)row.DataBoundItem; dt2.ImportRow(drv.Row); dt.Rows.Remove(drv.Row); } } } To make the example complete, drop two grids and button onto a form. DataTable dt; DataTable dt2; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { dt = GetTable(); dt2 = GetTable(); FillTable(dt); dataGridView1.DataSource = dt; dataGridView2.DataSource = dt2; } private DataTable GetTable() { DataTable dt = new DataTable(); dt.Columns.Add("Col1", typeof(string)); dt.Columns.Add("Col2", typeof(string)); dt.Columns.Add("Col3", typeof(string)); return dt; } private void FillTable(DataTable dt) { for (int i = 0; i < 10; i++) { dt.Rows.Add("C0R" + i, "C1R" + i, "C2R" + i); } } Hope this helps.
unknown
d11441
train
It's bogus. Templates have no special properties re casting that a normal class wouldn't have. Make sure you always use the appropriate cast and you will be fine. A: This is unrelated to templates vs. normal classes, but if your class has multiple inheritance you should always start with the same type before casting to void*, and likewise when casting back. The address of a pointer will change based on which parent class the pointer type is. class ParentA { // ... int datumA; }; class ParentB { // ... int datumB; }; class Derived : public ParentA, public ParentB { // ... }; int main() { Derived d; ParentA * ptrA = &d; ParentB * ptrB = &d; assert((void*)ptrA == (void*)ptrB); // asserts! } A: It is always safe to cast some pointer Foo* onto void* and then restore on the same type Foo*. When inheritance is used however, a special care should be taken. Upcasting/downcasting shouldn't be done through the void* pointer. Consider the following code: #include <cassert> class Parent { int bar; }; class Derived : public Parent { virtual void foo() { } }; int main() { Derived d; Derived* ptr_derived = &d; void *ptr_derived_void = ptr_derived; Derived* ptr_derived_from_void = (Derived*)ptr_derived_void; assert(ptr_derived_from_void == ptr_derived); //that's OK Parent* ptr_parent = ptr_derived; //upcast Parent* ptr_parent_from_void = (Parent*)ptr_derived_void; //upcast? assert(ptr_parent_from_void == ptr_parent); //that's not OK return 0; } Also this post shows some problem with casting through void*. A: A template class instantiated with a classes A and B as template args involves the compiler creating two seperate classes that specifically handle these respective types. In many ways this is like an intelligent strongly typed preprocessor macro. It is not that different to manually copy-pasting two seperate "normal" classes who operate on A and B respectively. So no. The only way it will be dangerous is if you try to cast what was originally: MyClass<A> as MyClass<B> if A is not B, since they could have a different memory layout. A: Pointers are just that: pointers to data. The "type" of a pointer makes no difference to anything really (at compile time), it's just for readability and maintainability of code. For example: Foo<a> *x = new Foo<a>(); void *y = (void*)x; Foo<a> *z = (Foo<a>*)y; Is perfectly valid and will cause no issues. The only problem when casting pointer types is that you may run into dereferencing issues when you've forgotten what the underlying data-type a pointer is referencing actually is. If you're passing around void* everywhere, just be careful to maintain type integrity. Don't do something like: Foo<a> *x = new Foo<a>(); void *z = (void*)x; //pass around z for a while, then mistakenly... Foo<b> *y = (Foo<b>*)z; By accident!
unknown
d11442
train
From your sample screenshot it looks like your criteria1 might look like: "=" & B3 I would replace it with: IF(D3="yes","<>ABCDEF","=" & B3) Where ABCDEF is any string that does not exist in the criteria_range1, so the <>ABCDEF condition is always true. This trick should work for every type of data (strings, numbers, dates, blanks). The full formula for your sample screenshot would be: =AVERAGEIFS(E7:E15,C7:C15,IF(D3="yes","<>ABCDEF","=" & B3),D7:D15, IF(D4="yes","<>ABCDEF","=" & B4),B7:B15,"=" & B2,A7:A15,"=" & B1)
unknown
d11443
train
Take a screenshot on both devices, email it to a PC and compare the actual colours in photoshop. It's probably just the screen, they can vary wildly, I wouldn't worry about it unless your app has some special specific reason to be concerned about exact colour reproduction. Even on a single device there are sometimes settings which change the look completely, e.g. the Samsung Galaxy S6: http://www.phonearena.com/news/Samsung-Galaxy-S6-Review-of-the-various-display-modes_id69968
unknown
d11444
train
The data in the question was replicated for Congo and we use a width of 2 instead of 10 so we can run this without having a trivial result of all NA: # data for DF Lines <- " Date Value Site 2008-08-20 NA Kenya 2008-08-29 12.954 Kenya 2008-08-18 29.972 Kenya 2008-08-16 5.080 Kenya 2009-04-21 3.048 Kenya 2009-04-22 12.954 Kenya 2008-08-20 NA Congo 2008-08-29 12.954 Congo 2008-08-18 29.972 Congo 2008-08-16 5.080 Congo 2009-04-21 3.048 Congo 2009-04-22 12.954 Congo" # set up DF, convert Date column to "Date" class DF <- read.table(text = Lines, header = TRUE) DF$Date <- as.Date(DF$Date) Sort the rows and use ave to perform the rolling mean by Site and year/month: # sort rows o <- order(DF$Site, DF$Date) DF <- DF[o, ] # perform rolling mean library(zoo) # w <- 10 w <- 2 roll <- function(x) rollapplyr(c(rep(NA, w-1), x), w, mean) DF$mean <- ave(DF$Value, DF$Site, as.yearmon(DF$Date), FUN = roll) This gives: > DF Date Value Site mean 10 2008-08-16 5.080 Congo NA 9 2008-08-18 29.972 Congo 17.526 7 2008-08-20 NA Congo NA 8 2008-08-29 12.954 Congo NA 11 2009-04-21 3.048 Congo NA 12 2009-04-22 12.954 Congo 8.001 4 2008-08-16 5.080 Kenya NA 3 2008-08-18 29.972 Kenya 17.526 1 2008-08-20 NA Kenya NA 2 2008-08-29 12.954 Kenya NA 5 2009-04-21 3.048 Kenya NA 6 2009-04-22 12.954 Kenya 8.001 UPDATES Rearranged presentation and added changed ave line to use yearmon.
unknown
d11445
train
Eloquent will assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention. In each of your models add its primary key like so for Department model: protected $primaryKey = 'department_id'; Eloquent assumes that the foreign key should have a value matching the id (or the custom $primaryKey) column of the parent. In other words, Eloquent will look for the value of the department id column in the department_id column of the employee record. If you would like the relationship to use a value other than id, you may pass a third argument to the belongsTo method specifying your custom key: In your case you are calling department() of your employee model: return $this->belongsTo('GloboDeals\Department', 'departments_id', 'departments_id'); This means the Employee model will eager load the department details where the relation departments_id of departments table = departments_id of the employees table.
unknown
d11446
train
Try the below. mysql_query returns a 'resource' that represents the resultset, and to get values you need to use one of the mysql_fetch_ functions. $row = mysql_fetch_array($query); echo $row[0]; A: $query, after executing the query doesn't have just a number. It'll have a Resource just like any other query you would execute. In order to actually get the result, treat it like you would treat any other resource: $result = mysql_fetch_array($query); echo $result[0]; A: $result = mysql_fetch_array($query); echo $result[0]; A: As mentioned before, this is because the variable is a resource. Visit this link to learn more about PHP variable types. It is only possible to echo strings or types that can be cast to strings. Such as int, float and objects implementing the __toString magic function.
unknown
d11447
train
PTR records are usually necessary if you are running a DNS or SMTP server to provide some proof that you are legitimate. I found this article to be quite illuminating. I think the answer to this question is found towards the bottom of the link in the question. You have to fill out a form and AWS will create the PTR record for you. Creating a hosted zone in Route 53 for the pointer record does not appear to have any effect. Nothing in the RFC prohibits the owner of the public IP address from allowing a customer to create a PTR record for that public IP address. Although AWS could allow customers to create PTR records for their Elastic IP addresses, they do not. There are a lot of articles discussing how you need to create your own hosted zones for the PTR records, such as but not limited to Amazon's own article the question linked to. You can definitely do this for private IP addresses if you are running a DNS server for a private network. However, if you are running a publicly available DNS or SMTP server on a public IP address, more vetting is required. In order to verify that the records are set up correctly, you have to get an answer to: dig -x 34.65.125.52 (must answer ns1.hostingcompany.de) Unless you do this, the TLD registrar will not accept your nameserver, and your SMTP mail will probably be rejected as spam. In addition to the above, another problem was that these lines should also be included in the zone file for hostingcompany.de hostingcompany.de. 300 IN NS ns1.hostingcompany.de. hostingcompany.de. 300 IN NS ns2.hostingcompany.de. It is still unclear to me why the top level domain requires that the domains own nameservers are listed as being nameservers for its own domain, but this does appear to be a requirement for some top-level domains. After correcting the above problems, everything works. I spent a long time trying to track down the above problems, and it did not seem to be documented anywhere, so I hope this helps someone. I also found this RFC to be quite interesting and informative. It is always good to read stuff written by the authorities.
unknown
d11448
train
curses doesn't provide separate events for key presses and releases, so you'd probably be better off with pygame if you want it to work that way. (Weird quasi-exception: ncurses and PDCurses can provide separate press and release events for mouse buttons, if you wanted to go that way. This isn't quite standard curses, and I don't know if the Python interface supports it.)
unknown
d11449
train
Ok, so as I suspected. It worked with svg's instead of groups/paths. Paths/groups are 2D only, as figured out. But svg's are possible to make 3D and use translateZ on. Down here is the answer for the future ones looking for answer. Ps. The code could be cleaned up a bit, but it works. So the basic structure is now split into many svg's instead of one svg containing many groups: <body> <div class="container"> <div class="image"> <svg class="sun"> <g> ... </g> </svg> <svg class="cloud-left"> <g> ... </g> </svg> ... </div> </div> </body> And here is the "finale" code and solution: https://jsfiddle.net/saturday99/fkrh6bzm/. Feel free to fork the code.
unknown
d11450
train
The main problem is that your $.each is wrong by assuming the first argument to be the actual element in the prices array. In fact, the first argument is the index, the second argument is the actual price you want to augment. Also, you seem to have a typo in the computed function calculation, it's price.Price instead of prices.Price. Try this: $.each(self.prices(), function (index, price) { price.FinalPrice = ko.computed(function() { return price.Price * irt * parseInt(pax); }); }); And in your HTML, something like: <div data-bind="foreach: prices"> <span name="totalprice" data-bind="text: FinalPrice"></span> </div> See Fiddle
unknown
d11451
train
If your Trie data structure implements serializable then writing to and from a file should be fairly straight forward. Java will take care of the file representation. See this link. A: Maybe good idea - to keep tried in the memory buffer in the position-independent code, and read it into memory by mmap(). This is mostly quick way to work with trie from "cold start". Also, maybe you can keep data not in the tries, but in the hashtable. By this method, you can keep in the memory only "bucket index", which is very small. And, when compute hash - pread() bucket into memory from file, and search in loaded part.
unknown
d11452
train
itertools.groupby provides one easy way to do this: >>> import itertools >>> T, F = True, False >>> b_List = [T,T,T,F,F,F,F,T,T,T,F,F,T,F] >>> [len(list(group)) for value, group in itertools.groupby(b_List) if value] [3, 3, 1] A: Using NumPy: >>> import numpy as np >>> a = np.array([ True, True, True, False, False, False, False, True, True, True, False, False, True, False], dtype=bool) >>> np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2] array([3, 3, 1]) >>> a = np.array([True, False, False, True, True, False, False, True, False]) >>> np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2] array([1, 2, 1]) Can't say that this is the best NumPy solution, but it is still faster than itertools.groupby: >>> lis = [ True, True, True, False, False, False, False, True, True, True, False, False, True, False]*1000 >>> a = np.array(lis) >>> %timeit [len(list(group)) for value, group in groupby(lis) if value] 100 loops, best of 3: 9.58 ms per loop >>> %timeit np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2] 1000 loops, best of 3: 1.4 ms per loop >>> lis = [ True, True, True, False, False, False, False, True, True, True, False, False, True, False]*10000 >>> a = np.array(lis) >>> %timeit [len(list(group)) for value, group in groupby(lis) if value] 1 loops, best of 3: 95.5 ms per loop >>> %timeit np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2] 100 loops, best of 3: 14.9 ms per loop As @justhalf and @Mark Dickinson pointed out in comments the above code will not work in some cases, so you need to append False on both ends first: In [28]: a Out[28]: array([ True, True, True, False, False, False, False, True, True, True, False, False, True, False], dtype=bool) In [29]: np.diff(np.where(np.diff(np.hstack([False, a, False])))[0])[::2] Out[29]: array([3, 3, 1]) A: Your original try has some problems: i = 0 ml = [] for el in b_List: if (b_List): # b_list is a list and will evaluate to True # unless you have an empty list, you want if (el) i += 1 ml.append(i) # even if the above line was correct you still get here # on every iteration, and you don't want that i = 0 You probably want something like this: def count_Trues(b_list): i = 0 ml = [] prev = False for el in b_list: if el: i += 1 prev = el else: if prev is not el: ml.append(i) i = 0 prev = el if el: ml.append(i) return m Result: >>> T, F = True, False >>> b_List = [T,T,T,F,F,F,F,T,T,T,F,F,T,F] >>> count_Trues(b_List) [3, 3, 1] >>> b_List.extend([T,T]) >>> count_Trues(b_List) [3, 3, 1, 2] >>> b_List.extend([F]) >>> count_Trues(b_List) [3, 3, 1, 2] This solution runs surprisingly fast: In [5]: T, F = True, False In [6]: b_List = [T,T,T,F,F,F,F,T,T,T,F,F,T,F] In [7]: new_b_List = b_List * 100 In [8]: import numpy as np # Ashwini Chaudhary's Solution In [9]: %timeit np.diff(np.insert(np.where(np.diff(new_b_List)==1)[0]+1, 0, 0))[::2] 1000 loops, best of 3: 299 us per loop In [11]: %timeit count_Trues(new_b_List) 1000 loops, best of 3: 130 us per loop In [12]: new_b_List = b_List * 1000 # Ashwini Chaudhary's Solution In [13]: %timeit np.diff(np.insert(np.where(np.diff(new_b_List)==1)[0]+1, 0, 0))[::2] 100 loops, best of 3: 2.25 ms per loop In [14]: %timeit count_Trues(new_b_List) 100 loops, best of 3: 1.33 ms per loop
unknown
d11453
train
Get the current item or use reset and extract the entire columns indexing by order_id: $result = array_column(current($array), null, 'order_id'); If there could be multiple arrays, then just loop and append: $result = []; foreach($array as $v) { $result += array_column($v, null, 'order_id'); } A: you can use that function //$array is your input array //$mergedArray is the result wanted $mergedArray = array_reduce($array, function($acc, $val) { foreach ($val as $order) { $acc[$order['order_id']] = $order; } return $acc; }, []); you can try it on http://sandbox.onlinephpfunctions.com/ <?php $array = [ 787 => [ 0 => [ "ID" => 1, "vendor_id" => "37", "order_id" => 776], 1 => [ "ID" => 2, "vendor_id" => "37", "order_id" => 787], 2 => [ "ID" => 1, "vendor_id" => "37", "order_id" => 790], ], 734 => [ 0 => [ "ID" => 1, "vendor_id" => "37", "order_id" => 722], 1 => [ "ID" => 2, "vendor_id" => "37", "order_id" => 735], 2 => [ "ID" => 1, "vendor_id" => "37", "order_id" => 734], ], ]; $t = array_reduce($array, function($acc, $val) { foreach ($val as $order) { $acc[$order['order_id']] = $order; } return $acc; }, []); var_dump($t); A: The other answers do not maintain the multi-level structure described as your desired output. The order_id values must be used as first level keys, and the second level keys must be incremented/indexed as they are encountered. This will allow for multiple entries which share the same first level key. foreach() inside of a foreach(): (Demo) $result = []; foreach ($array as $group) { foreach ($group as $row) { $result[$row['order_id']][] = $row; } } var_export($result); array_reduce() with foreach(): (Demo) var_export( array_reduce( $array, function ($carry, $group) { foreach ($group as $row) { $carry[$row['order_id']][] = $row; } return $carry; } ) );
unknown
d11454
train
If you want to integrate over the third dimension using trapz you need to specify the dimension of integration as the third argument. From the MathWorks page for trapz: Q = trapz(Y) Q = trapz(X,Y) Q = trapz(___,dim) You will need to use something like: INTEGRAL = trapz(x, INTEGRAND, 3);
unknown
d11455
train
I think that there is no need of your own ThreadLocal you can use request attributes. @Override public Object afterBodyRead( Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) { var common = ((MyGenericPojo) body).getCommon(); if (common.getRequestId() == null) { common.setRequestId(generateNewRequestId()); } Optional.ofNullable((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .map(ServletRequestAttributes::getRequest) .ifPresent(request -> {request.setAttribute(Common.class.getName(), common);}); return body; } @Override public MyGenericPojo beforeBodyWrite( MyGenericPojo body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { Optional.ofNullable(RequestContextHolder.getRequestAttributes()) .map(rc -> rc.getAttribute(Common.class.getName(), RequestAttributes.SCOPE_REQUEST)) .ifPresent(o -> { Common common = (Common) o; body.setCommon(common); }); return body; } EDIT Optionals can be replaced with RequestContextHolder.getRequestAttributes().setAttribute(Common.class.getName(),common,RequestAttributes.SCOPE_REQUEST); RequestContextHolder.getRequestAttributes().getAttribute(Common.class.getName(),RequestAttributes.SCOPE_REQUEST); EDIT 2 About thread safety 1) standard servlet-based Spring web application we have thread-per-request scenario. Request is processed by one of the worker threads through all the filters and routines. The processing chain will be executed by the very same thread from start to end . So afterBodyRead and beforeBodyWrite guaranteed to be executed by the very same thread for a given request. 2) Your RequestResponseAdvice by itself is stateless. We used RequestContextHolder.getRequestAttributes() which is ThreadLocal and declared as private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal<>("Request attributes"); And ThreadLocal javadoc states: his class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. So I don't see any thread-safety issues into this sulotion. A: Quick answer: RequestBodyAdvice and ResponseBodyAdvice are invoked within the same thread for one request. You can debug the implementation at: ServletInvocableHandlerMethod#invokeAndHandle The way you're doing it is not safe though: * *ThreadLocal should be defined as static final, otherwise it's similar to any other class property *Exception thrown in body will skip invocation of ResponseBodyAdvice (hence the threadlocal data is not removed) "More safe way": Make the request body supports any class (not just MyGenericPojo), in the afterBodyRead method: * *First call ThreadLocal#remove *Check if type is MyGenericPojo then set the common data to threadlocal A: Also I have already answered this thread, but I prefer another way to solve such kind of problems I would use Aspect-s in this scenario. I have written included this in one file but you should create proper separate classes. @Aspect @Component public class CommonEnricher { // annotation to mark methods that should be intercepted @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface EnrichWithCommon { } @Configuration @EnableAspectJAutoProxy public static class CommonEnricherConfig {} // Around query to select methods annotiated with @EnrichWithCommon @Around("@annotation(com.example.CommonEnricher.EnrichWithCommon)") public Object enrich(ProceedingJoinPoint joinPoint) throws Throwable { MyGenericPojo myGenericPojo = (MyGenericPojo) joinPoint.getArgs()[0]; var common = myGenericPojo.getCommon(); if (common.getRequestId() == null) { common.setRequestId(UUID.randomUUID().toString()); } //actual rest controller method invocation MyGenericPojo res = (MyGenericPojo) joinPoint.proceed(); //adding common to body res.setCommon(common); return res; } //example controller @RestController @RequestMapping("/") public static class MyRestController { @PostMapping("/test" ) @EnrichWithCommon // mark method to intercept public MyGenericPojo test(@RequestBody MyGenericPojo myGenericPojo) { return myGenericPojo; } } } We have here an annotation @EnrichWithCommon which marks endpoints where enrichment should happen. A: If it's only a meta data that you copy from the request to the response, you can do one of the followings: 1- store the meta in the request/response header,and just use filters to do the copy : @WebFilter(filterName="MetaDatatFilter", urlPatterns ={"/*"}) public class MyFilter implements Filter{ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setHeader("metaData", httpServletRequest.getHeader("metaData")); } } 2- move the work into the service layer where you can do the cope through a reusable common method, or have it run through AOP public void copyMetaData(whatEverType request,whatEverType response) { response.setMeta(request.getMeta); }
unknown
d11456
train
Remove width and add negative left&right margins for #pagetop. #pagetop { margin: 0 -10px; width: auto; /* default value, just remove width: 100% */ } https://jsfiddle.net/hmv753s4/1/
unknown
d11457
train
The error explains the problem: This may happen if you return a Component instead of <Component /> from render An element should be created from WrappedComponent. HOC likely needs to pass props to it as well: return props.parent.children === undefined || props.parent.children.length === 0 ? ( <Tooltip title="Children of this element does not exist"> <WrappedComponent {...props}> </Tooltip> ) : ( <WrappedComponent {...props}> );
unknown
d11458
train
Instead of fstream fp("flight.dat",ios::binary); write: fstream fp("flight.dat",ios::binary|ios::in|ios::out); P.S.: Encountered Same Problem A minute ago..
unknown
d11459
train
According to this blog you can easily have code-behind. http://www.compiledthoughts.com/2011/01/aspnet-mvc3-creating-razor-view-engine.html Do you need it or not this is for you to decide. I strongly resent answers which starts with "you dont need it..". Every person in the world must have a choice whether to shoot for a moon or shoot himself in the foot. Thats what I think is right. A: There are no code behind files for Razor Views because you don't need them. You are writing the presentation logic using the Razor syntax on the view itself. Razor views simplifies the mixing of raw HTML with dynamic content rendered using Razor syntax so you don't need a separate file. Furthermore there are no such things as Controls or Components in razor views so you don't need to configure them in a separate file.
unknown
d11460
train
This article describes one way of Distributed graph processing with Akka: http://letitcrash.com/post/30257014291/distributed-in-memory-graph-processing-with-akka A: Simply use Akka Remote with some DIYing
unknown
d11461
train
To get table name with list of all column of that table public void getDatabaseStructure(SQLiteDatabase db) { Cursor c = db.rawQuery( "SELECT name FROM sqlite_master WHERE type='table'", null); ArrayList<String[]> result = new ArrayList<String[]>(); int i = 0; result.add(c.getColumnNames()); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { String[] temp = new String[c.getColumnCount()]; for (i = 0; i < temp.length; i++) { temp[i] = c.getString(i); System.out.println("TABLE - "+temp[i]); Cursor c1 = db.rawQuery( "SELECT * FROM "+temp[i], null); c1.moveToFirst(); String[] COLUMNS = c1.getColumnNames(); for(int j=0;j<COLUMNS.length;j++){ c1.move(j); System.out.println(" COLUMN - "+COLUMNS[j]); } } result.add(temp); } } A: Checked, tested and functioning. Try this code: Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null); if (c.moveToFirst()) { while ( !c.isAfterLast() ) { Toast.makeText(activityName.this, "Table Name=> "+c.getString(0), Toast.LENGTH_LONG).show(); c.moveToNext(); } } I am assuming, at some point down the line, you will to grab a list of the table names to display in perhaps a ListView or something. Not just show a Toast. Untested code. Just what came at the top of my mind. Do test before using it in a production app. ;-) In that event, consider the following changes to the code posted above: ArrayList<String> arrTblNames = new ArrayList<String>(); Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null); if (c.moveToFirst()) { while ( !c.isAfterLast() ) { arrTblNames.add( c.getString( c.getColumnIndex("name")) ); c.moveToNext(); } } A: Try adding the schema before the table schema.sqlite_master From SQL FAQ If you are running the sqlite3 command-line access program you can type ".tables" to get a list of all tables. Or you can type ".schema" to see the complete database schema including all tables and indices. Either of these commands can be followed by a LIKE pattern that will restrict the tables that are displayed. From within a C/C++ program (or a script using Tcl/Ruby/Perl/Python bindings) you can get access to table and index names by doing a SELECT on a special table named "SQLITE_MASTER". Every SQLite database has an SQLITE_MASTER table that defines the schema for the database. The SQLITE_MASTER table looks like this: CREATE TABLE sqlite_master ( type TEXT, name TEXT, tbl_name TEXT, rootpage INTEGER, sql TEXT ); A: Try this: SELECT name FROM sqlite_master WHERE type = "table"; A: Change your sql string to this one: "SELECT name FROM sqlite_master WHERE type='table' AND name!='android_metadata' order by name" A: I tested Siddharth Lele answer with Kotlin and Room, and it works as well. The same code but using Kotlin and Room is something like that: val cursor = roomDatabaseInstance.query(SimpleSQLiteQuery("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('android_metadata', 'sqlite_sequence', 'room_master_table')")) val tableNames = arrayListOf<String>() if(cursor.moveToFirst()) { while (!cursor.isAfterLast) { tableNames.add(cursor.getString(0)) cursor.moveToNext() } }
unknown
d11462
train
Simply: def foo(names: (String, String)*) = names.foreach(println) val folks = Map("john" -> "smith", "queen" -> "mary") foo(folks.toSeq:_*) // (john,smith) // (queen,mary) Where _* is a hint to compiler. A: Oh found the answer e.g. route(FakeRequest(POST, "/wharever/do").withFormUrlEncodedBody(data.toList: _*)) or route(FakeRequest(POST, "/wharever/do").withFormUrlEncodedBody(data.toSeq: _*)) or route(FakeRequest(POST, "/wharever/do").withFormUrlEncodedBody(data.toArray: _*))
unknown
d11463
train
Yes. Use a built-in script engine. Assuming you have a dataset DS and a field FIELD_NAME then instead of [DS."FIELD_NAME"] you should write [IIF(<DS."FIELD_NAME"> = 0, '-', <DS."FIELD_NAME">)] as your frxMemoView text.
unknown
d11464
train
Try the below code: * *Define your custom delegating handler by creating a new class that derives from DelegatingHandler and overrides its SendAsync method public class AuthHeaderHandler : DelegatingHandler { private readonly string _authToken; public AuthHeaderHandler(string authToken) { _authToken = authToken; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _authToken); return await base.SendAsync(request, cancellationToken); } } *Next, register the HttpClient and its associated delegating handler in the service collection. You can do this in the ConfigureServices method of your startup class. public void ConfigureServices(IServiceCollection services) { // Register the AuthHeaderHandler with the service collection services.AddTransient<AuthHeaderHandler>(sp => new AuthHeaderHandler(Configuration["AuthToken"])); // Register the HttpClient with the AuthHeaderHandler services.AddHttpClient("MyHttpClient").AddHttpMessageHandler<AuthHeaderHandler>(); // Add other services and dependencies as needed... } *Inject the HttpClient into your class or service using constructor injection. public class MyController : Controller { private readonly HttpClient _httpClient; public MyController(IHttpClientFactory httpClientFactory) { _httpClient = httpClientFactory.CreateClient("MyHttpClient"); } // Use the _httpClient instance to send HTTP requests... }
unknown
d11465
train
If my assumptions are correct, you're looking for this: SELECT A.StudentName, EC1,EC2,EC3,EC4,EC5,Total, case when failures > 6 or subjects > 2 then 'Failure' else 'Pass' end as Result FROM ( SELECT StudentName, EC1, EC2, EC3, EC4, EC5 FROM Student PIVOT(sum(Marks) for subject in([EC1],[EC2],[EC3],[EC4],[EC5]))as pt) A, ( select studentName, sum(case when Marks < 30 then 30 - Marks else 0 end) as failures, sum(case when Marks < 30 then 1 else 0 end) as subjects, sum(marks) as total from student group by studentname ) B where A.StudentName = B.StudentName Which is pretty close to the answer in your previous question SQL Fiddle Edit: Added the check for 2 subjects, although the test data does not contain any cases like that. A: I took a slightly different approach to this problem. If you add two columns to your table - "GraceMarks" (int) and Pass (bit), you can do this with a number of sequential and logical update queries and a simple select in the end. I had this in a table called "test", but you can change this of course to "student". -- Find if students passed or failed the year -- Assume students are all intitally flagged to Pass, and gracemarks are zero. update test SET Pass=1, GraceMarks=0 -- First, any mark <=23 is a fail update test SET Pass=0 where Mark<=23 -- if a student failed one subject, they fail them all update test SET Pass=0 where StudentID in ( SELECT StudentID from dbo.test where Pass=0) -- Next work out how many grace marks would be needed to pass each subject update test SET GraceMarks=30-Mark where Mark<30 and Pass=1 -- If a student used more that a total of 6 grace marks, they failed too update test SET Pass=0 where StudentID in ( SELECT StudentID FROM dbo.Test GROUP BY StudentID HAVING (SUM(GraceMarks) > 6)) -- If they used grace marks in 3 or more subjects ... fail update test SET Pass=0 where StudentID in ( SELECT StudentID FROM dbo.Test WHERE (GraceMarks > 0) GROUP BY StudentID HAVING (COUNT(GraceMarks) > 2)) -- Now show results select StudentID, StudentName, sum(case course when 'EC1' then mark end) as EC1, sum(case course when 'EC2' then mark end) as EC2, sum(case course when 'EC3' then mark end) as EC3, sum(case course when 'EC4' then mark end) as EC4, sum(case course when 'EC5' then mark end) as EC5, SUM(mark) as totalMark, CASE Pass WHEN 0 THEN 'Fail' ELSE 'Pass' END AS YearPassorFail from dbo.Test group by StudentID, StudentName, CASE Pass WHEN 0 THEN 'Fail' ELSE 'Pass' END order by StudentName The output of this code is this table -- 3 Abhi 40 38 35 45 37 195 Pass 6 Harish 60 64 26 28 29 207 Fail 4 Priya 60 49 26 29 44 208 Pass 2 Savita 50 55 28 30 60 223 Pass 5 Shanthi 70 19 45 44 50 228 Fail You could add an additional column called "reason" and change the queries above to include the reason why they failed (Harish because 3 subjects <30 or needing 7 grace marks, Shanthi because one subject below 24). The advantage of this approach is that you can see what is happening at each step, and you have a record of the Pass/Fail and grace marks used. You could then write queries finding out things like - how many grace marks were used? Who would have failed if the grace marks were only allowed at 3? etc. I also personally like lots of simple steps than one huge complex one, but that might just be me.
unknown
d11466
train
How about this: maxLen := -1; for I := 0 to Len(A) - 1 do if Len(A[I]) > maxLen then // (1) for J := 0 to Len(A[I]) do for K := 0 to Len(A[I]) - J do if J+K > maxLen then // (2) begin prf := LeftStr(A[I], J); suf := RightStr(A[I], K); found := False; for m := 0 to Len(sufList) - 1 do if (sufList[m] = suf) and (prfList[m] = prf) then begin maxLen := J+K; Result := prf+'/'+suf; found := True; // (3) n := 0; while n < Len(sufList) do if Len(sufList[n])+Len(prfList[n]) <= maxLen then begin sufList.Delete(n); prfList.Delete(n); end else Inc(n); // (end of 3) Break; end; if not found then begin sufList.Add(suf); prfList.Add(prf); end; end; In this example maxLen keeps sum of lengths of longest found prefix/suffix so far. The most important part of it is the line marked with (2). It bypasses lots of unnecessary string comparisons. In section (3) it eliminates any existing prefix/suffix that is shorter than newly found one (winch is duplicated).
unknown
d11467
train
The @ prefix allows you to use reserved words like class, interface, events, etc as variable names in C#. So you can do int @int = 1 A: event is a C# keyword, the @ is an escape character that allows you to use a keyword as a variable name. A: Try and make a variable named class and see what happens -- You'll notice you get an error. This lets you used reserved words as variable names. Unrelated, you'll also notice strings prefixed with @ as well -- This isn't the same thing... string says = @"He said ""This literal string lets me use \ normally and even line breaks""."; This allows you to use 'literal' value of the string, meaning you can have new lines or characters without escapes, etc...
unknown
d11468
train
We've recently had this exact situation occur in one of our DNN sites. It turn out that one of the site's administrators had accidentally renamed the Admin page from within the "Page Management" section (it's easy to see how that could happen). The fix was to go directly to /Admin/Pages.aspx and change the "Page Name" back to "Admin" ... and it will show up in the ribbon bar again. As a suggestion to DNN developers, I would recommend making the Admin page and its subpages impossible to rename.... A: Can you check the database to see if those pages exist? What if you try to navigate to http://website/admin.aspx do you see the admin page and all the child pages there?
unknown
d11469
train
Try to apply the formatting using a defined style. See if that makes a difference. A: You might try turning automatic pagination off while adding the lines, to see if that helps. Application.Options.Pagination = False
unknown
d11470
train
Assuming that your vendor's standard library uses the pthread_cond_* functions to implement C++11 condition variables (libstdc++ and libc++ do this), the pthread_cond_* functions are not async-signal-safe so cannot be invoked from a signal handler. From http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cond_broadcast.html: It is not safe to use the pthread_cond_signal() function in a signal handler that is invoked asynchronously. Even if it were safe, there would still be a race between the test of the Boolean pthread_cond_wait() that could not be efficiently eliminated. Mutexes and condition variables are thus not suitable for releasing a waiting thread by signaling from code running in a signal handler. If you're comfortable using semaphores, sem_post is designated async-signal-safe. Otherwise, your options for signal handling are the usual ones: the classic self-pipe, a signal handling thread blocked on sigwait/sigwaitinfo, or platform-specific facilities (Linux signalfd, etc.).
unknown
d11471
train
Because in both cin >> test and cout << test, two arguments exist. cin is of type istream. cout is of type ostream. These types could be other things than cout and cin. For example, they could be cerr, clog, or stringstream. That's why you need two arguments, since the one is the variable for the stream and the other is the object to be streamed. A: cin >> test; Here, left operand is the cin object of type std::istream, and the right operand is your CTest class object. Prototype of >> operator friend istream& operator >> (istream& s, Your class &); So, internally we have passed two arguments. A: In order to get a better understanding where the two arguments come from, you may rewrite your main() function as follows: int main() { CTest test; operator>>(std::cin, test); operator<<(std::cout, test); }
unknown
d11472
train
What programmer do you use? The brand new microcontroler might have lower clock than your previous one and it might be to slow for your programmer. Try decreasing your programmer bitclock (-B option of avrdude). It should be 4 times slower than the clock. Then you can change microcontroller fuses and use the programmer with the old bitclock.
unknown
d11473
train
Why would you want to add a get parameter to each view while the request already contains the user? Also you should probably use the middleware layer to log user actions. A: I don't think you would have to change anything except the templates for this. If your existing url like http://server/myapp/view1 then accessing an url like this http://server/myapp/view1?username=foo will also work. So your existing views will work as is. However, you will have to change templates that renders the links as per new scheme. For example for above view if you are doing {% url 'view1' %} to get a link, then you will have to change it to {% url 'view1'%}?username={{user}}.
unknown
d11474
train
If I understand correctly, you are trying to migrate your js code to its own file to be able to toggle your elements display. The elements onclick method takes in a function to execute when the event is triggered. What we will have to do is build a function in a JS file, import that file into our markup, and then we can reference our new function in our markup in the elements onclick. function showBox(){ document.getElementById("box1")style.display = 'block'; } function hideBox(){ document.getElementById("box1")style.display = 'none'; } #box1 { position: absolute; top: 10px; left: 10px; width: 260px; height: 260px; background: #E2E2E2; padding: 20px; display: none; } <script src="/path/to/lang-js.js" /> <ul onclick="showBox()" class="btn-menu">pop-out Interface</ul> <h2>More Page Content...</h2> <ul id="box1"> <li><a href="#" >Homes</a></li> A: Here's some code that will toggle a panel off/on when you click a menu button. Hope it helps you out. It uses a data-attribute to coordinate what menu button reveals which panel. // grab all the menu buttons const menuButtons = document.querySelectorAll('.btn-menu'); // attach a click event to each button menuButtons.forEach(button => button.addEventListener('click', toggleButton, false)); function toggleButton() { // get the data-id from the clicked element const id = this.dataset.id; // pick up the panel element with that id const panel = document.getElementById(id); if (panel.style.display === 'block') { panel.style.display = 'none'; } else { panel.style.display = 'block'; } } .panel { top: 20px; left: 10px; width: 100px; height: 20px; background: #E2E2E2; padding: 20px; display: none; } <ul data-id="box1" class="btn-menu">pop-out Interface</ul> <ul data-id="box2" class="btn-menu">pop-out Interface 2</ul> <h2>More Page Content...</h2> <ul id="box1" class="panel"> <li><a href="#">Homes</a></li> </ul> <ul id="box2" class="panel"> <li><a href="#">Gardens</a></li> </ul>
unknown
d11475
train
Sure, in Hero.h add: @property (nonatomic, retain) NSArray *walkingFrames; Then, in your +(id)hero method, instead of declaring a new array NSArray *heroWalkingFrames, use: +(id)hero { //Setup the array to hold the walking frames NSMutableArray *walkFrames = [NSMutableArray array]; //Load the TextureAtlas for the hero SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"]; //Load the animation frames from the TextureAtlas int numImages = (int)heroAnimatedAtlas.textureNames.count; for (int i=1; i <= numImages/2; i++) { NSString *textureName = [NSString stringWithFormat:@"hero%d", i]; SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName]; [walkFrames addObject:temp]; } //We set hero texture to the first animation texture: Hero *hero = [Hero spriteNodeWithTexture:walkFrames[0]]; // Set the hero property "walkingFrames" hero.walkingFrames = walkFrames; hero.name =@"Hero"; hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size]; hero.physicsBody.categoryBitMask = heroCategory; hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory; return hero; }
unknown
d11476
train
This works for me: class IconTextField: UITextField { @IBOutlet weak var view: UIView! @IBOutlet weak var test: UIButton! required init(coder: NSCoder) { super.init(coder: coder) NSBundle.mainBundle().loadNibNamed("IconTextField", owner: self, options: nil) self.addSubview(view) assert(test != nil, "the button is conected just like it's supposed to be") } } Once loadNibNamed:owner:options: is called the view and test button are connected to the outlets as expected. Adding the nib's view self's subview hierarchy makes the nib's contents visible. A: I prefer to load from nib, by implementing loadFromNib() function in a protocol extension as follows: (as explained here: https://stackoverflow.com/a/33424509/845027) import UIKit protocol UIViewLoading {} extension UIView : UIViewLoading {} extension UIViewLoading where Self : UIView { // note that this method returns an instance of type `Self`, rather than UIView static func loadFromNib() -> Self { let nibName = "\(self)".characters.split{$0 == "."}.map(String.init).last! let nib = UINib(nibName: nibName, bundle: nil) return nib.instantiateWithOwner(self, options: nil).first as! Self } } A: You can use this: if let customView = Bundle.main.loadNibNamed("MyCustomView", owner: self, options: nil)?.first as? MyCustomView { // Set your view here with instantiated customView }
unknown
d11477
train
Your command is well formed, and it isn't an escape code issue. Likely you are hitting a UAC / privilege issue. If you really want to go down this path rather than using the .NET registry API, I recommend you try the explicit form of creating a ProcessStartInfo and use Verb "runas" to get elevated privs. processStartInfo.UseShellExecute = true; processStartInfo.Verb = "runas"; The sure way to find out is to redirect IO and see what the process / shell is saying. processStartInfo.RedirectStandardInput = true; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; var child = Process.Start(processStartInfo); You'll need to read from stderr / stdout (start a thread, or just for this case do it synchronously) var sb = new StringBuilder(); while ((nRead = child.StandardError.Read(buffer, 0, BUFSIZE)) > 0) for (int n = 0; n < nRead; n++) sb.Append(buffer[n]); Console.WriteLine(sb.ToString()); A: Try using the Registry class. Even if you - for whatever reason - must use Process.Start it will help you debug your issue. string key = @"HKCR\CLSID\{323CA680-C24D-4099-B94D-446DD2D7249E}\ShellFolder"; string valueName = "Attributes"; string value ="0xA0900100"; Microsoft.Win32.Registry.SetValue(key, valueName, value, Microsoft.Win32.RegistryValueKind.String);
unknown
d11478
train
If anyone is looking for an answer; or at least the solution that I used: parse_git_branch () { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/[\1]/' } modified () { git status 2> /dev/null | grep -q modified } untracked () { git status 2> /dev/null | grep -q Untracked } clean () { git status 2> /dev/null | grep -q clean } NO_COLOR="\033[0m" GREEN="\033[0;32m" YELLOW="\033[0;33m" RED="\033[0;31m" set_color () { if untracked ; then echo -e $RED elif modified ; then echo -e $YELLOW elif clean ; then echo -e $GREEN else echo -e $NO_COLOR fi } PS1="\u:\w\$(set_color)\$(parse_git_branch)$NO_COLOR> " The main difference between the code in the question and this one is that I did add the -e flag to echo, and removed the \'s from the color variables. Hope this helps someone EDIT After receiving a bit more feedback, here is what this looks like now: parse_git_branch () { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/[\1]/' } no_color="\033[0m" green="\033[0;32m" yellow="\033[0;33m" red="\033[0;31m" set_color () { case "$(git status 2> /dev/null)" in *Untracked*) printf '%b' "$red";; *modified*) printf '%b' "$yellow";; *clean*) printf '%b' "$green";; *) printf '%b' "$no_color";; esac } PS1="\u:\w\$(set_color)\$(parse_git_branch)$no_color> " All of this came from @Charles Duffy. The only thing I did not incorporate was using tput to get the color escape sequences.
unknown
d11479
train
It takes some time for website to show the latest version, but it also takes some time for npm show <package-name> From my experience I haven't noticed difference between the command and between the website. You should also receive email. I recommend waiting a few minutes. A: The npm website takes time to show the latest packages or package versions because of the delays in CDN, website cache etc. But it will show up eventually. Meanwhile, you can check for the package with: npm show <package-name> This will output all the versions of the package as well so you can be confident that the package exists or the latest version is published. Your package now shows up correctly in npm website at https://www.npmjs.com/package/and-or-search
unknown
d11480
train
The solution to the above problem was to create an object to use focus() and to add the jQquery cookie plug-in. The change is below: "$.cookie("inputFocus").focus();" to "$($.cookie("inputFocus")).focus()" Added the below code to the page: ""
unknown
d11481
train
I reached out to a contact I have at Google. They recommended that you can pass the list that is passed to ParallelFor to set_display_name for each 'iteration' of the loop. When the pipeline is compiled, it'll know to set the corresponding iteration. # Create component that returns a range list model_list_op = model_list(n_models) # Parallelize jobs ParallelFor(model_list_op.outputs["model_list"], parallelism=100) as x: x.set_display_name(str(model_list_op.outputs["model_list"]))
unknown
d11482
train
I didn't try it but maybe it can help you. If it's way to find out if swagger is running and when yes you can dynamically set System.setProperty("server.servlet.context-path", "/"); SpringApplication.run(Application.class, args); But as I said I didn't test and maybe this is stupid. Anyway I will try to test some solutions and I will write you
unknown
d11483
train
Read file and store in JS object. const obj = JSON.parse(fs.readFileSync(userInfoFile)); Change whatever you want to change. obj.ifRegenerateQR = false; Write obj back to file. fs.writeFile(JSON.stringify(obj));
unknown
d11484
train
You can't access another java process classloader class definitions. See this question for how to load a jar properly : How to load a jar file at runtime Once your jar is loaded, you can use Class.forName to access the second jar desired class EDIT : Here is a little snippet to help you read process standard output. //open a buffered reader on process std output InputStreamReader ir = new InputStreamReader(theProcess1.getInputStream()); BufferedReader in = new BufferedReader(ir); //read it line per line String line; while ((line = in.readLine()) != null) { System.out.println(line); }
unknown
d11485
train
The compiler is telling you that it could not figure out the type of the first argument to std::bind. If you look at io_service::run, you will see that it is overloaded. The compiler had a choice, and this is a possible reason for the compiler not figuring out the type. To test this, you can use a cast: std::bind(static_cast<size_t (boost::asio::io_service::*)()>(&boost::asio::io_service::run), &io) This way makes the choice explicit in the code. With a modern compiler, you don't need to use bind at all. You can do something like this: [&]() { io.run(); } That avoids all the problems with the std::bind template. You need to consider variable lifetime and copies vs. references.
unknown
d11486
train
Turns out writing my own instances for (Jab record) fixed this issue. This is how I fixed it, for reference: * *Removing the Eq, Show and Read from the deriving clause of Jab *Making my own Eq, Show and Read instances for (Jab record) *After that compiled I had to consequently make a PersistField instance for (Bar record) (The following is all put in a separate file to be imported to Models.hs) module Custom.TypesAndInstances where import ClassyPrelude.Yesod import Prelude (read) import qualified Data.Text as T import qualified Text.Read.Lex as L import Text.ParserCombinators.ReadPrec import GHC.Read import GHC.Show (appPrec) -- instance for PersistField (Bar record) instance (PersistEntity record, PersistField record) => PersistField (Bar record) where toPersistValue = PersistText . T.pack . show fromPersistValue (PersistText t) = Right $ read $ T.unpack t -- instances for Jab Eq, Read and Show instance PersistEntity record => Eq (Jab record) where Jab x a == Jab y b = x == y && a == b instance PersistEntity record => Show (Jab record) where show (Jab x a) = "Jab " ++ show x ++ " " ++ show a instance PersistEntity record => Read (Jab record) where readPrec = parens (prec appPrec (do expectP (L.Ident "Jab") x <- step readPrec y <- step readPrec return (Jab x y)) ) readListPrec = readListPrecDefault readList = readListDefault ---------------------- data Bar record = Bar { a :: [Jab record] } deriving (Eq, Show, Read, Typeable) data Jab record = Jab { b :: Key record , c :: Int } deriving (Typeable)
unknown
d11487
train
Assuming you're trying to avoid picking up anything where there isn't a short name... var persons = from person in xmlDoc.Descendants("Table") let shortNameElement = person.Element("SHORTNAME") where shortNameElement != null && shortNameElement.Value.Contains("123") select new { shortName = person.Element("SHORTNAME").Value, longName = person.Element("LONGNAME").Value, address = person.Element("ADDRESS").Value, Phone = person.Element("PHONE") != null ? person.Element("PHONE").Value : "", zip = person.Element("ZIPCODE") != null ? person.Element("ZIPCODE").Value : "", }; Alternatively, you can use the null coalescing operator to make all of these a bit simpler: var emptyElement = new XElement("ignored", ""); var persons = from person in xmlDoc.Descendants("Table") where (person.Element("SHORTNAME") ?? emptyElement).Value.Contains("123") select new { shortName = person.Element("SHORTNAME").Value, longName = person.Element("LONGNAME").Value, address = person.Element("ADDRESS").Value, Phone = (person.Element("PHONE") ?? emptyElement).Value zip = (person.Element("ZIPCODE") ?? emptyElement).Value }; Or alternatively, you could write an extension method: public static string ValueOrEmpty(this XElement element) { return element == null ? "" : element.Value; } and then use it like this: var persons = from person in xmlDoc.Descendants("Table") where person.Element("SHORTNAME").ValueOrEmpty().Contains("123") select new { shortName = person.Element("SHORTNAME").Value, longName = person.Element("LONGNAME").Value, address = person.Element("ADDRESS").Value, Phone = person.Element("PHONE").ValueOrEmpty(), zip = person.Element("ZIPCODE").ValueOrEmpty() }; A: Use the null coalescing operator: Phone = person.Element("PHONE") ?? String.Empty;
unknown
d11488
train
Resolved this by copying over the respective dll file from the server.
unknown
d11489
train
In trying to create minimal sample data that would replicate the error, I managed to figure out the cause. There were some replicates in my data frame with only one value for time.var (the time series had just one time point). This was flagged by the function check_multispp(), which is supposed to check whether the time series has more than one species, but the error message was slightly misleading.
unknown
d11490
train
If you want to be flexible and e.g. add some easing at beginning and end but still finish within a fixed duration I would do it like this (I'll just assume here that your calculating the final rotation is working as intended) // Adjust the duration via the Inspector [SerializeField] private float duration = 5f; private IEnumerator RotateRoutine() { // calculate these values only once! // store the initial rotation var startRotation = tr.rotation; // Calculate and store your target ratoation var planetToCountry = (Destination.localPosition - Vector3.zero); var planetToCamera = (camTr.position - tr.position); var a = Quaternion.LookRotation(planetToCamera); var b = Quaternion.LookRotation(planetToCountry); b = Quaternion.Inverse(b); var targetRotation = a * b; if(duration <= 0) { Debug.LogWarning("Rotating without duration!", this); } else { // track the time passed in this routine var timePassed = 0f; while (timePassed < duration) { // This will be a factor from 0 to 1 var factor = timePassed / duration; // Optionally you can alter the curve of this factor // and e.g. add some easing-in and - out factor = Mathf.SmoothStep(0, 1, factor); // rotate from startRotation to targetRotation via given factor tr.rotation = Quaternion.Slerp(startRotation, targetRotation, factor); // increase the timer by the time passed since last frame timePassed += Time.deltaTime; // Return null simply waits one frame yield return null; } } // Assign the targetRotation fix in order to eliminate // an offset in the end due to time imprecision tr.rotation = targetRotation; Debug.Log("Destination reached"); } A: So the problem here is the t used on your Quaternion.Slerp method, it's constant. This t is the "step" the slerp will do, so if it's contstant, it won't depend on time, it will depend on distance. Try instead to do something like this, being timeToTransition the time you want that every rotation will match: public IEnumerator RotatintCoroutine(float timeToTransition) { float step = 0f; while (step < 1) { step += Time.deltaTime / timeToTransition; //...other stuff tr.rotation = Quaternion.Slerp(tr.rotation, newRotation, step); //...more stuff if you want yield return null; } } Edit: addapted to your code should look like this float timeToFly = 5f; while (!DestinationReached) { step += Time.deltaTime / timeToTransition; Vector3 planetToCountry = (Destination.localPosition - Vector3.zero);//.normalized; //vector that points from planet to country Vector3 planetToCamera = (camTr.position - tr.position).normalized; //vector that points from planet to camera/plane Quaternion a = Quaternion.LookRotation(planetToCamera); Quaternion b = Quaternion.LookRotation(planetToCountry); b = Quaternion.Inverse(b); newRotation = a * b; tr.rotation = Quaternion.Slerp(tr.rotation, newRotation, step); if (step >= 1) //if here the plane has arrived { Debug.Log("Destination reached"); DestinationReached = true; } yield return null(); }
unknown
d11491
train
Instead of setting .attr('onclick', you can bind into the event handler directly: $('#mktFrmSubmit').click(function () { doSomething(); alert('hi'); } $('#mktFrmSubmit').click(function () { alert('We can also bind to .click multiple times, and it adds events'); // Instead of just overwriting them } Now clicking #mktFrmSubmit will fire both those click handlers. A: this.onclick is returning the function onclick(event) {... To accomplish what you want, use this: $(document).ready(function(){ $("#mktFrmSubmit").attr ("onclick", function() { _gaq.push(['_trackEvent', 'Whitepaper Campaign', 'Submit Button','conceptshareexample.pdf']); formSubmit(document.getElementById("TESTForm_1001")); return false; }); });
unknown
d11492
train
Change this: onclick="deleteRow(deleteRow(<?php echo $row->aic ?>))"> to onclick="deleteRow(<?php echo $row->aic ?>)"> Another potential issue is that this: <?php echo $row->aic ?> may not be a number. So, you need to quote it. That is, change: onclick="deleteRow(<?php echo $row->aic ?>)"> to: onclick="deleteRow(\"<?php echo $row->aic ?>\")"> A: 2 issues - * *The one that might be causing issue - Incorrect Function Name *Other one - Calling deleteRow() twice - within each other (this should not cause any issue though) So, just change - function eliminaProdotto(rowID) to - function deleteRow(rowID) Edit: Based on modified question - Is $row->aic a string? If yes, then add quotes around it... onclick="deleteRow('<?php echo $row->aic ?>')"
unknown
d11493
train
Set header Content-Type: application/json. A: Set header Content-Type: application/json.
unknown
d11494
train
The way git does a merge is that it creates if you will, a patch of the diff between your current branch and the branch you are trying to merge. It then simply applies that patch as a whole to your branch with the commit - Merge "Source Branch" into "Target Branch" This is basically the only new commit that you are having. If you want to revert --D--E--F then you don't revert them individually, but revert this big merge commit. As for the time stamp, yes git will now also give you a merge of the commits themselves in both the branches that you can revert by yourself. So imagine it something like this, Branch 1: A - B - C - - G - H - I Branch 2: D - E - F Merging these together in Branch 1 will give you - Branch 1: A - B - C - D - E - F - G - H - I - J (Here, J = D + E + F) On the other hand, a rebase would give you : Branch 1: A - B - C - G - H - I - J - D* - E* - F* (Here, D* = D's changes) A: If you are on branch master, and execute git merge feature, your history will be changed from this : A--B--C---G--H--I (master) \ \-D--E--F (feature) to this : A--B--C---G--H--I---J (master) \ / \-D--E--F-/ (feature) git will compare the two diffs C vs I and C vs F, and try to build a new commit which combines the changes in these two diffs. git mays ask you to manually solve conflicts if some changes on I overlap some changes in F. git will not modify any of the existing commits, so that, on a shared repo, the other developpers' copy of the repo is not messed up. git merge does not take into account the date of the commit(s) ; it just looks at the succession of commits (the fact that G comes after C in the graph, for example). There is another command, git rebase, which will change the structure of the existing commits, and may force other developpers to do extra work if they want to keep their local copy in sync with the remote server. git rebase is a useful command, but it is generally advised to use it only locally, before you share some modification (e.g. : only use it on modifications which have not yet been git pushed). A: If you merge master branch to feature, it will make a new commit with its log like "Merge branch master to into feature". you won't get history like A-B-C-G-D-H-E-F
unknown
d11495
train
You can get this using GestureDetector.SimpleOnGestureListener. From here you can get the gesture related information as follows :- http://developer.android.com/reference/android/view/GestureDetector.SimpleOnGestureListener.html Here you will get the Methods as follows:- public boolean onScroll (MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) Inside this Method you need to add the distanceX to width of your coloumn view. like TextView_1.setWidth(TextView_1.getWidth()+Integer.parseInt(distanceX)); Hope you will get a clue from here. you can check this link as reference example of gesture detector http://www.androidsnippets.com/gesturedetector-and-gesturedetectorongesturelistener
unknown
d11496
train
you can use HasHSet like this for removing the redudancey list = new ArrayList<String>(new LinkedHashSet<String>(list))
unknown
d11497
train
IE7 and IE6 have a variety of problems with elements that have both float and clear on them. In IE7, using clear on an element with float only clears the float below other floats floated in the same direction. A modified version of the easyclearing fix may do the trick, but don't get your hopes up. See this page for details: New clearing method needed for IE7?. Bottom line is that you're probably not going to get this to work in IE6/7 without cheating: moving the div down in the text, embedding the divs in paragraphs, etc. A: I'm fairly sure this is one of those rare bugs in ie6 that doesn't have a pure CSS solution. Try using the ie7 javascript - it may fix the problem for you: http://code.google.com/p/ie7-js/
unknown
d11498
train
I know that Github have a diff expression who let you do something like this : https://gist.github.com/salmedina/ad8bea4f46de97ea132f71b0bca73663#file-markdowndiffexample-md But I thinks that there is no such way to do what your want in Markdown. Regards.
unknown
d11499
train
You could add initialization blocks for your trigger values? I don't know about what SubSystem0 looks like inside, but its output could use an initialization block as well, this way you guarantee that you have an input to Subsystem
unknown
d11500
train
You just need a space between unary_! and the : def unary_! : Boolean = ifThenElse(False,True) Alternatively, as pointed out by hezamu in the comments you can use parentheses (with or without the space) def unary_!(): Boolean = ifThenElse(False,True) This will work although it is worth noting that there is a convention in Scala that parentheses on a no-args method indicate that it has side effects which is not the case here. A third option where the return type can be inferred by the compiler (as is the case in this example) is to omit the return type entirely: def unary_! = ifThenElse(False, True)
unknown