_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d3001
train
If I understand this correctly you are having 2 handlers for navigated event (OnNavigatedFrom and browsers_Navigated). The problem probably is that in OnNavigatedFrom you are calling stream.Close(); so stream.WriteLine will fail the next time it is called since the stream was closed. Try moving stream.Close(); to the application close event and use stream.Flush() after stream.WriteLine.
unknown
d3002
train
what's the best approach to achieving a 'wait' so that parentWindow will know when childWindow has closed? You could use events so the parent window is notified when the child window closes. For instance, there is the Closed event. Window childWindow = new .... childWindow.Closed += (sender, e) => { // Put logic here // Will be called after the child window is closed }; childWindow.Show(); A: I think you can use this: public ShowChild() { childWindow child = new childWindow(); child.Closed += new EventHandler(child_Closed); child.Show(); } void child_Closed(object sender, EventArgs e) { // Child window closed }
unknown
d3003
train
Me.InvokeRequired is checking to see if it's on the UI thread if not it equals True, Me.Invoke is asking for a delegate to handle communication between the diff threads. As for your side note. I typically use an event to pass data - this event is still on the diff thread, but like above you can delegate the work. Public Sub UpdateGrid() 'why ask if I know it on a diff thread Me.Invoke(Sub() 'lambda sub DataGridView1.DataSource = dtResults DataGridView1.Refresh() btnRun.Text = "Run Query" btnRun.ForeColor = Color.Black End Sub) End Sub A: Invoke() makes sure that the invoked method will be invoked on the UI thread. This is useful when you want to make an UI adjustment in another thread (so, not the UI thread). InvokeRequired checks whether you need to use the Invoke() method. A: From the example you posted, the section that needs to update the UI is part of the Invoke logic, while the retrieval of the data can be done on a worker/background thread. If Me.InvokeRequired Then This checks to see if Invoke() is necessary or not. Me.Invoke(New MethodInvoker(AddressOf UpdateGrid)) This guarantees that this logic will run on the UI thread and since it is handling interacting with the UI (grid), then if you tried to run this on a background thread it would not work.
unknown
d3004
train
You need to properly escape the dot. Either regexp_pattern = '[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?' email = string.scan(/#{regexp_pattern}/).flatten.last Or regexp_pattern = /[a-zA-Z0-9!#\$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#\$%&'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/ email = string.scan(regexp_pattern).flatten.last Else, your "\." is parsed by the Ruby engine as a mere . that matches any character but a line break char by the Onigmo regex engine, and you get tripped up in the classical catastrophic backtracking. If you want to reproduce the same behavior in the regex tester as you have in the Ruby code, just remove a backslash before the dots in your pattern.
unknown
d3005
train
Close! string queryStr = "SELECT * FROM TMUser WHERE UserID=@UserID AND Password=@Password"; OleDbConnection conn = new OleDbConnection(_connStr); OleDbCommand cmd = new OleDbCommand(queryStr, conn); cmd.Parameters.AddWithValue("@UserID", UserName.Text); cmd.Parameters.AddWithValue("@Password", encode); The parameters are part of the command object and you use the Parameters.AddWithValue method to set the parameter values to what you have defined in the query string. By the way, you should be using using statements to encapsulate some of your objects, here is what I typically do: using (OleDbConnection conn = new OleDbConnection(_connStr)) using (OleDbCommand = conn.CreateCommand()) { conn.Open(); cmd.CommandText = "SELECT ..."; cmd.Parameters.AddWithValue(...); cmd.ExecuteReader(); //... } That way you don't have to worry about cleaning up resources if something goes wrong inside or closing the connection when you are done.
unknown
d3006
train
You could try and create an empty sheet with the following formula: =QUERY(Purchases_Completed!A2:H, "SELECT B, SUM(H) WHERE C LIKE '%Class%' GROUP BY B LABEL B 'Email', SUM(H) 'Purchased_Classes'") This formula uses QUERY and it calculates the sum of your items which contain the 'Class' keyword for each user. Here is the result using the query: You can learn more about the Google Query Language here.
unknown
d3007
train
If you want to center the text if it is smaller than the container and align it to the left and overflow it when the text is bigger than the container, you can use justify-content: safe center; { display : flex; align-items : center; justify-content : safe center; }
unknown
d3008
train
I was having the same problem and I want to share a hack that worked for me. My app is based on ionic/angular/cordova and the android version was giving me a white screen around 50% the times on pause/resume. When it happened, tapping anywhere on the screen or hitting the back button would make the screen to render again just fine. I added a div tied to a scope variable named random, like this: <body ng-app="starter" id="body"> <div>{{ random }}</div> <ion-nav-view> </ion-nav-view> </body> Then I added a listener inside my app.js to capture the resume event fired by cordova, to then change the random variable and call $apply(), like this: document.addEventListener("resume", function() { angular.element(document.querySelector('#body')).scope().random = Math.random(); angular.element(document.querySelector('#body')).scope().$apply(); }) Since the ion-nav-view takes over the whole screen that div never shows up, but angular doesn't know that and refreshes the page, causing the whole thing to work. (I tried to tie the variable to an invisible element but then angular doesn't refresh the page) I hope this helps someone! A: There seem to be issues around rendering the pages thru PhoneGap and 'Dialog'ing thru Client side FB authentication flow using the JS SDK. If I disable the client side authentication, then the rendering and display of the page works very well, when the app is brought to foreground from background (pause/resume/etc). I am assuming that the page will need to sense that it is being displayed over a mobile device and use the IOS or Androi SDK for client side authentication.. (if/when I get around to testing that, I update the answer - if there is anybody who has any more light to shed, please feel free to embellish). A: If you still say "I am happy for the app to exit every time the home button is entered and then do a full restart when the app is clicked on the mobile." then go for it. @Override protected void onStop(){ super.onStop(); } Try this from where you create activity or from the class which "extends DroidGap".
unknown
d3009
train
You don't have to remove Vim from your machine. Instead, tell your system and your tools to use Sublime Text as default editor. After you have followed that tutorial, which I must point out is part of Sublime Text's documentation, you should have a system-wide subl command that you can use instead of vim. For that, you need to add those lines to your shell configuration file: export EDITOR=subl export VISUAL=subl which will be honoured by basically every CLI program susceptible to open a file in a text editor. You can even add the following for good measure: export GIT_EDITOR=subl
unknown
d3010
train
If you want to invoke the method as object method (foo.vote_up()) then return an object from you immediate function instead of only create a function, and then invoke the method. I think that you're looking for something like: var foo = (function($) { return { vote_up : function () { $(".voteButton").html("Hello jQuery"); } } })(jQuery); foo.vote_up(); Hope this helps,
unknown
d3011
train
This can be done but not easily - someone at the SignalR team must have been trying real hard to make it near impossible to extend the parsing routine. I saw a bunch of JSonSerializer instantiation, instead of feeding the ones already registered in the GlobalConfig. Anyways here's how to do it: On client side, implement IHttpClient. This impelementation will strip out type information from the message envelope. We do NOT need to preserve type info on the envelope, as far as we're concerned one envelope is the same as another. It's the content Type that's important. Plus the envelope for WinRT references WinRT framework that is not compatible with the standard framework. public class PolymorphicHttpClient : IHttpClient { private readonly IHttpClient _innerClient; private Regex _invalidTypeDeclaration = new Regex(@"""?\$type.*?:.*?"".*?SignalR\.Client.*?"",?"); public PolymorphicHttpClient(IHttpClient innerClient) { _innerClient = innerClient; } public Task<IResponse> Get(string url, Action<IRequest> prepareRequest) { url = _invalidTypeDeclaration.Replace(url, ""); return _innerClient.Get(url, prepareRequest); } public Task<IResponse> Post(string url, Action<IRequest> prepareRequest, IDictionary<string, string> postData) { if (postData != null) { var postedDataDebug = postData; //TODO: check out what the data looks like and strip out irrelevant type information. var revisedData = postData.ToDictionary(_ => _.Key, _ => _.Value != null ? _invalidTypeDeclaration.Replace(_.Value, "") : null); return _innerClient.Post(url, prepareRequest, revisedData); } return _innerClient.Post(url, prepareRequest, null); } } You want to start your connection like this on the client side (in my case an appstore app) _hubConnecton.Start(new AutoTransport(new PolymorphicHttpClient(new DefaultHttpClient()))) I wished this was enough, but on the server side, the built in parser is a hot bungled mess, so I had to "hack" it together also. You want to implement IJsonValue. The original implementation creates a new instance of JSonSerializer that does not respect your configuration. public class SerializerRespectingJRaw : IJsonValue { private readonly IJsonSerializer _jsonSerializer; private readonly JRaw _rawJson; public SerializerRespectingJRaw(IJsonSerializer jsonSerializer, JRaw rawJson) { _jsonSerializer = jsonSerializer; _rawJson = rawJson; } public object ConvertTo(Type type) { return _jsonSerializer.Parse<object>(_rawJson.ToString()); } public bool CanConvertTo(Type type) { return true; } } Then you want to create your own parser. Note the reflection hack, you may want to change the type to whatever ver. of SignalR you have. This was also why I said whoever wrote this section must really hate OO, because all of the modules are internals - making them real hard to extend. public class PolymorphicHubRequestParser : IHubRequestParser { private readonly IJsonSerializer _jsonSerializer; private JsonConverter _converter; public PolymorphicHubRequestParser(IJsonSerializer jsonSerializer) { _converter = (JsonConverter) Type.GetType( "Microsoft.AspNet.SignalR.Json.SipHashBasedDictionaryConverter, Microsoft.AspNet.SignalR.Core, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35") .GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public) .Single(_ => !_.GetParameters().Any()) .Invoke(null); _jsonSerializer = jsonSerializer; } private IDictionary<string, object> GetState(HubInvocation deserializedData) { if (deserializedData.State == null) return (IDictionary<string, object>)new Dictionary<string, object>(); string json = ((object)deserializedData.State).ToString(); if (json.Length > 4096) throw new InvalidOperationException("Maximum length exceeded."); JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(_converter); return JsonSerializerExtensions.Parse<IDictionary<string, object>>((IJsonSerializer)new JsonNetSerializer(settings), json); } public HubRequest Parse(string data) { var deserializedInvocation = new JsonNetSerializer().Parse<HubInvocation>(data); var secondPass = new HubRequest() { Hub = deserializedInvocation.Hub, Id = deserializedInvocation.Id, Method = deserializedInvocation.Method, State = GetState(deserializedInvocation), ParameterValues = deserializedInvocation.Args.Select( _ => new SerializerRespectingJRaw(_jsonSerializer, _)) .Cast<IJsonValue>() .ToArray() }; return secondPass; } private class HubInvocation { [JsonProperty("H")] public string Hub { get; set; } [JsonProperty("M")] public string Method { get; set; } [JsonProperty("I")] public string Id { get; set; } [JsonProperty("S")] public JRaw State { get; set; } [JsonProperty("A")] public JRaw[] Args { get; set; } } } Now everything is in place, you wanna start your SignalR service with the following overrides. Container being whatever DI you register with the host. In my case container is an instance of IUnityContainer. //Override the defauult json serializer behavior to follow our default settings instead. container.RegisterInstance<IJsonSerializer>( new JsonNetSerializer(Serialization.DefaultJsonSerializerSettings)); container.RegisterType<IHubRequestParser, PolymorphicHubRequestParser>(); A: I think you're probably best off creating an intermediate type for JSON serialization that contains all of the data you'll need to manually regenerate your concrete type(s). Another option could be to create N methods with different names (not overloaded) for each concrete type that implements MyAbstractClass. Then each method could simply pass its argument through to your Process method which accepts the abstract type. You would have to be careful to call the right hub method with the right type, but it might work. A: Or... you could use the connection Received event instead, returning a string. Then, use JObject to parse it, determine it's type and deserialize it accordingly. A: RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(data); A msgBase = rootObject.A[0]; if (msgBase.CommandName == "RequestInfo") { RootObjectRequestInfo rootObjectRequestInfo = JsonConvert.DeserializeObject<RootObjectRequestInfo>(data); RequestInfo requestInfo = rootObjectRequestInfo.RequestInfo[0]; ConnectionID = requestInfo.ConnectionID; } else if (msgBase.CommandName == "TalkWord") { RootObjectTalkWord rootObjectTalkWord = JsonConvert.DeserializeObject<RootObjectTalkWord>(data); TalkWord talkWord = rootObjectTalkWord.TalkWord[0]; textBoxAll.Text += talkWord.Word + "\r\n"; } A: There is an easy solution, with only a few lines of code, but it requires an ugly reflection hack. The plus side is that this solution works for serialization and deserialization, that is, sending data to client and receiving from it. Using TypeNameHandling.Auto in the client side allows for full polymorphism in both sending and receiving. var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }; GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => JsonSerializer.CreateDefault(settings)); GlobalHost.DependencyResolver.Register(typeof(IParameterResolver), () => new CustomResolver()); class CustomResolver : DefaultParameterResolver { public override object ResolveParameter(ParameterDescriptor descriptor, Microsoft.AspNet.SignalR.Json.IJsonValue value) { var _value = (string)value.GetType().GetField("_value", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(value); var obj = JsonConvert.DeserializeObject(_value, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto }); return obj; } }
unknown
d3012
train
No, the bolded bit changes the meaning of the sentence quite significantly: Finally, dividing a task among multiple workers always involves some amount of coordination overhead; for the division to be worthwhile, this overhead must be more than compensated by productivity improvements due to parallelism. If that was simply "must be more than the productivity improvements..." then you would be right. What the above is saying is that the performance penalty you incur by dividing the tasks among your worker threads (the overhead), must be less than the performance increase you gain by doing it at all. For instance, if your overhead is 10 seconds and your performance gain is only 5 seconds, then parallelising the operation has actually decreased your overall performance. If your overhead is 10 seconds but the performance gain is 50 seconds, you've ended up with a 40 second reduction in the overall execution time (i.e. an improvement). Another way of saying it would be "...this overhead must be offset by the productivity improvements due to parallelism.".
unknown
d3013
train
Firstly, install the moment package via npm: npm install moment --save Secondly change your systemjs config (2 lines): (function (global) { // map tells the System loader where to look for things var map = { 'app': 'app', // 'dist', '@angular': 'node_modules/@angular', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', 'rxjs': 'node_modules/rxjs', 'moment': 'node_modules/moment', <== add this line }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'app': { main: 'main.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' }, 'moment': { main: 'moment.js', defaultExtension: 'js' } <== add this line }; Then you can use it: import * as moment from 'moment'; Typings will be available from node_modules/moment/moment.d.ts
unknown
d3014
train
Move maven local resolver out of plugins.sbt and into build.sbt. If you want that listed plugin to come from the snapshot resolver listed leave that in plugins.sbt otherwise remove that one as well and move to build.sbt.
unknown
d3015
train
It definitely isn't required, but I prefer to do it anyway - we run a ton of application servers and if we didn't disconnect the master process from the DB we'd be holding a lot of connections open for no reason.
unknown
d3016
train
Name the columns explicitly in your SELECT statement, and assign ALIASes to the columns with identical names: SELECT cart.id_col, cart.size AS CartSize, ttbl_product.size AS ProductSize FROM cart INNER JOIN tbl_product ON tbl_product.product_id = cart.product_id WHERE ....... then extract the value for ProductSize from the results. If you don't need the cart size, you can eliminate it from the list of columns return and leave out the ALIAS, as you'll only have a single Size column in the results: SELECT cart.id_col, ttbl_product.size FROM cart INNER JOIN tbl_product ON tbl_product.product_id = cart.product_id WHERE ....... In general, it's a good idea to explicitly name the columns you want in your SELECT statement as it makes it clearer what you're getting back, it will fail sooner if you are trying to get a column that's not there (when the SELECT executes, not when you try to retrieve the column value from the result set), and can lead to better performance if you're only interested in a small-ish subset of the available columns. A: A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name [...] This is a basic feature of the SELECT statement in SQL. Please consult the manual: http://dev.mysql.com/doc/refman/5.0/en/select.html A: Use SQL aliases. For examle: SELECT a.a AS aa, b.a AS ba FROM tbl1 AS a, tbl2 AS b A: Change SELECT * to SELECT [fields] where you manually specify which fields you need. If you only need one then there's nothing left to do. If you need both then you can use an alias for the fields like this: SELECT p.size AS product_size, c.size AS cart_size FROM ... Then they will be available in your array as keys product_size and cart_size. A: Try this: mysql_query("SELECT cart.size as cartsize, tbl_product.size as productsize, ... FROM cart INNER JOIN tbl_product ON tbl_product.product_id = cart.product_id WHERE ...) or die(mysql_error()); But if you don't work on some legacy code you don't want to rewrite completely use PDO instead, like suggested in first the comment. A: Several comments to begin with: * *I suggest to move away from mysql_* as soon as you can *Try not to use the * operator in your select statements As for your question, use an alias for the two columns, I also like to give my tables a simpler alias (makes the query more concise): SELECT t1.id, t1.size AS cart_size, t2.size AS product_size FROM cart t1 INNER JOIN tbl_product t2 ON t1.product_id = t2.product_id Hope this helps.
unknown
d3017
train
Data for memory optimized tables is held in data & delta files. A delete statement will not remove the data from the data file but insert a delete record into the delta file, hence your storage continuing to be large. The data & delta file are maintained in pairs know as checkpoint file pairs (CFPs). Over time closed CFPs are merged based upon a merge policy from multiple CFPs into one merged target CFP. A background thread evaluates all closed CFPs using a merge policy and then initiates one or more merge requests for the qualifying CFPs. These merge requests are processed by the offline checkpoint thread. The evaluation of merge policy is done periodically and also when a checkpoint is closed. You can force merge the files using stored procedure sys.sp_xtp_merge_checkpoint_files following a checkpoint. EDIT Run statement: SELECT container_id, internal_storage_slot, file_type_desc, state_desc, inserted_row_count, deleted_row_count, lower_bound_tsn, upper_bound_tsn FROM sys.dm_db_xtp_checkpoint_files ORDER BY file_type_desc, state_desc Then find the rows with status UNDER CONSTRUCTION and make a note of the lower and upper transaction id. Now execute: EXEC sys.sp_xtp_merge_checkpoint_files 'myDB',1003,1004; where 1003 and 1004 is the lower and upper transaction id. To completely remove the files you will have to ensure that you have to: * *Run Select statement from above *Run EXEC sys.sp_xtp_merge_checkpoint_files from above *Perform a Full Backup *CHECKPOINT *Backup the Log *EXEC sp_xtp_checkpoint_force_garbage_collection; *Checkpoint *Exec sp_filestream_force_garbage_collection 'MyDb' to remove files marked as Tombstone You may need to run steps 3 - 7 twice to completely get rid of the files. See The DBA who came to tea article CFP's go through the following stages: •PRECREATED – A small set of CFPs are kept pre-allocated to minimize or eliminate any waits to allocate new files as transactions are being executed. These are full sized with data file size of 128MB and delta file size of 8 MB but contain no data. The number of CFPs is computed as the number of logical processors or schedulers with a minimum of 8. This is a fixed storage overhead in databases with memory-optimized tables •UNDER CONSTRUCTION – Set of CFPs that store newly inserted and possibly deleted data rows since the last checkpoint. •ACTIVE - These contain the inserted/deleted rows from previous closed checkpoints. These CFPs contain all required inserted/deleted rows required before applying the active part of the transaction log at the database restart. We expect that size of these CFPs to be approximately 2x of the in-memory size of memory-optimized tables assuming merge operation is keeping up with the transactional workload. •MERGE TARGET – CFP stores the consolidated data rows from the CFP(s) that were identified by the merge policy. Once the merge is installed, the MERGE TARGET transitions into ACTIVE state •MERGED SOURCE – Once the merge operation is installed, the source CFPs are marked as MERGED SOURCE. Note, the merge policy evaluator may identify multiple merges a CFP can only participate in one merge operation. •REQUIRED FOR BACKUP/HA – Once the merge has been installed and the MERGE TARGET CFP is part of durable checkpoint, the merge source CFPs transition into this state. CFPs in this state are needed for operational correctness of the database with memory-optimized table. For example, to recover from a durable checkpoint to go back in time. A CFP can be marked for garbage collection once the log truncation point moves beyond its transaction range. •IN TRANSITION TO TOMBSTONE – These CFPs are not needed by in-memory OLTP engine can they can be garbage collected. This state indicates that these CFPs are waiting for the background thread to transition them to the next state TOMBSTONE •TOMBSTONE – These CFPs are waiting to be garbage collected by the filestream garbage collector. Please refer to FS Garbage Collection for details
unknown
d3018
train
First things first: don't encode your SVG as a base64, it is much longer than the original code and its unnecessary as you can just add the code to the url. You might need to URL encode it for IE11 and earlier, but otherwise all browsers support it. Now, to control your sizing in SVG tags, ommit the viewBox and simply give it a width and height of 100% and express all other values in percentage. Now you can control the size of the line by defining its pixel size, even though the points are defined in percentage: div { position: absolute; width: 100%; height: 100%; left: 0%; top: 0%; background: url('data:image/svg+xml;charset=utf8,<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">\ <line x1="0%" y1="50%" x2="100%" y2="50%" stroke="cyan" stroke-width="1px" stroke-dasharray="15px 15px" />\ </svg>') no-repeat 50% 50% / cover; } body { /* A reference grid */ background: url('data:image/svg+xml;charset=utf8,<svg width="15px" height="15px" xmlns="http://www.w3.org/2000/svg">\ <rect x="0" y="0" width="100%" height="100%" stroke="#222" stroke-width="1px" fill="black" />\ </svg>'); } <div></div> Once your SVG is correctly set up, it is as simple as defining the stroke-dasharray property with the pixel values: <line x1="0%" y1="50%" x2="100%" y2="50%" stroke="black" stroke-width="1px" stroke-dasharray="15px 15px" /> Now you can use CSS to change your box, or even SVG to change the offsets within the SVG background.
unknown
d3019
train
You mean image optimization or revisioning? There is no problem to configure GruntFile.js to your own needs. It makes Yeoman/Grunt very powerful, because it is highly adaptable. If you don't want image optimization, remove the configuration in the img task. // Optimizes JPGs and PNGs (with jpegtran & optipng) img: { }, If you dont want the renaming of image files, remove the img line from the rev task: // renames JS/CSS to prepend a hash of their contents for easier // versioning rev: { js: 'scripts/**/*.js', css: 'styles/**/*.css' }, A: If you remove the image revving it will bust your cache, you should try to keep the revving and update your JS files instead. Try updating your usemin block to something like this: usemin: { html: ['<%= yeoman.dist %>/{,*/}*.html'], css: ['<%= yeoman.dist %>/styles/{,*/}*.css'], js: '<%= yeoman.dist %>/scripts/{,*/}*.js', options: { assetsDirs: [ '<%= yeoman.dist %>', '<%= yeoman.dist %>/images', '<%= yeoman.dist %>/styles' ], patterns: { js: [ [/(images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images'] ] } } } You should already have the usemin method, just add the js attribute with you js path regex and add the pattern attribute. This will replace all occurrences of the image in your JS files with the new revved version, so that the clients' browsers don't use a cached image instead of a new one.
unknown
d3020
train
.NET Framework libraries are not technically compatible with .NET Core. .NET Standard libraries are, and since both .NET Framework and .NET Core implement .NET Standard, Microsoft made a special exemption in the compiler to allow .NET Framework libraries to be referenced by projects that target .NET Core, with the caveat that they may not actually work. You get a warning to this effect when you reference a .NET Framework library from a .NET Core project. The .NET Framework library will work as long as it only uses APIs compatible with .NET Standard 2.0. System.Web.HttpContext is not one such API, so it will not work in a .NET Core project. Period. Nothing you can do about that. You can attempt to multi-target your libraries and sub-in .NET Core compatible APIs using compiler directives. That'll work, but gets messy quick. Otherwise, you'll just have to write new versions of the libraries for ASP.NET Core, since presumably you're trying to maintain support in the current libraries for ASP.NET.
unknown
d3021
train
Using this article as a base about copy/paste, you may see that you can only put something to the clipboard but not directly changing the content of a foreign's process Textbox. You might want to get the window handle of the box and send a message to it using the Windows API. This works on windows only, I don't know whether there's an equivalent way on Mac OS / Linux. Maybe this doesn't even work directly from java. You would need to type some C/C++-code and use the Java Native Interface (JNI) regards A: It's a hack, but look into java.awt.Robot. It lets you programmatically make mouse clicks and key presses, among lots of other useful things. So one way to do it would be: * *Use Atmocreations' article to put text in the clipboard *When you want to paste it, use Robot to click at the current position (if you need to give that field focus) *Use Robot to press Ctrl-V (or whatever your system expects for a paste) Like I said, it's not at all a clean solution, but it will work in a pinch. A: If u are asking for the current cursor location, i think u should use this : Display.getCurrent().getCursorLocation() Having the cursor location, what to do next requires further details. If u want to automatically write some text into foreign applications like Word or Notepad, this sounds more like a virus to me..
unknown
d3022
train
Hi have you tried QT for iOS? QT for iOS
unknown
d3023
train
Add a , inside the string after the first Asc. ldv1.Sort = tbl1.Columns(0).ColumnName + " Asc, " + tbl1.Columns(1).ColumnName + " Asc"
unknown
d3024
train
If you want to declare function outside of the JSX then you can do as: <Button onClick={() => changeUser(user)}>{user.name}</Button> Declaration of function function changeUser(user) { setSelectedUser(user); setShowUser(true); }
unknown
d3025
train
I think there is a misunderstanding in the concept of how and which data to retrieve into the activities table. Let me state the differences between the case presented in the other StackOverflow question you linked, and the case you are trying to reproduce: * *In the other question, answers.creation_date refers to a date value that is not fix, and can have different values for a single user. I mean, the same user can post two different answers in two different dates, that way, you will end up with two activities entries like: {[ID:user1, date:2018-01],[ID:user1, date:2018-02],[ID:user2, date:2018-01]}. *In your question, the use of answers.user_dim.first_open_timestamp_micros refers to a date value that is fixed in the past, because as stated in the documentation, that variable refers to The time (in microseconds) at which the user first opened the app. That value is unique, and therefore, for each user you will only have one activities entry, like:{[ID:user1, date:2018-01],[ID:user2, date:2018-02],[ID:user3, date:2018-01]}. I think that is the reason why you are not getting information about the lagged retention of users, because you are not recording each time a user accesses the application, but only the first time they did. Instead of using answers.user_dim.first_open_timestamp_micros, you should look for another value from the ones available in the documentation link I shared before, possibly event_dim.date or event_dim.timestamp_micros, although you will have to take into account that these fields refer to an event and not to a user, so you should do some pre-processing first. For testing purposes, you can use some of the publicly available BigQuery exports for Firebase. Finally, as a side note, it is pointless to JOIN a table with itself, so regarding your edited Standard SQL query, it should better be: #standardSQL WITH activities AS ( SELECT answers.user_dim.app_info.app_instance_id AS id, FORMAT_DATE('%Y-%m', DATE(TIMESTAMP_MICROS(answers.user_dim.first_open_timestamp_micros))) AS period FROM `dataset.app_events_*` AS answers GROUP BY id, period
unknown
d3026
train
you can do that by created a new APP ID specifically for you or your fellow developers and link with the developer profile you create. Else you can also ask for .p12 file that can be exported from machine keychain from which your client first created CSR certificate from. Just you would require to add to it your mac and download the same profile and certificate from apple's developer portal, finally you can install it on your device.
unknown
d3027
train
Setting Message-ID is important for mail thread via phpmailer, you will get the thread id via $this->email->_get_message_id(); append this code to $this->email->set_header('Message-ID', $this->email->_get_message_id()); and your total code will be like $this->email->set_header('References', "CABOvPkdN1ed8NTkph0Ep+ogNaAgW_9R0dR4ZPLTpBn=vc7K7QA@mail.gmail.com"); $this->email->set_header('In-Reply-To', "CABOvPkdN1ed8NTkph0Ep+ogNaAgW_9R0dR4ZPLTpBn=vc7K7QA@mail.gmail.com"); $this->email->set_header('Message-ID', $this->email->_get_message_id()); please get in touch if it is not work :)
unknown
d3028
train
As mentioned here, it may be caused by outdated Composer version, which uses older Symfony's Console Component. So when Composer has previously loaded older version of this class, it's not autoloaded again when your Symfony instance is trying to access this class later in cache:clear command. The solution may be to update your Composer with composer self-update. A: I ran into a similar problem today: We use symfony/console 3.4+ in our project, which tries to load the command-name via getDefaultName. But composer uses internally an older version of symfony/console where this method does not exist, since it was added in v3.4.0. In this case a composer self-update won't help, but you can make sure to add the command to your service-definition like so: services: myvendorname.mypackagename.foo.command: class: MyVendorName\MyPackageName\Command\FooCommand tags: - { name: 'console.command', command: 'foo' } # ^^^^^^^^^^^^^^^^ # This is the important part This will load the name directly from the service definition and does not try to call getDefaultName().
unknown
d3029
train
I also had this error. In my case I am compiling using VS2015 in Windows. First time I choose compile static version of the MySQL lib. Then later I decided to compile the dynamic version. This time the error bad_alloc at memory went off. The solution is rolling back the CPPCONN_PUBLIC_FUNC= configuration. Go to project Property Pages, under C++ > Preprocessor > Preprocessor Definitions and remove the item CPPCONN_PUBLIC_FUNC=". A: I had the same error on linux. The error was : I was using g++-4.8 to build the project The issue lies on the version of the build tools (gcc,msvs,clang) used to build the project
unknown
d3030
train
You insert subview at 0 index, so, I think there are some views which are higher in subviews hierarchy. You can look at your subviews with "Debug View Hierarchy button"
unknown
d3031
train
Can you explain to me the point of a controller when all it does it return a view? Who said that all a controller does is to return a view? A controller does lots of other things. For example it could receive the user input under the form of an action parameters, check whether the ModelState.IsValid, do some processing on the Model and then return a View which is the whole point of the MVC pattern. I've come across a situation when trying to build a rudimentary CMS where the user can create views (stored in the database), but of course as they are user created, the controller's don't exist. So is there another way to serve them? Yes, of course. You could use a custom virtual path provider by implementing the VirtualPathProvider class.
unknown
d3032
train
Tab itself renders a button. So, to prevent nesting a button element inside another, you need to use the as prop on the Tab component: <Tab.List className="flex sm:flex-col"> <Tab as={Fragment}> {({ selected }) => ( <button className={`px-6 py-4 ${ selected ? 'bg-white text-black' : 'bg-red-600 text-white' }`} > Frontend </button> )} </Tab> {/*...*/} </Tab.List> You can also do: <Tab.List className="flex sm:flex-col"> <Tab className={({ selected }) => `px-6 py-4 ${selected ? 'bg-white text-black' : 'bg-red-600 text-white'}` } > Frontend </Tab> {/*...*/} </Tab.List> Reference: https://headlessui.dev/react/tabs#styling-the-selected-tab
unknown
d3033
train
Demo create table user_t ( id bigint ,address array<struct<street:string, city:string, state:string, zip:int>> ) ; insert into user_t select 1 ,array ( named_struct('street','street_1','city','city_1','state','state_1','zip',11111) ,named_struct('street','street_2','city','city_1','state','state_1','zip',11111) ,named_struct('street','street_3','city','city_3','state','state_3','zip',33333) ) union all select 2 ,array ( named_struct('street','street_4','city','city_4','state','state_4','zip',44444) ,named_struct('street','street_5','city','city_5','state','state_5','zip',55555) ) ; Option 1: explode select u.id ,a.* from user_t as u lateral view explode(address) a as details where details.city = 'city_1' ; +----+---------------------------------------------------------------------+ | id | details | +----+---------------------------------------------------------------------+ | 1 | {"street":"street_1","city":"city_1","state":"state_1","zip":11111} | | 1 | {"street":"street_2","city":"city_1","state":"state_1","zip":11111} | +----+---------------------------------------------------------------------+ Option 2: inline select u.id ,a.* from user_t as u lateral view inline(address) a where a.city = 'city_1' ; +----+----------+--------+---------+-------+ | id | street | city | state | zip | +----+----------+--------+---------+-------+ | 1 | street_1 | city_1 | state_1 | 11111 | | 1 | street_2 | city_1 | state_1 | 11111 | +----+----------+--------+---------+-------+ Option 3: self join select u.* from user_t as u join (select distinct u.id from user_t as u lateral view inline(address) a where a.city = 'city_1' ) as u2 on u2.id = u.id ; +----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | id | address | +----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | 1 | [{"street":"street_1","city":"city_1","state":"state_1","zip":11111},{"street":"street_2","city":"city_1","state":"state_1","zip":11111},{"street":"street_3","city":"city_3","state":"state_3","zip":33333}] | +----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
unknown
d3034
train
One idea is you can create two input arrays for the goal+team combo. You could repeat this combo for as many goals as you need. <input type="text" name="teams[]" value="" /> <input type="number" name="goals[]" value="" /> Then when your form submits, you have two arrays: $_POST['teams'] and $_POST['goals']. You can use the index to match teams to goals like: foreach($_POST['teams'] as $key => $team) { echo $team; $goal = $_POST['goals'][$key]; echo $goal; } And process as needed. You can add the form elements dynamically with jQuery like this: http://jsfiddle.net/6G7yB/6/ Hope this helps Edit: You can also do something like this: http://www.php.net/manual/en/reserved.variables.post.php#87650
unknown
d3035
train
I tend to follow a few simple rules... * *There is no single valid reason to ever use a TCM ID in anything - template code, configuration components, configuration files. *If I need webdav URLs in configuration, I try to always make them "relative", usually starting at "/Building%20Blocks" instead of the publication name. At runtime I can use Publication.WebDavUrl or PublicationData.LocationInfo.WebDavUrl to get the rest of the URL *Tridion knows what to do with managed links, so as much as possible, use them. (managed links are the xlink:href stuff you see a bit all over Tridion XML). I also tend to use a "configuration page" for content delivery, with a template that outputs the TCM IDs I may need to "know" from the content delivery application. This is then either loaded at run time as a set of configuration variables or as dictionary or as a set of constants (I guess it depends how I'm feeling that day). A: Although we commonly refer to a Template Type implementation as a Template Mediator, that's not the whole story. A Template Type implementation consists of both a Template Mediator, and a Template Content Handler, although the latter is optional. Whether a given implementation will process "includes" correctly depends not on the mediator but the handler. A good starting point in the documention can be found by searching for AbstractTemplateContentHandler. SDL Tridion's own Dreamweaver Templating implementation has such a handler. I've just looked at the Razor implementation, and it currently makes use of the Dreamweaver content handler. Obviously, YMMV for the various XSLT template type implementations that exist. As this is an extensibility point of SDL Tridion, whether included references will work "correctly" in lower publications depends on the implementer's view of what that would mean. One interesting possibility is to implement your own custom handler that behaves as you wish. The template type configuration (in the Tridion Content Manager configuration file) allows for the mediator and content handler for a given template type to be specified independently, which means you could potentially customise the content handling behaviour for an existing template type.
unknown
d3036
train
we will first convert the timestamp field into integer type if it is not already by any chance. val new_dataframe = dataframe.select($"unixtimestamp".cast(IntegerType).as("unixtimestamp")) 1) Create sqlContext in spark if not exists using the SparkContext object val sqlContext = new org.apache.spark.sql.SQLContext(sc) 2) Register this dataframe as a table new_dataframe.registerTempTable("user_timestamp_data") 3) Now with the prior created sqlContext we can query as val result = sqlContext.sql("SELECT q.user,ROUND(UNIX_TIMESTAMP(q.min)*1000) as MinimumUnixTimeStamp FROM ( select user, MIN(FROM_UNIXTIME(unixtimestamp/1000) min FROM user_timestamp_data GROUP BY user ORDER BY user ASC) AS q ") That should give you users and their corresponding minimum timestamp value A: Use groupBy and agg: val df2 = df.groupBy("user").agg(min(col("unixtimestamp")))
unknown
d3037
train
I had the same problem. This is how I solved it: I set up the UIPageViewController once again (exactly like when we did the first time) in the event of device rotation by adding the following method to UIPageViewController implementation file: -(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration Because most of the time, UIPageViewController is modally presented, so on device rotation, this controller will be called again. A: I also had an app that subclassed UIPageViewController. I had been using it for years but we had always limited it to Portrait mode. I recently began another project that started with this as a base but in this case we DID want to allow landscape modes. The app has a Navigation Controller and a couple of initial screens and then pushes to the PageViewController. The rotations would work with the conventional VC's on the Top of the Navigation Controller but if I tried rotation with the PageViewController displaying, I'd get an exception: 2020-07-24 19:33:01.440876-0400 MAT-sf[68574:12477921] *** Assertion failure in -[MAT_sf.SurveyVC willAnimateRotationToInterfaceOrientation:duration:], /Library/Caches/com.apple.xbs/Sources/UIKitCore_Sim/UIKit-3920.31.102/UIPageViewController.m:1055 2020-07-24 19:33:01.454443-0400 MAT-sf[68574:12477921] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'No view controllers' It turns out that all I had to do was add an override to my subclass: override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) } All it does is call the same function in the superclass. I'm guessing that this should be a required method if you subclass PageViewController. Hope this helps someone. This one cost me about a day of research until I stumbled on the solution. A: Thanks HSH, I had the same problem in Xamarin. I implemented: public override void WillAnimateRotation(UIInterfaceOrientation toInterfaceOrientation, double duration) { } Leaving it empty, prevents it from calling the base method. Which apparently does something that makes it crash. Implementing this override method without calling the base method, works for me. I had a similar exception when changing the orientation quickly. (MonoTouchException) Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: No view controllers Native stack trace: 0 CoreFoundation 0x0000000113e3302e __exceptionPreprocess + 350 1 libobjc.A.dylib 0x0000000114b7cb20 objc_exception_throw + 48 2 CoreFoundation 0x0000000113e32da8 +[NSException raise:format:arguments:] + 88 3 Foundation 0x00000001113a3b61 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 191 4 UIKitCore 0x00000001208b32c6 -[UIPageViewController willAnimateRotationToInterfaceOrientation:duration:] + 3983 5 UIKitCore 0x0000000120960d3e -[_UIViewControllerTransitionCoordinator _applyBlocks:releaseBlocks:] + 294 6 UIKitCore 0x000000012095d060 -[_UIViewControllerTransitionContext __runAlongsideAnimations] + 263 7 UIKitCore 0x000000012148862a +[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:animationStateGenerator:completion:] + 528 8 UIKitCore 0x0000000121488bd9 +[UIView(UIViewAnimationWithBlocks) animateWithDuration:delay:options:animations:completion:] + 99 9 UIKitCore 0x0000000120975276 __58-[_UIWindowRotationAnimationController animateTransition:]_block_invoke_2 + 278 10 UIKitCore 0x000000012148c788 +[UIView(Internal) _performBlockDelayingTriggeringResponderEvents:forScene:] + 174 11 UIKitCore 0x0000000120975004 __58-[_UIWindowRotationAnimationController animateTransition:]_block_invoke + 164 12 UIKitCore 0x000000012148862a +[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:animationStateGenerator:completion:] + 528 13 UIKitCore 0x0000000121488bd9 +[UIView(UIViewAnimationWithBlocks) animateWithDuration:delay:options:animations:completion:] + 99 14 UIKitCore 0x0000000120974edc -[_UIWindowRotationAnimationController animateTransition:] + 491 15 UIKitCore 0x0000000120fefef9 -[UIWindow _rotateToBounds:withAnimator:transitionContext:] + 525 16 UIKitCore 0x0000000120ff293c -[UIWindow _rotateWindowToOrientation:updateStatusBar:duration:skipCallbacks:] + 2331 17 UIKitCore 0x0000000120ff2f2f -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:isRotating:] + 633 18 UIKitCore 0x0000000120ff1e83 -[UIWindow _setRotatableViewOrientation:updateStatusBar:duration:force:] + 119 19 UIKitCore 0x0000000120ff0d00 __57-[UIWindow _updateToInterfaceOrientation:duration:force:]_block_invoke + 111 20 UIKitCore 0x0000000120ff0c29 -[UIWindow _updateToInterfaceOrientation:duration:force:] + 455 21 Foundation 0x0000000111426976 __NSFireDelayedPerform + 420 22 CoreFoundation 0x0000000113d96944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20 23 CoreFoundation 0x0000000113d96632 __CFRunLoopDoTimer + 1026 24 CoreFoundation 0x0000000113d95c8a __CFRunLoopDoTimers + 266 25 CoreFoundation 0x0000000113d909fe
unknown
d3038
train
This cannot be done in Pine. security() requires the symbol parameter to be a fixed string, which doesn't change during script execution. This is the case in your first example. Your second example includes month, which will change during script execution, hence the compiler error.
unknown
d3039
train
You can calculate the average date explicitly by adding half the timedelta between 2 dates to the earlier date. Then just extract the month: # convert to datetime if necessary df[df.columns] = df[df.columns].apply(pd.to_datetime) # calculate mean date, then extract month df['Month'] = (df['FromDate'] + (df['ToDate'] - df['FromDate']) / 2).dt.month print(df) FromDate ToDate Month 0 2016-01-31 2016-03-01 2 1 2016-06-15 2016-07-14 6 2 2016-07-14 2016-08-15 7 3 2016-08-07 2016-09-06 8 A: You need to convert the string to datetime before using dt.month. This line calculates the average month number : df['Month'] = (pd.to_datetime(df['ToDate']).dt.month + pd.to_datetime(df['FromDate']).dt.month)//2 print(df) FromDate ToDate Month 0 1/31/2016 3/1/2016 2 1 6/15/2016 7/14/2016 6 2 7/14/2016 8/15/2016 7 3 8/7/2016 9/6/2016 8 This only works with both dates in the same year. jpp's solution is fine but will in some cases give the wrong answer: ["1/1/2016","3/1/2016"] one would expect 2 because February is between January and March, but jpp's will give 1 corresponding to January.
unknown
d3040
train
self.btClient = BTAPIClient(authorization: tokenizationKey) A tokenization key can only be used for a full Braintree gateway integration. Such an integration requires setting up the new currency, PHP, on the gateway sandbox and later production accounts that you are using for processing. If you want to use the Braintree gateway in production, your business needs to apply and be approved for this. So basically, you need to set up PHP in your gateway interface if you are going to use that new currency with the above integration method. To instead use the Braintree SDK with PayPal more directly (no gateway account), the credential you need to use for authentication first is an access token. Use the access token on your server to obtain a client token, which your client will fetch as needed: https://developers.braintreepayments.com/guides/authorization/client-token A sandbox PayPal Braintree access token can be obtained from the bottom of: https://www.paypal.com/signin?intent=developer&returnUri=https%3A%2F%2Fdeveloper.paypal.com%2Fdeveloper%2Fapplication (For live mode, via https://www.paypal.com/api )
unknown
d3041
train
List the libraries last: gcc -Iinclude -Llib -DDMALLOC main.c -ldmalloc
unknown
d3042
train
PhpStorm does not support multiple independent projects in one window / frame: https://youtrack.jetbrains.com/issue/WI-15187 -- star/vote/comment to get notified on progress. But ... you can list files from another project there (in Project View panel). If that is good enough, then just go to Settings | Directories and add desired folder as an Additional Content Root. P.S. This also means that the setting from current project will be applied to all content roots.
unknown
d3043
train
Yes, they are specified in the annotations in the source code.
unknown
d3044
train
GWT library has very robust SuggestBox component for that. See description and example here: http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/SuggestBox.html Plus, I'd recommend to review a video tutorial how to use it: http://www.rene-pickhardt.de/building-an-autocomplete-service-in-gwt-screencast-part-3-getting-the-server-code-to-send-a-basic-response/ Actually there are set of videos, but suggestion box functionality is described exactly there. Hope this helps.
unknown
d3045
train
If you want to change the position of the custom options then the right place for you to look is in app/diesign/frontend/base/default/layout/catalog.xml First you should copy this file to you theme and edit there(Is the good practice in magento). In this file search for the code snippet as below. <catalog_product_view translate="label"> In this reference handle you will see the blocks <block type="catalog/product_view" name="product.info.addto" as="addto" template="catalog/product/view/addto.phtml"/> <block type="catalog/product_view" name="product.info.addtocart" as="addtocart" template="catalog/product/view/addtocart.phtml"/> Place these two blocks below the blocks which renders the custom options block i.e. <block type="catalog/product_view" name="product.info.options.wrapper" as="product_options_wrapper" template="catalog/product/view/options/wrapper.phtml" translate="label"> <label>Info Column Options Wrapper</label> <block type="core/template" name="options_js" template="catalog/product/view/options/js.phtml"/> <block type="catalog/product_view_options" name="product.info.options" as="product_options" template="catalog/product/view/options.phtml"> <action method="addOptionRenderer"><type>text</type><block>catalog/product_view_options_type_text</block><template>catalog/product/view/options/type/text.phtml</template></action> <action method="addOptionRenderer"><type>file</type><block>catalog/product_view_options_type_file</block><template>catalog/product/view/options/type/file.phtml</template></action> <action method="addOptionRenderer"><type>select</type><block>catalog/product_view_options_type_select</block><template>catalog/product/view/options/type/select.phtml</template></action> <action method="addOptionRenderer"><type>date</type><block>catalog/product_view_options_type_date</block><template>catalog/product/view/options/type/date.phtml</template></action> </block> <block type="core/html_calendar" name="html_calendar" as="html_calendar" template="page/js/calendar.phtml"/> </block> This should do the trick. Hope this will help.
unknown
d3046
train
I believe this is possible using CSS alone, however it is not very scaleable and it might end up being easier and more appropriate to use Javascript for this. For example: img#thumb1:hover ~ #img4>#image4{ display:none; } Your selector here is incorrect. The general sibling selector selects only elements after the first match. In this case, your image thumb is after your image, but this selector is looking for an image after an image thumb. This is the opposite of what you have. There is no 'sibling before' selector in CSS. An easier solution, rather than fiddling around with CSS selectors, would just be to bind each thumbnail to a click event that changes the source of a single image tag each time (or alternatively, scrolls across/fades, whatever animation you're looking for). This way, you save on markup, don't need to worry about positioning as much, and can dynamically generate the image display. For example, to get the ID of an image, you could bind a click event to each thumbnail and then grab the ID of the image which could stored in a data attribute: $('.thumbnail').on('hover', function() { var activeImg = $(this).data('imgid'); // From here, set the main image to have the associated image source } A: This is very possible to achieve with just CSS. The layout of your HTML is what needs to change. In this example: * *Each thumbnail and full-size image is placed inside a div container *The full-size image is hidden with opacity: 0; *When the div container is hovered, the full-size image is given opacity: 1 and will fade-in thanks to the transition *z-index: 1 keeps the full-size images above the thumbnails Full Example .item { float: left; position: relative; } img { display: block; cursor: pointer; margin: 5px; } .fullsize { position: absolute; opacity: 0; transition: opacity 0.6s; z-index: 1; top: 0; left: 0; pointer-events: none; } .item:hover .fullsize { opacity: 1; } <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div> <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div> <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div> <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div> <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div> <div class="item"> <img class="fullsize" src="http://lorempixel.com/output/people-q-c-600-600-9.jpg" /> <img class="thumb" src="http://lorempixel.com/output/people-q-c-200-200-9.jpg" /> </div>
unknown
d3047
train
std::string str("48656c6c6f"); std::string res; res.reserve(str.size() / 2); for (int i = 0; i < str.size(); i += 2) { std::istringstream iss(str.substr(i, 2)); int temp; iss >> std::hex >> temp; res += static_cast<char>(temp); } std::cout << res; A: int len = hex.length(); std::string newString; for(int i=0; i< len; i+=2) { std::string byte = hex.substr(i,2); char chr = (char) (int)strtol(byte.c_str(), null, 16); newString.push_back(chr); } A: Hex digits are very easy to convert to binary: // C++98 guarantees that '0', '1', ... '9' are consecutive. // It only guarantees that 'a' ... 'f' and 'A' ... 'F' are // in increasing order, but the only two alternative encodings // of the basic source character set that are still used by // anyone today (ASCII and EBCDIC) make them consecutive. unsigned char hexval(unsigned char c) { if ('0' <= c && c <= '9') return c - '0'; else if ('a' <= c && c <= 'f') return c - 'a' + 10; else if ('A' <= c && c <= 'F') return c - 'A' + 10; else abort(); } So to do the whole string looks something like this: void hex2ascii(const string& in, string& out) { out.clear(); out.reserve(in.length() / 2); for (string::const_iterator p = in.begin(); p != in.end(); p++) { unsigned char c = hexval(*p); p++; if (p == in.end()) break; // incomplete last digit - should report error c = (c << 4) + hexval(*p); // + takes precedence over << out.push_back(c); } } You might reasonably ask why one would do it this way when there's strtol, and using it is significantly less code (as in James Curran's answer). Well, that approach is a full decimal order of magnitude slower, because it copies each two-byte chunk (possibly allocating heap memory to do so) and then invokes a general text-to-number conversion routine that cannot be written as efficiently as the specialized code above. Christian's approach (using istringstream) is five times slower than that. Here's a benchmark plot - you can tell the difference even with a tiny block of data to decode, and it becomes blatant as the differences get larger. (Note that both axes are on a log scale.) Is this premature optimization? Hell no. This is the kind of operation that gets shoved in a library routine, forgotten about, and then called thousands of times a second. It needs to scream. I worked on a project a few years back that made very heavy use of SHA1 checksums internally -- we got 10-20% speedups on common operations by storing them as raw bytes instead of hex, converting only when we had to show them to the user -- and that was with conversion functions that had already been tuned to death. One might honestly prefer brevity to performance here, depending on what the larger task is, but if so, why on earth are you coding in C++? Also, from a pedagogical perspective, I think it's useful to show hand-coded examples for this kind of problem; it reveals more about what the computer has to do. A: strtol should do the job if you add 0x to each hex digit pair.
unknown
d3048
train
Given that your data is structured, you probably want to create a schema that better suits your structure and then load it in that format rather than just raw source data, or at the very least load the raw data and then transform it into your structure format for easier searching. Otherwise, you might be able to use full text search with GIN index or a GIN index with the pg_trgm operators.
unknown
d3049
train
string orig = "[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]"; string replace = "<a href=\"$1\" rel=\"nofollow\">$1</a>"; string regex = @"\[url:.*?](.*?)\[/url:.*?]"; string fixedLink = Regex.Replace(orig, regex, replace); A: This should capture the string \[([^\]]+)\]([^[]+)\[/\1\] and group it so you can pull out the URL like this: Regex re = new Regex(@"\[([^\]]+)\]([^[]+)\[/\1\]"); var s = @"[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]"; var replaced = s.Replace(s, string.Format("<a href=\"{0}\" rel=\"nofollow\">{0}</a>", re.Match(s).Groups[1].Value)); Console.WriteLine(replaced) A: This isn't doing it totally in Regex but will still work... string oldUrl = "[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]"; Regex regExp = new Regex(@"http://[^\[]*"); var match = regExp.Match(oldUrl); string newUrl = string.Format("<a href='{0}' rel='nofollow'>{0}</a>", match.Value); A: This is just from memory but I will try to check it over when I have more time. Should help get you started. string matchPattern = @"\[(url\:\w)\](.+?)\[/\1\]"; String replacePattern = @"<a href='$2' rel='nofollow'>$2</a>"; String blogText = ...; blogText = Regex.Replace(matchPattern, blogText, replacePattern);
unknown
d3050
train
Mac Catalyst allows iOS apps to be built for and run on macOS. So, by definition, Catalyst apps support iOS, and usually the iPhone. The only case in which they wouldn't is if the app was specifically an iPad-only app that runs on Catalyst on the Mac, but was not enabled to run on the iPhone. More about Catalyst: https://developer.apple.com/mac-catalyst/ You asked for personal experience: I have apps in the App Store for iOS, iPad, and Mac, via both Catalyst and non-Catalyst builds.
unknown
d3051
train
ngModelOptions directive $evals its value, but doesn't observe it for changes. In other words, you cannot achieve what you are looking for with something like the following: <input ng-model="foo" ng-model-options="fooOptions"> and then change it in the controller: $scope.fooOptions = {updateOn: "blur"}; $scope.changeOptions = function(){ $scope.fooOptions = {updateOn: "default"}; } For simple cases, you could add another variable that changes how you show validation messages: <form name="form1"> <input name="foo" ng-model="foo" ng-model-options="{updateOn: 'default'}" ng-blur="startShowingErrors = true" minlength="3"> <span ng-show="startShowingErrors && form1.foo.$invalid">invalid entry</span> </form> But, if you want the actual form state not update, then you'd need another directive as a facade to ngModelOptions to cause a $compile on every change.
unknown
d3052
train
You wanna check if any ng-content is empty, right? Here is a possible solution on Stackoverflow. template: `<div #ref><ng-content></ng-content></div> <span *ngIf="!ref.children.length"> Display this if ng-content is empty! </span>` So in short words: You can handle it with css but your solution is absolutely fine. CSS Example HTML <div class="wrapper"> <ng-content select="my-component"></ng-content> </div> <div class="default"> This shows something default. </div> CSS .wrapper:not(:empty) + .default { display: none; }
unknown
d3053
train
So, I'm coming from the Eclipse environment, and whenever I built a libgdx project, I've never had to go into the "advanced" settings. so messing around some more I went into the advanced settings and saw a checkbox for IDEA(generates intellij IDEA project files) which has seemed to work in getting rid of that error.
unknown
d3054
train
You can download the latest FTD2XX_Net dll from official FTDI site here. The latest version is 1.1.0 so both nuget packages you mentioned are outdated because they are version 1.0.14. As an alternative to the dll, and I think that will be interesing for your case, you can directly include the source of the .Net wrapper. It can be downloaded here. Using the sources for debugging has the advantage that you gain more insight in whats happening when errors occure. You also directly get compiler errors when parts of the ftdi warpper implementation cannot be compiled for mono. Addidtionally you have to ensure that the ftdi driver is installed at all. FTD2XX_Net is just a wrapper around the native ftdi driver.
unknown
d3055
train
You are aware that ftp is not the program to use on the internet in 2011. The password will be send in cleartext. (In a wired or WPA Enterprise protected wireless network you might be OK as long as all your traffic stays inhouse) sftp is the secure replacement (based on ssh). put and get commands have the -P option to preserve the permissions. A: Basically all FTP clients (cute, filezilla, smart, yafc, etc) have the option to set file permissions. I have not yet seen any feature / option to permanently persist the file permissions from your computer to the server. However you can in filezilla and in cuteftp ( i use these 2) set an advanced property which will auto apply a permission set of your choice to all files uploaded. Also, i think this is not likely to ever be released as a feature since file permissions are also based on user! Different users on your computers and different users on your server all of which may or may not have differing permissions. Hope this helped. Cheers. PS: let me know if you can't find the option in filezilla or cuteftp A: It depends on your FTP client. I'm sure nearly all FTP clients have this option. For example, my favorite command-line FTP client, Yafc, lets you: put -p filename to put while preserving file permissions.
unknown
d3056
train
fix it with : pip install py-cpuinfo
unknown
d3057
train
hmm you can do it this way.. MessageBox.Show( String.Format( "\r\nSauce: {0} \r\nToppings ($1.50 each): {1} \r\nPizza total: {2:C} \r\nDrinkSection", 1, 2, 3)); you get the idea.. just replace 1,2,3 with your variables EDIT. String.Format adds readability. A: The following example displays currency symbol with two decimal points. billTotal.ToString("C"); A: billTotal.ToString("C", CultureInfo.CurrentCulture); billTotal.ToString("C", new CultureInfo("en-US"); You can format according to current culture or in a required culture by using overloaded ToString() method.
unknown
d3058
train
To recognize that we have reached end of RecyclerView you can use this class EndlessRecyclerOnScrollListener.java To load more next question, you should define one more field in Question class like number public class Question { private int number; // it must unique and auto increase when you add new question ... } Then when you load questions from FireBase you can do like public class MainActivity extends AppCompatActivity { private static final int TOTAL_ITEM_EACH_LOAD = 10; private DatabaseReference mDatabase; final List<Question> questionList = new ArrayList<>(); private int currentPage = 0; private RecyclerView recyclerView; private RecyclerViewAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { ... // init and set layout manager for your RecyclerView ... mAdapter = new RecyclerViewAdapter(questionList); recyclerView.setAdapter(mAdapter); recyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) { @Override public void onLoadMore(int current_page) { // when we have reached end of RecyclerView this event fired loadMoreData(); } }); loadData(); // load data here for first time launch app } private void loadData() { // example // at first load : currentPage = 0 -> we startAt(0 * 10 = 0) // at second load (first loadmore) : currentPage = 1 -> we startAt(1 * 10 = 10) mDatabase.child("questions") .limitToFirst(TOTAL_ITEM_EACH_LOAD) .startAt(currentPage*TOTAL_ITEM_EACH_LOAD) .orderByChild("number") .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if(!dataSnapshot.hasChildren()){ Toast.makeText(MainActivity.this, "No more questions", Toast.LENGTH_SHORT).show(); currentPage--; } for (DataSnapshot data : dataSnapshot.getChildren()) { Question question = data.getValue(Question.class); questionList.add(question); mAdapter.notifyDataSetChanged(); } } @Override public void onCancelled(DatabaseError databaseError) {}}); } private void loadMoreData(){ currentPage++; loadData(); } } Here is my DEMO project A: To check whether you have reached the bottom of the RecyclerView, you can use the onScrolled listener as below, the if condition here is important and it is defining when a user has reached to the bottom. mRV.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); mTotalItemCount = mLayoutManager.getItemCount(); mLastVisibleItemPosition = mLayoutManager.findLastVisibleItemPosition(); if (!mIsLoading && mTotalItemCount <= (mLastVisibleItemPosition + mPostsPerPage)) { getUsers(mAdapter.getLastItemId()); mIsLoading = true; } } }); Secondly, you can use startAt and limitToFirst methods to get questions in batches as shown below: query = FirebaseDatabase.getInstance().getReference() .child(Consts.FIREBASE_DATABASE_LOCATION_USERS) .orderByKey() .startAt(nodeId) .limitToFirst(mPostsPerPage); I have created an open source app that shows exactly how it is done. Please have a look: https://blog.shajeelafzal.com/2017/12/13/firebase-realtime-database-pagination-guide-using-recyclerview/ A: You can create Firebase Queries to your FirebaseRecyclerAdapter, using startAt and limitToFirst to download records in batches. The limitToFirst page size would be increased by and event, such as a click or a pull to refresh.
unknown
d3059
train
The only way to add GUI controls to an image, is to draw them yourself. The only way to do that, would be to create an image GUI element, and position the other GUI elements relative to the image element. However, this will not do double-buffering of the UI like you want to do, it doesn't actually draw the UI elements in the image, just places them on top of the image.
unknown
d3060
train
Your Redis config looks OK. You are using Redis to cache Meatada (Doctrine collected about Entities mappings, etc) and Query (DQL to SQL). To use Redis as Cache for Results you must write custom Query and define that it is cacheable. Please follow the Doctrine manual http://docs.doctrine-project.org/en/latest/reference/caching.html#result-cache and this GitHub issue https://github.com/snc/SncRedisBundle/issues/77
unknown
d3061
train
ID Field1 Field2 Field3 TableB: ID TableAID (foreign key) Field1 RestrictedField2 In my domain service class I have something like this that was generated when I created the service. I added the includes (which are working fine): <RequiresAuthentication()> Public Function GetTableA() As IQueryable(Of TableA) Return Me.ObjectContext.TableA.Include("TableB") End Function My question is, how do I get all of the columns from TableA and also get Field1 from TableB without returning the RestrictedField2? I'm pretty sure this is done through some Linq fanciness, but I'm not quite sure how. Thanks! Matt Update One requirement that I didn't list above. The column must be removed on the server side as the data in RestrictedField1 cannot have any chance of being sent to the client. Also, I will need to use this field in a different domain service method (protected with RequiresRoleAttribute), so I can expose the information to an administrator. This requirement means that I don't want to create a different complex type and return that. I would prefer to continue working with the EF model type. A: Check this link, I think it may solve your problem without the need of a view model http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/ab7b251a-ded0-487e-97a9- I appears you can return an anonymous type then convert it to your needed type. A: Based on some information that I found, the best way to accomplish what I need is to create a view in the database and expose the data I need via EF and RIA Services. This appears to be the best solution available.
unknown
d3062
train
We could use complete from tidyr to expand the dataset based on the 'ID_WORKES' and the valuse of 'ID_SP_NAR' in the second dataset library(tidyverse) mydata1 %>% mutate_if(is.factor, as.character) %>% complete(ID_WORKES, ID_SP_NAR = mydata2$ID_SP_NAR, fill = list(prop_violations = '0', mash_score = 0)) %>% fill(3:5) # A tibble: 12 x 7 # ID_WORKES ID_SP_NAR KOD_DEPO KOD_DOR COLUMN_MASH prop_violations mash_score # <int> <int> <int> <int> <int> <chr> <dbl> # 1 58002666 21 1439 92 5 1 2 # 2 58002666 463 1439 92 5 0 0 # 3 58002666 465 1439 92 5 1 2 # 4 58002666 500 1439 92 5 0 0 # 5 58002666 600 1439 92 5 0 0 # 6 58002666 1951 1439 92 5 0 0 # 7 58005854 21 1439 92 5 0 0 # 8 58005854 463 3786 58 6 0.2 0 # 9 58005854 465 3786 58 6 0 0 #10 58005854 500 3786 58 6 0 0 #11 58005854 600 3786 58 6 0 0 #12 58005854 1951 3786 58 6 1 2
unknown
d3063
train
You should use parent->child logic For example : <div class="parent"><div class="child"></div></div> EXAMPLE : Codepen
unknown
d3064
train
You need to move Route::controller definition into the route group that has the web middleware added, otherwise the session will not be enabled for it and the authentication system needs the session in order to work. So it should be like this: Route::group(['middleware' => ['web']], function () { Route::get('/', 'UnloggedController@index'); Route::get('/me', 'MeController@index'); Route::controller('/','Auth\AuthController'); });
unknown
d3065
train
// This creates a function, which then returns an object. // Person1 isn't available until the assignment block runs. Person = function() { return { //... } }; person1 = Person(); // Same thing, different way of phrasing it. // There are sometimes advantages of the // two methods, but in this context they are the same. // Person2 is available at compile time. function Person2() { return { //... } } person2 = Person2(); // This is identical to 'person4' // In *this* context, the parens aren't needed // but serve as a tool for whoever reads the code. // (In other contexts you do need them.) person3 = function() { return { //... } }(); // This is a short cut to create a function and then execute it, // removing the need for a temporary variable. // This is called the IIFE (Immediate Invoked Function Expression) person4 = (function() { return { // ... } })(); // Exactly the same as Person3 and Person4 -- Explained below. person5 = (function() { return { // ... } }()); In the contexts above, * *= function() {}(); *= (function() {}()); *= (function() {})(); All do exactly the same thing. I'll break them down. function() {}(); <functionExpression>(); // Call a function expression. (<functionExpression>()); // Wrapping it up in extra parens means nothing. // Nothing more than saying (((1))) + (((2))) (<functionExpression>)(); // We already know the extra parens means nothing, so remove them and you get <functionExpression>(); // Which is the same as case1 Now, all of that said == why do you sometimes need parens? Because this is a *function statement) function test() {}; In order to make a function expression, you need some kind of operator before it. (function test() {}) !function test() {} +function test() {} all work. By standardizing on the parens, we are able to: * *Return a value out of the IIFE *Use a consistent way to let the reader of the code know it is an IIFE, not a regular function. A: The first two aren't a module pattern, but a factory function - there is a Person "constructor" that can be invoked multiple times. For the semantic difference see var functionName = function() {} vs function functionName() {}. The other three are IIFEs, which all do exactly the same thing. For the syntax differences, see Explain the encapsulated anonymous function syntax and Location of parenthesis for auto-executing anonymous JavaScript functions?. A: I've found a extremely detail page explaining this kind of stuff Sth called IIFE Hope will help.
unknown
d3066
train
I recommend you look into iconv for doing such conversions. A: nkf is a Linux command line program which can meet your requirement. I am sure it is available at Debian. So you can download sorce code from the Net.
unknown
d3067
train
Try: test %>% map(~.x %>% mutate(year = as.integer(str_sub(names(.x[1]), -4)))) [[1]] # A tibble: 2 x 4 geoid_1970 name_1970 pop_1970 year <dbl> <chr> <dbl> <int> 1 123 here 1 1970 2 456 there 2 1970 [[2]] # A tibble: 2 x 4 geoid_1980 name_1980 pop_1970 year <dbl> <chr> <dbl> <int> 1 234 here 3 1980 2 567 there 4 1980 A: We can get the 'year' with parse_number library(dplyr) library(purrr) map(test, ~ .x %>% mutate(year = readr::parse_number(names(.)[1]))) -output #[[1]] # A tibble: 2 x 4 # geoid_1970 name_1970 pop_1970 year # <dbl> <chr> <dbl> <dbl> #1 123 here 1 1970 #2 456 there 2 1970 #[[2]] # A tibble: 2 x 4 # geoid_1980 name_1980 pop_1970 year # <dbl> <chr> <dbl> <dbl> #1 234 here 3 1980 #2 567 there 4 1980
unknown
d3068
train
Methods on hubs to be called from clients need to be public- try switching from Internal to Public for Send2-
unknown
d3069
train
Although it is possible to use some preprocessor juggling, the right solution is to simply use C++ as it was intended to be used. Only declare these class members and methods in the header file: static const char * STRINGS[]; const char * getText( int enum ); And then define them in one of the source files: const char * Packet::STRINGS[] = { "ONE", "TWO", "THREE" }; const char * Packet::getText( int enum ) { return STRINGS[enum]; } With the aforementioned preprocessor juggling, all it ends up accomplishing is the same logical result, but in a more confusing and roundabout way.
unknown
d3070
train
Unfortunately you cannot do this using cornerRadius and autolayout — the CGLayer is not affected by autolayout, so any change in the size of the view will not change the radius which has been set once causing, as you have noticed, the circle to lose its shape. You can create a custom subclass of UIImageView and override layoutSubviews in order to set the cornerRadius each time the bounds of the imageview change. EDIT An example might look something like this: class Foo: UIImageView { override func layoutSubviews() { super.layoutSubviews() let radius: CGFloat = self.bounds.size.width / 2.0 self.layer.cornerRadius = radius } } And obviously you would have to constrain the Foobar instance's width to be the same as the height (to maintain a circle). You would probably also want to set the Foobar instance's contentMode to UIViewContentMode.ScaleAspectFill so that it knows how to draw the image (this means that the image is likely to be cropped). A: First of all, I should mention that u can get a circle shape for your UIView/UIImageView only if the width and height will be equal. It's important to understand. In all other cases (when width != height), you won't get a circle shape because the initial shape of your UI instance was a rectangle. OK, with this so UIKit SDK provides for developers a mechanism to manipulate the UIview's layer instance to change somehow any of layer's parameters, including setting up a mask to replace the initial shape of UIView element with the custom one. Those instruments are IBDesignable/IBInspectable. The goal is to preview our custom views directly through Interface Builder. So using those keywords we can write our custom class, which will deal only with the single condition whether we need to round corners for our UI element or not. For example, let's create the class extended from the UIImageView. @IBDesignable class UIRoundedImageView: UIImageView { @IBInspectable var isRoundedCorners: Bool = false { didSet { setNeedsLayout() } } override func layoutSubviews() { super.layoutSubviews() if isRoundedCorners { let shapeLayer = CAShapeLayer() shapeLayer.path = UIBezierPath(ovalIn: CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: bounds.height )).cgPath layer.mask = shapeLayer } else { layer.mask = nil } } } After setting the class name for your UIImageView element (where the dog picture is), in your storyboard, you will get a new option, appeared in the Attributes Inspector menu (details at the screenshot). The final result should be like this one. A: Setting radius in viewWillLayoutSubviews will solve the problem override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() profileImageView.layer.cornerRadius = profileImageView.frame.height / 2.0 } A: It seems when you add one view as a subview of another that netted view will not necessarily have the same height as its superview. That's what the problem seems like. The solution is to not add your imageView as a subview, but have it on top of your backgroundView. In the image below I'm using a UILabel as my backgroundView. Also in your case, when you're setting the cornerRadius use this: let radius: CGFloat = self.bounds.size.height / 2.0. A: create new interface in your .h file like @interface CornerClip : UIImageView @end and implementation in .m file like @implementation cornerClip -(void)layoutSubviews { [super layoutSubviews]; CGFloat radius = self.bounds.size.width / 2.0; self.layer.cornerRadius = radius; } @end now just give class as "CornerClip" to your imageview. 100% working... Enjoy A: With my hacky solution you'll get smooth corner radius animation alongside frame size change. Let's say you have ViewSubclass : UIView. It should contain the following code: class ViewSubclass: UIView { var animationDuration : TimeInterval? let imageView = UIImageView() //some imageView setup code override func layoutSubviews() { super.layoutSubviews() if let duration = animationDuration { let anim = CABasicAnimation(keyPath: "cornerRadius") anim.fromValue = self.imageView.cornerRadius let radius = self.imageView.frame.size.width / 2 anim.toValue = radius anim.duration = duration self.imageView.layer.cornerRadius = radius self.imageView.layer.add(anim, forKey: "cornerRadius") } else { imageView.cornerRadius = imageView.frame.size.width / 2 } animationDuration = nil } } An then you'll have to do this: let duration = 0.4 //For example instanceOfViewSubclass.animationDuration = duration UIView.animate(withDuration: duration, animations: { //Your animation instanceOfViewSubclass.layoutIfNeeded() }) It's not beautiful, and might not work for complex multi-animations, but does answer the question. A: Swift 4+ clean solution based on omaralbeik's answer import UIKit extension UIImageView { func setRounded(borderWidth: CGFloat = 0.0, borderColor: UIColor = UIColor.clear) { layer.cornerRadius = frame.width / 2 layer.masksToBounds = true layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor } } Sample usage in UIViewController 1.Simply rounded UIImageView override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() imageView.setRounded() } 2.Rounded UIImageView with border width and color override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() imageView.setRounded(borderWidth: 1.0, borderColor: UIColor.red) } A: write this code override viewDidLayoutSubViews() { profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2 profileImageView.clipsToBounds = true } in this case it will called after calculating the autolayout calculations in the first code you called the cornerradius code before calculating the actual size of the view cuz it's dynamically calculated using aspect ratio , the actual corner radius is calculated before equaling the width and the height of the view A: I have same problem, and Now I get what happened here, hope some ideas can help you: there are something different between the tows: * *your profileImageView in storyboard *your profileImageView in viewDidLoad the size of bound and frame is different when viewDidLoad and in storyboard,just because view is resize for different device size. You can try it print(profileImageView.bounds.size) in viewDidLoad and viewDidAppear you will find the size in viewDidLoad you set cornerRadius is not the real "running" size. a tips for you: you can use a subClass of ImageView to avoid it, or do not use it in storyboard, A: If you have subclassed the UIImageView. Then just add this piece of magical code in it. Written in : Swift 3 override func layoutSubviews() { super.layoutSubviews() if self.isCircular! { self.layer.cornerRadius = self.bounds.size.width * 0.50 } } A: I am quite new to iOS native development, but I had the same problem and found a solution. So the green background has this constraints: backgroundView.translatesAutoresizingMaskIntoConstraints = false backgroundView.topAnchor.constraint(equalTo: superview!.safeAreaLayoutGuide.topAnchor).isActive = true backgroundView.leftAnchor.constraint(equalTo: superview!.leftAnchor).isActive = true backgroundView.widthAnchor.constraint(equalTo: superview!.widthAnchor).isActive = true backgroundView.heightAnchor.constraint(equalTo: superview!.heightAnchor, multiplier: 0.2).isActive = true The image constraints: avatar.translatesAutoresizingMaskIntoConstraints = false avatar.heightAnchor.constraint(equalTo: backgroundView.heightAnchor, multiplier: 0.8).isActive = true avatar.widthAnchor.constraint(equalTo: backgroundView.heightAnchor, multiplier: 0.8).isActive = true avatar.centerYAnchor.constraint(equalTo: backgroundView.centerYAnchor, constant: 0).isActive = true avatar.leadingAnchor.constraint(equalTo: backgroundView.leadingAnchor, constant: 20).isActive = true on viewWillLayoutSubviews() method I set the corner radius to avatar.layer.cornerRadius = (self.frame.height * 0.2 * 0.8) / 2 Basically, I am simply calculating the height of the image and then divide it by 2. 0.2 is the backgroungView height constraint multiplier and 0.8 the image width/height constraint multiplier. A: Solution: Crop the image [imageView setImage:[[imageView image] imageWithRoundedCorners:imageView.image.size.width/2]]; imageView.contentMode = UIViewContentModeScaleAspectFill; I was looking for the same solution for profile pictures. After some hit and try and going through available functions, I came across something which works and is a nice way to ensure its safe. You can use the following function to crop out a round image from the original image and then you need not worry about the corner radius. Post this even if your view size changes the image remains round and looks good. A: Can be easily done by creating an IBOutlet for the constraint which needs to be changed at runtime. Below is the code: * *Create a IBOutlet for the constraint that needs to be changed at run time. @IBOutlet var widthConstraint: NSLayoutConstraint! *Add below code in viewDidLoad(): self.widthConstraint.constant = imageWidthConstraintConstant() Below function determines for device types change the width constraint accordingly. func imageWidthConstraintConstant() -> CGFloat { switch(self.screenWidth()) { case 375: return 100 case 414: return 120 case 320: return 77 default: return 77 } } A: Add a 1:1 aspect ratio constraint to the imageView for it to remain circular, despite any height or width changes. A: I added custom IBInspectable cornerRadiusPercent, so you can do it without any code. class RoundButton: UIButton { override var bounds: CGRect { didSet { updateCornerRadius() } } //private var cornerRadiusWatcher : CornerRadiusPercent? @IBInspectable var cornerRadiusPercent: CGFloat = 0 { didSet { updateCornerRadius() } } func updateCornerRadius() { layer.cornerRadius = bounds.height * cornerRadiusPercent } }
unknown
d3071
train
The aggregate initialization of the base class you tried Derived(int a): Base{{}, a} {} // ^^ Would have worked if the constructor of boost::noncopyable wasn't protected (see here). The easiest fix should be to add a constructor to the base class. #include <boost/core/noncopyable.hpp> struct Base: private boost::noncopyable { int a; Base(int a_) : a{a_} {} }; struct Derived: public Base { Derived(int a): Base{a} {} };
unknown
d3072
train
You could try using a serialization surrogate, but without something we can reproduce it will be hard to give a decent answer. The fundamental problem, however, is that BinaryFormatter is simply very, very brittle when it comes to things like assemblies. Heck, it is brittle enough even within an assembly. It sounds like TreeViewData is tree based, so I wonder whether xml would have been a better (i.e. more version tolerant) option. If efficiency is a concern, there are custom binary formats (like protobuf-net) that offer high performance, version tolerant, portable binary serialization. If your data is already serialized... I wonder if it might be time to change track? Try using the old assembly to deserialize the data, and switch to a more robust serialization strategy. A: You can use a SerializationBinder to solve this: private class WeakToStrongNameUpgradeBinder : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { try { //Get the name of the assembly, ignoring versions and public keys. string shortAssemblyName = assemblyName.Split(',')[0]; var assembly = Assembly.Load(shortAssemblyName); var type = assembly.GetType(typeName); return type; } catch (Exception) { //Revert to default binding behaviour. return null; } } } Then var formatter = new BinaryFormatter(); formatter.Binder = new WeakToStrongNameUpgradeBinder(); Voila, your old serialized objects can be deserialized with this formatter. If the type have also changed you can use a SerializationSurrogate to deserialize the old types into your new types. As others have mentioned, doing your own serialization rather than relying on IFormatter is a good idea as you have much more control over versioning and serialized size. A: My recommendation is to never use the builtin serializes for your persistent storage. Always code your own if for no other reason someday in the future you will need to read and write your file formats from another language.
unknown
d3073
train
That option is created because your model does not contain one of opt1 or opt2, so it creates an option to match the current value of your model. The way to avoid that is to set your model to a value first.
unknown
d3074
train
My solution adds a second protocol conformance: Numeric provides basic arithmetic operators for scalar types. Then you are able to calculate the zero value in the generic type func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor { let zero = value - value if value > zero { return Theme.Colors.gain } else if value < zero { return Theme.Colors.loss } else { return Theme.Colors.noChange } } or with a switch statement func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor { let zero = value - value switch value { case zero: return Theme.Colors.noChange case zero...: return Theme.Colors.gain default: return Theme.Colors.loss } } or with the ternary operator (added by OP) func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor { let zero = value - value return value > zero ? Theme.Colors.gain : value < zero ? Theme.Colors.loss : Theme.Colors.noChange }
unknown
d3075
train
This is one way of solving the problem: List<Address> addresses = Optional.ofNullable(users) .orElseGet(Collections::emptyList) .stream() .filter(Objects::nonNull) .flatMap(x -> x.getAddress().stream()) .collect(Collectors.toList());
unknown
d3076
train
Try this code func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.row == manArray.count - 1 { let tmpArray = ["Men","m1","m2","m3","m4","m5","m6","m7"] let tmpArray2 = ["789","1259","959","1625","1259","936","980","1500"] manArray.append(contentsOf: tmpArray) mPrice.append(contentsOf: tmpArray2) yourCollectionView.reloadData() } }
unknown
d3077
train
If you want to have stable ID's, you certanly need to store them in the table. You'll need to assign a new sequential ID for every student that joins a course and just delete it if the student leaves, without touching others. If you have concurrent access to your tables, don't use MAX(id), as two queries can select same MAX(id) before inserting it into the table. Instead, create a separate table to be used as a sequence, lock each course's row with SELECT FOR UPDATE, then insert the new student's ID and update the row with a new ID in a single transaction, like this: Courses: Name NextID ------- --------- Math 101 Physics 201 Attendants: Student Course Id ------- ------ ---- Smith Math 99 Jones Math 100 Smith Physics 200 BEGIN TRANSACTION; SELECT NextID INTO @NewID FROM Courses WHERE Name = 'Math' FOR UPDATE; INSERT INTO Attendants (Student, Course, Id) VALUES ('Doe', 'Math', @NewID); UPDATE Courses SET NextID = @NewID + 1 WHERE Course = 'Math'; COMMIT; A: Your first suggestions seems good: have a last_id field in the course table that you increase by 1 any time you enroll a student in that course. A: Creating a column for the ID instead of calculating it. When a new relationship is created assigning an ID based on the max(id)+1 of the students in the course That how I'd do it. There is no point of calculating it. And the id's shouldn't change just because someone dropped out. Adding a column "disabled" and setting it True when a student leaves the course. Yes, that would be a good idea. Another one is creating another table of same structure, where you'll store dropped students. Then of course you'll have to select max(id) from union of these two tables. A: I think there are two concepts that you need to help you out here. * *Sequences where the database gets the next value for an ID for you automatically *Composite keys where more than one column can be combined to make the primary key of a table. From a quick google it looks like Django can handle sequences but not composite keys, so you will need to emulate that somehow. However you could equally have two foreign keys and a sequence for the course/student relationship As for how to handle deletions, it depends on what you need from your app, you may find that a status field would help you as you may want to differentiate between students who left and those that were kicked out, or get statistics on how many students leave different courses.
unknown
d3078
train
It depends on how it is implemented, one common way is to store them in a database table called PersistedGrants. The Authorization Codes are also stored in this table, however they are deleted as as soon as they are used. The image shows what it can look like in this table. The Code_challenge is stored together with the access-code in the database and you can see the code where they pack it all together and then store it as an encrypted blob in the database. * *AuthorizeResponseGenerator.cs (look at the end of the file) The authorization code is stored in the database as the image below shows: The actual payload is encrypted and protected, at it looks like this: { "PersistentGrantDataContainerVersion": 1, "DataProtected": true, "Payload": "CfDJ8OFLAj3iVVVHvhgvjcKB19Z7-Hms4IIQobGgGl7VnJQCtKiB-Inr3h-mcWCxxD8dJ4QNTbuVeywbT6ROsaf13EpaIQDWtLgbnSPvCDTLQeWTO_vP0UtDwJ7TTCc5aTvKEp_9hX9S1b3l685bmBMlTIcZFqGGM2VfK0qasWCqKSQcTxeN6cgJygZEQNMgAG4ipqr..." }
unknown
d3079
train
If you don't use any third party libraries, then no. The host has to have the .NET 3.5 SP1 installed. However you need to be aware of the trust level issues. Most shared hosts run in medium trust mode. Although this will suffice for the MVC itself, it may not for your other code. If you use reflection for example, you will need the full trust enabled. Basically this simple code may get you into trouble: object something = 5; if (something is int) { // Do something } Check your code and choose the host wisely.
unknown
d3080
train
You are really very close. To define a recursive grammar like this, you need to forward-declare the nested expression. As you have already seen, this: arg = at_identifier | color_hex | decimal | quotedString function_call = identifier + LPAR + Optional(delimitedList(arg)) + RPAR only parses function calls with args that are not themselves function calls. To define this recursively, first define an empty placeholder expression, using Forward(): function_call = Forward() We don't know yet what will go into this expression, but we do know that it will be a valid argument type. Since it has been declared now we can use it: arg = at_identifier | color_hex | decimal | quotedString | function_call Now that we have arg defined, we can define what will go into a function_call. Instead of using ordinary Python assignment using '=', we have to use an operator that will modify the function_call instead of redefining it. Pyparsing allows you to use <<= or << operators (the first is preferred): function_call <<= identifier + LPAR + Optional(delimitedList(arg)) + RPAR This is now sufficient to parse your given sample string, but you've lost visibility to the actual nesting structure. If you group your function call like this: function_call <<= Group(identifier + LPAR + Group(Optional(delimitedList(arg))) + RPAR) you will always get a predictable structure from a function call (a named and the parsed args), and the function call itself will be grouped.
unknown
d3081
train
Attribute Selector Syntax For straight CSS it is: [class='My class1'] For most javascript frameworks like jQuery, MooTools, etc., it is going to be the same selector string used as for the straight CSS. The key point is to use an attribute selector to do it, rather than selecting directly by the class name itself. The class= (with just the equals sign) will only select for an exact match of the string following. If you also have need of catching class1 My then you would need to select as well for [class='class1 My']. That would cover the two cases where only those two classes are applied (no matter the order in the html). A: Class definitions in elements are separated by spaces, as such your first element infact has both classes 'My' and 'class1'. If you're using Mootools, you can use the following: $$("div.My.class1:not(div.234):not(div.haha)") Example in Mootools: http://jsfiddle.net/vVZt8/2/ Reference: http://mootools.net/docs/core125/core/Utilities/Selectors#Selector:not If you're using jQuery, you can use the following: $("div.My.class1").not("div.234").not("div.haha"); Example in jQuery: http://jsfiddle.net/vVZt8/3/ Reference: http://api.jquery.com/not-selector/ These two examples basically retrieve all elements with the classes 'My' and 'class1', and then remove any elements that are a 'div' element which have the either of the '234' or 'haha' classes assigned to them. A: jQuery equals selector: http://api.jquery.com/attribute-equals-selector/ jQuery("[class='My class1']"). or $("[class='My class1']"). or $$("[class='My class1']").
unknown
d3082
train
PHP runs on the server, generates the content/HTML and serves it to the client possibly along with JavaScript, Stylesheets etc. There is no concept of running some JS and then some PHP and so on. You can however use PHP to generate the required JS along with your content. The way you've written it won't work. For sending the value of clicked_tag to your server, you can do something like (using jQuery for demoing the logic) function show_region(chosen_region_id) { ... $.post('yourserver.com/getclickedtag.php', {clicked_tag: chosen_region_id}, function(data) { ... }); ... } A: In your script the variable chosen_region_id is already in the function so you don't really need to declare it again with PHP.
unknown
d3083
train
Since you are working on a Spring based application, I would suggest using Spring RestTemplate to request your GET/POST endpoints. The following may be a short snippet of what could be done and you can refer to this Spring tutorials (1,2 and 3) for more details: public void getOrPostTest() { String GET_URL = "http://localhost:8080/somepath"; RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<String, String>(); params.put("prop1", "1"); params.put("prop2", "value"); String result = restTemplate.getForObject(GET_URL, String.class, params); } A: You can use HttpClient, look this example. HttpClient httpClient = login(HTTP_SERVER_DOMAIN, "[email protected]", "password"); GetMethod getAllAdvicesMethod = new GetMethod(URL); getAllAdvicesMethod .addRequestHeader("Content-Type", "application/json"); try { httpClient.executeMethod(getAllAdvicesMethod); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } If you need another method request you can changes GetMethod for PostMethod postDateMethod = new PostMethod(URL);
unknown
d3084
train
On chrome right click on the page , select inspect element then go to the resources panel and check the scripts folder. A: Inside your links it's a custom-made server-side calendar. It has nothing to do with jQuery.
unknown
d3085
train
First we need to uninstall G1ANT robot from manage nutmeg package present under Project as it is old version and then go to browse menu and Search G1ANT there and install it and then try to build your addon. Hope it works! A: You might have to try 2 3 times . I had to re-install g1ant language package 2 times to stop receiving those errors. Also you can check reference to verify that whether g1ant language is un-installed and then re-install it.
unknown
d3086
train
There is two ways to do that. The first one is to connect your host machine to Ad-Hoc using its driver. The second way is to passthrough Wi-Fi adapter to the VM and connect to Ad-Hoc using driver installed there.
unknown
d3087
train
I am not sure WHY you want to do this, but it is possible. Just remember that simply because you can do something does not mean that you SHOULD do that thing (see C++ Faq Law of Least Surprise. Aside from violating the law of least surprise, you can do what you are trying to do, your code just has several simple compile errors in it that once fixed will work just fine (see here for working example). Here are the changes to make it compile: friend istream& operator << (istream& ,a& ); // Note the addition of the & // Here the variabe is dout, so change to dout. I also added some spacing ostream& operator << (ostream& dout,a a1){ dout<<"Name = "<< a1.name<<" Age = "<<a1.age<<" Salary = "<<a1.salary<<endl; return dout; } // Here you are using din, so you need to change to din, also you had end instead of endl istream& operator << (istream& din,a& a1){ cout<<"Enter Your Name , Age , Salary .....Press Enter To Seperate New Value"<<endl; din>>a1.name>>a1.age>>a1.salary; return din; } Just so the complete code is also in one easy place for you. Here is your entire program with the changes to make it compile. #include<iostream> using namespace std; class a { private: string name; int age; unsigned long int salary; public: friend ostream& operator << (ostream& ,a ); friend istream& operator << (istream& ,a& ); }; ostream& operator << (ostream& dout,a a1){ dout << "Name = "<< a1.name <<" Age = "<< a1.age <<" Salary = "<< a1.salary << endl; return dout; } istream& operator << (istream& din,a& a1){ cout <<"Enter Your Name , Age , Salary .....Press Enter To Seperate New Value" << endl; din >> a1.name >> a1.age >> a1.salary; return din; } main(int argc, char const *argv[]) { a a1; cin<<a1; cout<<a1; return 0; } Now, if we want to follow the Law of Least surprise, then we would change the istream operator overload to use >> instead of << and move the console text out of the >> operator overload and just present it to the user before reading the values. #include<iostream> using namespace std; class a { private: string name; int age; unsigned long int salary; public: friend ostream& operator << (ostream& ,a ); friend istream& operator >> (istream& ,a& ); }; // Note - Changed variable 'dout' to 'os' for clarity ostream& operator << (ostream& os, a a1){ os << "Name = " << a1.name << " Age = " << a1.age << " Salary = "<< a1.salary << endl; return os; } // Changed variable from 'din' to 'is' for clarity istream& operator >> (istream& is,a& a1){ is >> a1.name >> a1.age >> a1.salary; return is; } main(int argc, char const *argv[]) { a a1; cout << "Enter Your Name , Age , Salary .....Press Enter To Seperate New Value" << endl; cin >> a1; cout << a1; return 0; }
unknown
d3088
train
I wrote a library RateLimiter to handle this kind of constraints. It is composable, asynchroneous and cancellable. Its seems that Face API quota limit of 10 calls per second, so you can write: var timeconstraint = TimeLimiter.GetFromMaxCountByInterval(10, TimeSpan.FromSeconds(1)); for(int i=0; i<1000; i++) { await timeconstraint.Perform(DoFaceAPIRequest); } private Task DoFaceAPIRequest() { //send request to Face API } It is also available as a nuget package.
unknown
d3089
train
When a shared library is used, there are two parts to the linkage process. At compile time, the linker program, ld in Linux, links against the shared library in order to learn which symbols are defined by it. However, none of the code or data initializers from the shared library are actually included in the ultimate a.out file. Instead, ld just records which dynamic libraries were linked against and the information is placed into an auxiliary section of the a.out file. The second phase takes placed at execution time, before main gets invoked. The kernel loads a small helper program, ld.so, into the address space and this gets executed. Therefore, the start address of the program is not main or even _start (if you have heard of it). Rather, it is actually the start address of the dynamic library loader. In Linux, the kernel maps the ld.so loader code into a convenient place in the precess address space and sets up the stack so that the list of required shared libraries (and other necessary info) is present. The dynamic loader finds each of the required libraries by looking at a sequence of directories which are often point in the LD_LIBRARY_PATH environment variable. There is also a pre-defined list which is hard-coded into ld.so (and additional search places can be hard-coded into the a.out during link time). For each of the libraries, the dynamic loader reads its header and then uses mmap to create memory regions for the library. Now for the fun part. Since the actual libraries used at run-time to satisfy the requirements are not known at link-time, we need to figure out a way to access functions defined in the shared library and global variables that are exported by the shared library (this practice is deprecated since exporting global variables is not thread-safe, but it is still something we try to handle). Global variables are assigned a statics address at link time and are then accessed by absolute memory address. For functions exported by the library, the user of the library is going to emit a series of call assembly instructions, which reference an absolute memory address. But, the exact absolute memory address of the referenced function is not known at link time. How do we deal with this? Well, the linker creates what is known as a Procedure Linkage Table, which is a series of jmp (assembly jump) instructions. The target of the jump is filled in at run time. Now, when dealing with the dynamic portions of the code (i.e. the .o files that have been compiled with -fpic), there are no absolute memory references whatsoever. In order to access global variables which are also visible to the static portion of the code, another table called the Global Offset Table is used. This table is an array of pointers. At link time, since the absolute memory addresses of the global variables are known, the linker populates this table. Then, at run time, dynamic code is able to access the global variables by first finding the Global Offset Table, then loading the address of the correct variable from the appropriate slot in the table, and finally dereferencing the pointer.
unknown
d3090
train
I had this same issue. Removing the @netlify/plugin-nextjs from the plugins tab on Netlify fixed the issue for me. I removed the plugin and triggered a new deploy. A: I had the same issue and I resolved it by updating the plugin from the plugins tab in Netlify. A: In my case, the solution was to disable the plugin, and then re-enable it. Disabling the plugin broke my site temporarily because it's needed to run Next.js, but it was the only way I could get my deploy to succeed. Other things I tried that did not work: * *Re-building node_modules *Updating package-lock.json *Triggering a re-deploy without cache A: If you are using a monorepo to fix this issue go to the deploy settings of your site and under build settings change the publish directory to [subdir]/.next where [subdir] is the sub directory you have your next project in. After that clear change and deploy again A: I have faced the same issues. I tried adding the NETLIFY_NEXT_PLUGIN_SKIP= "TRUE"to the environment variables and it worked for me A: 1st in your project folder cmd or git bash run (yarn build) then go to the netlify build setting and change (Build command: next build) this process is work for me A: remove the netlify.toml file and let netlify build it with the default npm run build A: I also faced the same issue. There is something wrong in @netlify/plugin-nextjs plugin latest version 4.0 Try doing this and this worked for me. In netlify, under your project, do this. Site Settings -> Plugins -> Next.js Runtime -> click Change version and select version 3. NextJs plugin version change screenshot And redeploy the site.
unknown
d3091
train
Well, you could use: if( count($_GET) > 1 || !isset($_GET['page'])) { /*error*/ } A: You should care only of GET/POST variables used in your application. Validate and escape them accordingly, check if they're set. The rest should be ignored - you don't need to care of them and display errors. A: $allowedKeys = array('page'); $_GET = array_intersect_key($_GET, array_flip($allowedKeys)); You won't have to worry about your undesired parameters and values, as they will not be accepted via the $_GET method. With the above code, the only allowed $_GET parameters is 'page' A: I might do this: <?php if ($_GET) { foreach($_GET as $key=>$value) { if($key!='page') { $error=true; } } } ?>
unknown
d3092
train
Then use COUNT() SELECT DBID, COUNT(*) TotalRows, SUM(TalkTime) TotalTalkTime FROM Incoming_Calls GROUP BY DBID * *TSQL Aggregate Function A: Select DBID, SUM(TalkTime), COUNT(TalkTime) TalkTimeCount FROM Incoming_Calls GROUP BY DBID OR, If you want to include null values count then you can you this Select DBID, SUM(TalkTime), @@ROWCOUNT FROM Incoming_Calls GROUP BY DBID
unknown
d3093
train
You are using Python2 so you need to use raw_input instead of input. opclo = raw_input('>') if opclo == 'CLOSED': print "Good night." elif opclo == 'WACKED': print "wacked" else: print "Good morning." A: tl;dr input('>') - for python expressions raw_input - for strings. You should use raw_input
unknown
d3094
train
You are close, you need OR or IN() instead of AND: SELECT * FROM house h LEFT JOIN people p ON p.id IN(h.person1,h.person2,h.person3) But I believe, a better approach is to change your table design as proposed by the comments. In that case you will simply need: SELECT * FROM house h LEFT JOIN people p ON h.person = p.id A: You should use self join on table people 3 name with 3 alias $pdo = $db->query(' SELECT *, people1.name as name1, people2.name as name2, people3.name as name3 FROM house LEFT JOIN people as people1 ON house.person1=people1.id LEFT JOIN people as people2 ON house.person2=people2.id LEFT JOIN people as people3 ON house.person3=people3.id ;'); while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) { echo "Person 1 = ".$row['name1']; echo "Person 2 = ".$row['name2']; echo "Person 3 = ".$row['name3']; } A: if you need to know the name of the 3 person in every house, you can use this $pdo = $db->query(' select A.house, B.name as person1, C.name as person2, D.name as person3 from house A join people B on (A.person1=B.id) left join people C on (A.person2=C.id) join people D on (A.person3=D.id) ;'); while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) { echo "house = ".$row['house']; echo "Person 1 = ".$row['person1']; echo "Person 2 = ".$row['person2']; echo "Person 2 = ".$row['person3']; }
unknown
d3095
train
<dx:BootstrapGridView runat="server" ID="GVcity" AutoGenerateColumns="False" AllowPaging="True" OnPageIndexChanging="OnPageIndexChanging" OnPageIndexChanged="GVcity_PageIndexChanged"> <Columns> <dx:BootstrapGridViewTextColumn FieldName="localRegionName" VisibleIndex="0" Caption="Regional"></dx:BootstrapGridViewTextColumn> <dx:BootstrapGridViewTextColumn FieldName="localRegionCode" VisibleIndex="1" Caption="Code"></dx:BootstrapGridViewTextColumn> <dx:BootstrapGridViewTextColumn FieldName="CityName" VisibleIndex="2" Caption="City"></dx:BootstrapGridViewTextColumn> <dx:BootstrapGridViewCommandColumn ShowClearFilterButton="true" ShowApplyFilterButton="true" VisibleIndex="3" /> </Columns> </dx:BootstrapGridView>
unknown
d3096
train
Very Close. Excel stores dates and times as days and fractions of days since 1/1/1900 or 1/1/1904. You need to ADD the time to the date, not concatenate. And you can simplify getting the Date portion from F11. Try: =SUMIFS( Last36Hours!$K$2:$K$10000, Last36Hours!$T$2:$T$10000,">=" & INT(F11)+ TIME(6,0,0)) You could also hard code yesterday at 6AM by replacing DATE(YEAR(F11),MONTH(F11),DAY(F11)) & TIME(6,0,0) with TODAY()-0.75 which is the same as: TODAY() - 1 + TIME(6,0,0)
unknown
d3097
train
Set Your TableViewController an Initial View Controller from the Storyboard A: You need to mark a viewController in your Storyboard and set it to the initial viewController. You do this under the Attributes Inspector. This means that you set which viewController shall open when you start your application. A: I fixed this by renaming the default "ViewController.swift" as "MainViewController.swift". Perhaps this is a warning to the user to insure everything is defined as you expect it to be. I experienced this issue again and backtracked, eventually clearing the storyboard and then deleting it entirely from the project and the issue was still present. Relaunching Xcode fixed the issue. A: For me I just had a view controller that wasn't attached to anything, i.e. I had a UITabBar Controller, and a few View Controllers attached to the TabBar, but there was one View Controller that was stranded, with out any connection to another view. From my experience, the error message was, “View Controller“ is unreachable because it has no entry points, and no identifier for runtime access via -[UIStoryboard instantiateViewControllerWithIdentifier:]. The View controller name was the text in quotes, i.e. “View Controller“. Hope this helped someone! A: Just add an ID in Storyboard ID (and restoration ID in case) A: I solved my issue as follows: * *Make sure the storyboard is Initial View Controller *In Custom Class, the selected class is ViewController A: I'd reached the same error. This answer would be useful, I think: Xcode: "Scene is unreachable due to lack of entry points" but can't find it The problem was that because of some experiments and copy-pasting I had an actual copy of a view controller located outside the visible part of the screen or it could be stacked exactly on top of its twin. So I just deleted unwanted one :-) You should open Document Outline and сheck for copies :-) A: In my case I accidentally deleted Storyboard Entry Point without knowing, and app wasn't starting, After several undo's, I saw the problem and corrected it A: When you have 2 or more navigation controllers(embedded UIVIewcontrollers) or 2 or more UIViewcontrollers in your storyboard. Xcode may be looking for a startup view controller. You can mark either of one of them as startupviewcontroller, just by selecting the "is initial viewcontroller" OR you can give a unique storyboard id for each and every UInavigationcontrollers or UIViewcontrollers or UITabviewcontrollers in your storyboard. A: This is my error. warning: Unsupported Configuration: “View Controller“ is unreachable because it has no entry points, and no identifier for runtime access via -[UIStoryboard instantiateViewControllerWithIdentifier:]. I delete the code in ViewController , but I don't disconnect the connect in ViewController of Main.storyborad. A: I had the same problem. I figured out that I had forgotten to add an "ID" to my Tab Bar Controller. Hope this help somebody. A: I had same issue that to solve this problem I opened the Document Outline then realized that I have accidentally deleted the Segue between two pages. Steps: 1) Editor> Show Document Outline document outline 2) Check the Document Outline for any copy-paste, segue error or etc. screenshot A: The problem is exactly as the warning says: this View Controller is unreachable because it has no entry points. If you have only one View Controller then this controller is missing its entry point. You can fix this by setting this View Controller as "Is Initial View Controller". If you have several View Controllers and this View Controller is not in the beginning of your storyboard sequence, then you are missing a segue which should display this View Controller. You can fix this by adding a segue which should show this View Controller. In general, Xcode tells you that this View Controller is not connected to the storyboard sequence because it has no incoming connections.
unknown
d3098
train
The problem here is that the ListBox has a selection, and selected items get highlighted. You need to disable this highlighting to get the desired result, for example by setting ListBox.ItemContainerStyle as described in this answer. This will remove the (lightblue) selection color. A: Each item in the ItemsSource is wrapped in a ListBoxItem inside the ListBox. A ListBox is a control derived from Selector, which is a base type for items controls that allow selection of items. Represents a control that allows a user to select items from among its child elements. What you specified as DataTemplate will be placed in a ListBoxItem at runtime, which is the container for the content. This container has a default style and control template that defines its appearance and visual states. What you see is the MouseOver state and the Selected state. You can change this by extracting the default style for ListBoxItem and adapting it or by writing your own. * *How to create a template for a control (WPF.NET) However, it seems that your intention is different. What you probably wanted was to simply display buttons in a UniformGrid depending on a bound collection, without any selection. You can achieve this by using an ItemsControl instead. It does not offer any selection capabilities, but lets you bind a collection with the UniformGrid as items panel. <ItemsControl Width="1000" Grid.Row="1" VerticalAlignment="Top" VerticalContentAlignment="Top" Margin="50" ItemsSource="{Binding SomeItemsList}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Columns="2" Background="Transparent" Name="uniformGrid1"></UniformGrid> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Button Margin="50" Height="70" Click="keyword_Click" Width="250" Foreground="Black" FontSize="16" FontFamily="Helvetica Neue" FontWeight="Bold" BorderBrush="SlateGray" Content="{Binding Name}"> <Button.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="White" Offset="0.073" /> <GradientStop Color="White" Offset="1" /> <GradientStop Color="#FFE9E9F9" Offset="0.571" /> <GradientStop Color="#FFD7D7EC" Offset="0.243" /> </LinearGradientBrush> </Button.Background> </Button> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> Please note that I have removed one of two Name="uniformGrid1" as duplicate names lead to a compilation error. If your content exceeds the viewport and you need scrollbars, you have to add a ScrollViewer, since this is built into the ListBox, but not the ItemsControl. <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"> <ItemsControl Width="1000" Grid.Row="1" VerticalAlignment="Top" VerticalContentAlignment="Top" Margin="50" ItemsSource="{Binding SomeItemsList}"> <!-- ...other code. --> </ItemsControl> </ScrollViewer>
unknown
d3099
train
You are using the mapboxgl.LngLat() function. The function name already contains the order in which it expects you to pass longitude and latitude -- > first longitude then latitude. You are passing first latitude then longitude. This will definitely cause a problem. Your code: function findpos(){ var ptt = new mapboxgl.LngLat(latitude,longitude); var ptt2 = destinationPoint(179.85, 0.226, ptt); return ptt2; } Try this: function findpos(){ var ptt = new mapboxgl.LngLat(longitude,latitude); var ptt2 = destinationPoint(179.85, 0.226, ptt); return ptt2; } Similar for this part of your code: return new mapboxgl.LngLat(lat2.toDeg(), lon2.toDeg()); A: Have a look on Turf documentation It provide's two different methods. You can try : http://turfjs.org/docs/#bearing http://turfjs.org/docs/#rhumbBearing
unknown
d3100
train
Try this: Dim _dLocation As String = udDefaultLocationTextEdit.Text Dim _intDLocation As Nullable(Of Integer) If Not String.IsNullOrEmpty(_dLocation) Then _intDLocation = Integer.Parse(_dLocation) End If A: Integers cannot be set to Null. You have to make the integer "nullable" by adding a question mark after the word Integer. Now _intDLocation is no longer a normal integer. It is an instance of Nullable(Of Integer). Dim _dLocation As String = udDefaultLocationTextEdit.Text Dim _intDLocation As Integer? If _dLocation <> "" Then _intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text) Else _intDLocation = Nothing End If Later on, if you want to check for null you can use this handy, readable syntax: If _intDLocation.HasValue Then DoSomething() End If In some cases you will need to access the value as an actual integer, not a nullable integer. For those cases, you simply access _intDLocation.Value Read all about Nullable here. A: My application uses a lot of labels that start out blank (Text property), but need to be incremented as integers, so I made this handy function: Public Shared Function Nullinator(ByVal CheckVal As String) As Integer ' Receives a string and returns an integer (zero if Null or Empty or original value) If String.IsNullOrEmpty(CheckVal) Then Return 0 Else Return CheckVal End If End Function This is typical example of how it would be used: Dim Match_Innings As Integer = Nullinator(Me.TotalInnings.Text) Enjoy! A: _intDLocation = Nothing
unknown