INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Print doc files in asp.net mvc project I am working on an asp.net mvc project. How can I open doc.file to print it from page? The only thing I can do now is downloading, however, I'd like to open it as print friendly file in sort of window.print()
Normally you just supply correct content type. Then user can view the file inside the browser and print it. However, if the browser doesn't have appropriate plugin, then user can only download the file. public ActionResult Download() { return File("~/MyDocument.doc", "application/vnd.ms-word", "MyDocument.doc"); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, model view controller, doc" }
Get the number before a certain value in each row I haven't be able to find this anywhere. I want to be able to create a column that uses the data from the column before the column that contains "end". I may not even be explaining that well. For Example: df = V1 V2 V3 V4 V5 V6 0 start 1 end ended 0 3 end 0 start 5 0 2 start 3 next 6 end I want the new column to be the number before the following column says "end". V1 V2 V3 V4 V5 V6 end_num 0 start 1 end ended 0 1 3 end 0 start 5 0 3 2 start 3 next 6 end 6
A possible solution in `base R`: df$end_num <- apply(df, 1, \(x) x[which(x == "end") - 1]) df #> V1 V2 V3 V4 V5 V6 end_num #> 1 0 start 1 end ended 0 1 #> 2 3 end 0 start 5 0 3 #> 3 2 start 3 next 6 end 6
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 6, "tags": "r, dataframe, dplyr" }
DATE_DIFF Casting date column as date? If I have a simple date diff filter as below: date_diff('year', date_column_a, date_column_b) If I need to cast or convert the date columns to date prior to `date_diff()` can I do it in the function itself? Thanks!
If I understand you correctly: > If I need to cast or convert the date columns to date prior to date_diff() can I do it in the function itself? Yes, you can. To cast your arguments inside the parentheses, you would simply write something like: date_diff('year', cast(date_column_a as date), cast(date_column_b as date))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, presto" }
Web Apps: Storing ID in hidden fields safe? I just had this thought, I don't know if I am slow though. Usually, I store the id of the item I am editing in a hidden field. Then in backend (I am using PHP/Zend Framework btw), I get it to determine which item gets edited. But then I thought, in something more secure, eg. edit profile, the user can somehow edit a hidden field right? Then he can edit someone else's profile. I know for edit profile, I can get the id form the session variable, but what if i got something that requires me to store the id somewhere? I got ACL (Zend_Acl) I do this. Basically grab the id from the request params $id = $req->getParam('id'); then check if the logged in user is allowed to edit the item. But the thing is I wonder if the url is something like `/users/edit/1` where 1 is the id. But somehow, the hidden field is changed to 2, what will the request param be? How would you deal with this?
You must store some kind of id at the client-otherwise how would you know which item to edit? This does not free you from the **mandatory** check on the server that the current user has privileges to edit/see the edited item. Other then that, why would you care how he got to edit the item (whether by lawful use of the web tool, or by editing the hidden/whatever field).
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 6, "tags": "php, web applications, authorization" }
'NOT NULL constraint failed' after adding to models.py I'm using userena and after adding the following line to my models.py zipcode = models.IntegerField(_('zipcode'), max_length=5) I get the following error after I hit the submit button on th signup form: IntegrityError at /accounts/signup/ NOT NULL constraint failed: accounts_myprofile.zipcode My question is what does this error mean, and is this related to Userena?
You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add `null=True` and create and run migration.
stackexchange-stackoverflow
{ "answer_score": 98, "question_score": 63, "tags": "python, django, django models, django migrations" }
SparkleXRM empty GUID after SOAP request create I have a problem with FetchXML in SparkleXML. When I want to add GUID filter in condition clause in FetchXML I get empty string value in SOAP request <fetch version='1.0' output-format='xml-platform' mapping='logical' returntotalrecordcount='true' no-lock='true' distinct='false'> <entity name='ic_orderline'> <attribute name='ic_orderlineid' /> <attribute name='ic_quantity' /> <attribute name='ic_product' /> <filter type='and'> <condition attribute='ic_order' operator='eq' value=''/> </filter> </entity> </fetch>"; Fetch looks like one above in SOAP request. Anyone had problem like that?
Problem was that I passed GUID in curly brackets format (eg.`"{F2D136B5-3439-E611-80E9-5065F38A3951}"`), but you need to pass GUID without brackets (`"F2D136B5-3439-E611-80E9-5065F38A3951"`) because there is some regex in JavaScript that escapes curly brackets and it's contents in FetchXML.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "soap, dynamics crm, crm, fetchxml" }
Javascript Loadingbar I am attempting to create a loading bar in javascript here is my code: function load(barsize){ parseInt(barsize); var loadingbar = ''; for(i = 1; i<=barsize;i++){ loadingbar += '<div style="width:5px; height: 5px; float:left;background-color:green;"></div>' } document.getElementById('loadingbar').innerHTML = loadingbar; if(barsize < 80){ barsize++; timeout = window.setTimeout('load('+barsize+')', 100); } } The debugger is saying "Uncaught ReferenceError: load is not defined" after doing nothing with the statement: timeout = window.setTimeout('load('+barsize+')', 100);
Change your : timeout = window.setTimeout('load('+barsize+')', 100); with : timeout = window.setTimeout(function() { load(barsize); }, 100); This way you can pass params to the `load` function without getting the `undefined` error
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, html" }
Forms authentication failed for the request. Reason: The ticket supplied has expired My event log is flooded with this message: > Forms authentication failed for the request. Reason: The ticket supplied has expired. I think this happens when people timeout instead of logout. First of all , this is not an error, it's `Type: Information` I don't want this information, how do I stop ASP.NET from logging it? My application is not web-farmed, and uses a static machine key.
Here's the solution: <?xml version="1.0"?> <configuration> <system.web> <healthMonitoring> <rules> <remove name="Failure Audits Default" /> </rules> </healthMonitoring> </system.web> </configuration> Note that this will prevent the logging off all `System.Web.Management.WebFailureAuditEvent` events, which covers the event range 4005-4011. There is probably a way to just remove 4005, but this solution is good enough for me. These are the links that helped me: * < * <
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 20, "tags": ".net, asp.net" }
How can I get the ID attribute of a logged in User and set it as a foreign key in the database So here is the thing. I have 2 tables in the database: **User** and **Client**. A user can add one or many clients in the database. So what I want is when a user will add a client - the function will retrieve the **id** of the logged in User and add it as a **foreign key** in the client table. I have already done the `OneToMany` Mapping. Here is my controller: @RequestMapping(value = "/postficheclient", method = RequestMethod.POST) public ResponseEntity<?> createClient(@RequestBody Client newClient) { // newClient.setUser(user); return new ResponseEntity<Client>(clientservices.save(newClient), HttpStatus.CREATED); } With that function, it adds a `null` value in the `Client` table. Can someone help me, please? PS: I use the spring security system.
With Spring Security, you can get the logged client through SecurityContextHolder.getContext().getAuthentication() and you can get various details from: * getPrincipal() - usually the user identifier * getAuthorities() - the authorities * getDetails() - additional user details The infos put in the various fields depends how spring security handle your authentication mecanism, but I guess you can find what you need for in principal.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "spring, spring mvc, spring boot, jakarta ee, spring security" }
POST data for url with cuRL I am trying to send some data to an curl URL to obtain a key. The curl command is: curl -X POST " -H "accept: application/json" -H "Authorization: xx:xxxxxxxxxxxxxxxx" -H "content-type: application/x-www-form-urlencoded" -d "grant_type=password&[email protected]&password=xxxx" Any idea how this will look into a php code to get the response key ?
You can try like this, $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, " curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=password&[email protected]&password=xxxx"); curl_setopt($ch, CURLOPT_POST, 1); $headers = array(); $headers[] = "Accept: application/json"; $headers[] = "Authorization: xx:xxxxxxxxxxxxxxxx"; $headers[] = "Content-Type: application/x-www-form-urlencoded"; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) { echo 'Error:' . curl_error($ch); } curl_close ($ch);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, curl" }
cant compare 0 in a conditional statement in js well this is in node to be exact but, when i do the following conditional statement on a string of a length of zero or above zero, it will only ever do the condition if the string is not 0. if(string.length == 0) { console.log(string.length) } else { console.log(string.length) }; no matter what it wont respond if the string.length is 0. i have also tried: if(string.length > 0) { console.log('greater than zero') } else { console.log('zero') }; but with the same results. no matter what it wont respond if the string.length is zero. i have printed the string.length outside of the if/else statement, and have been able to have it print 0. why wont the conditional statement work in this case? why does it just not respond if the string.length == 0?
i was getting whitespace if the string was 0. i solved the error by doing string.trim()
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, string, node.js, conditional statements" }
Even counting integers Python Hey guys I have been having a little trouble in trying to count all of the even integers within my list and print the number of even integers. I am new to programming so may not be up to date with the knowledge and terminology of some of you guys on here. If you could help me out that would be great! Here is what i have started already. list = [2,4,5,6,8] count_even=0 while count_even<len(list): if list[count_even]%2==0: count_even=count_even + 1 else: list[count_even]%2!=0 count_even=count_even print count_even
num_list = [2,4,5,6,8] count_even=0 for n in num_list: if n%2==0: count_even=count_even + 1 print count_even * * * Explanation of changes: * Change `list` variable name. Don't use the name of a Python object. * Change from `while` to `for`; Don't need to do list indexing this way * Remove the `else` block; It's not doing anything right now anyway. There is no point in `count_even=count_even` Your issue was with indexing. Everything was based on the `count_even` variable. Your `while` loop was continuing while it was less than the length of the list and in your `else` block you weren't incrementing it. Thus, you have an infinite loop if there is an odd number in the list
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python" }
Weird issue trying to print ApplicationContext content in a JSP I am going crazy here. Just trying to print all the Spring beans in a JSP. I am using `getBeanDefinitionNames`, `getPackage`(), `getName`() from applicationContext to print some bean names and their packages. Everything runs fine and I could verify all the beans with a debugger, but as soon as I populate the list on JSP with a populated model object(list of objects containing bean attributes), every element of the list shows: org.springframework.web.servlet.view.InternalResourceViewResolver and it's corresponding package: `package org.springframework.web.servlet.view` Why is it acting this way?
You've instantiated a single `SpringBeanStore` object and re-used that same object in your for loop, adding it X number of times in your result set. It will obviously hold the value of the last bean in your `myBeans`. Initialize the `SpringBeanStore` inside your enhanced for loop.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, spring, jsp, spring mvc, model" }
Conditional formatting to entire row I have a code in C# with EPPLUS for Excel that fills a cell green if the value of the cell is over 100. It works: ExcelAddress _formatRangeAddress = new ExcelAddress("G4:G" + (c.Count + 4)); string _statement = "IF(G4>100,1,0)"; var _cond2 = hoja.ConditionalFormatting.AddExpression(_formatRangeAddress); _cond2.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; _cond2.Style.Fill.BackgroundColor.Color = System.Drawing.Color.LimeGreen; _cond2.Formula = _statement; But what I really need is to fill the entire row. If I change the range: ExcelAddress _formatRangeAddress = new ExcelAddress("A4:G" + (c.Count + 4)); Applies only for the cells in the A column, not to the entire row. What I am doing wrong?
Make the reference to `G4` absolute otherwise the formula will be apply relative to that cell. So change this line: string _statement = "IF(G4>100,1,0)"; to apply to the entire row based ONLY on `G4` string _statement = "IF($G$4>100,1,0)"; **(Response to Comments)** to apply to entire rows relative to row number but keep the column fixed to G: string _statement = "IF($G4>100,1,0)";
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, excel, epplus" }
Possible to configure https proxy for DXA connection to microservices? I don't see any mention of it in the docs, but I was wondering if it was possible to set a proxy at application level just for the DXA web application connection to the discovery, content, model and other microservices? I will be using SDL Web Cloud with own hosted DXA 2.0 web application. If not I assume I can do this with some OS level proxy settings in Linux, but as the SDL microservices are the only services I need to have access to over the internet it would be neater to solve this at application level.
AFAIK, there is currently no application-level support for proxies. Note that in case of DXA 2.0, support would be needed in the DXA Framework, but also in the UDP CIL. So, this seems like an Enhancement Request for both DXA and UDP. If you think this adds much value, I would recommend to submit it as an Idea on the SDL Community Site.
stackexchange-tridion
{ "answer_score": 3, "question_score": 5, "tags": "dxa, microservices, sdl cloud" }
run a bash script located in public folder github actions I have this script `createmap.sh` in the `public/scripts` folder. I need to run it on master deployment the code in yaml file is name: create-map on: push run: .public/script.sh runs-on: ubuntu-latest shell: bash it is a simple script that is supposed to create a sitemap and ping google # yarn sitemap $ cd public $ rm -rf sitemap $ mkdir sitemap $ cd .. $ cd scripts $ node ./sitemap-posts.js $ node ./compress-map.js $ node ./create-one-map.js $ curl My folder structure is `rootdirectory/scripts` and `rootdirectory/public` When I deploy the scripts are not run and I don't know where the problem is
You need to add permission for execution: jobs: run_tests: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 - name: Run script file run: | chmod +x ./public/scripts/test.sh ./public/scripts/test.sh shell: bash
stackexchange-stackoverflow
{ "answer_score": 32, "question_score": 20, "tags": "bash, github actions" }
HTTP content length exceeded 4194304 bytes While testing I observed that media attachments more than 4194304 bytes are rejected by the proxy. It throws the message - "HTTP content length exceeded 4194304 bytes". Is this the functionality of LittleProxy implementation or there is any configuration which will allow bigger size of attachments than this?
This sounds like a `TooLongFrameException` thrown by `HttpObjectAggregator`. The only way that I think this could happen is when using an `HttpFiltersSource` that specifies a non-zero value from `getMaximumRequestBufferSizeInBytes()` or `getMaximumResponseBufferSizeInBytes()`. You can increase those, but that increases your memory usage. If the filter can be rewritten so as to work with frames (chunks) as they stream through, then you can set the buffer size to 0 and dramatically reduce your memory consumption.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "little proxy" }
Benefit of using pointers for dynamic memory allocation with arrays I am trying to understand the benefit using this... double *x = new double[n]; instead of just using this... double x[n]; Thanks #include <iostream> using namespace std; main() { int n; cout<<"# of elements in array"<<endl; cin>>n; double *x = new double[n]; //or double x[n] int i; for(i=0;i<n;i++) { cout<<x[i]<<endl; } return 0; }
### Mandatory note: std::vector<double> x(n); beats what you have there. ### Actual answer: The benefit is that double *x = new double[n]; is legal, whereas double x[n]; is not, unless `n` is a compile-time constant (in your case, it's not). C++ doesn't support variable-length-arrays.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "c++, arrays, memory, pointers" }
Determine Location Of Ruby Gems How do I determine the location of my ruby gems?
you can try gem which rails to fetch location for particular gem, or echo $GEM_HOME to fetch home dir of your gems
stackexchange-stackoverflow
{ "answer_score": 65, "question_score": 56, "tags": "ruby, ruby on rails 3, rubygems" }
Identify the top 2 preferred users in descending order who offered rides !carpooling database schema the users in ride_users table are also the ride provider in RIDE table with column ride_provider_id. I have to identify the top two users who have offered maximum ride as ride provider. I have tried this but didn't get desired results: select distinct r1.user_id, u.first_name||' '||u.last_name as user_name from user_details u inner join ride_users r1 on u.user_id=r1.user_id inner join ride r2 on r1.ride_id =r2.ride_id where r1.user_id = r2.ride_provider_id order by r1.user_id desc;
the inner inline table will give the ride count, which you can use to order by and limit on. SELECT u.* FROM user_details u INNER JOIN (SELECT r.ride_provider_id, count(*) rides FROM ride r GROUP BY r.ride_provider_id ) mr on mr.ride_provider_id = u.user_id ORDER BY mr.rides DESC LIMIT 2
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "mysql, sql, rdbms" }
Set custom data type in Argument I got a little problem in Android. I am creating a App and want to pass a Object to my Fragment. I'm searching for a way to pass a custom Object to my Fragment, something like: Fragment frag = new myFragment(); Bundle args = new Bundle(); args.put("Arg1", myObject); Is there a way to do something like that? Thanks!
Getters and setters are good for this job rather than using arguments when you pass object between two fragments Answer is given in this link Android: Passing Objects Between Fragments
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android, android fragments" }
How can I combine two lists of lm models element-wise? I have two lists of fits generated by lm and I would like to combine them element-wise. Right now, I have something like: fits1 = list(fit1, fit2, fit3) (where fit1, fit2, and fit3 are models generated by lm) and fits2 = list(fit4, fit5, fit6). What I would like to do is produce a list combined elementwise: list(list(fit1, fit4), list(fit2, fit5), list(fit3, fit6)). I found some stuff about how to combine lists element-wise but all the solutions I've seen have required switching to a dataframe and you cannot include elements of class lm in a dataframe. Thank you!
I think `Map` will give you what you are looking for. fits1 <- list("fit1", "fit2", "fit3") fits2 <- list("fit4", "fit5", "fit6") Map(list, fits1, fits2) **Result:** [[1]] [[1]][[1]] [1] "fit1" [[1]][[2]] [1] "fit4" [[2]] [[2]][[1]] [1] "fit2" [[2]][[2]] [1] "fit5" [[3]] [[3]][[1]] [1] "fit3" [[3]][[2]] [1] "fit6" In `tidyverse` speak, that would use `purrr`. library(purrr) map2(fits1, fits2, list)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "r, lm" }
Prevent bootstrap 3 from resetting nested grids / use master grid Is there a way to make Bootstrap 3 use just my outer grid columns? For example, I've built Bootstrap to use 10 columns instead of 12. I've divided my layout to have a 2 column left div and an 8 column right div. My main content goes in the right. I want to divide the main content into four equal columns, which should just be four .col-md-2 elements. Bootstrap however wants to reset the grid back to ten when I place .col elements into the right div. Help?
Well the outer column is 8 and 2 = 10 but you want 4 equal inside the main content which should equal 10, but instead you have col-md-2 x 4 = 8 so you can't do that you need to have that add to 10 inside that main content. You'll need use columns that are 25% in width, if you converted correctly to use 10 columns then it's probably col-md-4. You need to post a fiddle or a bootply to get better answers. Or switch back to 12 columns and fiddle with the widths of those columns in LESS (less painful).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css, twitter bootstrap, twitter bootstrap 3" }
How can I decrypt a password stored in database and generated by the jhipster web-app? I have this in my application-dev.yml file: security: authentication: jwt: # This token must be encoded using Base64 and be at least 256 bits long (you can type `openssl rand -base64 64` on your command line to generate a 512 bits one) base64-secret: ODNiNWQ5NmY0M2ZiNTg3MDI1YjA2N2Y1OGVjMTY1ZWM3NzkxZTdlN2FiZGYyYzM2ZTljNTVkZGZiZmQzZDFlMTJhODNkMTEyNzM5NmY0MDMzZmI4Y2E2YjFkNzg1MDM2NzAwNDhhZDI1NGVjOGIyMDNlMGU3ZDZhNmQyZDk1YWY= # Token is valid 24 hours token-validity-in-seconds: 86400 token-validity-in-seconds-for-remember-me: 2592000 and I want to decrypt one of the user passwords stored in the postgres database, for example: `$2a$10$j8S5d7Sr7.8VTOYNviDPOeWX8KcYILUVJBsYV83Y5NtECayypx9lO` How can I do it?
You cannot decrypt password hashes, they are encrypted using 10 rounds BCrypt (Spring Framework default configuration). The JWT secret has nothing to do with password encryption. If a user has lost his password he should request a password reset and will receive a reset link by email. If the problem is that you have lost the password for a user in your development environment it could be faster to just encrypt a new password using the same 10-rounds Bcrypt algorithm (this can even be done online) and replace the `password_hash` in the database directly. Also, please generate a new `base64-secret` key and do not share it with anyone as instructed in the jhipster documentation.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "jhipster" }
How to edit xml/dom with Emacs Lisp How can I, if possible at all, programmatically edit xml data in Emacs Lisp? What I need to do, is to programmatically add new nodes into arbitrary locations in the xml: <root> <child> </child> </root> (xml-add-element xml "hello" (xml-element-by-tagname xml "child")) <root> <child> <hello></hello> </child> </root> * * * **Edit:** I got as far as parsing the xml into a lisp structure and editing it with `xml.el` and `dom.el`, but now I need to turn the lisp structure **back into xml data**.
here's my version for converting s-expressions created from xml-parse* functions back into xml strings. Hope it's helpful! <
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "xml, emacs, elisp" }
Detect Exchange version by Redemption does anybody know how to detect Exchange server version when connected by Redemption? rdoSession.ExchangeMailboxServerName returns the machine name rdoSession.ExchangeMailboxServerVersion returns something like "14.3.181.4006" what I need to find out is whether its 2007 or 2010, etc.
You have enough information to determine the exact version of Exchange you are connected to. The _ExchangeMailboxServerVersion_ is returning the build number of the server you are connecting to, and you can compare this number to a list of server versions. For example, I know that the build number you reference is **Update Rollup 5 for Exchange Server 2010 SP3**. For a list of the build numbers, product names, and release dates check out this article on TechNet: Exchange Server Build Numbers and Release Dates I hope this helps. If this does resolve your question, please mark this post as answered. Thanks, \--- Bob ---
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "exchange server, outlook redemption" }
Laravel > nested eager load with restriction Assumed we've got users, friends and restaurants. Don't want to go to deep into the Model and relationship setup. While me as a user is logged in: How can I get all friends who are "customers" of the restaurant? I've got this and it's already working: $friends = array_dot(Auth::user()->friends()->select('users.id')->get()); $customers = Restaurant::with(['users' => function($query) use($friends) { $query->whereIn('users.id', $friends); }])->find(restaurant_id); But is this even possible with a single query?
It sounds like you want to find all of your friends that have a relationship to the restaurant. If so, you're looking for `whereHas()`. General idea: $restaurantId = 1; $user = Auth::user(); $friendCustomers = $user->friends()->whereHas('restaurant', function ($query) use ($restaurantId) { $query->where('id', $restaurant_id); })->get(); You can read more about querying relations, and `whereHas`, here.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "laravel, eager loading" }
Calling multiple objects with a method in Java I'm trying to create a calendar using Java GUI and I want to create a method to create the cells of each date. Is there any way to create a method to create a bunch of JTextAreas without manually creating each individual cell? Creating a cell one by one I do: public void createCell() { cell1 = new JTextArea(CELL_DIMENSIONS, CELL_DIMENSIONS); }
You have many ways of doing that one possibility would be to create a `List` inside the method with the assistance of a `for` loop and make the method return it for you to use somewhere else. public List<JTextArea> createMultipleCells(int numOfCells) { List<JTextArea> cells = new LinkedList<JTextArea>(); for(int i = 0; i < numOfCells; i++){ cells.add(new JTextArea(CELL_DIMENSIONS, CELL_DIMENSIONS)); } return cells; } Same thing with an array: public JTextArea[] createMultipleCells(int numOfCells) { JTextArea[] cells = new JTextArea[numOfCells]; for(int i = 0; i < numOfCells; i++){ cells[i] = new JTextArea(CELL_DIMENSIONS, CELL_DIMENSIONS); } return cells; }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java" }
how to create a custom user group in AEM using APIs I am looking to solve a use case that needs me to create a custom user group using any API available within AEM 6.1. Beyond this, i also want to add specific permissions onto the custom group. Any pointers will be greatly appreciated Thanks, Hemant
You can use UserManager \- createGroup() to create the groups and for permissions you might have to use. javax.jcr.security.AccessControlManager org.apache.jackrabbit.api.security.JackrabbitAccessControlList javax.jcr.security.Privilege
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "security, aem" }
Why is std::rotate faster than this way of doing it? void rotate(vector <int> &a) { int lastElem = a[a.size()-1]; for(int i=a.size()-1;i>0;i--){ a[i] = a[i-1]; } a[0] = lastElem; } Versus rotate(a.begin(),a.end()-1,a.end()); As far as I can see the algorithm above is O(n) so why is STL way faster(I thought it was linear time as well).
The standard library implementation of `std::rotate` is likely using a call to `memmove()` for bulk data copying. That would be one reason that it's faster than your hand-written loop. Since you are only rotating a single element you can replace your loop with a call to `std::copy_backward`. That will also compile to `memmove()` and provide better performance. void rotate(std::vector<int> &a) { int lastElem = a.back(); std::copy_backward(a.begin(), a.end() - 1, a.end()); // memmove() a.front() = lastElem; } You can examine the generated assembly here on Compiler Explorer.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++, algorithm, performance, stl" }
How do I define a SWIG typemap for a reference to pointer? I have a Publisher class written in C++ with the following two methods: PublishField(char* name, double* address); GetFieldReference(char* name, double*& address); Python bindings for this class are being generated using SWIG. In my swig .i file I have the following: %pointer_class(double*, ptrDouble); This lets me publish a field that is defined in a Python variable: value = ptrDouble() value.assign(10.0) PublishField("value", value.cast()) Trying to using the GetFieldReference method results in a TypeError however: GetFieldReference("value", newValue) I think I need to create a typemap for the double*& that returns a ptrDouble, but I am not quite sure what that would look like.
Here is a working solution that I came up with. Add a wrapper function to the swig.i file: %inline %{ double * GetReference(char* name, Publisher* publisher) { double* ptr = new double; publisher->GetFieldReference(name, ptr); return ptr; } %} Now from Python I can use the following: value = ptrDouble.frompointer(GetFieldReference("value", publisher)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c++, python, swig" }
Add code to html pages automatically I need to add some code to the of several html contained in a folder on my desktop. How can i do that? I am using a prototyping tool (Axure) on Mac and I want to add some html meta tags to the generated pages. These pages can be overwritten every time I generate the prototype. What I need is a sort of script that I can launch after re-generating the prototype, to reinsert the code. There is something for windows but it doesn't work on Mac: < thanks
This is a very simple problem to solve using a shell script. If you are not familiar with scripting, then check out the Automator program built-in to OS X. This provides a "visual" way of building automation workflows. This is the basic steps that your workflow will need to perform. Find the files that need updating. For each file Open the file using TextEdit Tell TextEdit to Find the Head element and replace with the new Head Element that includes the script Save the file. Repeat
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "html, automation, scripting" }
How to print int to std::wcerr? How do I write the output `operator<<` if my object needs to print a `std::wstring` as well as ints, etc? #include <iostream> struct Foo { int i; std::wstring wstr; }; std::ostream& operator<<(std::ostream& out, Foo const& foo) { out << foo.i << foo.wstr; // error return out; } int main() { Foo foo; std::wcerr << foo << std::endl; } In other words: How can I print `int`s and other primitive data types if I am passed a `wcerr`? Do I need `boost::lexical_cast<std::wstring>` or similar?
#include <iostream> struct Foo { int i; std::wstring wstr; }; std::wostream& operator<<(std::wostream& out, Foo const& foo) { out << foo.i << foo.wstr; return out; } int main() { Foo foo; std::wcerr << foo << std::endl; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "outputstream, widestring" }
Rank of a linear transformation. Let $V$ be the vector space of all continuous function from $[0,1]$ to $\mathbb{R}$ on the field $\mathbb{R}$. What is the rank of the linear transformation $T:V\rightarrow V $ which was defined as below? $$T(f(x))=\int_{0}^{1}(3x^3y-5x^4y^2)f(y)dy$$
$T(f(x)) = $$\displaystyle\int_{0}^{1}(3x^3y-5x^4y^2)f(y)dy\\\ \displaystyle3x^3\int_{0}^{1}yf(y)\ dy-5x^4\int_0^1 y^2 f(y)\ dy$ $\int_{0}^{1}yf(y)\ dy$ is a constant as is $\int_0^1 y^2 f(y)\ dy$ So what does that say about $T(f(x))$?
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "linear algebra, linear transformations" }
Finding average length of items in a list. Python my_list = [['abcdefg','awdawdawd'],['awdwer'],[],'rtgerfwed','wederfrtg']] so i have a list and i want to find the average lengths for each sublist within the list i tried this but it didn't seem to work lengths = [] lengths = my_list for k in lengths: k = len(k) print lengths # i get this again -> [['abcdefg','awdawdawd'],['awdwer'],[],'rtgerfwed','wederfrtg']] i want the output to be lengths = [8,6,0,9]
A list of the lengths of each element in a list: lengths = [len(i) for i in my_list] For the average: def averageLen(lst): lengths = [len(i) for i in lst] return 0 if len(lengths) == 0 else (float(sum(lengths)) / len(lengths)) If it's a list of lists: lengths = [averageLen(i) for i in my_list]
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "python, string, list, average" }
joining @ManyToOne's @OneToMany 1. Each `Account` has a `Origin` via `@ManyToOne` 2. Each `Origin`s has `Shadow`s via `@OneToMany` With given `Root<Account>`, How can I join those `Shadow`s so that I can put some conditions for them on where? final Root<Account> account; final Path<Origin> origin = account.get(Account_.origin);
Provided that the `@OneToMany` property in `Origin` entity is called `shadows`, you need to use Join as follows: Join<Origin, Shadow> shadows = origin.join(Origin_.shadows); Then, you can write conditions on `Shadow`s properties like in this trivial String case, since `Join<Z,X>` has `Path<X>` as SuperInterface: String name; Predicate condition = criteriaBuilder.equals(shadows.get(Shadow_.name, name));
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jpa, join, criteria api" }
TypeScript Type Inference For Simple Function Combination I'm having a tough time with what I would think should be relatively simple. I can't get the types to comes through in trying to do a simple combination of a couple functions. Is there a way to tell TS to figure out the type inference without having to explicitly put something? import { pipe, map } from 'ramda' type TODO = unkown export const mapP = (xf: TODO) => (data: TODO) => pipe( map(xf), x => Promise.all(x), )(data) I really just want to let `map` dictate the types for the function and not have to retype them. Thanks in advance!
import { pipe, map } from 'ramda' export const mapP = <T,R>(xf: (value:T) => Promise<R>|R) => (data: T[]): Promise<R[]> => pipe( map(xf), x => Promise.all(x), )(data) Does this require any explanantions?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "typescript, functional programming, typescript typings, ramda.js" }
Break Away Valves for Launch I forgot to hang up the fuel pump and broke it off and costed around 80 dollars to replace. While there I wandered could this be adapted to a rocket in some way? How much fuel capacity would be saved if the fuel was fed to the rocket to keep it topped off until it has fully left the launch tower? The length of the fuel line and break away valve would be the height of the launch tower. Could it be fed through an extended tower with a fuel line that travels aside the rocket not to burden the rocket with the weight of the fuel line or cause a whip in the fuel line? ![enter image description here]( <
Theoretically yes. However there are concerns: 1) Propellant load is dangerous under the best circumstances. Add in all the vibration loads of an "on" rocket and you have a doozie. 2) Most rockets already have umbilicals that disconnect slightly after liftoff. The recent Rocketlab launch video has a good angle of this 3) It's a bit of added weight and complexity. These are all surmountable, but then what would you be gaining? I'm sure someone can do a calculation (slightly related to this question) but I suspect it's a negligible amount of payload/mass gain.
stackexchange-space
{ "answer_score": 3, "question_score": 2, "tags": "launch, fuel, engines, design alternative" }
Replace character with page break In MS Word I need to string replace a pattern (`$$$newpage`) with a page break. Is this possible with standard page search? Or do I need to do it programmatically?
go to "find and replace" and enter your "find" character and replace it with `^m` You can read more about it _here_
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 6, "tags": "ms word" }
How do I get the sys_language_uid with extbase In TYPO3 9.5 is only $GLOBALS['TSFE']->sys_language_isocode available. How do I get the numeric sys_languagae_uid in my controller?
You can use the new `Context` singleton for this: $context = GeneralUtility::makeInstance(Context::class); return (int)$context->getPropertyFromAspect('language', 'id'); This will return the numerical "sys_language_uid". When you look into the docblock of the Context class (see `public/typo3/sysext/core/Classes/Context/Context.php`, there is also a list of possible aspects you may use. There also is a documentation available.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "extbase, typo3 9.x" }
How separate grep result with comma in bash? I have following grep command `echo $a | grep -Po '(?<=demo-jms2;)[^;]+'`. How I can separate the result of this command with comma?
how about pipe the grep output to `tr '\n' ','`
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 3, "tags": "bash, grep, design patterns" }
Identifying what is returned when submitting a form using jquery Is it possible to identify what a page returns when using jquery? I'm submitting a form here using jquery like this: $("#sform").submit(function() { $.ajax({ type: "POST", data: $(this).serialize(), cache: false, url: "user_verify.php", success: function(data) { $("#form_msg").html(data); } }); return false; }); ​ The user_verify.php page does its usual verification work, and returns error messages or on success adds a user to the db. If its errors its a bunch of error messages or on success its usually "You have successfully signed up". Can I somehow identify using jquery if its errors messages its returning or the success message. So that way if its errors I can use that data in the form, or if its success, I could close the form and display a success message.
Yes, it's this: success: function(data) { $("#form_msg").html(data); } You can manipulate `data` in any way you want. You can return a JSON (use `dataType`) encoded string from server side and process data in the `success` function success: function(data) { if(data->success == 'ok'){ // hide the form, show another hidden div. } } so `user_verify.php` should print for example: // .... queries $dataReturn = array(); $dataReturn['success'] = 'ok'; $dataReturn['additional'] = 'test'; echo json_encode($dataReturn); die; // to prevent any other prints.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, jquery" }
Editor opens wrong file when trying to commit I am new to Git and am trying to commit changes to a repository. I have set up Sublime as my default editor with the following line in my .gitconfig file: editor = C:/Program\\ Files/Sublime\\ Text\\ 2/sublime_text.exe -n -w When I use `git commit` Sublime opens correctly, however rather than opening the COMMIT_EDITMSG file as expected, it opens a new empty file called $@ in the working directory. Writing a commit message and saving and closing the file results in the error message: Aborting commit due to empty commit message I am using Git 1.9.5 on Windows 7 64-bit.
This problem occurs because the path of the editor is not configured correctly. Simply put the unescaped path in quotes. It should look something like this: editor = "C:/Program Files/Sublime Text 2/sublime_text.exe" -n -w Hope this helps you!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "git" }
How can I add CommandBar buttons in SharePoint online using JSOM? ![enter image description here]( As shown in figure I want to add button (right side by send by mail) on each CommandBar in SharePoint site?
You can insert some code into React script editor web part to append the custom button. <script src=" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { var commandset= $("button[name='Send by email'][role='menuitem']").parent().parent(); commandset.append( "<p>Test</p>" ); }); ![enter image description here](
stackexchange-sharepoint
{ "answer_score": 1, "question_score": 0, "tags": "sharepoint online, spfx, jsom, modern team site" }
innerHTML value of contenteditable div on modification I have a content editable div: <div contenteditable="true" id="my-div"> <? if(isset($data["description"])) { print_r($data["description"]); } ?> </div> Once the user edits the div I am trying to pass the modified value of the div to a hidden form element. document.getElementById("desc").value =document.getElementById("my-div").innerHTML(); I am getting the original value on page load, not the modified value as innerHTML. How do I get the updated value?
$('#my-div').on('keypress', function() { $('#desc').val($(this).html()); }); you need to listen to changes to the editable div and update input value i assume you use jquery if not document.getElementById('my-div').addEventListener('keypress', function(e) { document.getElementById('desc').value = this.innerHTML; });
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "javascript, jquery, html, contenteditable" }
Sum a python list without the string values So according to duck-typing advice, you aren't advised to check types in python, but simply see if an operation succeeds or fails. In which case, how do I sum a list of (mainly) numbers, while omitting the strings. sum([1,2,3,4,'']) #fails sum(filter(lambda x: type(x)==int, [1,2,3,4,''])) #bad style
I will do something like this a = [1,2,3,4,''] print sum(x if not isinstance(x,str) else 0 for x in a)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python" }
yii not showing with this $model->errors code - using composite primary key hello friends i am using composite primary key in my yii application and i am trying to import csv file into database using save() function and i have only three rows but when i am trying to import those only one row getting insert not all. and if i am trying to access the error then nothing is showing .. but when using model->validate then it returning false. CVarDumper::dump($model->errors,10, CVarDumper::dump($model->attributes, 10, true); CVarDumper::dump($model->validate(), 10, true); what should i use to print error .. above three are not able to print error. but error is their. regards anil
before validating you do not have any errors, because you haven't checked for anything, validate your model and after that you can catch your errors $model->validate(); var_dump($model->errors);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "yii" }
Is it possible to choose the effect for a switchClass jQuery UI function? I would like to add a subtle and quick fadeOut and FadeIn effect to a button change through switchClass. `jQuery("a#btnPause").switchClass(pauseClass,playClass,200);` The effect used by default is a slideLeft. If I would use standard jQuery, I would like to put an effect on addClass and removeClass, but is that possible?
Is something like $("a#btnPause").fadeOut(200).switchClass(pauseClass,playClass,200).fadeIn(200); what you're looking for?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, class, jquery ui" }
Calculate element height in directive Why is `nextTick` required in my example below in order to calculate the element height? As far as I know, `nextTick` is used to wait for DOM updates after reactive data has been modified, which is not the case below: Vue.directive('test', { bind: function(el) { console.log($(el).css('height')) Vue.nextTick(() => { console.log($(el).css('height')) }) } }); var demo = new Vue({ el: '#demo' }) <div id="demo"> <div v-test> lorem lorem </div> </div> <
You are using the wrong hook. > **Hook Functions** A directive definition object can provide several hook functions (all optional): > > 1. bind: called only once, when the directive is first bound to the element. This is where you can do one-time setup work. > > 2. inserted: called when the bound element has been inserted into its parent node (this only guarantees parent node presence, not necessarily in-document). > > Vue.directive('test', { inserted: function(el) { console.log($(el).css('height')) } }); var demo = new Vue({ el: '#demo' }) See Fiddle
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, vue.js" }
Trouble with an easy complex equation For the following equation: > $\frac{Aj}{100\sqrt{2}} -\frac{A}{100\sqrt{2}} +\frac{x}{200}-\frac{xj}{200} =0$ where $A$ is a constant and $j$ is the imaginary unit. I thought the solution would be found by isolating the real and imaginary parts and setting them both equal to zero. I would then get the answer $\frac{2A}{\sqrt{2}}+\frac{2A}{\sqrt{2}}j$, when the answer is $\frac{2A}{\sqrt{2}}$ (This is obvious by just plugging this solution in). Why does setting the real and imaginary parts to the real and imaginary parts of the right side, which are both zero, produce the wrong answer? Thank you.
You have:$$\frac{Aj}{100\sqrt{2}} -\frac{A}{100\sqrt{2}} +\frac{x}{200}-\frac{xj}{200} =0$$$$\therefore\left(\frac{A}{100\sqrt{2}}-\frac{x}{200}\right)j+\left(\frac{x}{200}-\frac{A}{100\sqrt{2}}\right) =0$$Both real and imaginary components must equal zero which both lead to the answer:$$\frac{x}{200}=\frac{A}{100\sqrt{2}}$$Which simplifies to your desired answer. * * * In general, if:$$a+bj=0$$Then this implies that $a=0$ and $b=0$ * * * Even more generally, if:$$\color{red}{a}+\color{blue}{b}j=\color{red}{c}+\color{blue}{d}j$$Then this implies that $\color{red}{a}=\color{red}{c}$ and $\color{blue}{b}=\color{blue}{d}$
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "complex numbers" }
Custom highlight to jqPlot stacked bar chart When adding a custom highlight to the jqPlot chart, I simply use $('#chart').bind('jqplotDataHighlight', function (ev, sIndex, pIndex, data) { var chart_top = $('#chart').offset().top, y = plot1.axes.yaxis.u2p(data[1]); // convert y axis units to pixels $('#tooltip').css({ top: chart_top + y }); } as seen in the last example here. This works great on my simple bar chart. I then try the same on a stacked bar chart, and the x-values are off. Does anyone know how I can get these values or what I am doing wrong?
Check out how I do a custom tooltip on my stacked bar chart. The jsfiddle sample is available here.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "javascript, jquery, jqplot" }
How to pull huge table (80 millions rows) from Oracle into SQL DB or SQL dump via VPN I have the task to pull a huge table from an Oracle DB into a SQL DB or SQL dump via the internet. The source DB (Oracle) is in an enterprise setting which I access via Cisco VPN (Split tunneling is not allowed). I have tried a tool from Intelligent Converters: Progress is very slow, which seems to be a **latency** issue (84MB in 8 hours pulled), at this rate I need more than 60 days. The table itself is extremely simple (no no views, storage produceres, no indexes, identities etc.). Options are restricted by the VPN that does not allow split tunneling: The moment the connection stands no internet connection is present on the connected machine, I therefore need physical access.
Why not create a database dump using expdp, compress it using bzip2 / gzip and then transfer via scp? I'm assuming Oracle is hosted on a *nix based OS
stackexchange-superuser
{ "answer_score": 0, "question_score": 1, "tags": "vpn, sql, dump, database administration" }
css validator error HTML5 Conformance Checker Error Line 22, Column 63: Element link is missing required attribute property. link rel="stylesheet" type="text/css" href="css/layout.css"
Move your link element to the `<head>` section of your HTML document.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "css" }
How to get filename of image resource to a textbox? I have looked and nothing I am finding is helping me out but I would like to know how to get a filename to a textbox. Lets say I have a image in the project settings called image1 so the code would be Properties.Resources.Image; but I need the Image name to appear in a textbox. Hope someone can help me out with this.
textbox.Text = nameof(Properties.Resources.Image);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#" }
Sync branch with master in git. I have a branch with couple of commits, I want to sync it with the master branch. I am trying to rebase it interactively and I am picking all the commits. git rebase -i master In this case I have to manually resolve all the conflicts for each commit, is there a way to avoid that and resolve the conflicts only for the last commit.
You can first squash all commits and then do the rebase. git merge-base <my_branch> master Result is the hash of the best common ancestor between your branch and master git rebase -i <hash> Squash all your commits to a single commit git rebase -i master Now you should see only a single commit there, and you can solve the conflicts once.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "git" }
Driving with a CB (citizen band radio) in the US I'm thinking about buying a CB to put in my car so I can use it for a long road trip. I'm debating it though because I'm not sure if the benefits will outweigh the trouble of installing the unit as well as the antenna. Basically I think it would be useful if truckers actually share road and weather information while they drive. My questions are: 1. Does anybody have any experience getting useful information using a CB or is usually just useless chatter? 2. Is channel 19 the channel truckers generally use nationwide or is that just a regional thing?
I would recommend getting a CB. Quite often I got good information from truckers about traffic conditions. You don't need to actually install one though. I use a mobile CB that looks like a Walkee talkee. I use one like the one here: < and would recommend one like it if you aren't going to be using it on a daily basis. So my answers are: 1) Yes, I got good info from truckers before and the above website shares some times he found it useful as well. 2) In my limited experience wherever I am, truckers seem to hang out on 19 a lot but don't necessarily limit themselves to that channel. I know you didn't mention this but another use of the CB is it is potentially useful if you have an emergency. Channel 9 is reserved for that.
stackexchange-travel
{ "answer_score": 6, "question_score": 6, "tags": "usa, driving, road trips" }
How to run a command before download with apt-get? How can I run a command before apt-get starts to download a package? I know about the dpkg pre-invoke hook ( hook a script to apt-get ), but that seems to be run after the download. $ apt-get update Get: 11 wheezy/updates/main qemu amd64 1.1.2+dfsg-6a+deb7u7 [115 kB] Fetched 70.9 MB in 10s (6,776 kB/s) refreshing freenet index --2015-05-19 15:55:25-- What we need is to run a command _before_ the download. More exactly: The script must run after calling apt-get but before apt-get accesses any online resource. Is there something like a Pre-Download hook? It is important that the installation can be done without having to replace the script apt-get (and without doing anything else which could be undone by an update).
First determine where is apt-get using `whereis apt-get` or `which apt-get`; I will assume it's in _/usr/bin/apt-get_ Then create a file in **/usr/local/bin/apt-get** with this content: #!/bin/bash # (commands to run before apt-get) exec /usr/bin/apt-get "$@" now `chmod +x /usr/local/bin/apt-get`. This should survive all upgrades of the distribution but it should not change the behavior of apt-get (aside from running the command before doing anything else). As bonus, it could parse the command line arguments to only run the command when it is truly needed. _(This answer builds upon theanswer from Mohammad Etemaddar, merged with the feedback from muru)_
stackexchange-unix
{ "answer_score": 3, "question_score": 8, "tags": "apt, hook" }
Mogno: поиск записи по дате, если дата в формате строки Всем привет. Так получилось, что у меня даты с Монго сохранены как строки. Но мне нужно по ним отфильтровать записи и найти те, которые попадают в интервал. Может кто-то сталкивался с таким. Я много читал, что можно фильтровать, если даты сохранены в типе Date, но так вышло, что у меня в строках.
Для данных вида: { "_id" : ObjectId("613b6f94272a50ce7c777549"), "dateProperty" : "2021-09-06T12:36:41.555Z" } Запрос: db.getCollection('Test').find({ $expr: { $and: [ { $gte: [ {$dateFromString: {dateString: '$propertyName'}}, ISODate('2021-01-01T00:00:00.000Z') ], }, { $lte: [ {$dateFromString: {dateString: '$propertyName'}}, ISODate('2022-01-01T00:00:00.000Z') ], }, ], }, }) Если дата имеет другой формат, то у операции $dateFromString можно указать формат данных. * * * !!! Хочу также обратить внимание, что если дата в виде строки в формате ISO (как на примере), то можно просто сравнивать строки вместо дат. Результат будет тем же
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mongodb, pymongo" }
Automatic imports from imported file I have a file called `utils.py` with the following code: from __future__ import division import numpy as np In another file `test.py` I call the previous one: from utils import * print np.sqrt(4) print 1/2 Now, as an outcome I get `2` and `0`. That is, `np` imported in `utils.py` also imports to `test.py` through `utils.py`, however the division module does not. Is there a way to make sure division is imported to `test.py` by importing everything from `utils.py`? The motivation is that in almost all my files I import `utils.py` so I do not want to import division in each file separately, as I can currently do with `np`.
Imports from `__future__` **are not real imports!** They are a different kind of statement that happen to have a similar syntax. The documentation states clearly: > It allows use of the new features **on a per-module basis** before the release in which the feature becomes standard. They are a way to tell python to treat _that file_ in a different way, in particular to compile the code using a possibly different syntax or semantics. So, no you cannot "re-export" `__future__` imports.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "python, import" }
Kanban-style view : Group nodes in a view into columns based on a field value I have a custom node type in Drupal - Order - which has a status field. The status can have three values. What I would like to do is create a view in which orders are grouped into columns based on their status - essentially a primitive Kanban board - and the columns are ordered in a particular way. Is this possible and if so, how?
One possible solution would be to use the Views Field View module, which provides a Global: View option as a field in a view. < ![Main View]( You would create a main page view, use the Table format. Then create an Embed display for each status that filters your items by that status. Back on your main view you would add a Global: View field for each status and select your status displays. ![enter image description here]( I'll note that the main page view needs to bet set to show 1 item, so you don't have multiple rows of the same content. Each embed display would be set to show all items. One issue with this method is the vertical alignment is in the middle of the table columns when there are is a different number of items per column. It's a little bit hacky but may be a step in the right direction.
stackexchange-drupal
{ "answer_score": 1, "question_score": 2, "tags": "views, 8" }
Need help coding iterator for a circular linked list in C++ So I'm creating a circular linked list to solve the Josephus Problem for an assignment. I had a really bad professor for my C++ class and I don't really know how to do anything in C++. I'm trying to code an iterator to transverse the list, but I have no clue where to start or how to implement it. Can anyone give me an suggestions or advice on how to start coding this?
It's pretty much just like the `std::list` iterator, except the end iterator is where the next pointer is the head of the list, not when it's `NULL`. A reference page will tell you what you're supposed to implement. The underlying representation will be a pointer to a list node, `operator*` will return a reference to the data, `operator++` will set the pointer to `next`, etc. Alternatively, use an array implementation with modular arithmetic.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -9, "tags": "c++, listiterator" }
stop function after x seconds angular 9 i want to stop a function in 10000 seconds but this doesnt work on angular: setTimeout(() => { this .ngZone .run(() => { if (device.name.includes('DeviceName')) { this.connectToDevice(device) } }); }, 10000, console.log('not found')); this start the function after 10000, but i need to stop the function after 10000 seconds and show a message..
you can use pipe with timeout from rxjs > import { timeout } from 'rxjs/operators'; example: your_subscription .pipe(timeout(10000)) // closed after 10 seconds .subscribe((result) => { // do stuff });
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "angular" }
How to get the correct timing of a key being released (JS' keyup is not accurate)? When I use keyup I never get a timestamp later then about keydown+500ms even if I hold down the key much longer. I'm using document.addEventListener('keyup', function(event) { if (event.code == 'KeyZ' ) { var d = new Date();var time = d.getTime(); } });
This is because the `keydown` will be fired multiple times when the key is held down. Try placing a `console.log` in the `keydown` event handler and you'll see. This behaviour is not consistent between browsers and operating systems. For a detailed list of behaviours, check out < The timing between each `keydown` event when a key is held down can even be configured on Windows computers and possibly on other operating systems too. See <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
Atom UI issues after installation and reinstallation I am having issues with using Atom text-editor. I have used it before on my system and all was fine. However, opening it today, I had the UI looking like this: ![Atom GUI]( I have uninstalled it and reinstalled it, but to no avail. I have also deleted the local data file after installation and I keep getting the same UI. Any help would be awesome!
I managed to fix it. I was not expecting the above layout after a fresh reinstall. This was what I expected (and am used to). Somehow the .atom folder in C:\Users\%USER%.atom was completely hidden and read only, so I had trouble locating it. After using the terminal to access the folder, I inspected discovered its properties. After removing the hidden and read-only attributes, I deleted the folder and reinstalled Atom and it managed to fix the issue.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "user interface, text editor, atom editor" }
WPF UI Animation Library Is there a WPF library that can be used for animations? It should support animating transitions from one WPF form to another (like flip effects etc) and also been able to animate toolbox components (like labels etc).
There's some effects and transitions libraries on Codeplex. * < * < And this one which lets you transition between different UserControls. * < In fact, have a good scout around on Codeplex and CodeProject and you will find several other libraries that may help you out.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 8, "tags": "c#, wpf" }
How to use any button as a variable in a method? I have different buttons with different in different groups in a JFrame Form and I want to create a method that lets me use any of them. The VarButton would get the button it's supposed to operate like Button1 and then I write VarButton.setEnabled() and it enables Button1. I tried it with getName and setName but it didn't work.
To me it sounds like you are coming from Android where you do stuff like `R.id.button_id`. But in java it is much more simple. Just use a parameter of the class Button: public void yourMethod(JButton varButton) { VarButton.setEnabled(); } Then call it like this: JButton button1 = new JButton("Hello"); yourMethod(button1);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "java" }
Von Neumann algebra generated by a non-self-adjoint operator Let $A$ be a bounded linear operator on a separable Hilbert space ${\cal H}$, and suppose that $A$ is distinct from its adjoint $A^*$. **Question:** Can the double commutant of $A$ be distinct from the double commutant of $\\{A,A^*\\}$? If so, is there a simple example? * * * This question was inspired by the following statement from section 3.3 in Vaughan Jones (2009), _Von Neumann Algebras_ (< > If $S \subseteq {\cal B(H)}$, we call $(S \cup S^*)''$ the von Neumann algebra generated by $S$. I don't know if this was meant to be the most _efficient_ definition, and that's exactly what prompted my question. Maybe the Hilbert space wasn't assumed to be separable in that context, but I am interested in the separable case (if it matters).
Here is a simple example. Let $H=\mathbb C^2$ and $A=\begin{bmatrix}0&1\\\0&0\end{bmatrix}$. Then $\\{A,A^*\\}''=M_2(\mathbb C)$, while $$ \\{A\\}''=\left\\{\begin{bmatrix}a&b\\\0&a\end{bmatrix}:\ a,b\in\mathbb C\right\\}. $$
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "operator algebras, von neumann algebras" }
Safe way to save encryption keys in iOS In my iOS4+ app i use AES encryption on several places and whole app has to be very secure. In order to do this I have to hard code several keys in this app which are then randomly picked when I need to encrypt something... My question is how to store those private keys? Is it safe to hard-code them using `NSString`? Or #define SecretKeyString @"febd9a24d8b65c1c787d50a4ed3619a9" If user jailbreaks iPhone with this app installed, couldn't he get those hard-coded keys? How can i hide them most effectively? Thanks for any suggestion...
What others apps do is require the user to "log in" before they can use the app. Then you use their userid/password as a key to encrypt the keys or use a secured web service to get the keys for that user. If you use a `#define` or even an NSString, there are ways to guess the keys. Obviously, you have to truly be willing to spend a lot of time to find those keys in compiled code, but depending on the level of security you are looking for and the people you are guarding against, this might be a problem.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "iphone, objective c, ios, security, encryption" }
Getting error in accessing a link using WWW::Mechanize Getting the following error in a JavaScript link using perl - WWW::Mechanize. > Error GETing javascript:submt_os('2','contact%20info','contact%20info'):Protocol scheme 'javascript' is not supported This is my code: #!/usr/bin/perl use WWW::Mechanize; my $mech = WWW::Mechanize->new(); $uri=" $mech->get($uri); # error on this link $mech->follow_link( text => 'Contact Information'); print $mech->content(); Once I get the page, I want to click _Contact Information_. Is there any other way to click _Contact Information_?
You can't follow a javascript link with WWW::Mechanize. Even if you had a javascript interpreter you'd need complete DOM support for anything non-trivial. So - you need to script a web-browser. I use Selenium in my testing, which is quite bulky and requires java. You might want to investigate WWW::Mechanize::Firefox. I've not used it but it does provide a mechanize style interface to Firefox.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "perl, mechanize" }
Disable maven build for particular project Is it possible to disable **settings.xml** for particular project build using **pom.xml**? I want to avoid using repositories specified in settings.xml file but only for one project.
Repositories are defined inside profiles in `settings.xml` file. You can activate and deactivate profiles based on some criteria. See documentation regarding profile activation. You could: * deactivate given profile per project by passing `-P !profile-name` * you could define the profile as <activation> <property> <name>skipThisProfile</name> <value>!true</value> </property> </activation> and then run your project with `-DskipThisProfile` * define the profile as <activation> <file> <missing>.doNotRunProfile</missing> </file> </activation> and will not run for any project where there is `.doNotRunProfile` file
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, maven, maven 3" }
Extract first item from enumerable <list customers> I am new to LINQ/C#. I have an enumerable list: System.Collections.Generic.IEnumerable<System.Collections.Generic.List> I would like to extract the first item from each list and place that in a new list: System.Collections.Generic.List For example List<customers> = from myEnumerable select item[0]; What would be the correct way to form the linq query to extract element 0 from each list in the enumerable? Thank You
> What would be the correct way to form the linq query to extract element 0 from each list in the enumerable? IEnumerable<List<T>> input = ...; var result = input.Select(l => l[0]).ToList();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c#, linq" }
awk text processing take values of limits i have a txt file like this 32 1 32 2 32 3 32 4 32 5 17 8 17 9 17 10 17 11 14 33 14 34 14 35 and i want to get txt file lke this one ! so we take the limits MIN and MAX of a value in field one from field two and print them . 32 1 5 17 8 11 14 33 35 any idea ? thank you .
Use `datamash`: datamash -t ' ' -g 1 min 2 max 2 < file Output: 32 1 5 17 8 11 14 33 35
stackexchange-unix
{ "answer_score": 4, "question_score": -1, "tags": "text processing, awk" }
Azure service fabric : Container images not refresh I have build and deployment created on visual studio online for an angular app created using asp.net core template. I create the images and deploy them to azure container repository and in the deployment of service fabric project, i just update the code and package versions. Even though the container gets re-spawned, the images on the service fabric cluster are not refreshed. They only get refreshed post manually deleting them. Is there something wrong that i am doing?
Make sure to use an explicit version tag on your container image, don't rely on the [latest] tag. Please use an explicit version. The orchestrator doesn't check if the image tagged 'latest' was changed in the repository, it just checks for an image with that tag. To fix this when using VSTS, you can use $(Build.BuildId) in the Docker-Compose build task, in Additional Image Tags, so every image gets tagged with the build ID that created it. Use a tokenize task to replace the image version in your manifest.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "azure, docker, azure service fabric" }
Qt application in kiosk mode I need to start my qt application on desktop under windows and linux in kiosk mode. May I do it, using qt or special system calls? (not adjusting operation system)
I think you could look into the KDE iosk framework: < This is basically written in Qt, and should be working both on Linux and Windows. If you face any troubles, you can at least take their code as a good and robust base. Here you can find the first paragraph of the introduction inline for your convenience: > The KDE Kiosk is a framework that has been built into KDE since version 3. It allows administrators to create a controlled environment for their users by customizing and locking almost any aspect of the desktop which includes the benign such as setting and fixing the background wallpaper, the functional such as disabling user log outs and access to the print system and the more security conscientious such as disabling access to a command shell.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "c++, qt, kde plasma, kiosk" }
When using bootstrap analysis, which estimates should be reported, the original ones or the bootstrap derived ones I'm moving more and more to bootstrap for my analyses to estimate the variability of parameters of glm regression models. I usually report the bootstrap estimate of the parameter (the mean of the bootstrap distribution), but from the theory I know that the bootstrap estimate should approach the original estimate if all $n^n$ possible resamples are evaluated to build the distribution. So I started to wonder that maybe in the results I should report the original parameter instead of the bootstrap one, together with the bootstrap derived variability statistics (eg, BCa CIs)? Or maybe the bias corrected estimate ($2*\theta-\theta^*$)? What is the common place and the right thing to do from your experience?
Bootstrapping is solely for estimating _variability/precision_ not for estimating a point value. You should use the estimate based on your data and use the bootstrap standard errors or confidence interval to report precision (or p-value if you're using boostrapping for a hypothesis test).
stackexchange-stats
{ "answer_score": 1, "question_score": 4, "tags": "bootstrap, reporting" }
TripleDESCryptoServiceProvider Specified key is not a valid size for this algorithm at 128 bytes? I'm trying to update my encrypt decrypt function from DES to TripleDES. However, when I try to increase my key and iv byte array size from 8 to 128: byte[] key = new byte[128], iv = new byte[128]; TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); Where 8 was used for DESCryptoServiceProvider and 128 is now used for TripleDESCryptoServiceProvider I always get the same error: Specified key is not a valid size for this algorithm. Even though my byte arrays are complete filled in. What am I doing wrong? Is there any requirement besides the length to allow my key and iv to be used to create an Encryptor?
Key sizes are in **bits** not in bytes. 3DES key size is 168, 112 or 56 bits, depending on keying option. The C# implementation supports key sizes of 128 and 192 **bits** , from which it will only use 112 and 168 bits, respectively.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "c#, encryption, tripledes" }
Converting nested list of tuples to nested list of first element from tuples I have a nested list like this one: a = [([('m', 2), ([('o', 1), ([('k', 1), ('h', 1)], 2)], 3)], 5), ([('e', 3), ([([('t', 1), ('a', 1)], 2), (' ', 2)], 4)], 7)] I'd like to get rid of the second element in every tuple, so the list becomes a list of chars only. Like that: [['m', ['o', ['k', 'h']]], ['e', [['t', 'a'], ' ']]] I've tried the following: def transform(array): for x in array: if type(x[0]) is list: transform(x[0]) else: x = x[0] It turns tuples to chars, but it doesn't affect the given array
Using a recursive list comprehension: def recursive_strip(my_list): """Recursively remove the second element from nested lists of tuples.""" return [ recursive_strip(one) if isinstance(one, list) else one for one, two in my_list ] Running this code on the example provided we get: a = [([('m', 2), ([('o', 1), ([('k', 1), ('h', 1)], 2)], 3)], 5), ([('e', 3), ([([('t', 1), ('a', 1)], 2), (' ', 2)], 4)], 7)] result = recursive_strip(a) With `result` being: [['m', ['o', ['k', 'h']]], ['e', [['t', 'a'], ' ']]]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, list, nested" }
How can I decrease timing to solve this equation? I want to find the numbers $a, b, c, d, m, n, p, q, r$ so that the equation has the form $$ \left |(a x + b) (c x + d)\right | + \left |m x + n\right | + p x^2 + q x + r=0 $$ has six solutions $-5,-3,-1,1,2,3$. I tried Clear[f, a, b, c, d, m, n, p, q, r] f[x_] := Abs[(a x + b)* (c x + d)] + Abs[m x + n] + p x^2 + q x + r; FindInstance[{f[-1] == 0 && f[-5] == 0 && f[-3] == 0 && f[1] == 0 && f[2] == 0 && f[3] == 0 && 1 <= a <= 10 && -100 <= b <= 100 && 1 <= c <= 10 && -100 <= d <= 100 && 1 <= m <= 10 && -100 <= n <= 100 && -10 <= p <= -1 && -100 <= q <= 100 && -50 <= r <= 100 && a > c && a c + p != 0 && c a - p != 0 }, {a, b, c, d, m, n, p, q, r}, Reals] I got > {{a -> 2, b -> -8, c -> 1, d -> -(23/13), m -> 32/13, n -> 64/13, p -> -(34/13), q -> 118/13, r -> -(240/13)}} I got the answer about 20 minutes (or longer). How can I decrease the time?
The use of `RealAbs` instead of `Abs` in your `f[x_]` does the job. Clear[f, a, b, c, d, m, n, p, q, r] f[x_] := RealAbs[(a x + b)*(c x + d)] + RealAbs[m x + n] + p x^2 + q x + r;FindInstance[{f[-1] == 0 && f[-5] == 0 && f[-3] == 0 && f[1] == 0 && f[2] == 0 && f[3] == 0 && 1 <= a <= 10 && -100 <= b <= 100 && 1 <= c <= 10 && -100 <= d <= 100 && 1 <= m <= 10 && -100 <= n <= 100 && -10 <= p <= -1 && -100 <= q <= 100 && -50 <= r <= 100 && a > c && a c + p != 0 && c a - p != 0}, {a, b, c, d, m, n, p, q, r}, Reals]//AbsoluteTiming > {30.195,{{a->3/2,b->-(43/8),c->1,d->98/67,m->40685/4288,n->-(56959/4288),p->-(4921/2144),q->27045/4288,r->-(74397/4288)}}}
stackexchange-mathematica
{ "answer_score": 7, "question_score": 3, "tags": "equation solving" }
Protocols/Framework in Class Diagram In Class Diagram for iOS App. How can we show OS Class Protocols/Framework. Suppose we have our 5 own classes and we are and some Frameworks and protocols in these classes So how can we show them in hierarchy
Basically, this is how you can show the relationship between protocol and classes in a class diagram. !enter image description here
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "iphone, ios, uml" }
How to run process in background using gcloud ssh I have two gcp linux VMs, with that I am doing ssh from one instance to another and running process using below command, that works fine when command #1 is executed but when I use option to run process in background command #2, the command shows no results. gcloud compute ssh -zone {Zone-Name} {vm1} -- 'cd /app/bin && ./clearcache && nohup ./startWeblogicAdmin >> admin.log' ==== This works fine gcloud compute ssh -zone {Zone-Name} {vm2} -- 'cd /app/bin && ./clearcache && nohup ./startWeblogicAdmin >> admin.log &' === This does not gets executed. Need way to start process in background, event I log out of this ssh seesion from VM2
Having no idea of gcp linux, I suppose, the second example doesn't work because "&" is used by the shell to run commands in background. But ssh doesn't start any shell when you specify a command, it just runs the command, then exits. So, if my assumption is right, you need to login to the remote system and execute commands using expect-like chat-language or try sending the whole command to background on your local system. Something like that: nohup gcloud compute ssh -zone {Zone-Name} {vm2} -- 'cd /app/bin && ./clearcache && nohup ./startWeblogicAdmin >> admin.log' &
stackexchange-unix
{ "answer_score": 1, "question_score": 2, "tags": "ssh" }
Difference between maximal and maximum ideal. For example, I consider this: $\ p\mathbb{Z}$ is maximal ideal of $\mathbb{Z}$ iff $\ p$ is prime. But my question is for two distinct primes $ p_1$ and $ p_2$, which one will be maximal ideal (namely $ p_1\Bbb{Z}$ and $ p_2\Bbb{Z}$)? > $\ M\subset R$ is a maximal ideal if $\exists$ an ideal $\ U$ of $\ R$ such that $\ M \subset U \subset R$ implies either $\ M=U$ or $\ U=R$. So i) how can two distinct ideals $\ p_1\mathbb{Z}$ and$\ p_2\mathbb{Z}$ both be maximal? ii) Or can I say a maximal ideal is actually a maximum ideal? (As I know $ p_1\Bbb{Z} \not\subset p_2\Bbb{Z}$ and vice-versa)
Both ideals are maximal. Rings can have multiple maximal ideals, and usually do so. In fact, rings which have only a single maximal ideal are called _local rings_ and are "comparatively simple".
stackexchange-math
{ "answer_score": 4, "question_score": 0, "tags": "abstract algebra, ring theory" }
The complement of the closed subset of a closed set Suppose that I had a closed set. Suppose that I made it so that there was nothing else outside such closed set. I will call this set "A". Now, suppose that I picked a closed subset from A. I will call this subset "B". Considering this, is the complement of subset B open or closed? According to most textbooks, it would be open: the complement of a closed set is open. However, the complement of a subset B is everything that is inside a closed set, and hence it wouldn't be open. Is this a contradiction? Also, could someone clarify what assumptions concepts that I have made are erroneous? I am starting to learn about sets in my introductory real-analysis class, so I am not very familiar with set theory.
If there is nothing outside the closed set $A$, then $A$ is the space itself. Now, the complement of a closed subset $B\subset A$ is open. The complement of $B$ may be the whole of $A$, in which case it is both open and closed. This is absolutely allowed: sometimes sets which are both open and closed are called 'clopen'. Examples of clopen sets: * The empty set. * The real numbers, considered as a subset of the space of all real numbers. * Given any topological space $X$, X itself. * The maximal connected components of a topological space. * In $\mathbb Q$, $\\{x\in\mathbb Q:x^2>2\\}$. It's a bit confusing that the sets are called 'open' and 'closed' - it makes you expect that open sets can't be closed and that closed sets can't be open. But they can.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "analysis, elementary set theory" }
Как словить определенную ошибку Работаю с ботом телеграм,который парсит гугл-таблицы. Когда данных после парсинга нет, я получаю raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: <HttpError 404 when requesting returned "Requested entity was not found."> Вопрос в том, как словить эту ошибку? Например, так: try: ... except googleapiclient.errors.HttpError: ...
> нужно сделать так, чтобы заключить код в try/except, и когда он получит эту ошибку код выполнялся заново. Для этого очень удобно использовать декоратор `retrying.retry`. Функция в параметре `retry_on_exception` определяет нужно ли пытаться выполнить повтор для данного исключения: import retrying i = 1; # Глобальная переменная исключительно для демонстрации @retrying.retry( stop_max_attempt_number=5, retry_on_exception=lambda ex: True, # Для любого исключения wait_exponential_multiplier=500, wait_exponential_max=8000) def foo(): global i; print(f'Try foo...{i}') i+=1 if i < 3: raise Error('Any error') print('Success') foo() > > Try foo...1 > Try foo...2 > Success >
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, python 3.x" }
Export SVN dir from one repository and commit to another one We have an SVN repository which is stored online with all our tickets, wikis, etc. For deployment purposes, we need to use a second SVN repository on which we have no control: we cannot use svndump, svnload, svnsync, etc. We can update and commit basically. At deployment time, I would like to export a working copy from Dev Repo and then commit it to Staging+Live repo. Please see following sketch for a rough idea of what I need to do. !SVN Workflow Is there an SVN command doing just that? I could use the svn export command but then I would have to add all new files by hand I believe. Also, I would like to avoid to export all the files when only few changed. So I would like to avoid recreating the S working copy each time I want to deploy the site. Or maybe there is a much simpler solution? Best regards
I'd suggest this approach: * create a working copy via `svn co s+l_repo` (initial checkout, can be done manually) * export your dev repo via `svn export` into this working copy, overwriting all files in it * add all new files via `svn add --force` * commit your working copy to s+l repo Easily scripted, and you can run it via a batch job every night.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 6, "tags": "svn" }
Python: call the same function with the same arguments several times, or save the result as an intermediate value? If I have a function def bar(n): return n**100 Would there be a performance difference between for i in range(1000000): x = bar(30) # use x for something and x = bar(30) # use x for something 1,000,000 times I don't know if the interpreter has been optimized for cases like this?
The CPython compiler only does very few simple peephole optimisations, but it will certainly never optimise away a function call -- how would it know if the function has side effects anyway? At compilation time, it usually doesn't even know which function the name `bar` refers to, and the name binding might change at any time. If in doubt, simply measure the performance yourself -- the `timeit` module is your friend.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "python, performance" }
application stack trace interpretation using mdb Can someone please help me with interpreatation of this stack trace: Loading modules: [ libumem.so.1 libc.so.1 libuutil.so.1 ld.so.1 ] > $c libc.so.1`strlen+0xc(80b37ba, fe679d2c, fe679d00, 0) libc.so.1`snprintf+0x74(fe67d970, 1388, 80b37b8, efef9f68, 80b379d, fe679e30) > 80b37ba::whatis 80b37ba is unknown > fe679d2c::whatis fe679d2c is unknown > fe679d00::whatis fe679d00 is unknown strlen function gets one argument, but in this stack trace I see 3 addresses ? What is the meaning of them ? regards
The debugger doesn't manage to interpret most of it. The debugger may not know how many parameters a function gets. So it prints more. But you can ignore the extra parameters. The parts that do make sense show that `snprintf` was called, and then call `strlen`. This is probably due to `%s` in the format string. The `strlen` parameter is similar (not identical, I don't know why), to `snprintf`'s 3rd parameter. So probably some code does something like `snprintf("%d %s\n", number, string)`. You can find the actual format string at `fe67d970`, and it will probably let you identify who called it (unless you use the same format string everywhere).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c, debugging, solaris" }
python-pip package disappeared in Ubuntu 20.04 I have recently upgraded from Ubuntu 18.04 to 20.04 LTS. Before upgrading, I had the `python-pip` package installed. But after upgrading, when I try this command the terminal says: $ sudo pip install foo sudo: pip: command not found I tried to update repository information and install python-pip package, but APT says that there is no package named `python-pip` in the repository.
`python-pip` package is no longer supported by Ubuntu as Python 2.7 is no longer supported. So forget that package. But you can still install it by issuing the following on terminal: wget python2 get-pip.py As `python3-pip` package is supported, which provides `pip3` command you can install it Python 3 with apt by: sudo apt update sudo apt install python3-pip
stackexchange-askubuntu
{ "answer_score": 7, "question_score": 8, "tags": "upgrade, python, 20.04, pip" }
How can I undo the effects of grub-reboot? I accidentally ran `sudo grub-reboot 4` (background) twice in a row, and now GRUB permanently boots to the fourth menu item. How can I restore the default boot behavior?
Use the grub-set-default command. For example, assuming you want the first grub entry to be your default: `sudo grub-set-default 0`
stackexchange-askubuntu
{ "answer_score": 6, "question_score": 6, "tags": "grub2" }
$firebaseSimpleLogin and session without re-login I am using $firebaseSimpleLogin to log into Firebase using email/password. It is working rather well when I log in using email/password, I could see sessionkey being saved automatically as a cookie. However, would like to remember the log in such that user only have to log in once. So I included {rememberMe: true} during auth. How do I check if the session is still alive at the beginning of the page being loaded?
From your question, I assume you're using Angular JS. You can execute a `run` block on your main module, which is run everytime the page is loaded. I don't know much about Angularfire, this is the code I'm using on a hack day project to check auth and redirect to the login page if needed. `FirebaseRef` is a wrapper that points to my Firebase instance. This also makes sure that the `currentUser` object is available in all scopes. var minib = angular.module('minib', ['ngRoute', 'firebase']); minib.run(function($rootScope, $location, $firebaseSimpleLogin, firebaseRef) { $rootScope.auth = $firebaseSimpleLogin(firebaseRef()); $rootScope.auth.$getCurrentUser().then(function(user) { if (user) { $rootScope.currentUser = user; } else { $location.path('/login'); } }); });
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "firebase, angularfire, firebase security" }
How do I run migrations on GCloud SQL instance? I want to run a migration on the GCloud MySQL instance for my site. I have already tried making a new bucket on the GCloud console and importing my local MySQL dump into that and then adding that to the MySQL instance. It didn't work. I also saw someone recommending to connect to the GC using the GC proxy and Google Compute Engine. I am new to this so I couldn't follow along very well, and I found out that App and Compute Engine are two different things. Here's my requirements file; asn1crypto==0.24.0 cffi==1.12.2 cryptography==2.6.1 Django==2.1.7 django-crispy-forms==1.7.2 freeze==1.0.10 mysql==0.0.2 mysqlclient==1.4.2.post1 Pillow==6.0.0 psycopg2==2.8.1 pycparser==2.19 PyMySQL==0.9.3 pytz==2018.9 six==1.12.0
You will either need direct access via public IP to your Cloud SQL instance or use this tutorial to setup Cloud SQL Proxy with a Service Account and direct the SQL connector to that proxy <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "mysql, django, google app engine, google cloud platform" }
Ruby on Rails Forms: how to create a CheckBox Table (or List) What's the best way to create a related set of checkboxes in Ruby on Rails? In the ToscaWidgets library used by Turbogears you can do the following: twf.CheckBoxTable('arbitrary_numbers', num_cols=5, options=['1','2','3','4','5','6','7','8','9','10']), This generates 10 labeled checkboxes in two rows of 5 checkboxes. I'm trying to duplicate this in Rails without just creating 10 separate checkbox controls. No big deal, just hoping for a clean way to do this.
Something like this: <% 10.times do |i| %> <%= label_tag i %>: <%= check_box_tag "alternate_numbers[#{i}]" %> <br /> <% end %> will produce 10 checkboxes and if you will put it into form and submit it, you will have access to it in `params[:alternate_numbers][index]` where number is your number. You can put it into helper and call many times. You can also add some parameters to helper to customize output.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 3, "tags": "ruby on rails, ruby, forms, checkbox" }
How to select rows that differ only in some condition? Can I somehow select only rows with same id, where difference between values not more than 10? CREATE TABLE EXAMPLE_TEST (ID NUMBER, VALUE NUMBER); INSERT INTO EXAMPLE_TEST(ID, VALUE) VALUES (1, 1); INSERT INTO EXAMPLE_TEST(ID, VALUE) VALUES (2, 4); INSERT INTO EXAMPLE_TEST(ID, VALUE) VALUES (1, 9); INSERT INTO EXAMPLE_TEST(ID, VALUE) VALUES (2, 15); INSERT INTO EXAMPLE_TEST(ID, VALUE) VALUES (1, 17); The only thing I came up with is to join the same table, but it is obviously wrong approach as you don't know how many rows there'll be. May be PLSQL is the key here? But I couldn't come up with it either.
You want to select each record for which **exists** a close-value record. So use `EXISTS`: select * from example_test where exists ( select * from example_test other where other.id = example_test.id and other.value <> example_test.value and abs(other.value - example_test.value) <= 10 ) order by id, value;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sql, oracle, plsql" }
How to get response from foo.onload = function(){? I have a function that is triggered using .onload. I'd like return a value: newImg.onload = function() { var height = newImg.height; var width = newImg.width; if(height > width){ console.log(false); return false; } else { console.log(true); return true; } } newImg.src = imgSrc; // this must be done AFTER setting onload Normaly I'd do something like var foo = function(){... but this doesn't work in this case. What should I do instead?
Asynchronous calls can not return values. You would need to use a callback like you would do in an Ajax request. function loadImg (imgSrc, callback) { var newImg = new Image(); newImg.onload = function() { var height = newImg.height; var width = newImg.width; if(height > width){ console.log(false) if(callback) callback(false); } else { console.log(true) if(callback) callback(true); } }; newImg.onerror = function () { if(callback) callback('error'); }; newImg.src = imgSrc; } loadImg("foo.gif", function(status) { console.log("Do Next Step"); })
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "javascript, jquery" }
Animate new data insertion in core-plot (iOS) I am trying to animate the "drawing" of new data using a CPTScatterPlot objects. I am now looking at the RealTime example that you can find here in the examples subdirectory. It is one of the example of the CorePlotGallery. Make sure you use the iOS one. This RealTime plot is pretty simple: it injects some random data in the graph every second. What I am trying to accomplish is to animate the drawing of the line so that it seems that the line is being drawn realtime. If you take a close look at the example, you will notice that "segments" appear in the chart as soon as new data is inserted into it. How can I animate the "creation" of those segments? Thank you
Until this is added natively to Core Plot (see this outstanding issue), use a timer to animate the line. Each time the timer fires, use the `-reloadDataInIndexRange:` method to update the last point on the line, moving it closer to the final value each time.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "ios, core animation, core plot, scatter plot" }
How to use npm packages in an angular 2 app? I want to send some UDP packets from my angular 2 app. While searching for a solution I found some npm packages that look like they could do the job. I thought I could just install and use this packages in angular but it did not work. Some research reavled some howtos but they look very diferent so that I am totally confused. Can I use every npm package with angular? If yes, how?
No, not every package; there are limits. Browserify implements replacements for many of Node's built-in APIs, but not everything is possible in the browser. This is discussed in the compatibility section of the documentation. If a package relies upon an built-in API that is not browser-compatible - or relies upon native code - it won't work. And, as far as I am aware, sending UDP packets is not going to be possible.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "angular, npm" }
NullReferenceException when loading images in pictureBox vb c# I'm a beginner on visual basic, and I'm working on this game, it's supposed to load the images that are stored in the picture box array and show them randomly, but I keep getting the runtime error "NullReferenceException" in this line: if(egypt[randomNumber]==egypt[0]) The lines before were: PictureBox [] egypt = new PictureBox [5]; Image egypt1 = Image.FromFile(Application.StartupPath + @"\image\egypt1.png"); egypt[0].Image = egypt1; Thank you.
I suspect the error is actually on the `egypt[0].Image = egypt1` line because there is a bug in Visual Studio that means that occasionally the Exception Assistant highlights the line after the one that threw the exception. Anyway... `egypt[0]` is `null` because you have not yet assigned an actual object to it. You have only reserved the space for the array but not put anything in there (the array is full of nulls when created) You need to add aline before it so it reads something like this: egypt[0] = new PictureBox(); // This is the new line egypt[0].Image = egypt1; // This is the existing line I suspect this will solve your problem.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c#" }
PHP: Using require_once() for a form? I am using HTML to make a form with a php processor, like so: <?php require_once("./scripts/process.php"); ?> <form action="" method="post"> <input type="text" name="name" /> <input type="submit" value="Submit" /> </form> I have, in my PHP form, a script that `echo`s a message that says "You didn't fill in some of the required fields. Go back and fill them in." But, when I load the page for the first time, it says "You didn't fill in some of the required fields. Go back and fill them in." How can I make it so it says this only when the form is submitted? I can't use `<form action="./scripts/process.php` it gives me a 500 Server Error, so I want to do it this way. Is there another PHP method to do this? If so, how? Thanks!
You can check if form have been submitted by checking $_POST value if(!empty($_POST)) { // some code } But this can fail when there is another form on the same page. In this case, you have to do it like following if(isset($_POST["name"])) { // some code }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, html, forms, process" }
The Cauchy principal value of the Riemann Zeta function In many online sources, you can find $$ \zeta(s) \overset{C.P.}{=} \lim_{\epsilon \to 0} \left(\frac{\zeta(s+\epsilon)+\zeta(s-\epsilon)}{2}\right). $$ This seems quite logical, but I neither know how to derive it nor how to derive the second equality $$ \zeta(1) \overset{C.P.}{=}\lim_{\epsilon \to 0} \left(\frac{\zeta(1+\epsilon)+\zeta(1-\epsilon)}{2}\right)=\gamma $$ (where $\gamma$ is the Euler-Mascheroni-constant). I always knew the Cauchy principal value as a a method for assigning values to improper integrals, and although I know many integral representations of the Riemann Zeta function, I dont't really know how to show this specific result. Many thanks in advance!
The asymptotic $$ \zeta(s) = \frac{1}{s-1} + \gamma + O(|s - 1|) $$ for the Riemann zeta function near $ s = 1 $ is well known, and it immediately implies your result, since the $ 1/(s-1) $ terms cancel when computing the limit in your principal value. For a proof of this asymptotic, see this post.
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "limits, riemann zeta, singularity, euler mascheroni constant, cauchy principal value" }
Can my enums have friendly names? I have the following `enum` public enum myEnum { ThisNameWorks, This Name doesn't work Neither.does.this; } Is it not possible to have `enum`s with "friendly names"?
Enum value names must follow the same naming rules as all identifiers in C#, therefore only first name is correct.
stackexchange-stackoverflow
{ "answer_score": 77, "question_score": 200, "tags": "c#, enums" }
Convert Word to HTML then render HTML on webpage I have a tough project in my pipeline and I'm not sure where to begin. My boss wants the ability to display a Word Document in HTML and it look the same as the word document. After trying time after time to just let me show the word document in a pop up or a light box he is stuck on stripping out the contents of the word converting it to HTML saving that in a database and then displaying it as HTML on a webpage. Can you guys either give me some good ammo as to if showing the word document is better (less cumbersome, less storage space more secure etc). Or if it's pretty easy to convert a word document to HTML ways for me to do that. The technologies I current have are Entity Framework, LINQ, MVC, C#, Razor. We currently use HTmlAgilityPack, but this strips out all of the formatting and doesn't allow the document to show very well.
We use < (I think the one we use is Aspose words) to perform s similar task, and it works quite well. (there is a cost involved) I would suggest that converting to HTML gives the worst rendition of the document. One solution we use, is to generate a Jpeg image of the document and display that. If you need to be able to perform operations like find and copy/pasting text - I would recommend converting the document to a .pdf, and displaying it inline, in whichever standard pdf viewer the client machine has installed.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 11, "tags": "c#, ms word" }