_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d19501
test
If fetching the entity doesn't emit a Last-Modified header, then I would say this is a bug in the client, not SDR. If none of your entities support Last-Modified, maybe create a filter that strips If-Modified-Since from the request or catches it early and responds appropriately. All of that said, I also don't think a NPE is acceptable and a SDR bug should be filed.
unknown
d19502
test
Try with utf8_encode($string) or utf8_decode($string). I never remember which one to use, sorry. A: 1.) Are you sending the output in UTF-8? header('content-type: text/html; charset=utf-8') 2.) Have you also set the MySQL connection to UTF-8? mysql_query("SET NAMES 'utf-8'"); A: It looks like your database is in some encoding (not UTF-8) and your output is in a different encoding. Find out which encoding the database uses.
unknown
d19503
test
"Looking for much simple way since full query have more than 15 columns" Sorry, you can have a complex query or no query at all :) The problem is the structure of the posted table mandates a complex query. That's because it uses a so-called "generic data model", which is actually a data anti-model. The time saved in not modelling the requirement and just smashing values into the table is time you will have to spend writing horrible queries to get those values out again. I assume you need to drive off the other table you referred to, and the posted table contains attributes supplementary to the core record. select ano.id , ano.name , ano.address , ano.region , t1.value as alt_id , t2.value as birth_date , t3.value as contact_no from another_table ano left outer join ( select id, value from generic_table where key = 'alt_id' ) t1 on ano.id = t1.id left outer join ( select id, value from generic_table where key = 'birth_date' ) t2 on ano.id = t2.id left outer join ( select id, value from generic_table where key = 'contact_no' ) t3 on ano.id = t3.id Note the need to use outer joins: one of the problems with generic data models is the enforcement of integrity constraints. Weak data typing can also be an issue (say if you wanted to convert the birth_date string into an actual date). A: PIVOT concept fits well for these types of problems : SQL> create table person_info(id int, key varchar2(25), value varchar2(25)); SQL> create table person_info2(id int, name varchar2(25), address varchar2(125), region varchar2(25)); SQL> insert into person_info values(4150521,'contact_no',772289317); SQL> insert into person_info values(4150522,'alt_id','98745612V'); SQL> insert into person_info values(4150522,'birth_date',date '1990-04-21'); SQL> insert into person_info values(4150522,'contact_no',777894561); SQL> insert into person_info2 values(4150521,'ABC','AAAAAA','ASD'); SQL> insert into person_info2 values(4150522,'XYZ','BBBBB','WER'); SQL> select p1.id, name, address, region, alt_id, birth_date, contact_no from person_info pivot ( max(value) for key in ('alt_id' as alt_id,'birth_date' as birth_date,'contact_no' as contact_no) ) p1 join person_info2 p2 on (p1.id = p2.id); ID NAME ADDRESS REGION ALT_ID BIRTH_DATE CONTACT_NO ------- ------- ------- ------ --------- ---------- ---------- 4150521 ABC AAAAAA ASD 12345678V 21-APR-89 772289317 4150522 XYZ BBBBB WER 98745612V 21-APR-90 777894561
unknown
d19504
test
So i'm going to post what it solved my problem, but i have absolutely no idea why that happened, so if anyone has a better answer i will check that as accepted. To solve my problems i removed the binding for width and height and simply added in the constructor of the DialogWindow this.Width = OwnerActualWidth; this.Height = OwnerActualHeight; since i am passing those parameter in input
unknown
d19505
test
First you are using module and trying to do weird things in your parent pom (dependency-plugin, build-helper etc.). In a parent there should never be an execution like you have in your pom. You should make the appropriate configuration/execution within the appropriate modules cause this definition will be inherited of all childs. Would you like to create an ear file? Than you should use packaging ear and your ear file will simply being deployed by using mvn deploy. Furthermore you seemed to misunderstand the life cycle cause if you call: mvn clean package deploy this can be reduced to: mvn clean deploy cause the package life cycle is part of deploy so i recommend to read the life cycle information.
unknown
d19506
test
This is what you need: objects_in_db = Model.all objects_in_array = Model.first(2) objects_in_array.delete_if { |obj| !objects_in_db.include?(obj)} In your case, Model.limit(2) may not return the first two object and so the array a may not contain b and hence, it returns nil. A: a.to_a - [b] Background: a.to_a convertrs the relation into an array in in memory. [b] is an array whith just the element, you want to delete (in memory). a.to_a - [b] does an array substraction. (In Rails 3.2 .to_a was applied automatically to a relation when it was accessed. I agree with gregates: It's better to convert the relation to an array explicitly) A: There's potentially some confusion here because in ActiveRecord, Model.limit(2) does not return an array. Model.limit(2).class #=> ActiveRecordRelation So when you call a.delete(b), you may not be calling Array#delete. Try this instead: a = Model.limit(2).to_a # Executes the query and returns an array b = Model.first a.delete(b)
unknown
d19507
test
This is way easier than you think. You can use the same algorithm that itertools uses for their pairwise recipe except itertools.tee isn't needed as your input is a list therefore slicing will work. B, C, D, E = zip(A, A[1:]) Results: >>> print(B, C, D, E, sep='\n') (0, 1) (1, 2) (2, 3) (3, 4) A: You could use a list comprehension to create a list of these lists: pairs = [A[i : i + 2] for i in range(len(A) - 1)] If you then want to unpack them into different variables, you can use tuple unpacking: B, C, D, E = pairs A: A more general solution for sublists of length n with overlap of k: def chunk(lst, n=2, k=1): return [lst[i:i+n] for i in range(0, len(lst)-k, n-k)] >>> A = [0, 1, 2, 3, 4, 5, 6, 7] >>> chunk(A) [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]] >>> chunk(A, 3) [[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7]] >>> chunk(A, 5, 2) [[0, 1, 2, 3, 4], [3, 4, 5, 6, 7]]
unknown
d19508
test
You should add AccountType property to Account class. There are two ways: Making Account class abstract: abstract class Account { public abstract string AccountType { get; } } class SavingsAccount : Account { public override string AccountType { get { return "Savings Account"; } } } class CreditAccount : Account { public override string AccountType { get { return "Credit Account"; } } } Or making AccountType property virtual: class Account { public virtual string AccountType { get { return string.Empty; } } } class SavingsAccount : Account { public override string AccountType { get { return "Savings Account"; } } } class CreditAccount : Account { public override string AccountType { get { return "Credit Account"; } } } This would make sense if Account should be instantiated on its own and can provide a valid implementation for AccountType property. Otherwise you should go with the abstract class. A: Well, you wrote: foreach (Account a in c.Accounts) { textWriter.WriteLine("\t\t{0}", a.AccountType); ... } The problem is that you have defined the AccountType property in SavingsAccount and CreditAccount, the classes inherited from the Account class. The error happens when a in c.Accounts is not a SavingsAccount or CreditAccount. The solution would be adding the (virtual) AccountType property to the Account class, and overriding it in the child classes. A: here: foreach (Account a in c.Accounts) You are making a of the account type. here you are saying that saving account implements account. class SavingsAccount : Account { public string AccountType { get { return "Savings Account"; } } } SavingAccount is where the AccountType exists not in Account. Your base class of Account needs be like this. public abstract class Account { public abstract string AccountType { get; } } and your saving account needs to be this: public class SavingAccount : Account { public override string AccountType { get { return "Savings Account"; } } }
unknown
d19509
test
Pages normally have controller(s), a service can be created to share data between pages ( by injecting service in associated controllers). Like: app.factory('myService', function() { var savedData = {} function set(data) { savedData = data; } function get() { return savedData; } return { set: set, get: get } }); In your controller A: myService.set(yourSharedData); In your controller B: $scope.desiredLocation = myService.get(); Happy Helping! A: Use a service (best) https://docs.angularjs.org/guide/services Or $rootScope (bad, but simpler) https://docs.angularjs.org/api/ng/service/$rootScope
unknown
d19510
test
You can use the allMatch method like this: int correctSize = 3; List<String> myStrings = List.of("abc", "xyz", "def"); boolean allAreCorrectSize = myStrings.stream() .allMatch(s -> s.length() == correctSize); A: Here both implementation, both can be used * *Using Stream API public static boolean isValidUsingStreamAPI(List<String> list){ int correctSize=3; return list.stream().allMatch(f->f.length()==correctSize); } *Classic Way public static boolean isValidClassic(List<String> list){ int correctSize=3; for(String s:list){ if(s.length()!=correctSize)return false; } return true; }
unknown
d19511
test
Your issue apparently is "how do I know which button was clicked?". You already know how to create a button, add it to the form and attach a click-handler: Button Remove_button = new Button(); this.Controls.Add(Remove_button); Remove_button.Name = "Remove_button" + Convert.ToString(rownumb); Remove_button.Click += new System.EventHandler(Remove_button_Click); To know which button was clicked, you can set its .Tag property: Remove_button.Tag = Convert.ToString(rownumb); // or whatever the primary key for this row is Next, in the click handler, you need to read that property. Fortunately, when the button calls the handler, it uses (a reference to) itself as the sender parameter. So when you cast that sender to a Button, you get the real button that originated the command and you can access all its properties, such as .Tag: private void Remove_button_Click(object sender, EventArgs e) { Button clickedButton = (Button)sender; string rownumb = clickedButton.Tag; DialogResult selection = MessageBox.Show("Are you sure you want to remove item #" + rownumb + "?", "Remove", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); // TODO execute a DELETE command for this row when the user clicked OK }
unknown
d19512
test
I have taken the .NET 3.1 Azure Function Project with Timer Trigger in the VS 2022 IDE: Published the .NET Core 3.1 Azure Functions Project to Azure Function App in the Azure Portal and then changed the FUNCTIONS_EXTENSION_VERSION to 4 using Azure CLI Command by following this MS Doc: Running locally after migration to V4-.NET 6: Then, deployed the migrated project to the Azure Function App and tested as shown below: A: I was able to find the reason for the issue by running "Diagnose and solve problems" from Azure portal. The issue was related to the function name. My function name length was more than 32 characters long. By default, the Host ID is auto-generated from the Function App name, by taking the first 32 characters. If you have multiple Function Apps sharing a single storage account and they're each using the same Host ID (generated or explicit), that can result in a Host ID collision. For example, if you have multiple apps with names longer than 32 characters their computed IDs may be the same. Consider two Function Apps with names myfunctionappwithareallylongname-eastus-production and myfunctionappwithareallylongname-westus-production that are sharing the same storage account. The first 32 characters of these names are the same, resulting in the same Host ID myfunctionappwithareallylongname being generated for each(Please refer https://github.com/Azure/azure-functions-host/wiki/Host-IDs#host-id-collisions for more information). So, to solve the issue, I just rename the function name on Azure.
unknown
d19513
test
@published - is two way binding ( model to view and view to model) Use case for @published is ,if your model property is also attribute in a tag. Example : For a table-element you want to provide data from external source ,so you'll define attribute data,in this case data property should be @published . <polymer-element name = "table-element" attributes ="structure data"> <template> <table class="ui table segment" id="table_element"> <tr> <th template repeat="{{col in cols}}"> {{col}} </th> </tr> <tr template repeat="{{row in data}}"> etc...... </template> <script type="application/dart" src="table_element.dart"></script> </polymer-element> @CustomTag("table-element") class Table extends PolymerElement { @published List<Map<String,String>> structure; // table struture column name and value factory @published List<dynamic> data; // table data @observable - is one way binding - ( model to view) If you just want to pass data from model to view use @observable Example : To use above table element i have to provide data ,in this case data and structure will be observable in my table-test dart code. <polymer-element name = "table-test"> <template> <search-box data ="{{data}}" ></search-box> <table-element structure ="{{structure}}" data = "{{data}}" ></table-element> </template> <script type="application/dart" src="table_test.dart"></script> </polymer-element> dart code CustomTag("table-test") class Test extends PolymerElement { @observable List<People> data = toObservable([new People("chandra","<a href=\"http://google.com\" target=\"_blank\"> kode</a>"), new People("ravi","kiran"),new People("justin","mat")]); @observable List<Map<String,String>> structure = [{ "columnName" : "First Name", "fieldName" : "fname"}, {"columnName" : "Last Name", "fieldName" : "lname","cellFactory" :"html"}]; Test.created():super.created(); Examples are taken from My Repo
unknown
d19514
test
I think you just need the right group by clause: SELECT platform, version, COUNT(*) AS count FROM user GROUP BY platform, version; Your query is not actually syntactically correct SQL. The column platform is in the SELECT but it is not in the GROUP BY. Almost any database other than MySQL would correctly return an error.
unknown
d19515
test
I think the documentation (and the solution linked in the question) give good guidance. But here's what I got to work, anyhow: Receiving API endpoint: [HttpPost] [Route("{*filePath:regex(^.*\\.[[^\\\\/]]+[[A-Za-z0-9]]$)}")] public async Task<IActionResult> AddFile([FromRoute] AddFileRequest request, [FromForm] AddFileRequestDetails body, CancellationToken cancellationToken) And the corresponding refit client call: [Multipart] [Post("/{**filePath}")] Task AddFile(string filePath, [AliasAs("Description")] string description, [AliasAs("File")] StreamPart filepart); The important thing here is that ALL of the member properties of the Form body(not including file) have to be decorated with the "AliasAs" attribute. Calling on the sending side: System.IO.Stream FileStream = request.File.OpenReadStream(); StreamPart sp = new StreamPart(FileStream, request.FileName); try { await _filesClient.AddFile(request.FilePath, request.Description, sp); } catch (ApiException ae) { ... throw new Exception("Refit FileClient API Exception", ae); } Hope this helps the next person...
unknown
d19516
test
You can use iTextSharp or PdfSharp to implement a solution, assuming each exercise starts on a new page. Loop through the document's pages and search the current page for the word 'Exercise'. If the word is found, create a new empty document, extract the page from the source file and insert it in the new document. Search the next page, if the 'Exercise' word is found, save the previous document and create a new one. If the word is not found, extract the page and insert in the document you already created. In this way you can implement any filtering you want.
unknown
d19517
test
Something like this should work: Right("0" & Month([DateField]),2) & "/" & Right(Year([DateField]),2) & "-" & [GroupNumber]
unknown
d19518
test
You can try something like, 1 User fills out the form and hits submit 2 in the POST view where you handle the form, use the "**is_authenticated**" function and, a)if the user is authenticated you handle the form as usual... b)else set the contents of the form into a session variable in the views and redirect to the login page like, request.session['review_body'] = request.post.get(the_form_body_field) 3 as per what you've said, after login it goes to profile page and form is submitted... a)so in views where you serve the profile page, check if the session variable containing form data's exist and has values b)if yes, directly save the contents from your views and clear the session data
unknown
d19519
test
SELECT * FROM ( SELECT date_trunc('week', created_at) AS week , rank() OVER (PARTITION BY date_trunc('week', created_at) ORDER BY sum(win_price) DESC NULLS LAST) AS rnk , sum(win_price) AS win_price , user_id , min(created_at) min_create FROM coupons WHERE played = true AND win = 'Y' AND created_at BETWEEN '27-07-2015' AND '03-08-2015' GROUP BY 1, 4 -- reference to 1st & 4th column ) sub WHERE rnk = 1 ORDER BY week; This returns the winning users per week - the ones with the greatest sum(win_price). I use rank() instead of row_number(), since you did not define a tiebreaker for multiple winners per week. The added clause NULLS LAST prevents NULL values from sorting on top in descending order (DESC) - if you should have NULL. See: * *Sort by column ASC, but NULL values first? The week is represented by the starting timestamp, you can format that any way you like with to_char(). The key feature of this query: you can use window functions over aggregate functions. See: * *Postgres window function and group by exception Consider the sequence of events in a SELECT query: * *Best way to get result count before LIMIT was applied
unknown
d19520
test
It appears that you try to set "by reference" assignment so that Application("Admin") will change when Session("Admin") changes. I fear such thing is not possible in classic ASP. The only elegant way I can think of is adding helper method that will be included in all pages: Sub AssignAdminSession(value) Session("Admin") = value Application("Admin") = value End Sub Then instead of just Session("Admin") = "something" have everywhere: Call AssignAdminSession("value here")
unknown
d19521
test
It happens because ALAssets is fetching in block. This means, you call Share controller when image is not fetched yet. I propose you add some progress hud like this with 2-3 seconds delay. This will solve your problem and it'll be friendly for the user. To check if it really works, test the code below: - (void)fetchLastPhoto { __block UIImage *latestPhoto; ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) { [group setAssetsFilter:[ALAssetsFilter allPhotos]]; [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) { if (alAsset) { ALAssetRepresentation *representation = [alAsset defaultRepresentation]; latestPhoto = [UIImage imageWithCGImage:[representation fullScreenImage]]; _imageToShare = latestPhoto; *stop = YES; *innerStop = YES; } NSLog(@"Image fetched"); }]; } failureBlock: ^(NSError *error) { NSLog(@"No groups"); }]; } - (IBAction)buttonShare:(id)sender { [self fetchLastPhoto]; [self performSelector:@selector(openShareController) withObject:nil afterDelay:3.0f]; } -(void)openShareController { NSLog(@"Share controller called"); SLComposeViewController *slComposeViewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter]; [slComposeViewController addImage:self.imageToShare]; [self presentViewController:slComposeViewController animated:YES completion:NULL]; }
unknown
d19522
test
Consider checking for a malicious code included on your pages. And yes it's likely that some one is trying to access those pages but it may not execute because it's invalid path. You should consider blocking such ip addresses after checking in logs. A: Although trying to reach an admin page seems a suspicious action, in our website we come accross this issue every one in ten thousand requests. We think that a browser extension or a virus like program tries to change URL or trying to add this keyword to URL. Not for a hacking purpose, but to redirect to their advertisement website. Very similar issue here: Weird characters in URL
unknown
d19523
test
You can use different methodes $this->Connect = new mysqli( $Config['mysql']['hostname'], $Config['mysql']['username'], $Config['mysql']['password'], $Config['mysql']['database'], $Config['mysql']['dataport']) or die('The connection fails, check config.php'); or if (!$this->Connection) { die('The connection fails, check config.php'); } I should put the error in the die part too if I was you: die('Connection failed' . mysqli_connect_error());
unknown
d19524
test
You cannot define page methods in ascx pages. You have to define them in your web form. If you want to have a page method, defined in your user control, you'd have to define a forwarding page method in you aspx page like below (source): in user control: [WebMethod] [ScriptMethod(UseHttpGet = true)] public static string MyUserControlPageMethod() { return "Hello from MyUserControlPageMethod"; } in aspx.cs page: [WebMethod] [ScriptMethod] public static string ForwardingToUserControlMethod() { return WebUserControl.MyUserControlMethod(); } and in aspx page: function CallUserControlPageMethod() { PageMethods.ForwardingToUserControlPageMethod(callbackFunction); } Alternatively, you could use ASMX services and jquery ajax methods (jQuery.ajax, jQuery.get, jQuery.post) to call your methods asynchronously (sample). Another option would be defining http handlers and call them via jQuery as well (tutorial).
unknown
d19525
test
You can get view's next row within the repeat with var nextRow = view1.getAllEntries().getNthEntry(repeatIndex + 2); "view1" is the xp:dominoView assigned to repeat control and "repeatIndex" is the indexVar of xp:repeat. You can get next row document's UniqueID then with nextRow ? nextRow.getUniversalID() : "" and the e.g. Form field with nextRow ? nextRow.getDocument().getItemValueString("Form") : "" Accordingly, you get the previous row with var prevRow = view1.getAllEntries().getNthEntry(repeatIndex);
unknown
d19526
test
The multiple enumeration potential is you calling Any, which will cause the first enumeration, and then a potential second enumeration by the caller of that method. In this instance, I'd guess it is mostly guaranteed that two enumerations will occur at least. The warning exists because an IEnumerable can disguise something expensive such as a database call (most likely an IQueryable), and as IEnumerable doesn't have caching as part of it's contract, it will re-enumerate the source fresh. This can lead to performance issues later on (we have been stung by this a surprising amount and we don't even use IQueryable, ours was on domain model traversal). That said, it is still only a warning, and if you are aware of the potential expense of calling an enumerable over potentially slow source multiple times then you can suppress it. The standard answer to caching the results is ToList or ToArray. Although I do remember making an IRepeatable version of IEnumerable once that internally cached as it went along. That was lost in the depths of my gratuitous code library :-) A: Enumerable.Any executes the query to check whether or not the sequnce contains elements. You could use DefaultIfEmpty to provide a different default value if there are no elements: public IEnumerable<Contact> GetContacts(IContactManager contactManager, string query) { IEnumerable<Contact> contacts = contactManager.GetContacts(query) .DefaultIfEmpty(new Contact { Name = "Example" }); return contacts; } Note that this overload is not supported in LINQ-To-SQL.
unknown
d19527
test
Since we should expect TRUE is already defined when FALSE is defined too. So in this case this would be a redefinition and be invalid. If you stay intern the #define TRUE FALSE would be valid to the standard, but would be invalid according to all logics I could imagine. But a way i have already often seen was : #define FALSE 0 #define TRUE !FALSE A: You have to remember that preprocessor macros are simply substituted. If you do e.g. #define TRUE FALSE then the processor simply replaces all places where it finds TRUE will be replaced by whatever FALSE is defined to. So indeed it's a good definition. And yes it will most likely change the program workflow, possibly in very unexpected ways that may even cause undefined behavior.
unknown
d19528
test
Add scrollPositionRestoration: "enabled" to your routing module as option. @NgModule({ imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: "enabled", //--> add this })], exports: [RouterModule] })
unknown
d19529
test
I wouldn't use this approach because it makes building a project checked out from the SCM not possible without providing the build.number property. I don't think that this is a good thing. Maybe I'm missing something though. Actually, I don't get what you are trying to achieve exactly (why don't you write the build number in the manifest for example). But, according to the Maven Features on the Teamcity website: By default, it also keeps TeamCity build number in sync with the Maven version number (...). Couldn't that be helpful? There is another thread about this here. A: Try to use generateReleasePoms property of maven-realease-plugin, maybe that helps a little.
unknown
d19530
test
string.replace(s, old, new[, maxreplace]) Function parameters * *s: The string to search and replace from. *old: The old sub-string you wish to replace. *new: The new sub-string you wish to put in-place of the old one. *maxreplace: The maximum number of times you wish to replace the sub-string. And your function: ch = ch.replace(u'۔','</s><s>') Where is the string you whant to make change as a parameter? I did not understand what is u for there Try this: ch = ch.replace(ch,'۔','</s><s>') And maybe the program reads from right to left but writes from left to right.
unknown
d19531
test
This worked for me in a word document. It may do the same for you... Function I used: import re def removeSpecialCharacters(cellValue): text=re.sub(r"[\r\n\t\x07\x0b]", "", cellValue) return text Afterwards, I used this for the values: character = table.Cell(Row = 1, Column = 1).Range.Text character = removeSpecialCharacters(character) You may also use a for loop for your solution as well.
unknown
d19532
test
Michael hartls tutorial explains well what you need, but for a short list: Curl is needed to get RVM and to test HTTP requests. You will need it to install some requirements also. Git: You need it during the tutorial, and to get some gems directly from github. Any JS platform: I've choosen NODEJS because it's the easiest one to install, but you can use any of your like: rubyracer, v8... Ruby interpreter: Then Install a ruby version. I've always install the last one as default and then install the ones needed in the project. The gems: If you are using Ruby > 2.0 install byebug if not install debugger. And rails, the last version as well. If you are following a tutorial install other version. Any editor: If you want to learn I recommend you VIM, as you will get used to develop and will learn a nice editor. Learning a nice command line editor is allways payed. So don't be afraid. You can learn sublime or gedit at any moment, but learning VIM is hardest, so start now. Then databases. Install whichever you want: MySQL. PostgreSQL SQlite Or mongo, just to practice. that should be enough to start the tutorial.
unknown
d19533
test
In general you should avoid global variables. If it will be practical, I recommend keeping them as locals and passing them as parameters to your functions. As Josh pointed out, if these variables are only used inside a single instance of the class, then you should just make them private (or protected) members of that class and be done with it. Of course, then they could only be passed in as parameters to other methods with the same access level (IE, private). Alternatively, you may consider using the Singleton Design Pattern, which is slightly cleaner (and preferable) to using globals. A: If the scope of the objects is the lifetime of the class they are instantiated in, then they should be private member variables. If they do not maintain state themselves, then you should make them static classes. You should still pass them around as variables, or at least create property accessors to get at the backing field. This way you can change implementation details without blowing up your code. SOLID design principles are a good place to start when thinking about these things. A: I have two objects that I will be mainly use inside of single class. I will initialize them at the beginning and use them throughout the life of the program. This sounds like a perfect time to use a private static readonly variable. These can be initialized in their declaration, or you can make a static constructor to initialize them. The fact that you are only referencing these objects within a single class is key point. There are other better ways to do things if these objects are ever needed outside of the single class. A: If the objects will be the same for every instance of the class then static const double PI = 3.14158; A: You should generally use accessor methods (e.g. getters and setters) and keep your internal variables private. This way the rest of your code, outside of your class, is not dependent on your actual variables. See this tutorial. A: If your class is dependent on these 2 objects then they should probably be members on the class itself. Something like this (where A is the class you are talking about and B is one of the objects you initialize: public class A { private B _b; public A(B b) { _b = b; } public void DoSomething() { //do something with _b; } private void DoSomethingElse() { //do something else with _b; } } In this example A is dependent on B (so you pass your instance of B into A's constructor or through some Dependency Injection framework). It wouldn't make a lot of sense for every method on class A to need a parameter of type B to be passed to it. A: I think in this case you should ask what makes more sense. Is there some kind of relationship between the 2 objects and the new class. Also, how often are they used in the class. Generally, If only a couple of methods use the objects, pass them around otherwise, instantiate them as class level variables (possibly using private static readonly as Jefferey suggests) and use them in the class. Making the code more readable should be your goal here.
unknown
d19534
test
for file in * do >$file done A: Just redirect from nowhere: > somefile.txt A: If you want to truncate a file to keep the n last lines of a file, you can do something like (500 lines in this example) mv file file.tmp && tail -n 500 file.tmp > file && rm file.tmp
unknown
d19535
test
hello you need to install your perDependencies, if you install a package that depends on specific versions of other packages, If it didn't find the correct version of package then "Peer dependency" is unmet, try this: npm install -g npm-install-peers npm-install-peers this will install peerDependencies
unknown
d19536
test
to show full output of your cursor use following. Log.v("Cursor Object", DatabaseUtils.dumpCursorToString(cursor)) A: Log.d("TAG", "Your Message : " + innerCursor.getString(1)); i hope it's helpful to you ..!
unknown
d19537
test
This problem seem to be a known bug for E-Lib in previous versions too. Known as: Unhandled exception when using the logging AB from multiple threads. "The underlying issue is that in .NET 2.0 RTM a parent thread's operation stack was shared with its children if such a stack existed by the time the children were created." Read more here: http://entlib.codeplex.com/workitem/9592 Hard to suggest a generic solution to this as it is very depends on the architecture of your app.
unknown
d19538
test
Defining the function like this : -->deff('y=f(x)','y=ones(x)./(1+(x.^5))') Will give the expected result : -->f(0:.5:3) ans = 1. 0.9696970 0.5 0.1163636 0.0303030 0.0101362 0.0040984
unknown
d19539
test
Skype for Business does not support its own calendar. Instead, it gets calendar data from the Exchange account of the signed in user. You can easily add a new event to the user's calendar by using the Microsoft Graph RESTful API: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/calendar_post_events
unknown
d19540
test
To get you started, here's basically how you'd start to isolate the individual fields on each line using GNU awk for FIELDWIDTHS: $ cat tst.awk BEGIN { origFS=FS } /---/ { origFS=FS split($0,f,/\s+|-+/,s) FIELDWIDTHS="" for (i=1; i in s; i++) { FIELDWIDTHS = (i>1 ? FIELDWIDTHS " " : "") length(s[i]) } } /^\s*$/ { FIELDWIDTHS="" FS=origFS } { for (i=1; i<=NF; i++) { printf "<%s>", $i, (i<NF?OFS:ORS) } print "" } . $ awk -f tst.awk file <User:><x0000001> <Forced><into><restricted><environment:><No> <Role><Name><Avail><Restricted><Env> <---------------><-----><--------------> < ><login/Corp_All >< ><Yes >< ><None >< > < ><_Example-Role-->< ><Yes >< ><_Example-Role-><-> < ><ALL_Servers-Win>< >< >< ><ALL_Servers-Wi><n> < ></US_All >< >< >< ></US_All ><> < ><Domain_GLOBAL-R><o ><Yes >< ><Domain_GLOBAL-><R> < ><le-CORE_Group-A><L >< >< ><le-CORE_Group-><A> < ><L-MacOS/Domain_>< >< >< ><L-MacOS/Domain><_> < ><GLOBAL >< >< >< ><GLOBAL ><> <Effective><rights:> <Password><login> <Non><password><login> <Allow><normal><shell> <PAM><Application><Avail><Source><Roles> <---------------><-----><--------------------> <* >< ><Yes >< ><login/US_All >< > <Privileged comm><an><ds:><><><> < Name >< >< Ava><i><l Command >< > < -------------><-->< ---><-><- ------------------><-> < ><CORP_GLOBAL-Com>< ><Yes >< ></usr/bin/getfacl >< ><CORP_GLOBAL-Role-COR>< > < ><mand-CORE_SVR_I>< >< >< >< >< ><E_SVR_INFRA_ALL-LNX/>< > < ><NFRA_ALL-V042-S>< >< >< >< >< ><CORP_GLOBAL >< > < ><00042/CORP_GLOB>< >< >< >< >< >< >< > < ><AL >< >< >< >< >< >< >< > < ><CORP_GLOBAL-Com>< ><Yes >< ></usr/bin/dzdo -l >< ><CORP_GLOBAL-Role-COR>< > < ><mand-CORE_SVR_I>< >< >< >< >< ><E_SVR_INFRA_ALL-LNX/>< > < ><NFRA_ALL-V042-S>< >< >< >< >< ><CORP_GLOBAL >< > < ><00048/CORP_GLOB>< >< >< >< >< >< >< > < ><AL >< >< >< >< >< >< >< > < ><CORP_GLOBAL-Com>< ><Yes >< ></bin/cp temp_auth >< ><CORP_GLOBAL-Role-COR>< > < ><mand-CORE_SVR_I>< >< >< ></home/sudocfg/author>< ><E_SVR_INFRA_ALL-LNX/>< > < ><NFRA_ALL-V042-S>< >< >< ><ized_keys >< ><CORP_GLOBAL >< > < ><00085/CORP_GLOB>< >< >< >< >< >< >< > < ><AL >< >< >< >< ><><><> You're going to want to buy the book Effective Awk Programming, 4th Edition, by Arnold Robbins and have it handy for reference as you start tinkering with that to see how it works and then building on it. A: I can handle one-liners, but for a report like this? I wouldn't know where to even begin. Indeed this seems hardly possible with a one-liner (unless it's one very long line). But to begin with, the problem can be analyzed and a possible solution outlined. * *Identify what parts of the input constitute the tables (where column lines are to be combined): We could use the lines of hyphens between column headers and text to identify the start of a table, and a short line or an unfitting line, where the gaps between the columns are not blank, to identify the end. *Read a table in line by line, split each line into the columns (whose margins can be derived from the hyphen lines), and, if the current line is a wrapped continuation line of the preceding line (i. e. if it has empty columns), concatenate each column's texts. In the course of this, the required column widths can be determined from the maximum combined text lengths. *Write the table out, using the before determined column widths. The following Perl program implements a solution. Note however that, since it uses seek, it cannot work on piped input, but only on a file. #!/usr/bin/perl -wn if (/---/) # here comes a table { seek ARGV, $priprior, 0; # set position back to header line push @gap, $-[1] while /(?<=-) *( )-/g; # find the column gaps $tabrow = -1; # index of current table row: no rows yet @maxlng = (0)x($#gap+2); # maximum length of text in each column while (<>) # read the table, starting with headers { # check for end of table: last if length() <= $gap[-1] or substr($_, $gap[-1], 1) ne ' '; $offset = 0; # first column start $contin = 0; # is it a continuation line? foreach $i (0..$#gap+1) { # extract column: if ($i <= $#gap) # not last column? { $column[$i] = substr $_, $offset, $gap[$i]-$offset; $offset = $gap[$i]; } else # last column { $column[$i] = substr $_, $offset; } $column[$i] =~ s/\s+$//; # remove trailing whitespace $contin += $column[$i] eq '' # column empty? } ++$tabrow unless $contin; foreach $i (0..$#gap+1) { # ugly fix to restore the space in "temp_auth /home/...", where # the column is wrapped early: -------------------- # ... # /bin/cp temp_auth # /home/sudocfg/author # ized_keys $table[$tabrow][$i] .= ' ' if $contin and length($table[1][$i])> length($table[$tabrow][$i]); # now that's fixed, proceed with normal unwrapping of the column $column[$i] =~ s/^ +// if $contin or $i; # remove leading spaces $table[$tabrow][$i] .= $column[$i]; $maxlng[$i] = length $table[$tabrow][$i] # update maximum length if $maxlng[$i] < length $table[$tabrow][$i]; } undef $_; last if eof } foreach $e (@table) { foreach $i (0..$#gap+1) { printf "%-*s", $maxlng[$i]+1, $$e[$i]; } print "\n"; } undef @gap; undef @table; } else { print $previous_line if $previous_line } $previous_line = $_; $priprior = $prior; $prior = tell ARGV; END { print $previous_line if $previous_line }
unknown
d19541
test
You can also check out archive-tar-minitar, it is partially based on minitar that you already tested out, and it doesn't seem that it emmits calls to the command line. A: I ended up giving up with using a gem to manipulate the tar archives, and just doing it by shelling out to the commandline. `cd #{container} && tar xvfz sdk.tar.gz` `cd #{container} && tar xvfz Wizard.tar.gz` #update the framework packaged with the wizard FileUtils.rm_rf(container + "/Wizard.app/Contents/Resources/SDK.bundle") FileUtils.rm_rf(container + "/Wizard.app/Contents/Resources/SDK.framework") FileUtils.mv(container + "/resources/SDK.bundle", container + "/Wizard.app/Contents/Resources/") FileUtils.mv(container + "/resources/SDK.framework", container + "/Wizard.app/Contents/Resources/") config_plist = render_to_string({ file: 'site/_wizard_config', layout: false, locals: { app_id: @version.app.id }, formats: 'xml' }) File.open(container + "/Wizard.app/Contents/Resources/Configuration.plist", 'w') { |file| file.write( config_plist ) } `cd #{container} && rm Wizard.tar.gz` `cd #{container} && tar -cvf Wizard.tar 'Wizard.app'` `cd #{container} && gzip Wizard.tar` All these backticks make me feel like I'm writing Perl again.
unknown
d19542
test
As the compiler and @xaxxon have already pointed out, there is no such wait() overload in QWaitCondition. If you want to check a condition before going on you can do it like this while (!condition()) { cond.wait(mutex); } You can of course put that into a helper function that takes a QWaitCondition, QMutex and std::function if you need this in more places. Or derive from QWaitCondition adding the overload doing the loop above.
unknown
d19543
test
/// <summary> /// Checks if string contains only letters a-z and A-Z and should not be more than 25 characters in length /// </summary> /// <param name="value">String to be matched</param> /// <returns>True if matches, false otherwise</returns> public static bool IsValidString(string value) { string pattern = @"^[a-zA-Z]{1,25}$"; return Regex.IsMatch(value, pattern); } A: The string can be up to 25 letters long. (I'm not sure if regex can check length of strings) Regexes ceartanly can check length of a string - as can be seen from the answers posted by others. However, when you are validating a user input (say, a username), I would advise doing that check separately. The problem is, that regex can only tell you if a string matched it or not. It won't tell why it didn't match. Was the text too long or did it contain unallowed characters - you can't tell. It's far from friendly, when a program says: "The supplied username contained invalid characters or was too long". Instead you should provide separate error messages for different situations. A: The regular expression you are using is an alternation of [^a-z] and [^A-Z]. And the expressions [^…] mean to match any character other than those described in the character set. So overall your expression means to match either any single character other than a-z or other than A-Z. But you rather need a regular expression that matches a-zA-Z only: [a-zA-Z] And to specify the length of that, anchor the expression with the start (^) and end ($) of the string and describe the length with the {n,m} quantifier, meaning at least n but not more than m repetitions: ^[a-zA-Z]{0,25}$ A: Regex lettersOnly = new Regex("^[a-zA-Z]{1,25}$"); * *^ means "begin matching at start of string" *[a-zA-Z] means "match lower case and upper case letters a-z" *{1,25} means "match the previous item (the character class, see above) 1 to 25 times" *$ means "only match if cursor is at end of string" A: I'm trying to create a regex to verify that a given string only has alpha characters a-z or A-Z. Easily done as many of the others have indicated using what are known as "character classes". Essentially, these allow us to specifiy a range of values to use for matching: (NOTE: for simplification, I am assuming implict ^ and $ anchors which are explained later in this post) [a-z] Match any single lower-case letter. ex: a matches, 8 doesn't match [A-Z] Match any single upper-case letter. ex: A matches, a doesn't match [0-9] Match any single digit zero to nine ex: 8 matches, a doesn't match [aeiou] Match only on a or e or i or o or u. ex: o matches, z doesn't match [a-zA-Z] Match any single lower-case OR upper-case letter. ex: A matches, a matches, 3 doesn't match These can, naturally, be negated as well: [^a-z] Match anything that is NOT an lower-case letter ex: 5 matches, A matches, a doesn't match [^A-Z] Match anything that is NOT an upper-case letter ex: 5 matches, A doesn't matche, a matches [^0-9] Match anything that is NOT a number ex: 5 doesn't match, A matches, a matches [^Aa69] Match anything as long as it is not A or a or 6 or 9 ex: 5 matches, A doesn't match, a doesn't match, 3 matches To see some common character classes, go to: http://www.regular-expressions.info/reference.html The string can be up to 25 letters long. (I'm not sure if regex can check length of strings) You can absolutely check "length" but not in the way you might imagine. We measure repetition, NOT length strictly speaking using {}: a{2} Match two a's together. ex: a doesn't match, aa matches, aca doesn't match 4{3} Match three 4's together. ex: 4 doesn't match, 44 doesn't match, 444 matches, 4434 doesn't match Repetition has values we can set to have lower and upper limits: a{2,} Match on two or more a's together. ex: a doesn't match, aa matches, aaa matches, aba doesn't match, aaaaaaaaa matches a{2,5} Match on two to five a's together. ex: a doesn't match, aa matches, aaa matches, aba doesn't match, aaaaaaaaa doesn't match Repetition extends to character classes, so: [a-z]{5} Match any five lower-case characters together. ex: bubba matches, Bubba doesn't match, BUBBA doesn't match, asdjo matches [A-Z]{2,5} Match two to five upper-case characters together. ex: bubba doesn't match, Bubba doesn't match, BUBBA matches, BUBBETTE doesn't match [0-9]{4,8} Match four to eight numbers together. ex: bubba doesn't match, 15835 matches, 44 doesn't match, 3456876353456 doesn't match [a3g]{2} Match an a OR 3 OR g if they show up twice together. ex: aa matches, ba doesn't match, 33 matches, 38 doesn't match, a3 DOESN'T match Now let's look at your regex: [^a-z]|[^A-Z] Translation: Match anything as long as it is NOT a lowercase letter OR an upper-case letter. To fix it so it meets your needs, we would rewrite it like this: Step 1: Remove the negation [a-z]|[A-Z] Translation: Find any lowercase letter OR uppercase letter. Step 2: While not stricly needed, let's clean up the OR logic a bit [a-zA-Z] Translation: Find any lowercase letter OR uppercase letter. Same as above but now using only a single set of []. Step 3: Now let's indicate "length" [a-zA-Z]{1,25} Translation: Find any lowercase letter OR uppercase letter repeated one to twenty-five times. This is where things get funky. You might think you were done here and you may well be depending on the technology you are using. Strictly speaking the regex [a-zA-Z]{1,25} will match one to twenty-five upper or lower-case letters ANYWHERE on a line: [a-zA-Z]{1,25} a matches, aZgD matches, BUBBA matches, 243242hello242552 MATCHES In fact, every example I have given so far will do the same. If that is what you want then you are in good shape but based on your question, I'm guessing you ONLY want one to twenty-five upper or lower-case letters on the entire line. For that we turn to anchors. Anchors allow us to specify those pesky details: ^ beginning of a line (I know, we just used this for negation earlier, don't get me started) $ end of a line We can use them like this: ^a{3} From the beginning of the line match a three times together ex: aaa matches, 123aaa doesn't match, aaa123 matches a{3}$ Match a three times together at the end of a line ex: aaa matches, 123aaa matches, aaa123 doesn't match ^a{3}$ Match a three times together for the ENTIRE line ex: aaa matches, 123aaa doesn't match, aaa123 doesn't match Notice that aaa matches in all cases because it has three a's at the beginning and end of the line technically speaking. So the final, technically correct solution, for finding a "word" that is "up to five characters long" on a line would be: ^[a-zA-Z]{1,25}$ The funky part is that some technologies implicitly put anchors in the regex for you and some don't. You just have to test your regex or read the docs to see if you have implicit anchors. A: Do I understand correctly that it can only contain either uppercase or lowercase letters? new Regex("^([a-z]{1,25}|[A-Z]{1,25})$") A regular expression seems to be the right thing to use for this case. By the way, the caret ("^") at the first place inside a character class means "not", so your "[^a-z]|[^A-Z]" would mean "not any lowercase letter, or not any uppercase letter" (disregarding that a-z are not all letters).
unknown
d19544
test
From looking at the CascadingDropDown sample and your code, I think you may have the properties set slightly wrong. Your CascadingDropDown's TargetControlId is currently ddlCategories, however I think this value should be set to the ParentControlId property instead, and you need another DropDownList which becomes the target control of the extender e.g. <asp:DropDownList ID="ddlCategories" runat="server" /><br/> <asp:DropDownList id="ddlSubcategories" runat="server" /> <asp:CascadingDropDown ID="cddCategory" TargetControlID="ddlSubcategories" ParentControlId="ddlCategories" runat="server" ServicePath="~\Categories.asmx" ServiceMethod="GetCategories" Category="Category" PromptText="Please select a category" LoadingText="[Loading categories...]" />
unknown
d19545
test
Since I wasn't using the fetchAppInitialization action for anything but this single use case, I've simply removed it and moved the logic straight into the setupStoreAsync function. This is a bit more compact. It's not optimal, since the results.map logic is still included, but at least we don't use createAsyncThunk any more. export const setupStoreAsync = () => { return new Promise((resolve, reject) => { const store = setupStore() new Promise((resolve, reject) => Promise.all([store.dispatch(fetchVersionInfo())]).then(results => { results.map(result => result.action.error && reject(result.error)) resolve() }) ) .then(_ => resolve(store)) .catch(e => reject(e.message)) }) } Update: I was able to make the code even prettier by using async/await. export const setupStoreAsync = async () => { const store = setupStore() const results = await Promise.all([store.dispatch(fetchVersionInfo())]) results.forEach(result => { if (result.action.error) throw result.error }) return store }
unknown
d19546
test
memory_block next; It is a wrong code. Try this memory_block *next; next = malloc(sizeof(memory_block));
unknown
d19547
test
Use GroupBy.transform with GroupBy.last for each column generated by Index.difference: df['timestamp'] = pd.to_datetime(df['timestamp'], format='%m/%d/%y') for c in df.columns.difference(['project_id','timestamp']): df[c] = df.groupby(['project_id',c], sort=False)['timestamp'].transform('last') print (df) project_id project_name region style effect representative \ 0 1 2020-09-05 2020-04-06 2019-10-15 2020-09-05 2020-04-06 1 1 2020-09-05 2020-04-06 2019-10-15 2020-09-05 2020-04-06 2 1 2020-08-20 2020-04-06 2019-10-15 2019-10-15 2020-04-06 3 1 2019-10-15 2020-04-06 2019-10-15 2019-10-15 2020-04-06 4 1 2019-10-15 2019-10-15 2019-10-15 2019-10-15 2019-10-15 5 1 2019-10-15 2019-10-15 2019-10-15 2019-10-15 2019-10-15 timestamp 0 2020-10-01 1 2020-09-05 2 2020-08-20 3 2020-04-06 4 2019-12-31 If need original format add Series.dt.strftime: df['timestamp'] = pd.to_datetime(df['timestamp'], format='%m/%d/%y') for c in df.columns.difference(['project_id','timestamp']): df[c] = (df.groupby(['project_id',c], sort=False)['timestamp'].transform('last') .dt.strftime('%m/%d/%y')) print (df) project_id project_name region style effect representative \ 0 1 09/05/20 04/06/20 10/15/19 09/05/20 04/06/20 1 1 09/05/20 04/06/20 10/15/19 09/05/20 04/06/20 2 1 08/20/20 04/06/20 10/15/19 10/15/19 04/06/20 3 1 10/15/19 04/06/20 10/15/19 10/15/19 04/06/20 4 1 10/15/19 10/15/19 10/15/19 10/15/19 10/15/19 5 1 10/15/19 10/15/19 10/15/19 10/15/19 10/15/19 timestamp 0 2020-10-01 1 2020-09-05 2 2020-08-20 3 2020-04-06 4 2019-12-31 5 2019-10-15 EDIT: Add fillna by minimal timestamp: df['timestamp'] = pd.to_datetime(df['timestamp'], format='%m/%d/%y') min1 = df['timestamp'].min() for c in df.columns.difference(['project_id','timestamp']): df[c] = df.groupby(['project_id',c], sort=False)['timestamp'].transform('last').fillna(min1) print (df) project_id project_name region style effect representative \ 0 1 2020-09-05 2020-04-06 2019-10-15 2020-09-05 2020-04-06 1 1 2020-09-05 2020-04-06 2019-10-15 2020-09-05 2020-04-06 2 1 2020-08-20 2020-04-06 2019-10-15 2019-10-15 2020-04-06 3 1 2019-10-15 2020-04-06 2019-10-15 2019-10-15 2020-04-06 4 1 2019-10-15 2019-10-15 2019-10-15 2019-10-15 2019-10-15 5 1 2019-10-15 2019-10-15 2019-10-15 2019-10-15 2019-10-15 lazy timestamp 0 2020-09-05 2020-10-01 1 2020-09-05 2020-09-05 2 2019-10-15 2020-08-20 3 2019-10-15 2020-04-06 4 2019-10-15 2019-12-31 5 2019-10-15 2019-10-15
unknown
d19548
test
Some quick first impressions I got when browsing your projects before cloning them: * *You should not use Lombok + native AspectJ together in a compile-time weaving scenario, see my answer here. *Possible workarounds would be multi-phase compilation, i.e. first Java + Lombok and then post-compile-time weaving with AspectJ, see my answer here. Alternatively, use delombok in order to first generate source code with Lombok annotations expanded into equivalent source code and then compile the generated sources with AspectJ. *On a second look, your sample aspect module does not seem to use any Lombok, so you do not need that dependency. But probably your real project does, hence my remarks above. *Of course, you can use compile-time weaving in order to weave your aspects, as you suggested. You need to correctly configure AspectJ Maven Plugin in this case, though, which you did not. You need to tell it in the Spring Boot module where to find the aspect library and which dependencies to weave, in addition to the main application. Did you ever read the plugin documentation, e.g. chapters Weaving classes in jars, Using aspect libraries and Multi-module use of AspectJ? I also answered tons of related questions here already. *But actually, the preferred approach for weaving aspects into Spring applications is to use load-time weaving (LTW), as described in the Spring manual. That should be easier to configure and you would not need any AspectJ Maven Plugin stuff and probably would not have any Lombok issues during compilation either. Judging from your sample projects and the absence of any aspectLibraries and weaveDependencies sections in your AspectJ Maven configuration, you simply did not bother to read any documentation, which leaves me to wonder what you did during the one month you tried to get this working. I would appreaciate a comment, explaining why you want to use CTW instead of LTW. The only reason I can think of is that in addition to your native aspect, you also want to use Spring AOP aspects withing your Spring application. But if you activate native AspectJ LTW, you cannot use Spring AOP at the same time anymore. If that is not an issue, I recommend LTW, as it is documented and tested well in Spring. CTW is no problem either, but more difficult to understand and manage in your POMs. Update: OK, I did not want to wait any longer for your reason to use CTW and simply decided to show you a LTW solution instead. What I did was: * *Remove AspectJ Maven Plugin and AspectJ Tools from your Spring project *Add src/main/resources/org/aspectj/aop.xml, configuring it to use your aspect and target your base package + subpackages *Fix pointcut to also use your base package + subpackages, because in your base package there are no classes. This is a typical beginner's mistake. You need to use execution(* com.ak..*(..)) with .., not just com.ak.*. Non-essential cosmetics I applied are: * *Call context.getBean(TestController.class).mainRequest() from the Spring Boot application's main method in order to automatically produce some aspect output, in order to avoid having to use curl or a web browser in order to call a local URL. *Use the Spring application as an auto-closeable via try-with-resources in order to make the application close after creating the desired log output. *Change the aspect to also log the joinpoint in order to see in the log, which methods it actually intercepts. Otherwise all log lines look the same, which is not quite helpful. *Use try-finally in order to make sure that the log message after proceeding to the original method is also logged in case of an exception. The diff looks like this (I hope you can read diffs): diff --git a/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java b/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java --- a/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java (revision Staged) +++ b/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java (date 1626233247623) @@ -7,14 +7,14 @@ @Aspect public class MethodLogAspect { - @Around("@annotation( MethodLog) && (execution(* com.ak.*(..)))") + @Around("@annotation(MethodLog) && execution(* com.ak..*(..))") public Object wrap(final ProceedingJoinPoint joinPoint) throws Throwable { - System.out.println("***Aspect invoked before calling method***"); - - final Object obj = joinPoint.proceed(); - - System.out.println("***Aspect invoked after calling method***"); - - return obj; + System.out.println("[BEFORE] " + joinPoint); + try { + return joinPoint.proceed(); + } + finally { + System.out.println("[AFTER] " + joinPoint); + } } } diff --git a/src/main/java/com/ak/ParentprojectSpringbootApplication.java b/src/main/java/com/ak/ParentprojectSpringbootApplication.java --- a/src/main/java/com/ak/ParentprojectSpringbootApplication.java (revision Staged) +++ b/src/main/java/com/ak/ParentprojectSpringbootApplication.java (date 1626233555873) @@ -1,14 +1,17 @@ package com.ak; +import com.ak.controller.TestController; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication(scanBasePackages = { "com.ak.*" }) -//@SpringBootApplication public class ParentprojectSpringbootApplication { public static void main(String[] args) { - SpringApplication.run(ParentprojectSpringbootApplication.class, args); + try (ConfigurableApplicationContext context = SpringApplication.run(ParentprojectSpringbootApplication.class, args)) { + context.getBean(TestController.class).mainRequest(); + } } } diff --git a/parentproject-springboot/pom.xml b/parentproject-springboot/pom.xml --- a/parentproject-springboot/pom.xml (revision Staged) +++ b/parentproject-springboot/pom.xml (date 1626232421474) @@ -71,13 +71,6 @@ <version>1.9.6</version> </dependency> - <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjtools --> - <dependency> - <groupId>org.aspectj</groupId> - <artifactId>aspectjtools</artifactId> - <version>1.9.6</version> - </dependency> - <dependency> <groupId>com.ak.aspect</groupId> <artifactId>aspect-test-project</artifactId> @@ -100,24 +93,6 @@ </configuration> </plugin> - <plugin> - <groupId>com.nickwongdev</groupId> - <artifactId>aspectj-maven-plugin</artifactId> - <version>1.12.6</version> - <configuration> - <source>11</source> - <target>11</target> - <complianceLevel>11</complianceLevel> - </configuration> - <executions> - <execution> - <goals> - <goal>compile</goal> - <goal>test-compile</goal> - </goals> - </execution> - </executions> - </plugin> </plugins> </build> For your convenience, here are the complete changed files: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.2</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.ak</groupId> <artifactId>parentproject-springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>parentproject-springboot</name> <description>Test project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.ak.dependency</groupId> <artifactId>dependencyprojet</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- aspectj runtime dependency --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.9.6</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.6</version> </dependency> <dependency> <groupId>com.ak.aspect</groupId> <artifactId>aspect-test-project</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project> <!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"> <aspectj> <weaver options="-verbose -showWeaveInfo"> <!-- only weave classes in our application-specific packages --> <include within="com.ak..*"/> </weaver> <aspects> <aspect name="com.ak.aspect.MethodLogAspect"/> </aspects> </aspectj> package com.ak.aspect; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @Aspect public class MethodLogAspect { @Around("@annotation(MethodLog) && execution(* com.ak..*(..))") public Object wrap(final ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("[BEFORE] " + joinPoint); try { return joinPoint.proceed(); } finally { System.out.println("[AFTER] " + joinPoint); } } } package com.ak; import com.ak.controller.TestController; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication(scanBasePackages = { "com.ak.*" }) public class ParentprojectSpringbootApplication { public static void main(String[] args) { try (ConfigurableApplicationContext context = SpringApplication.run(ParentprojectSpringbootApplication.class, args)) { context.getBean(TestController.class).mainRequest(); } } } Now you simply make sure to add the JVM argument -javaagent:/path/to/aspectjweaver-1.9.6.jar to your Java command line in order to activate native AspectJ LTW. For more details about how to configure LTW within Spring if more sophisticated ways, please read the Spring manual, section Using AspectJ with Spring Applications. The console log should look something like this: [AppClassLoader@3764951d] info AspectJ Weaver Version 1.9.6 built on Tuesday Jul 21, 2020 at 13:30:08 PDT [AppClassLoader@3764951d] info register classloader jdk.internal.loader.ClassLoaders$AppClassLoader@3764951d [AppClassLoader@3764951d] info using configuration /C:/Users/alexa/Documents/java-src/SO_AJ_SpringCTWMultiModule_68040124/parentproject-springboot/target/classes/org/aspectj/aop.xml [AppClassLoader@3764951d] info register aspect com.ak.aspect.MethodLogAspect [AppClassLoader@3764951d] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified [RestartClassLoader@1f385e10] info AspectJ Weaver Version 1.9.6 built on Tuesday Jul 21, 2020 at 13:30:08 PDT [RestartClassLoader@1f385e10] info register classloader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@1f385e10 [RestartClassLoader@1f385e10] info using configuration /C:/Users/alexa/Documents/java-src/SO_AJ_SpringCTWMultiModule_68040124/parentproject-springboot/target/classes/org/aspectj/aop.xml [RestartClassLoader@1f385e10] info register aspect com.ak.aspect.MethodLogAspect . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.5.2) (...) [RestartClassLoader@1f385e10] weaveinfo Join point 'method-execution(com.ak.dependency.model.AccountInfo com.ak.service.TestService.incomingRequest())' in Type 'com.ak.service.TestService' (TestService.java:20) advised by around advice from 'com.ak.aspect.MethodLogAspect' (MethodLogAspect.java) [RestartClassLoader@1f385e10] weaveinfo Join point 'method-execution(com.ak.dependency.model.AccountInfo com.ak.dependency.Route.accountInfo())' in Type 'com.ak.dependency.Route' (Route.java:12) advised by around advice from 'com.ak.aspect.MethodLogAspect' (MethodLogAspect.java) [RestartClassLoader@1f385e10] weaveinfo Join point 'method-execution(com.ak.dependency.model.BalanceInfo com.ak.dependency.Pipeline.balanceInfo())' in Type 'com.ak.dependency.Pipeline' (Pipeline.java:11) advised by around advice from 'com.ak.aspect.MethodLogAspect' (MethodLogAspect.java) (...) Controller [BEFORE] execution(AccountInfo com.ak.service.TestService.incomingRequest()) [BEFORE] execution(AccountInfo com.ak.dependency.Route.accountInfo()) [BEFORE] execution(BalanceInfo com.ak.dependency.Pipeline.balanceInfo()) [AFTER] execution(BalanceInfo com.ak.dependency.Pipeline.balanceInfo()) [AFTER] execution(AccountInfo com.ak.dependency.Route.accountInfo()) [AFTER] execution(AccountInfo com.ak.service.TestService.incomingRequest()) (...)
unknown
d19549
test
Appreciate that applying or popping a Git stash just alters the working directory and/or stage. It does not make a new commit. Therefore, simply doing a hard reset should get you back to where you were before the first stash: # from your branch git reset --hard That being said, if you wanted to retain some permutation of the changes since the first stash, that is another story and would require more work and thought to pull off. Note: Generally speaking, popping a Git stash is risky, because if something goes wrong along the way, you can't reapply the same stash as it has already been popped from the stack. Use git stash apply for best results. A: git stash list <shows all the saved stashes> git stash show 'stash{0}' <displays changes in this stash> <change index according to the one you want, 0 is the last saved stash> git stash apply 'stash{0}' <applies the stash>
unknown
d19550
test
One solution is union all: select o.Object_ID, reqCon.Connector_ID, req.Object_ID as Requirement_ID from t_object o join t_connector reqCon on reqCon.End_Object_ID = o.Object_ID and reqCon.Stereotype = 'deriveReqt' join t_object req on reqCon.Start_Object_ID = req.Object_ID and req.Stereotype = 'functionalRequirement' union all select o.Object_ID, min(reqCon.Connector_ID), null as Requirement_ID from t_object o left join t_connector reqCon on reqCon.End_Object_ID = o.Object_ID and reqCon.Stereotype = 'deriveReqt' left join t_object req on reqCon.Start_Object_ID = req.Object_ID and req.Stereotype = 'functionalRequirement' group by o.Object_Id having sum(req.Object_Id is not null) = 0; The first query brings in the matches. The second brings in the one row per object that has no match.
unknown
d19551
test
It shows you installed all the simulators. Just Quit the Xcode and open again. It wil show you a window same as below. Also please cross check that, the downlaoded SDK's are available under Application->Xcode.app->right-click->Show Package Contents ->Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs Also cross check the Base SDK and Target devices.
unknown
d19552
test
Your code is unreachable because you have an infinite while loop before main() definition. It's a good practice in applications that require while loop to put it inside if name == 'main' condition after all variables are declared. Like this: if __name__ == '__main__': while True: do_something()
unknown
d19553
test
Export to a CSV file instead of an XLS - there's no size limit in CSVs. I get 10 GB+ CSV files from my clients on a regular basis. A: Yes that is a limitation of Excel in any version eralier than 2007. If you are going from one server to another server, it is silly to use Excel anyway as it has all kinds of bad issues with data conversion. Use a pipe delimted text file and life will be much better. Frankly SSIS is so bad at handling Excel, we try very hard to get clients to accept a text file even if the file is going to a person who wants to play with it in Excel (Excel can easily open a text file.)
unknown
d19554
test
A").Find(" test1234 : ", LookIn:=xlValues) If Not a Is Nothing Then wks.Cells(LastRow, 1) = Split(a.value, ":")(1) End If wkbData.Close False Range("A:M").EntireColumn.AutoFit Range("A1").AutoFilter Debug.Print "A: " & oFSO.GetBaseName(ofile) Dict.Add oFSO.GetBaseName(ofile), 1 Next file Else 'skip Debug.Print "E: " & oFSO.GetBaseName(ofile) End If Next ofile Application.ScreenUpdating = True Application.EnableEvents = True Application.DisplayStatusBar = True End Sub
unknown
d19555
test
I suggest you look at ResourceT: ResourceT is a monad transformer which creates a region of code where you can safely allocate resources. A: You can use System.Mem.Weak.addFinalizer for this. Unfortunately the semantics for weak references can be a little difficult to understand at first. The warning note is particularly important. If you can attach an IORef, MVar, or TVar to your key, and make a weak reference/finalizer associated with that, it's likely to be much more reliable. In the special case that your key is a pointer to non-managed memory (e.g. some C data structure), you should instead create a ForeignPtr and attach a finalizer to it. The semantics for these finalizers are a little different; rather than an arbitrary IO action the finalizer must be a function pointer to an external function.
unknown
d19556
test
Your filter should work just fine, but the problem you're facing is another. If you are using views (as you appear to do in the example) you need to return a redirect view from your controller in order to force a redirect; just instructing the response object to redirect won't work because Spring MVC infrastructure will try to do its thing (i.e. view resolution) before the Response is returned to the Servlet container. For instance, if you use the convention to return the view name as a String from your controller method, you need to do the following in your controller: @RequestMapping("/redirectTest") public String redirectTest() { return "redirect:http://www.example.com"; }
unknown
d19557
test
After a 5 minute search on Google I found the following link https://www.experts-exchange.com/questions/27768384/Outlook-macro-to-resize-picture-s.html to summarise though this should help you (untested): This macro will resize all pictures, including those in your signature (if any), in the currently open message to 75% of their height and width. Follow these instructions to add the code to Outlook. * *Start Outlook *Press ALT+F11 to open the Visual Basic Editor *If not already expanded, expand Microsoft Office Outlook Objects *If not already expanded, expand Modules *Select an existing module (e.g. Module1) by double-clicking on it or create a new module by right-clicking Modules and selecting Insert > Module. *Copy the code from the code snippet box and paste it into the right-hand pane of Outlook's VB Editor window *Click the diskette icon on the toolbar to save the changes *Close the VB Editor Here's how to add a button to the QAT for running the macro with a single click. Outlook 2010. http://www.howto-outlook.com/howto/macrobutton.htm#qat Sub ResizeAllPicsTo75Pct() Const wdInlineShapePicture = 3 Dim olkMsg As Outlook.MailItem, wrdDoc As Object, wrdShp As Object Set olkMsg = Application.ActiveInspector.CurrentItem Set wrdDoc = olkMsg.GetInspector.WordEditor For Each wrdShp In wrdDoc.InlineShapes If wrdShp.Type = wdInlineShapePicture Then wrdShp.ScaleHeight = 75 wrdShp.ScaleWidth = 75 End If Next Set olkMsg = Nothing Set wrdDoc = Nothing Set wrdShp = Nothing End Sub
unknown
d19558
test
I struggled with this - I kept getting an error saying package couldn't be found. Running below in command prompt worked for me. conda install -c asmeurer pattern=2.5 A: On windows, open cmd.exe and type: conda install pattern This should do it ;) A: Sometimes this happens when you have multiple versions of Python/Anaconda installed on your machine. As the Pattern package does not run on Python 3.4, you need to launch IPython Notebook from the Anaconda server that runs Python 2.7. So the first step is to make sure that you install the Pattern package using pip in the version of Anaconda that runs Python 2.7. For example, C:\Users\MyName\Anaconda\Scripts\pip install pattern The second step is to make sure that you run ipython notebook from the correct path. For example, C:\Users\MyName\Anaconda\Scripts\ipython notebook That should do it.
unknown
d19559
test
Since the documentation doesn't say anything, you can safely assume that the delegate will be called from the run loop (main thread or UI thread, depending on which term you prefer).
unknown
d19560
test
Try this one: '"C:\Program Files(x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86 & msbuild ALL_BUILD.vcxproj' You can't use inside "" - " (it will be escaped) A: the "x x" on command line is equivalent to a 'x x' in subprocess.call. eventually you can leave some of the " out. however.. did you try os.system? import os os.system('cmd.exe /k ""C:\Program Files(x86)\Microsoft Visual Studio 10.0\VC vcvarsall.bat" x86 & msbuild ALL_BUILD.vcxproj"') A: The following from a Windows command-line reference I have seems relevant: * Using multiple commands You can use multiple commands separated by the command separator && for string, but you must enclose them in quotation marks (for example, "command&&command&&command"). * Processing quotation marks If you specify /c or /k, cmd processes the remainder of string and quotation marks are preserved only if all of the following conditions are met: o You do not use /s. o You use exactly one set of quotation marks. o You do not use any special characters within the quotation marks (for example: &<>( ) @ ^ |). o You use one or more white-space characters within the quotation marks. o The string within quotation marks is the name of an executable file. If the previous conditions are not met, string is processed by examining the first character to verify whether or not it is an opening quotation mark. If the first character is an opening quotation mark, it is stripped along with the closing quotation mark. Any text following the closing quotation marks is preserved.
unknown
d19561
test
I don't believe you need Business Intelligence Development Studio for this. You should be able to link to the remote server, run an external query and then do an SELECT INTO statement to insert the table data directly into your database. A: (i am assuming that you are running SQL Server 2005+) If you have access to both SQL Servers, simply use the Data Import / Export wizard. * *Open Management Studio and connect to source database server. *Right click the source database and click Export Data. *Follow the wizard. It will ask to target database and table. You can create a new database / table at the target system with this wizard. You can also use SQL Script Generator, a free & great tool which allows you to script both database, table with it's data. See http://sqlscriptgenerator.com/ for more information about the tool. And yes, you don't need Business Intelligence Development Studio.
unknown
d19562
test
Here are some ideas, I am not sure what your requirements are, so they might not fit: * *Change Visit into operator(). Then the call syntax reduces to dynamic_call<A,B>::call(v, a); as you required. Of course that is only possible if the interface of the visitor may be changed. *Change func(*t) in call_impl to func.Visit(*t). Then again the caller can use dynamic_call<A,B>::call(v, a); and no change to the interface of the visitor is necessary. However every visitor used with dynamic_call now needs to define Visit as visitor method. I think operator() is cleaner and follows the usual patterns, e.g. for Predicates in the standard library more. I don't particularly like either of these because the caller always has to know the possible overloads available in the visitor and has to remember using dynamic_call. So I propose to solve everything in the visitor struct: *struct Visitor { void Visit(A&) { cout << "visited for a" << endl; } void Visit(B&) { cout << "visited for b" << endl; } void Visit(Base& x) { dynamic_call<A,B>::call([this](auto& x){Visit(x);}, x); } }; This can be called with v.Visit(a), v.Visit(b) and v.Visit(base). This way the user of Visitor does not need to know anything about the varying behavior for different derived classes. *If you do not want to modify Visitor, then you can just add the overload via inheritance: struct DynamicVisitor : Visitor { void Visit(Base& x) { dynamic_call<A,B>::call([this](auto& x){Visit(x);}, x); } }; The points can be combined, for example into: struct Visitor { void operator()(A&) { cout << "visited for a" << endl; } void operator()(B&) { cout << "visited for b" << endl; } void operator()(Base& x) { dynamic_call<A,B>::call(*this, x); } }; Used as v(a), v(b) and v(base).
unknown
d19563
test
You can use broadcasted comparison to generate a mask, and index into arr accordingly: arr[np.arange(arr.shape[1]) <= idxs[:, None]] = 0 print(arr) array([[0, 2, 3, 4], [0, 0, 3, 4], [0, 0, 0, 4], [0, 2, 3, 4]]) A: This does the trick: import numpy as np arr = np.array([[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]) idxs = [0,1,2,0] for i,j in zip(range(arr.shape[0]),idxs): arr[i,:j+1]=0 A: Here is a sparse solution that may be useful in cases where only a small fraction of places should be zeroed out: >>> idx = idxs+1 >>> I = idx.cumsum() >>> cidx = np.ones((I[-1],), int) >>> cidx[0] = 0 >>> cidx[I[:-1]]-=idx[:-1] >>> cidx=np.cumsum(cidx) >>> ridx = np.repeat(np.arange(idx.size), idx) >>> arr[ridx, cidx]=0 >>> arr array([[0, 2, 3, 4], [0, 0, 3, 4], [0, 0, 0, 4], [0, 2, 3, 4]]) Explanation: We need to construct the coordinates of the positions we want to put zeros in. The row indices are easy: we just need to go from 0 to 3 repeating each number to fill the corresponding slice. The column indices start at zero and most of the time are incremented by 1. So to construct them we use cumsum on mostly ones. Only at the start of each new row we have to reset. We do that by subtracting the length of the corresponding slice such as to cancel the ones we have summed in that row. A: import numpy as np arr = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) idxs = np.array([0, 1, 2, 0]) for i, idx in enumerate(idxs): arr[i,:idx+1] = 0
unknown
d19564
test
Here you have the main type of collections available in C#: https://msdn.microsoft.com/en-us/library/ybcx56wz.aspx All of them can be used in Windows Phone.
unknown
d19565
test
Try this: https://codepen.io/tjvantoll/pen/JEKIu (you need to set fixed column widths) HTML: <table class="fixed_headers"> <thead> <tr> <th>Name</th> <th>Color</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>Apple</td> <td>Red</td> <td>These are red.</td> </tr> <!-- more stuff --> </tbody> </table> CSS: .fixed_headers { width: 750px; table-layout: fixed; border-collapse: collapse; } .fixed_headers th { text-decoration: underline; } .fixed_headers th, .fixed_headers td { padding: 5px; text-align: left; } .fixed_headers td:nth-child(1), .fixed_headers th:nth-child(1) { min-width: 200px; } .fixed_headers td:nth-child(2), .fixed_headers th:nth-child(2) { min-width: 200px; } .fixed_headers td:nth-child(3), .fixed_headers th:nth-child(3) { width: 350px; } .fixed_headers thead { background-color: #333; color: #FDFDFD; } .fixed_headers thead tr { display: block; position: relative; } .fixed_headers tbody { display: block; overflow: auto; width: 100%; height: 300px; } .fixed_headers tbody tr:nth-child(even) { background-color: #DDD; } .old_ie_wrapper { height: 300px; width: 750px; overflow-x: hidden; overflow-y: auto; } .old_ie_wrapper tbody { height: auto; }
unknown
d19566
test
I have switched to the mjackson expect library. It seems to be working fine. Thanks. A: Please see https://github.com/JamieMason/Jasmine-Matchers/tree/master/examples/jest for a working example of jasmine-expect with jest, thanks.
unknown
d19567
test
SIGINT is ignored by the application that calls system (for as long as system is executing). It's not ignored by the application that's spawned by system. So if you hit CTRL+c, that will abort the execution of loop.py, but not of test_loop.py. So if you add some code after the call to system, you'll see that that code will execute after you press CTRL+c.
unknown
d19568
test
Assuming you have a Panel somewhere on your site: Label myLabel = new Label(); myLabel.Text = "My Name"; myLabel.CssClass = "labelClass"; pnlItems.Controls.Add(myLabel); To have ul / li items (or something completely customisable): HtmlGenericControl ulControl = new HtmlGenericControl("ul"); pnlItems.Controls.Add(ulControl); foreach (object myThing in myItems) { HtmlGenericControl itemControl = new HtmlGenericControl("li"); itemControl.InnerHtml = myThing.GetMarkup(); ulControl.Controls.Add(itemControl); } Note this is untested - I'm fairly sure you can add controls to an Html Generic Control.
unknown
d19569
test
the documentation says that firebase.auth().currentUser NOT firebase.auth().currentUser() is the correct way to get the user
unknown
d19570
test
https://au.mathworks.com/help/symbolic/differentiation.html You need to define the symbols using syms which requires the Symbolic Math Toolbox, which I don't have, but this should work (according to the documentation): >> syms x >> f = x^3 - 3*x^2 - 10; >> diff(f) should give you something like ans = 3*x^2-6*x
unknown
d19571
test
I'd handle it this way. Set up an array of all your open times. If you know you're closed on Saturday and Sunday, there's really no need to proceed with with checking times at that point, so kill the process there first. Then simply find out what day of the week it is, look up the corresponding opening and closing times in your $hours array, create actual DateTime objects to compare (rather than integers). Then just return the appropriate message. function getStatus() { $hours = array( 'Mon' => ['open'=>'08:15', 'close'=>'17:35'], 'Tue' => ['open'=>'08:15', 'close'=>'17:35'], 'Wed' => ['open'=>'08:15', 'close'=>'17:35'], 'Thu' => ['open'=>'08:15', 'close'=>'22:35'], 'Fri' => ['open'=>'08:15', 'close'=>'17:35'] ); $now = new DateTime(); $day = date("D"); if ($day == "Sat" || $day == "Sun") { return "Sorry we're closed on weekends'."; } $openingTime = new DateTime(); $closingTime = new DateTime(); $oArray = explode(":",$hours[$day]['open']); $cArray = explode(":",$hours[$day]['close']); $openingTime->setTime($oArray[0],$oArray[1]); $closingTime->setTime($cArray[0],$cArray[1]); if ($now >= $openingTime && $now < $closingTime) { return "Hey We're Open!"; } return "Sorry folks, park's closed. The moose out front should have told ya."; } echo getStatus(); A: Use a switch statement: $thisDate = date('D Hi'); $hoursOfOpArray = array("Mon_Open" => "815", "Mon_Close" => "1730", "Tue_Open" => "815", "Tue_Close" => "1730"); //repeat for all days too fill this array $explode = explode(" ", $thisDate); $day = $explode[0]; $time = (int)$explode[1]; switch($day) { case "Sun": $status = "Closed"; break; case "Mon": $status = ($time < $hoursOfOpArray[$day . "_Open"] || $time > $hoursOfOpArray[$day . "_Close"]) ? "Closed" : "Open"; break; //same as Monday case for all other days } echo $status; This should also work: echo ($day === 'Sun' || ($time < $hoursOfOpArray[$day . "_Open"]) || ($time > $hoursOfOpArray[$day . "_Close"])) ? "Closed" : "Open"; A: This one works, added remarks to explain as much as possible. <?php date_default_timezone_set('America/New_York'); // Runs the function echo time_str(); function time_str() { if(IsHoliday()) { return ClosedHoliday(); } $dow = date('D'); // Your "now" parameter is implied // Time in HHMM $hm = (int)date("Gi"); switch(strtolower($dow)){ case 'mon': //MONDAY adjust hours - can adjust for lunch if needed if ($hm >= 0 && $hm < 830) return Closed(); if ($hm >= 830 && $hm < 1200) return Open(); if ($hm >= 1200 && $hm < 1300) return Lunch(); if ($hm >= 1300 && $hm < 1730) return Open(); if ($hm >= 1730 && $hm < 2359) return Closed(); break; case 'tue': //TUESDAY adjust hours if ($hm >= 830 && $hm < 1730) return Open(); else return Closed(); break; case 'wed': //WEDNESDAY adjust hours if ($hm >= 830 && $hm < 1730) return Open(); else return Closed(); break; case 'thu': //THURSDAY adjust hours if ($hm >= 830 && $hm < 1730) return Open(); else return Closed(); break; case 'fri': //FRIDAY adjust hours if ($hm >= 830 && $hm < 1730) return Open(); else return Closed(); break; case 'sat': //Saturday adjust hours return Closed(); break; case 'sun': //Saturday adjust hours return Closed(); break; } } // List of holidays function HolidayList() { // Format: 2009/05/11 (year/month/day comma seperated for days) return array("2016/11/24","2016/12/25"); } // Function to check if today is a holiday function IsHoliday() { // Retrieves the list of holidays $holidayList = HolidayList(); // Checks if the date is in the holidaylist - remove Y/ if Holidays are same day each year if(in_array(date("Y/m/d"),$holidayList)) { return true; }else { return false; } } // Returns the data when open function Open() { return 'Yes we are Open'; } // Return the data when closed function Closed() { return 'Sorry We are Closed'; } // Returns the data when closed due to holiday function ClosedHoliday() { return 'Closed for the Holiday'; } // Returns if closed for lunch // if not using hours like Monday - remove all this // and make 'mon' case hours look like 'tue' case hours function Lunch() { return 'Closed for Lunch'; } ?> A: $o = ['Mon' => [815, 1735], /*and all other days*/'Sat' => [815, 1300]]; echo (date('Hi')>=$o[date('D')][0] && date('Hi')<=$o[date('D')][1]) ? "open": "closed"; Done! And dont ask.
unknown
d19572
test
From the Interaction Engine docs: If you intend to use the Interaction Engine with Oculus Touch or Vive controllers, you'll need to configure your project's input settings before you'll be able to use the controllers to grasp objects. Input settings are project settings that cannot be changed by imported packages, which is why we can't configure these input settings for you. You can skip this section if you are only interested in using Leap hands with the Interaction Engine. Go to your Input Manager (Edit -> Project Settings -> Input) and set up the joystick axes you'd like to use for left-hand and right-hand grasps. (Controller triggers are still referred to as 'joysticks' in Unity's parlance.) Then make sure each InteractionXRController has its grasping axis set to the corresponding axis you set up. The default prefabs for left and right InteractionXRControllers will look for axes named LeftXRTriggerAxis and RightXRTriggerAxis, respectively. Helpful diagrams and axis labels can be found in Unity's documentation.
unknown
d19573
test
You can get the list of installed programs from the registry. It's under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall If this is a once-off exercise you may not even need to write any code - just use Regedit to export the key to a .REG file. If you do want to automate it Python provides the _winreg module for registry access. A: There are two tools from Microsoft that may be what you need: RegDump and RegDiff. You can download them from various places, including as part of the Microsoft Vista Logo Testing Toolkit. Also, there is Microsoft Support article How to Use WinDiff to Compare Registry Files. For a Pythonic way, here is an ActiveState recipe for getting formatted output of all the subkeys for a particular key (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall for example). A: Personally I always liked sysinternals' stuff (powerfull, light, actual tools - no need to install) There is command line tool psinfo that can get you what you want (and then some) in various formats, distinguishing hotfixes and installed software, on local or remote computer (providing system policies allow it on remote). You can also run it live from here, so though not strictly pythonic you could plug it in quite nicely. A: Taken from List installed software from the command line: If you want to list the software known to Windows Management Instrumentation (WMI) from the command line, use WMI command line (WMIC) interface. To list all products installed locally, run the following command: wmic product Caveat: It seems that this command only list software installed through Windows Installer. See Win32_Product class
unknown
d19574
test
There's unfortunately no automated/very simple/built-in way to do this. Regarding your idea to use a cache, if you use something like Redis, it's increment and decrement operations are atomic so you'd never get a case where both workers got back the same number. One worker and one worker only would get the zero back: http://redis.io/commands/decr
unknown
d19575
test
Take note that each row of mapMatrix must be ascending startMatrix <- t(matrix( c(2.3, 1.2, 3.6, 6.9, 5.3, 6.7), nrow = 3, ncol = 2)) mapMatrix <- t(matrix( c(1, 1.3, 2, 2.5, 3, 5, 5.6, 6, 6.2, 7), nrow = 5, ncol = 2)) res <- do.call(rbind,lapply(1:nrow(startMatrix), function(m) mapMatrix[m,][findInterval(startMatrix[m,],mapMatrix[m,])])) Hope this helps! > res [,1] [,2] [,3] [1,] 2.0 1 3.0 [2,] 6.2 5 6.2
unknown
d19576
test
Read the Apache FOP configuration, you will need an output colorspace specified in the pdf renderer filterList like: <output-profile>C:\FOP\Color\EuropeISOCoatedFOGRA27.icc</output-profile> See https://xmlgraphics.apache.org/fop/1.1/configuration.html Of course, you need to select the appropriate ".icc" file for your application.
unknown
d19577
test
Replace both of your rules with this single rule: RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !^www\.mydomain\.fr$ [NC] RewriteRule ^ https://www.mydomain.fr%{REQUEST_URI} [L,R=301,NE] Test the change after completely clearing your browser cache.
unknown
d19578
test
The problem is here: def computer_move (computer, board, human): best = (4,0,8,2,6,1,3,5,7) board = board [:] for i in legal_moves(board): board[i] = computer if winner(board) == computer: return i board = EMPTY At the end of the function, you assign EMPTY to board, but EMPTY is an empty string, as defined on line 4. I assume you must have meant board[i] = EMPTY. A: In line 120, you reassign board to EMPTY (ie an empty string). So from that point on, board is no longer a list, so you can't assign board[i]. Not quite sure what you meant to do there. Generally, your code would greatly benefit from using object-orientation - with Board as a class, keeping track of its member squares. A: Looks like board is a string. I get the same error when I do this: >>> s = '' >>> s[1] = 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment
unknown
d19579
test
You can use ListView component, the first row would be your header (renderHeader), others are rows (renderRow). Both row and header would be the same component containing a parent View with flexDirection: 'row' with 4 Text components. Each Text component would have a flex: 1 if you want them to be of the same widths. A: import React from "react"; import { registerComponent } from "react-native-playground"; import { StatusBar, StyleSheet, Text, View } from "react-native"; class App extends React.Component { render() { return ( <View> <View style={{ height: 50, flexDirection: "row", flex: 1, borderWidth: 1, padding: 2, justifyContent: "space-around" }} > <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Jill</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Smith</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>50</Text> </View> </View> <View style={{ height: 50, flexDirection: "row", flex: 1, borderWidth: 1, padding: 2, justifyContent: "space-around" }} > <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Eve</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Jackson</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>94</Text> </View> </View> <View style={{ height: 50, flexDirection: "row", flex: 1, borderWidth: 1, padding: 2, justifyContent: "space-around" }} > <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>First Name</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Last Name</Text> </View> <View style={{ flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" }} > <Text>Age</Text> </View> </View> </View> ); } } registerComponent(App); Here's the working code https://rnplay.org/apps/e3MZAw
unknown
d19580
test
This is easy to reproduce and I'm not sure if it's a bug or not. * *Create a new web app using the ASP.NET MVC template *Install the Microsoft.AspNet.WebApi.Owin and Microsoft.Owin.Host.SystemWeb NuGet packages *Move Web API startup from WebApiConfig.cs to a new Startup.cs file *Create a DelegatingHandler and add it to config.MessageHandlers in the Startup class *The DelegatingHandler will be invoked for MVC and API requests I tried several combinations of initializing in Startup.cs and WebApiConfig.cs without success. If you;re not using attribute routing, the solution is to add the handler to the route. If you are, the only workaround I found was to examine the route in the handler and only wrap the API response if the route starts with "/api/". public class WtfDelegatingHandler : DelegatingHandler { protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = await base.SendAsync(request, cancellationToken); if (request.RequestUri.LocalPath.StartsWith("/api/", StringComparison.OrdinalIgnoreCase)) { response = new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("I'm an API response") }; } return response; } }
unknown
d19581
test
You can either include it in the template, or place it just outside the templated div, and set its position absolutely with CSS. <img src="/Content/images/ajax-loader.gif" class="ajax-loader" /> <div style="height: 100%; width: 100%;" data-bind="template: { name: $root.currentChildTemplate() }"></div> You could go a step further, and have it only visible when a certain observable is true. <img src="/Content/images/ajax-loader.gif" class="ajax-loader" data-bind="visible: ajaxLoading" />
unknown
d19582
test
You need to use document.getElementById('company').value to get value of select box.i.e : console.log("button", document.getElementById("button")) document.getElementById('button').onclick = function() { console.log("clicked!") let company = document.getElementById('company').value;//get value of select box console.log(company) let headers = new Headers() let init = { method: 'GET', headers: headers } let params = { 'company': company } $.get("/getmethod/<params>"); $.get("/getpythondata", function(data) { console.log($.parseJSON(data)) }) } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <div class="form-group"> <label>Store ID</label> <select class="form-control" id="company"> <option selected>All</option> <option>Air France</option> <option>Lufthansa</option> </select> <button class="btn btn-primary" type='button' id="button">Refresh</button> </div> </form>
unknown
d19583
test
In my case (I used AWS SDK for Go V2), I needed both ssm:GetParametersByPath and ssm:GetParameter to make it work. A: Played around with this today and got the following, dropping the s from ssm:GetParameters and using ssm:GetParameter seems to work when using the GetParameter action. ie AWS_PROFILE=pstore aws ssm get-parameter --name param_name. This weirded me out a bit because I cannot find this at all in the iam action docs here. However it does seem to work, and ssm is still a bit under documented. Amazon has updated and moved it's docs. The new docs incude both ssm:GetParameters and ssm:GetParameter. { "Version": "2012-10-17", "Statement": [ { "Action": [ "ssm:DescribeParameters" ], "Resource": "*", "Effect": "Allow" }, { "Action": [ "ssm:GetParameter" ], "Resource": "arn:aws:ssm:eu-west-1:redacted:parameter/*", "Effect": "Allow" } ] } A: Ran into the same error today. The following Java code caused it when encrypted = false and paramName referred to an unencrypted parameter GetParameterRequest request = new GetParameterRequest() .withName(paramName) .withWithDecryption(encrypted); GetParameterResult resultPacket = ssmClient.getParameter(request); The fix was to create the unencrypted parameter request without setting the WithDecryption flag - GetParameterRequest request = new GetParameterRequest().withName(paramName); A: It really depends on the command you use in your Lambda. If you use boto3.client('ssm').get_parameters(Names=[param1, param2]), then you need "Action": ["ssm:GetParameters"], or alternatively when you use boto3.client('ssm').get_parameter(Name=param), you would need "Action": ["ssm:GetParameter"] A: regarding the confusion ssm:GetParameter and ssm:GetParameters. I attached the policy AmazonEC2RoleforSSM to some user and ran into the same problem, "not authorized to perform: ssm:GetParameter" because this Policy only has ssm:GetParameters. AWS had a deprecation warning attached to that policy and recommended to use AmazonSSMManagedInstanceCore instead, which has both Actions ssm:GetParameters and ssm:GetParameter. Which then worked fine. A: In my case, I was using s3:GetObject and s3:ListBucket. To fix the error I had to add the bucket twice in resources and append to one of them a *. For example: { "Statement" : [ { "Effect" : "Allow", "Action" : [ "s3:GetObject", "s3:ListBucket", ], "Resource" : [ "arn:aws:s3:::mybucket/*", "arn:aws:s3:::mybucket", ] }, ] } A: For me I had the path wrong (I was missing the leading / on the path name when making the request - it seems obvious but it's easy to miss and worth double checking if you're experiencing this issue. ❌ Wrong var getParameterResponse = await _ssm.GetParameterAsync(new GetParameterRequest { Name = "my-component-namespace/my-parameter", WithDecryption = true }); ✅ Correct var getParameterResponse = await _ssm.GetParameterAsync(new GetParameterRequest { Name = "/my-component-namespace/my-parameter", WithDecryption = true });
unknown
d19584
test
There's no way to save DOM elements as an image (unless you just use Firefox or something), but you can convert the DOM elements into canvas and save the image from there. See http://html2canvas.hertzen.com/ Then use canvas.toDataURL() to save the image.
unknown
d19585
test
You have to have to define a Style for each control. This is because the visuals and visual states are defined by the internal ControlTemplate of each control. But you can significantly reduce the amount of work by reusing templates and cascading styles. To allow easy color theming and centralized customization, you should create a resource that defines all relevant colors of your theme: ColorResources.xaml <ResourceDictionary> <!-- Colors --> <Color x:Key="HighlightColor">DarkOrange</Color> <Color x:Key="DefaultControlColor">LightSeaGreen</Color> <Color x:Key="ControlDisabledTextColor">Gray</Color> <Color x:Key="BorderColor">DarkGray</Color> <Color x:Key="MouseOverColor">LightSteelBlue</Color> <!-- Brushes --> <SolidColorBrush x:Key="HighlightBrush" Color="{StaticResource HighlightColor}" /> <SolidColorBrush x:Key="ControlDisabledTextBrush" Color="{StaticResource ControlDisabledColor}" /> <SolidColorBrush x:Key="BorderBrush" Color="{StaticResource BorderColor}" /> <SolidColorBrush x:Key="MouseOverBrush" Color="{StaticResource MouseOverColor}" /> </ResourceDictionary> You may add the following styles an templates to the App.xaml file: App.xaml <Application> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/File/Path/To/ColorResources.xaml" /> </ResourceDictionary.MergedDictionaries> ... </ResourceDictionary> </Application.Resources> </Application> To override the color of the selected row in a GridView or DataGrid you simply need to override the default brush SystemColors.HighlightBrush used by these controls: <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{StaticResource HighlightColor}" /> To override the default color of controls like the column headers of e.g DatGrid you simply need to override the default brush SystemColors.ControlBrush used by these controls: <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{StaticResource DefaultControlColor}" /> For simple ContentControls like Button or ListBoxItem you can share a common ControlTemplate. This shared ControlTemplate will harmonize the visual states: <ControlTemplate x:Key="BaseContentControlTemplate" TargetType="ContentControl"> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"> <ContentPresenter/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Foreground" Value="{StaticResource ControlDisabledTextBrush}" /> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Opacity" Value="0.7" /> <Setter Property="Background" Value="{StaticResource MouseOverBrush}" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> This base template will be applied using base styles. This allows simple chaining (style inheritance) and reuse of the BaseContentControlTemplate for different controls like Button or ListBoxItem: <Style x:Key="BaseContentControlStyle" TargetType="ContentControl"> <Setter Property="Template" Value="{StaticResource BaseContentControlTemplate}" /> </Style> Some ContentControl like a Button might need additional states like Pressed. You can extend additional basic visual states by creating a base style that e.g., targets ButtonBase and can be used with any control that derives from ButtonBase: <Style x:Key="BaseButtonStyle" TargetType="ButtonBase" BasedOn="{StaticResource BaseContentControlStyle}"> <Style.Triggers> <Trigger Property="IsPressed" Value="True"> <Setter Property="Background" Value="{StaticResource HighlightBrush}" /> </Trigger> </Style.Triggers> </Style> To apply this base styles you have to target the controls explicitly. You use this styles to add more specific visual states or layout e.g., ListBoxItem.IsSelcted, ToggleButton.IsChecked or DataGridColumnHeader: <!-- Buttons --> <Style TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}" /> <Style TargetType="ToggleButton" BasedOn="{StaticResource BaseButtonStyle}"> <Style.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter Property="Background" Value="{StaticResource HighlightBrush}" /> </Trigger> </Style.Triggers> </Style> <!- ListBox --> <Style TargetType="ListBoxItem" BasedOn="{StaticResource BaseContentControlStyle}"> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="{StaticResource HighlightBrush}" /> </Trigger> </Style.Triggers> </Style> <!-- ListView --> <Style TargetType="ListViewItem" BasedOn="{StaticResource {x:Type ListBoxItem}}" /> <!-- GridView Since GridViewColumnHeader is also a ButtonBase we can extend existing style --> <Style TargetType="GridViewColumnHeader" BasedOn="{StaticResource BaseButtonStyle}" /> <Style x:Key="BaseGridViewStyle" TargetType="ListViewItem"> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="{StaticResource HighlightBrush}" /> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="{StaticResource {x:Static SystemColors.HighlightBrushKey}}" /> </Trigger> </Style.Triggers> </Style> <!-- DataGrid Since DataGridColumnHeader is also a ButtonBase we can extend existing style --> <Style TargetType="DataGridColumnHeader" BasedOn="{StaticResource BaseButtonStyle}"> <Setter Property="BorderThickness" Value="1,0" /> <Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" /> </Style> Other more complex composed controls like ComboBox, TreeView or MenuItem require to override the control's template individually. Since these controls are composed of other controls, you usually have to override the styles for this controls too. E.g., ComboBox is composed of a TextBox, ToggleButton an Popup. You can find their styles at Microsoft Docs: Control Styles and Templates. This is a very simple and basic way to add theming to your application. Knowledge of the inheritance tree of the controls helps to create reusable base styles. Reusing styles helps to reduce the effort to target and customize each control. Having all visual resources like colors or icons defined in one place makes it easy to modify them without having to know/modify each control individually. A: If you have a look at the default styles (https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/button-styles-and-templates), you will find out, that each style uses static resources for declaring the colors. So to achieve your project you would have to overwrite these static resources where the colors are stored. Unfortunately, this is not possible in WPF (was already asked before: Override a static resource in WPF). So your only solution would be to write a separate Style for each control and to re-declare the colors.
unknown
d19586
test
EDIT I think that it is duplicate. Select :last-child with especific class name (with only css) So you need which div you want to point. In this case, this is second div so we specified: div:nth-child(2) And then we just select last li as below: li:last-child So finaly we got: div:nth-child(2) li:last-child{ background-color: red; } EDIT With jQuery: $('li').last().css('background', 'red'); Just to let you know, your html structure is incorrect as you should set li right after ul or ol $('li').last().css('background', 'red'); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </div> <div> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li> </div>
unknown
d19587
test
I am not entirely sure I am grasping the whole picture here, but it seems to me that you need two ArrayList fields. List<Item> downloadedItems = new ArrayList<Item>; List<Item> searchItems = new ArrayList<Item>; then what you need to do is create your own custom ListAdapter for the DownloadListView and create your own custom download_item.xml that you will inflate inside of the ListAdapter. In your case it sounds like this download_item.xml will consist of a textview, and a progressbar, and will need the containing (or top layer) layout set to wrap content. Now in the on click listener for the SearchListView set it so that it will call a function that will take the item that was tapped and add it to the downloadedItems ArrayList and start the download, as well as refresh the listadapter dataset so it knows to update the items in the list. The download should be in a AsyncTask, and you will want to use the @Override publishProgress() portion of this, so that you can update the status of the download bar. forgive me for any mis sights or mistakes, I just woke up.
unknown
d19588
test
Since you did not come here to be told that your idea is bad and people will hate it: here is an idea that you can play with: :on https://guides.rubyonrails.org/active_record_validations.html#on validates :name, whitespace: true, on: :preview and then in the controller: def something @model.valid?(:preview) end If you want to run the validation also on createand update you can specify something like on: [:create,:update,:preview] (Thanks engineersmnky) Also: I don't think that giving early feedback to users, before they actually save the record is a bad idea if properly implemented. A: This feels like trying to solve a problem (leading/trailing whitespace) by creating a new problem (rejecting the object as invalid), and I agree with the comment about this being a brittle strategy. If the problem you want to solve here is whitespace, then solve that problem for the specific attributes where it matters before saving the object; check out Rails before_validation strip whitespace best practices
unknown
d19589
test
The same way you would add multiple users to a normal instance. I am going to assume you are using linux and can login to the instance, if not, see this post. Now you just need to add a user, and setup the ssh keys.
unknown
d19590
test
If you just want to print all the values higher then 50 a simple loop will do. data = [10, 90, 20, 80, 30, 40, 70, 60] for value in data: if value > 50: print(value) If you need the indexes use this code. enumerate will give you an automatic counter. data = [10, 90, 20, 80, 30, 40, 70, 60] for index, value in enumerate(data): if value > 50: print(index) If you need a list of indexes to print the values (your question is unclear at that point) then construct this list and loop over it. data = [10, 90, 20, 80, 30, 40, 70, 60] indexes = [index for index, value in enumerate(data) if value > 50] for index in indexes: print(data[index]) According to the question in your comment you could do the following (based on the last solution). data = [10, 90, 20, 80, 30, 40, 70, 60] characters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] indexes = [index for index, value in enumerate(data) if value > 50] for index in indexes: print('{}: {}'.format(characters[index], data[index])) This code uses the index for both lists. If this is homework and you can't use enumerate you have to construct the indexes list with a standard for loop. indexes = [] for index in range(len(data)): if data[index] > 50: indexes.append(index) A pythonic solution would be something like this. data = [10, 90, 20, 80, 30, 40, 70, 60] characters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] for char, value in zip(characters, data): if value > 50: print('{}: {}'.format(char, value)) A: In case you want the elements of the list which are greater than 50, you can simply use a list comprehension: [el for el in lst if el>50] where lst is your input list. If you also wanted the index of those elements, you could: [(i,el) for (i,el) in enumerate(lst) if el>50] which would give you a list of tuples (index, element) A: You want an if loop; if x is greater than one of the numbers, print it? example: myList = list(range(0,100)) for numb in myList: if numb > 50: print numb Honestly, I'm not sure what OP wants to do. But this is just an example. A: If you would like to use enumerate(), and you would like to store both the indexes of the numbers above 50 and the values themselves, one way would be to do it like so: >>> a = [1,2,3,4,5,50,51,3,53,57] >>> b, c = zip(*[(d, x) for d, x in enumerate(a) if x > 50]) >>> print b (6, 8, 9) >>> print c (51, 53, 57) Enumerate takes any object that supports iteration, and returns a tuple, (count, value), when the next() method of the iterator is called. Since enumerate() defaults to start its count at 0, and increments the count by one each iteration, we can use it to count the index of the array that the iteration is currently on. Now, our list comprehension is returning a list of tuples, if we were to print the comprehension we would get: >>> print [(d, x) for d, x in enumerate(a) if x > 50] [(6, 51),(8, 53),(9, 57)] Zip creates a list of tuples when given two arrays, for example: >>> f = [1, 2, 3] >>> g = [4, 5, 6] >>> zipped = zip(f, g) >>> zipped [(1, 4), (2, 5), (3, 6)] When used with the * operator, zip() will "unzip" a list. So, when we "unzip" the list comprehension, two tuples are returned. Hope this helps!
unknown
d19591
test
You could use regular string add operator <div id="@(Model.MyLabel + "Car")"></div> Or C# 6's string interpolation. <div id="@($"{Model.MyLabel}Car")"></div> A: What you want is to use the <text></text> pseudo tags <div id="@Model.MyLabel<text>Cars</text>" ...>
unknown
d19592
test
A").ColumnWidth = 27 Columns("B:B").ColumnWidth = 28.57 Columns("A:A").ColumnWidth = 31.29 Range("B1:B11").Select Selection.Cut Destination:=Range("C1:C11") Range("C1:C11").Select Columns("C:C").ColumnWidth = 15.43 ActiveWindow.SmallScroll Down:=6 Range("B13:B14").Select Selection.Cut Destination:=Range("C13:C14") Range("B18:B19").Select Selection.Cut Destination:=Range("C18:C19") Range("C18:C19").Select ActiveWindow.SmallScroll Down:=9 Range("B27:B28").Select Selection.Cut Destination:=Range("C27:C28") Range("B30:B32").Select Selection.Cut Destination:=Range("C30:C32") Range("C30:C32").Select ActiveWindow.SmallScroll Down:=9 Range("B36:B45").Select Selection.Cut Destination:=Range("C36:C45") Range("C36:C45").Select ActiveWindow.SmallScroll Down:=12 Range("B46:B53").Select Selection.Cut Destination:=Range("C46:C53") Range("C46:C53").Select ActiveWindow.SmallScroll Down:=9 Range("B55:B62").Select Selection.Cut Destination:=Range("C55:C62") Range("C55:C62").Select ActiveWindow.SmallScroll Down:=12 Range("B64:B67").Select Selection.Cut Destination:=Range("C64:C67") Range("C64:C67").Select ActiveWindow.SmallScroll Down:=30 Range("B94:B104").Select Selection.Cut Destination:=Range("C94:C104") Range("B105").Select Selection.Cut Destination:=Range("C105") Range("C105").Select ActiveWindow.SmallScroll Down:=27 Range("B128:B136").Select Selection.Cut Destination:=Range("C128:C136") Range("C128:C136").Select ActiveWindow.SmallScroll Down:=-147 Range("E1").Select ActiveCell.FormulaR1C1 = "=TRIM(RC[-4])" Range("F3").Select Columns("E:E").ColumnWidth = 20.71 Columns("F:F").ColumnWidth = 27.71 Range("F1").Select ActiveCell.FormulaR1C1 = "=TRIM(RC[-3])" Range("E1:F1").Select Selection.AutoFill Destination:=Range("E1:F154"), Type:=xlFillDefault Range("E1:F154").Select Range("F160").Select ActiveWindow.SmallScroll Down:=-183 Range("E1:E154").Select Selection.Cut ActiveWindow.SmallScroll Down:=-15 Range("E5").Select Application.CutCopyMode = False Selection.Copy Range("F4").Select Application.CutCopyMode = False Range("E1:E154").Select Selection.Copy Range("A1").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Application.CutCopyMode = False Range("F1:F154").Select Selection.Copy Range("C1").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Range("D15").Select Application.CutCopyMode = False Range("E1:F154").Select Selection.ClearContents Range("D11").Select ActiveWindow.SmallScroll Down:=-51 Range("A1:C154").Select ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("C1:C154") _ , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("C1:C154") _ , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With ActiveWorkbook.Worksheets("Sheet1").Sort .SetRange Range("A1:C154") .Header = xlGuess .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With ActiveWindow.SmallScroll Down:=81 ChDir "D:\" ActiveWorkbook.SaveAs Filename:="D:\File List.xlsm", FileFormat:= _ xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False Selection.ClearContents Range("E10").Select ActiveWorkbook.Save End Sub A: This is my take. Not sure if the paste is working as it should. I've avoided the use of select as it only slows down the code. I've also trimmed the data from columns A & C in situ rather than copying it over to E & F columns. I've assumed that the data is in a workbook called Book1. You can of course rename the workbook and worksheet in the macro. Sub DataEdit() Dim wb As Workbook Dim ws As Worksheet Dim GCell As Range Dim NumberOfRowsOfData, Count As Integer Set wb = Workbooks("Book1") With wb Set ws = .Worksheets("Sheet1") With ws Set GCell = .Range("A1") GCell.PasteSpecial GCell.TextToColumns DataType:=xlDelimited, _ TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _ Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _ :="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True Set GCell = .Range("A:A") NumberOfRowsOfData = .Range("A10000").End(xlUp).Row GCell.ColumnWidth = 27 Set GCell = .Range("B:B") GCell.ColumnWidth = 28.57 Set GCell = .Range("C:C") GCell.ColumnWidth = 31.29 For Count = 1 To NumberOfRowsOfData If .Cells(Count, 3) = "" Then .Cells(Count, 3).Value = Cells(Count, 2).Value .Cells(Count, 2).ClearContents .Cells(Count, 1).Value = Trim(.Cells(Count, 1).Value) .Cells(Count, 3).Value = Trim(.Cells(Count, 3).Value) End If Range("A1:C" & NumberOfRowsOfData).Sort key1:=Range("C1:C" & NumberOfRowsOfData), order1:=xlAscending, Header:=xlNo Next Count End With End With End Sub
unknown
d19593
test
Okay, so it seems like you're going for a basic pagination scheme. First things first, you should look at the built-in solution in Django. You should definitely take an hour and try and make that work. Django's a heavyweight framework that has a built-in way of doing most things, and libraries for everything else. As a general rule, if you find yourself doing a common task in a convoluted way, there's probably a stock solution out there. If you decide you want to do it the quick and dirty way, how about calculating has_next_page and has_prev_page in limit_amount_in_a_page? @register.inclusion_tag('post/comment_block.html') def limit_amount_in_a_page(page_nr, topic_id=1, amount=5): topic = get_object_or_404(Topic, id=topic_id) comments = Comment.objects.filter(topic=topic) num_comments = comments.count() selected_comments = comments[page_nr*amount, (page_nr + 1)*amount] has_prev = (page_nr != 0) has_next = ((page_nr + 1) * amount) < num_comments return { 'topic': topic, 'page_nr': int(page_nr), 'selected_comments': selected_comments, 'has_next' : has_next, 'has_prev' : has_prev, 'amount_comments' : num_comments, } Also, note the use of slices to select comments. But again, I highly recommend checking out the Paginator class in Django. Reading through the docs and doing the tutorial is a great thing to do as well, if you have not yet. Skimming through all the docs gives you an idea of what is built-in, which saves a lot of time in the long run.
unknown
d19594
test
Try using split to split along the string before the = and after the =: const inputStr1 = ' name = value '; const inputStr2 = ' name value '; function validate(str) { if (!str.includes('=')) { console.log('no = found, returning'); return; } const [cleanedName, cleanedValue] = str.split('=').map(uncleanStr => uncleanStr.trim()); console.log('returning values "' + cleanedName + '" "' + cleanedValue + '"'); return [cleanedName, cleanedValue]; } const results1 = validate(inputStr1); const results2 = validate(inputStr2);
unknown
d19595
test
Under android's gradle plugin 0.7.3, the generated R.java file is only made for the src/main's package name. It contains all the resources for the different flavors, it just puts them into one generated R.java file. I heard this from an IO talk. What's your package name in the src/main/AndroidManifest.xml? My guess is that it's com.flyingspheres.android Try importing R in your classes which need to access resources programatically using your src/main's package name. E.g. import com.flyingspheres.android.R;
unknown
d19596
test
I cannot reproduce this on Alfresco Community Edition 5.1.f on Linux authenticating against OpenLDAP. The test steps are: * *Validate that authentication works for LDAP users. *Validate that Apache Chemistry CMIS Workbench can authenticate using LDAP users. *Add a new user to LDAP (tuser4). *Validate that I can log in to Share via the new user (tuser4). *Add another new user to LDAP (tuser5). *Validate that I can log in via CMIS Workbench using the new user (tuser5). All of these steps pass. The CMIS service URL I am using in Workbench is: http://alfresco.local:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom Make sure yours matches that. It could be the issue. If your service URL matches, please provide the code you are using to get a session.
unknown
d19597
test
requires jQuery animate $('.blue').click(function(){ //expand red div width to 200px $('.red').animate({width: "200px"}, 500); setTimeout(function(){ //after 500 milliseconds expand height to 800px $('.red').animate({height:"800px"}, 500); },500); setTimeout(function(){ //after 1000 milliseconds show textarea (or textbox, span, etc) $('.red').find('input[type="textarea"]').show(); },1000); }); A: This can be done really easily with CSS. This video explains it very well. There are a ton of other neat tricks in that video, but I linked to the part where she explains a light box. .container { padding: 100px; } .red, .blue { width: 20px; height: 20px; float: left; background-color: blue; } .red { background-color: red; font-size: 0; color: white; width: 50px; transition: 1s height, 1s margin, 1s font-size, 1s 1s width; } .blue:focus ~ .red { height: 100px; width: 150px; font-size: inherit; margin-top: -40px; transition: 1s width, 1s 1s height, 1s 1s margin, 1s 1s font-size; } .red .hint { font-size: 14px; padding: 4px; transition: 1s 1s font-size; } .blue:focus ~ .red .hint { font-size: 0; transition: 1s font-size; } <div class="container"> <div class="blue" tabindex="-1"></div> <div class="red"><span class="hint">text1</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt</div> </div> A: $(window).load(function(){ $(".blue").click(function(){ $(".red").animate({width:'400px'},1000).animate({height:'400px',top:'150px'},1000).text("qwqwqwq"); }) }) ` .blue{ width: 100px; height: 100px; background-color: blue; } .red{ width:200px; height:100px; background-color: red; left:100px; } div{ display: inline-block; margin:0; padding: 0; position: absolute; top:300px; }`
unknown
d19598
test
One of the solutions is to refresh the second iframed page sending the DropDownList selected value as its query string, using jQuery (to make things easier). To demonstrate, I'm basically updating a DropDownList on the second iframed page, but you can easily adapt to your needs: Main page (where the iframes are placed): <iframe id="iframe1" width="500" height="200" src="WebForm1.aspx"></iframe> <iframe id="iframe2" width="500" height="200" src="WebForm2.aspx"></iframe> First iframed page: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#ddl1").on("change", function () { // When the DropDownList selected value has been changed, // refresh the other iframed page changing its source // adding the value as its query string. $("#iframe2", parent.document).attr("src", "WebForm2.aspx?value=" + $(this).val()); return true; }); }); </script> <asp:DropDownList ID="ddl1" runat="server" AutoPostBack="true"> <asp:ListItem Text="Option 1" Value="1"></asp:ListItem> <asp:ListItem Text="Option 2" Value="2"></asp:ListItem> </asp:DropDownList> Second iframed page: <asp:DropDownList ID="ddl2" runat="server" AutoPostBack="true"> <asp:ListItem Text="Option 1" Value="1"></asp:ListItem> <asp:ListItem Text="Option 2" Value="2"></asp:ListItem> </asp:DropDownList> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) ddl2.SelectedValue = Request.QueryString["value"]; } UPDATE Regarding your question posted on the comments, you can find out what's the second page iframe's src (and subsequently change it) this way: $("#iframe2", parent.document).attr("src", $("#iframe2", parent.document).attr("src") + "?value=" + $(this).val()); UPDATE #2 As per your request, you want to load the iframe source dynamically, at the page load. That's how you can achieve this: Main page (where the iframes are placed): <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#iframe2").attr("src", "the-page-you-want-to-load-on-this-iframe"); }); </script> <iframe id="iframe1" width="500" height="200" src="WebForm1.aspx"></iframe> <iframe id="iframe2" width="500" height="200"></iframe> First iframed page: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#ddl1").on("change", function () { var iframe2BaseSrc = $("#iframe2", parent.document).attr("src"); if (iframe2BaseSrc) { iframe2BaseSrc = iframe2BaseSrc.split("?")[0]; $("#iframe2", parent.document).attr("src", iframe2BaseSrc + "?value=" + $(this).val()); } return true; }); }); </script>
unknown
d19599
test
Seems you reference the last edition of "Compilers: Principles, Techniques, and Tools" from 1986. (But even at that time the quoted part was already outdated). In modern programming languages like C# (or more precisely in its I/O library) this kind of buffering is already implemented (in a robust, tested, high performance way). Just use StreamReader which does all this work for you. Then just read character after character until you found a complete token, then process your tokens as described in this excellent book.
unknown
d19600
test
It is fairly straight forward, the first step is to enable the transport sender for VFS (and the receiver if you also want to read files) in de axis2.xml config file. The lines are already there and just need to be uncommented. <transportReceiver name="vfs" class="org.apache.synapse.transport.vfs.VFSTransportListener"/> <transportSender name="vfs" class="org.apache.synapse.transport.vfs.VFSTransportSender"/> Next you will need to transform your response to whatever format you want to write to the file. You could use an xslt transformation, payload mediator or datamapper mediator for example. After that you simple send the payload to a vfs endpoint. This can be a local file location, or a remote ftp location for example. Make sure you have the correct privileges to write a file in said location. For example if you run your esb as WSO2 user, and want to write files to /opt/wso2/fileexchange, make sure the WSO2 user has write privileges on that folder. Then to write to that location just use a send mediator like this: <property xmlns:ns2="http://org.apache.synapse/xsd" name="transport.vfs.ReplyFileName" value="myFile.txt" scope="transport"/> <property name="OUT_ONLY" value="true"/> <send> <endpoint name="FileEpr"> <address uri="vfs:file:///opt/wso2/fileexchange"/> </endpoint> </send> Make sure to set the transport.vfs.ReplyFileName property to the filename you want to write. And the OUT_ONLY property, since the filesystem is not going to send a nice reply back to you. For more on this subject you can always check this blog A: I prefer send the URI which refer to the file instead of sending the binary data. So the more efficient way is upload the file to a FileSystem, then transfer it with a String(URI). Only when you need read the file's data, then download it from FileSystem. And you should ensure the network is OK between FileSystem and the final user.
unknown