qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
15,285,068
I can open a password-protected Excel file with this: ``` import sys import win32com.client xlApp = win32com.client.Dispatch("Excel.Application") print "Excel library version:", xlApp.Version filename, password = sys.argv[1:3] xlwb = xlApp.Workbooks.Open(filename, Password=password) # xlwb = xlApp.Workbooks.Open(filename) xlws = xlwb.Sheets(1) # counts from 1, not from 0 print xlws.Name print xlws.Cells(1, 1) # that's A1 ``` I'm not sure though how to transfer the information to a pandas dataframe. Do I need to read cells one by one and all, or is there a convenient method for this to happen?
2013/03/08
[ "https://Stackoverflow.com/questions/15285068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479269/" ]
Assuming the starting cell is given as (StartRow, StartCol) and the ending cell is given as (EndRow, EndCol), I found the following worked for me: ``` # Get the content in the rectangular selection region # content is a tuple of tuples content = xlws.Range(xlws.Cells(StartRow, StartCol), xlws.Cells(EndRow, EndCol)).Value # Transfer content to pandas dataframe dataframe = pandas.DataFrame(list(content)) ``` Note: Excel Cell B5 is given as row 5, col 2 in win32com. Also, we need list(...) to convert from tuple of tuples to list of tuples, since there is no pandas.DataFrame constructor for a tuple of tuples.
Adding to @Maurice answer to get all the cells in the sheet without having to specify the range ``` wb = xw.Book(PATH, password='somestring') sheet = wb.sheets[0] #get first sheet #sheet.used_range.address returns string of used range df = sheet[sheet.used_range.address].options(pd.DataFrame, index=False, header=True).value ```
1,307
Many here are probably aware of Alon's recent super-linear lower bounds for $\epsilon$-nets in a natural geometric setting [[PDF]](http://www.tau.ac.il/~nogaa/PDFS/epsnet3.pdf). I would like to know what, if anything, such a lower bound implies about the approximability of the associated Set Cover/Hitting Set problems. To be slightly more specific, consider a family of range spaces, for example, the family: $\big\{(X,\mathcal{R})$ : $X$ is a finite planar point set, $\mathcal{R}$ contains all intersections of $X$ with lines$\big\}$ If, for some function $f$ that is linear or super-linear, the family contains a range space that does not admit $\epsilon$-nets of size $f(1/\epsilon)$, what, if anything, does this imply about the Minimum Hitting Set problem restricted to this family of range spaces?
2010/09/14
[ "https://cstheory.stackexchange.com/questions/1307", "https://cstheory.stackexchange.com", "https://cstheory.stackexchange.com/users/196/" ]
If a range space has $\epsilon$-net of size $f(1/\epsilon)$, then the integrality gap of the fractional hitting set (or set cover) is $f(1/\epsilon)/(1/\epsilon)$. See the work by Philip Long ([here](http://www.phillong.info/publications/intprog.pdf) [The Even etal. work is later than this work, and rediscover some of his stuff]). See also the slides 13-16 [here](http://valis.cs.uiuc.edu/~sariel/papers/10/haystacks/haystack.pdf). In short, having non-linear $\epsilon$-nets, indicates that approximating the relevant hitting-set/set cover problem within better than a constant factor is going to be very challenging.
I'm not sure it does imply anything. The main results flow in the other direction i.e by the [Bronnimann/Goodrich](http://www.cs.jhu.edu/~goodrich/cgc/pubs/cover.ps.gz) or [Even/Rawitz/Shahar](http://www.eng.tau.ac.il/~guy/Papers/VC.pdf) constructions, a linear sized net implies a constant factor approximation for the hitting set (for bounded VC dimension),
45,133,172
I've been stuggeling with this problem now for days: Installting Laravel passport. I did all accoring to the tutorial. What I did ``` composer require laravel/passport ``` Added `Laravel\Passport\PassportServiceProvider::class,` to the `config/app.php` run `php artisan migrate` and then `php artisan passport:install` The crasy thing is this works on my local machine. But when I upload this to my webspace via ftp and run `php artisan passport:install` it gets me this Error: ``` Uncaught exception - 'There are no commands defined in the "passport" namespace.' ``` Full error (see on [pastbin](https://pastebin.com/1e2t31R5)) ``` PHP Fatal error: Uncaught exception 'Symfony\Component\Console\Exception\CommandNotFoundException' with message 'There are no commands defined in the "passport" namespace.' in /mnt/web102/d0/25/58432925/htdocs/www/vendor/symfony/console/Application.php:533 Stack trace: #0 /mnt/web102/d0/25/58432925/htdocs/www/vendor/symfony/console/Application.php(565): Symfony\Component\Console\Application->findNamespace('passport') #1 /mnt/web102/d0/25/58432925/htdocs/www/vendor/symfony/console/Application.php(204): Symfony\Component\Console\Application->find('passport:instal...') #2 /mnt/web102/d0/25/58432925/htdocs/www/vendor/symfony/console/Application.php(130): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput)) #3 /mnt/web102/d0/25/58432925/htdocs/www/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Comp in /mnt/web102/d0/25/58432925/htdocs/www/vendor/symfony/console/Application.php on line 533 PHP Fatal error: Uncaught exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Uncaught exception 'Symfony\Component\Console\Exception\CommandNotFoundException' with message 'There are no commands defined in the "passport" namespace.' in /mnt/web102/d0/25/58432925/htdocs/www/vendor/symfony/console/Application.php:533 Stack trace: #0 /mnt/web102/d0/25/58432925/htdocs/www/vendor/symfony/console/Application.php(565): Symfony\Component\Console\Application->findNamespace('passport') #1 /mnt/web102/d0/25/58432925/htdocs/www/vendor/symfony/console/Application.php(204): Symfony\Component\Console\Application->find('passport:instal...') #2 /mnt/web102/d0/25/58432925/htdocs/www/vendor/symfony/console/Application.php(130): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput)) #3 /mnt/web102/d0/25/58432925/htdocs/www/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Symfony\Component\Consol in /mnt/web102/d0/25/58432925/htdocs/www/vendor/symfony/console/Application.php on line 533 Status: 500 Internal Server Error X-Powered-By: PHP/5.6.30 Content-type: text/html ``` What I did. 1. uploaded all my code without the ./vendor and composer.lock 2. (uploaded the server .env) 3. `php composer.phar clearcace` 4. `php composer.phar update` 5. `php artisan cache:clear` 6. `php artisan config:cache` 7. `php artisan migrate` 8. `php artisan passport:install` And then the error happens... If did `php composer.phar require laravel/passport` and can see via ftp that in the /vendor/laravel/ the passport folder is there!
2017/07/16
[ "https://Stackoverflow.com/questions/45133172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6615718/" ]
What I have done to do solve the problem! Inside `\vendor\laravel\passport\src\PassportServiceProvider.php` if deleted the ``` if ($this->app->runningInConsole()) { ``` in line 37. After uploading this to my webspace if could have full use of `laravel:passport` Thanks for all the other help!
I guess you have problem that passport not installed, if you are working via FTP do these steps: 1. Upload your code without vendor and composer.lock 2. Make sure that .env exist or fill 'key' in app.php 3. Run composer dumpautoload 4. Run this command composer update --no-scripts 5. Try to run php artisan just to list all commands, if you got all commands then you can run php artisan passport:install Hope this will work.
14,806,771
I wanted to create a paragraph on which if a user hovers the mouse, it should display an alert box. But the code that I typed did not work. As soon as the mouse entered the *page* the box displayed. I only want it to display when the mouse is on the *paragraph*. The code was : ``` <html> <script src="jquery.js" type="text/javascript"></script> <script> $('document').ready(function(){ $('#p1').hover( alert("you have entered p1 .") ); }); </script> <body> <p id="p1">hover here!!</p> </body> </html> ```
2013/02/11
[ "https://Stackoverflow.com/questions/14806771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2060348/" ]
[Working example on jsFiddle](http://jsfiddle.net/htmled/caVay/). Try this: ``` $('#p1').hover( alert("you have entered p1 ."); ); ``` or: ``` $('#p1').hover( function() { alert("you have entered p1 ."); }, function() { alert('you have exited p1 .'); } ); ```
You have two errors in your script: 1. 'document' the quotes not to be there 2. missing function in hover so it should be: ``` $(document).ready(function(){ // <----removed the quotes $('#p1').hover(function(){ //<------added the function here. alert("you have entered p1 .") }); }); ```
63,796,383
I have a setting in which I would like to dynamically change a buttons disabled state. Currently the logic I have looks as follows: ```rb <% if @has_attachment_file_sent %> <% if current_user.id != @offer.user_id %> <%= link_to send_signature_requests_path, remote: true, method: :post, data: { confirm: "Are you sure?" }, id: "signature_request_button", class: "button is-info is-fullwidth m-t-10 m-b-10" do %> <span>Send request</span> <% end %> <% end %> <% else %> <button class="button is-info is-fullwidth m-t-10 m-b-10" disabled>Send request</button> <% end %> ``` However, the problem with this method is that this only changes the state of the button when you refresh the page. Is there a way to do this kind of Ajax with RoR or what should I do here? Also tried using javascript as follows: ``` <script> $(document).ready(function() { var has_attachment_file_sent = <%= @has_attachment_file_sent %> console.log(has_attachment_file_sent); if(has_attachment_file_sent) { $('#signature_request_button').attr('disabled', true); } }) </script> ``` but this doesn't seem to be doing anything. Also here's my controller ``` def show @offer = Offer.find(params[:id]) @has_attachment_file_sent = Comment.where(user_id: @offer.user_id).any? {|obj| obj.attachment_file.attached?} respond_to do |format| format.html format.js { render layout: false, content_type: 'text/javascript' } end end ```
2020/09/08
[ "https://Stackoverflow.com/questions/63796383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13541811/" ]
First place your html in a partial and wrap the content in div, assume that the partial's name is 'buttons.html.erb' \_buttons.html.erb ``` <% if @has_attachment_file_sent %> <% if current_user.id != @offer.user_id %> <%= link_to send_signature_requests_path, remote: true, method: :post, data: { confirm: "Are you sure?" }, id: "signature_request_button", class: "button is-info is-fullwidth m-t-10 m-b-10" do %> <span>Send request</span> <% end %> <% end %> <% else %> <button class="button is-info is-fullwidth m-t-10 m-b-10" disabled>Send request</button> <% end %> ``` ``` <div id="buttons"> <%= render partial: 'buttons' %> </div> ``` Add button in view ``` <%= link_to 'Refresh', show_page_path(id: @offer.id), id: 'btn_call_ajax', remote: true %> ``` you should adapt show\_page\_path with your route ``` def show @offer = Offer.find(params[:id]) @has_attachment_file_sent = Comment.where(user_id: @offer.user_id).any? {|obj| obj.attachment_file.attached?} respond_to do |format| format.html format.js end end ``` Then you should create a file named show.js.erb that contain the following code: ``` $('#buttons').html('') $('#buttons').append("<%= escape_javascript render(:partial => 'buttons') %>"); ```
create the file `show.js.erb` and in your controller just leave it as `format.js` without curly braces. create a partial with ``` <button class="button is-info is-fullwidth m-t-10 m-b-10" disabled="<%= disabled ? “disabled” : “” %>”>Send request</button> ``` And add a div in original file, wrap rendering of the partial above ``` <div id=“woohoo”> <%= render partial: “file_above”, locals: {disabled: true} %> </div> ``` Then in that `.js.erb` file add this `$(‘#div-around-button’).html(“<%= j render(‘show’, disabled: @disabled_variable_from_controller) %>”)` and it will basically refresh that button with new value that you got from controller P.S. I wrote this all on my iPhone so I might have missed small things like syntax
3,918,735
Now to convert this strings to date time object in Python or django? ``` 2010-08-17T19:00:00Z 2010-08-17T18:30:00Z 2010-08-17T17:05:00Z 2010-08-17T14:30:00Z 2010-08-10T22:20:00Z 2010-08-10T21:20:00Z 2010-08-10T20:25:00Z 2010-08-10T19:30:00Z 2010-08-10T19:00:00Z 2010-08-10T18:30:00Z 2010-08-10T17:30:00Z 2010-08-10T17:05:00Z 2010-08-10T17:05:00Z 2010-08-10T15:30:00Z 2010-08-10T14:30:00Z ``` whrn i do this `datestr=datetime.strptime( datetime, "%Y-%m-%dT%H:%M:%S" )` it tell me that `unconverted data remains: Z`
2010/10/12
[ "https://Stackoverflow.com/questions/3918735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/375373/" ]
Use slicing to remove "Z" before supplying the string for conversion ``` datestr=datetime.strptime( datetime[:-1], "%Y-%m-%dT%H:%M:%S" ) >>> test = "2010-08-17T19:00:00Z" >>> test[:-1] '2010-08-17T19:00:00' ```
Those seem to be [ISO 8601 dates](http://en.wikipedia.org/wiki/ISO_8601). If your timezone is always the same, just remove the last letter before parsing it with strptime (e.g by slicing). The Z indicates the timezone, so be sure that you are taking that into account when converting it to a datetime of a different timezone. If the timezone can change in your application, you'll have to parse that information also and change the datetime object accordingly. You could also use the [pyiso8601 module](http://code.google.com/p/pyiso8601/) to parse these ISO dates, it will most likely also work with slighty different ISO date formats. If your data may contain different timezones I would suggest to use this module.
28,912,735
While I try to run the following mysqli call ``` $strSQL3=mysqli_query($connection," alter table mark_list add column 'mark' int(2) " ) or die(mysqli_error($connection)); ``` returns error ``` You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near `mark int(2)` at line 1 ```
2015/03/07
[ "https://Stackoverflow.com/questions/28912735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3856434/" ]
Single quotes (`'`) denote string literals. Object names (such as columns), are not strings - juts lose the quotes: ``` $strSQL3 = mysqli_query($connection ,"alter table mark_list add column mark int(2)" ) or die(mysqli_error($connection)); ```
Simply you need to remove the quotes near `'`mark ``` $strSQL3=mysqli_query($connection," alter table mark_list add column mark int(2) " ) or die(mysqli_error($connection)); ```
52,077,076
I am iterating loop over Div and in that div assigning encoded array as value to hidden field and want to get value of that hidden field in each loop but getting undefiened ```js var port_ofAir = null; $(".sublocation_div").find('.sublocation').each(function(index,value1){ port_ofAir = $(this).find(".port_arr").value; }); console.log(port_ofAir) ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="hidden" name="arr_port" class="port_arr" id="arr-port" value="[{"id":34,"client_id":"2"}]"> ``` I want to get that array in jquery function please any suggestion
2018/08/29
[ "https://Stackoverflow.com/questions/52077076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7596840/" ]
With C++20 and concept, you may use `requires`: ``` void notify_exit() requires has_member_function_notify_exit<Queue, void>::value; ```
Instantiating a template causes the member instantiation of all the declarations it contains. The declaration you provide is simply ill-formed at that point. Furthermore, SFINAE doesn't apply here, since we aren't resolving overloads when the class template is instantiated. You need to make the member into something with a valid declaration and also make sure the check is delayed until overload resolution. We can do both by making `notify_exit` a template itself: ``` template<typename Q = Queue> auto notify_exit() -> typename std::enable_if< has_member_function_notify_exit<Q, void>::value, void >::type; ``` `[A working cpp.sh example](http://cpp.sh/57pl5)`
217,447
Can I install Mac OS on my PC through VMware. I'm using Ubuntu 12.04 LTS as a host operating system.
2012/11/15
[ "https://askubuntu.com/questions/217447", "https://askubuntu.com", "https://askubuntu.com/users/63113/" ]
Run `update-alternatives --config java` and make sure you configure it correctly. Run `java -version` in a terminal and see the output. From freemind web: <http://freemind.sourceforge.net/wiki/index.php/Download> Freemind may not work with OpenJDK. I would recommend installing Sun/Oracle JRE/JDK. A simple way of installing it on Ubuntu (build .deb packages from OTN binaries and set up a local repository, use apt-get to install;-) Check it out here: <https://github.com/flexiondotorg/oab-java6>
I had this problem in Ubuntu 15.04 with the newest Oracle Java 8 (with no other JDK installed). I found the problem in the java-wrappers file which determines the available Java installations: In file `/usr/lib/java-wrappers/jvm-list.sh`, I added `/usr/lib/jvm/java-8-oracle` on line 35: ``` __jvm_oracle8="/usr/lib/jvm/java-8-oracle /usr/lib/jvm/jdk-8-oracle-* /usr/lib/jvm/jre-8-oracle-*" ``` As the current installation of Oracle 8 Java is installed in this added path.
58,863,756
I have a simple grid where the left pane acts as the table of contents and the right pane is the content. How do I get the content in the left pane to stay where it is (fixed?) while the user scrolls through the content, so that it is always in view. Here is a js fiddle illustrating the problem and my code is below as well: <https://jsfiddle.net/ma60fxvk/> ``` <div id = 'grid'> <div id = "column-1"> Table of contents (How do I get this to stay in view while the user scrolls down to read the content in #column-2?) </div> <div id = "column-1"> <!-- lot of content here --> </div> </div> ``` css: ``` #grid{ display: grid; grid-template-columns: 1fr 3fr; } ``` Thanks in advance for any help.
2019/11/14
[ "https://Stackoverflow.com/questions/58863756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3131132/" ]
You Component hierarchy seems good, I would like to add one thing to keep things together, like for steps you can create an Array inside a main component state like this ``` class Main extends React.Component{ state = { ...OTHER_STATE_PROPERTIES, activeStep: 0 | 1| 2, steps: [{ name: 'step-name', icon: 'icon-name', content: Form1 | Form2 | Form3, // this is optional, you can use getContent too data: {} }] } // pass this function as prop to every Form Component // We will talk about this function soon handleStepSubmit = (stepIndex, data) => { this.setState((prevState) => ({ ...prevState, activeIndex: prevState.activeIndex + 1, steps: prevState.map((step, index) => { if(stepIndex !== index){ return step; } return { ...step, data } }) })) } //... Other stuff } ``` Now each **Form** should have its own `state` (so that only the form gets re-render on input changes) and `form`, where you can handle input and validate them and send it to parent component step using props, so we need to add a function in the parent component. **`handleStepSubmit`** function will only be called after validation of data on `onSubmit` call of `form` How to validate data is up to you, you can use ### default input attributes like, 1. required 2. min, max for number 3. type (email) 4. pattern ### Validate State using JS logic ### Use [yup](https://github.com/jquense/yup) ### Use [Formik](https://jaredpalmer.com/formik/docs/overview) with yup This is what I prefer by using formik you don't have to worry about `onChange`, **validation** and many more things, you can provide it `validate` prop where you can write validation logic yourself or `validationSchema` prop where just yup schema should be given, it will not allow if `onSubmit` to trigger if validation fails, you can also *input attributes* with it, if form is simple. We have to call `handleStepSubmit` on `onSubmit` P.S.: It maintains a local state ### What we have At step 0 we will have ``` // I am omitting other stuff for understanding state:{ activeStep: 0, steps: [ {data: {}}, {data: {}}, {data: {}}, ] } ``` When user submits Form 1 we will have ``` // I am omitting other stuff for understanding state:{ activeStep: 1, steps: [ {data: formOneData}, {data: {}}, {data: {}}, ] } ``` and so one now when `activeStep` is 3 you will have all the validated data in the state, Horray!! High-Five! You can also data from previous steps in further step if required as we have it all in our parent component state. ### Example: [![Edit formik-example](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/lpnmj?fontsize=14&hidenavigation=1&theme=dark)
Save all form data to your states (even completed steps like current step). For validating your given data you should arrange a handleChange function for each field.
5,294,509
I am new to TFS. At my job I mapped the TFS projects to local directories, performed a get, and everything works as I expected. When I edit files on my local copy, source control automatically checks them out for editing and tracks the files with pending changes via the pending changes window. Then I just check them in throughout the day using that window. However, at home this doesn't appear to be happening. I have access to source control and using source control explorer, have mapped the projects to local directories. This appeared to work fine. However, when I open the projects and open files, changes I make are not automatically checking out files. In fact, visual studio isn't even changing their read-only status until I try to save my changes; at that point it warns me that the file is read-only and asks if I would like it to try to overwrite the permissions and save. I do and it works fine. But again, no changes register in the pending changes window. I'm kind of lost. The only source control experience I really have is subversion and the visual studio AnkhSVN plugin. I've even opened my solution by double-clicking the solution file that is in source control explorer. You would think it would be fully-aware that the solution I'm opening should be tracked by source control. Edit ---- Since people seem to be questioning my use of the phrase "at home", let me clarify. There are no problems with the network. I am on a VPN. I can browse source control just fine. I have since reinstalled everything for various reasons. All went well. I'm just having an issue with Visual Studio not tracking changes to files and allowing them to be committed back to source control. So to sum it up: How could Visual Studio stop tracking changes after being mapped correctly, and allowing me to get latest? I can update from source control, I just can't commit. Pending changes window is empty even after making changes.
2011/03/14
[ "https://Stackoverflow.com/questions/5294509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/498624/" ]
I found one of my projects actually wasn't added to the source control at all - somehow that had been missed and so any changes to that project would not get checked out. I right-clicked on the solution node, clicked "add to source control" it warned me that some projects were already being tracked and I elected to ignore those projects and it proceeded to add the missing project(s) to source control. Now the check-out works perfectly. Sharing in case it helps anyone else!
Install 2 things: 1. **Team Explorer for VS2013** (<http://www.microsoft.com/en-us/download/details.aspx?id=40776>) 2. **Install VS TFS Power tools** (<https://visualstudiogallery.msdn.microsoft.com/f017b10c-02b4-4d6d-9845-58a06545627f>) That's it
20,090,181
I need to open some webpages using open-uri in ruby and then parse the content of those pages using Nokogori. I just did: ``` require 'open-uri' content_file = open(user_input_url) ``` This worked for: `http://www.google.co.in` and `http://google.co.in` but fails when user give inputs like `www.google.co.in` or `google.co.in`. One thing i can do for such inputs i can append `http://` and `https://` and return the content of the page that opens. But this seems like a big hack to me. Is there any better way to achieve this in ruby(i.e converting these user\_inputs to valid open\_uri urls).
2013/11/20
[ "https://Stackoverflow.com/questions/20090181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039932/" ]
Prepend the scheme if not present and then use `URI` which will check the URL validity: ``` require 'uri' url = 'www.google.com/a/b?c=d#e' url.prepend "http://" unless url.start_with?('http://', 'https://') url = URI(url) # it will raise error if the url is not valid open url ``` Unfortunately, an "object oriented" version of what you need is more verbose and even more hackish: ``` require 'uri' case url = URI.parse 'www.google.com/a/b?c=d#e' when URI::HTTP, URI::HTTPS # no-op when URI::Generic # We need to split u.path at the first '/', since URI::Generic interprets # 'www.google.com/a/b' as a single path host, path = url.path.split '/', 2 url = URI::HTTP.build host: host , path: "/#{path}" , query: url.query , fragment: url.fragment else raise "unsupported url class (#{url.class}) for #{url}" end open url ``` If you accept suggestions, don't break your head too much on this: I faced this matter often and I'm quite sure there aren't "polished" ways to do it
You need to prepend `http` to the urls, without an explicit scheme the uri could be anything, e.g. a local file. A uri is not necessarily an http url. You can check either by using the `URI` class or by using a regex: ``` user_input_url = URI.parse(user_input_url).scheme ? user_input_url : "http://#{user_input_url}" user_input_url = user_input_url =~ /https?:\/\// ? user_input_url : "http://#{user_input_url}" ```
17,433,261
I have a class that implements a few buttons and counters, when I press a button I need some text in a TextView to be set to something else. It isn't anything crazy, which is why I can't understand why it doesn't work. The button onClick method that works: ``` public class Main extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout linLayout = (LinearLayout)findViewById(R.id.main_view); Button button_2 = new Button(this); button_2.setText("2"); button_2.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ setValues(2, 2); ((TextView)findViewById(R.id.counter_label)).setText("You Pressed 2"); updateScrollText(); startTimer(200000); } } linLayout.addView(button_2); } public void setValues(int first, int second); this.first = first; this.second = second; } ... ``` But when I try to place it in my timer: ``` private void startTimer(long time){ counter = new CountDownTimer(time, 1000){ public void onTick(long millisUntilDone){ Log.d("counter_label", "Counter text should be changed"); ((TextView)findViewById(R.id.counter_label)).setText("You have " + millisUntilDone + "ms"); } public void onFinish() { ((TextView)findViewById(R.id.counter_label)).setText("DONE!"); } }.start(); } ``` The frustrating part is that the LogCat shows "Counter text should be changed" on every tick like it is supposed to, it just doesn't actually change the text. Any clue what is going on? I have Cleaned the project and everything else works as it should. I also just noticed that another counter timer that is doing a similar thing (showing me time until it is done) was working 100%, I haven't touched it and now it isn't setting the text either. It stops changing the text after 1 second but the counter keeps counting down.
2013/07/02
[ "https://Stackoverflow.com/questions/17433261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2387054/" ]
Without brackets only the next statement is affected whereas with brackets everything inside the brackets is affected. To add brackets to the loop and have it work exactly the same, just add them around the next statement: ``` function range(upto) { var result = []; for (var i = 0; i <= upto; i++) { result[i] = i; } return result; } ```
Bracket allow you to add more statement into one block. if I modify bit to show result ``` function range(upto) { var result = []; for (var i = 0; i <= upto; i++) { result[i] = i; result[i] = result[i]*2 } return result; } console.log(range(15)); ``` Result will be ``` [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30] ``` however, without bracket, ``` function range(upto) { var result = []; for (var i = 0; i <= upto; i++) result[i] = i; result[i] = result[i]*2 return result; } console.log(range(15)); ``` result will be like this ``` [1,2,3,4,5,6,7,8,9,10,11,12,13,14,30] ``` \*being rookie programmer, I think it probably will fail due to undeclared variable
2,426,160
Currently I use a `HashMap<Class, Set<Entry>>`, which may contain several millions of short-lived and long-lived objects. (`Entry` is a wrapper class around an `Object` and an integer, which is a duplicate count). I figured: these `Object`s are all stored in the JVM's Heap. Then my question popped in my mind; instead of allocating huge amounts of memory for the `HashMap`, can it be done better (less memory consumption)? **Is there a way to access `Object`s in the Java Heap indirectly, based on the `Class` of the `Object`s?** With "indirectly" I mean: without having a pointer to the `Object`. With "access" I mean: to retrieve a pointer to the `Object` in the heap.
2010/03/11
[ "https://Stackoverflow.com/questions/2426160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/252704/" ]
No. Basically, each object knows its class, but a class does not know all its objects - it's not necessary for the way the JRE works and would only be useless overhead. Why do you need to know all instances of those classes anyway? Maybe there's a better way to solve your actual problem.
The map contains only pointers to the objects on the heap. I do not think you can do better then that,
9,397,295
Is `(function_exists('ob_gzhandler') && ini_get('zlib.output_compression'))` enough ? I want to check if the host is serving compressed pages within one of the pages :)
2012/02/22
[ "https://Stackoverflow.com/questions/9397295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1209030/" ]
For PHP, they'll do fine. However, if your referring to compression of pages back to clients, you'll also need to check it's enabled in apache (assuming your using apache you'll need the mod\_gzip.c OR mod\_deflate.c modules). For instance: `# httpd -l` (apache 2) Ive also seen mention of needing to implement .htaccess overrides in the past: ``` #compress all text & html: AddOutputFilterByType DEFLATE text/html text/plain text/xml # Or, compress certain file types by extension: <Files *.html> SetOutputFilter DEFLATE </Files> ```
you can do this programmatically from php: ``` if (count(array_intersect(['mod_deflate', 'mod_gzip'], apache_get_modules())) > 0) { echo 'compression enabled'; } ``` This is of course not super reliable, because there might be other compression modules...
56,792,880
I'm new to Python, but I have set up an python script for searching some specific Values in 2 different excel sheets printing out matches (in excel). Problem is, that our work machines are heavily locked down and without admin privileges, we can't really install anything (we can download though). Is there any version of Python that is Windows 7 compatible that will run standalone without requiring any sort of installer? I have tried pyInstaller, but the problem is that in my script we need PANDAS. And there is no possibility to pip install pandas to our local machines. All is blocked. ("pip install pandas" is not possible. I did the code with Anaconda) So my question is: how can I set up a file for my coworkers, who have no permission to download pandas? Can I set up an exe file (all use windows 7/10) in my private computer where pandas is already installed and forward it to the workers? It should be very easy for them to use--> double click for executing the python script Thanks in advance for any advice.
2019/06/27
[ "https://Stackoverflow.com/questions/56792880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11438622/" ]
As @Angew mentioned, you have a bug in your code and he suggested a fix. The following topic is helpful to understand uninitalized values: [What happens to a declared, uninitialized variable in C? Does it have a value?](https://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value) As for variable scope, if you bring `std::cout << evenS << "\n";` and `std::cout << oddS << "\n";` into the loop, the values of `evenS` and `oddS` would be printed more frequently.
Here's an explanation of scope from [Tutorials Point](https://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm) (annotations in square brackets): > > A scope is a region of the program and broadly speaking there are three places, where variables can be declared − > > > 1. Inside a function or a block which is called local variables. *[Here block means a portion of code starting and ending on these brackets `{}`]* > 2. In the definition of function parameters which is called formal parameters. > 3. Outside of all functions which is called global variables. > > > **Local Variables** > > > Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. *[if you try to access outside either compiler will give you an error.]* > > > **Global Variables** > > > Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program. > > > Now in your case as you said > > Moved cout oddS and cout evenS to outside for loop. Code executes > properly. If moved inside for loop, code executes with improper values > for oddS and evenS. > > > If you declare variable inside for loop, its scope will remain within that block (within that loop).
50,358,231
I was hoping I can get help with a problem I am having. I'm using the php get meta tags function to see if a tag exist on a list of websites, the problem occurs when ever there is a domain without HTTP. Ideally I would want to add the HTTP if it doesn't exist, and also I would need a work around if the domain has HTTPS here is the code I'm using. I will get this error if I land on a site without HTTP in the domain. > > Warning: get\_meta\_tags(www.drhugopavon.com/): failed to open stream: No such file or directory in C:\xampp\htdocs\webresp\index.php on line 16 > > > ``` $urls = array( 'https://www.smilesbycarroll.com/', 'https://hurstbournedentalcare.com/', 'https://www.dentalhc.com/', 'https://www.springhurstdentistry.com/', 'https://www.smilesbycarroll.com/', 'www.drhugopavon.com/' ); foreach ($urls as $url) { $tags = get_meta_tags($url); if (isset($tags['viewport'])) { echo "$url tag exist" . "</br>"; } if (!isset($tags['viewport'])) { echo "$url tag doesnt exist" . "</br>"; } } ```
2018/05/15
[ "https://Stackoverflow.com/questions/50358231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217947/" ]
You could use `parse_url()` to check if the element `scheme` exists or not. If not, you could add it: ``` $urls = array( 'https://www.smilesbycarroll.com/', 'https://hurstbournedentalcare.com/', 'https://www.dentalhc.com/', 'https://www.springhurstdentistry.com/', 'https://www.smilesbycarroll.com/', 'www.drhugopavon.com/' ); $urls = array_map(function($url) { $data = parse_url($url); if (!isset($data['scheme'])) $url = 'http://' . $url ; return $url; }, $urls); print_r($urls); ```
you know whats funny, I thought it was because it had http but I put error\_reporting(0); in my original code and it worked as I wanted it to haha.
1,163,248
Obviously, "Hello World" doesn't require a separated, modular front-end and back-end. But any sort of Enterprise-grade project does. Assuming some sort of spectrum between these points, at which stage should an application be (conceptually, or at a design level) multi-layered? When a database, or some external resource is introduced? When you find that the you're anticipating spaghetti code in your methods/functions?
2009/07/22
[ "https://Stackoverflow.com/questions/1163248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/92995/" ]
> > when a database, or some external resource is introduced. > > > but also: > > always (except for the most trivial of apps) separate AT LEAST presentation tier and application tier > > > see: > > <http://en.wikipedia.org/wiki/Multitier_architecture> > > >
Thinking of it in terms of layers is a little limiting. It's what you see in whitepapers about a product, but it's not how products really work. They have "boxes" that depend on each other in various ways, and you can make it look like they fit into layers but you can do this in several different configurations, depending on what information you're leaving out of the diagram. And in a really well-designed application, the boxes get very small. They are down to the level of individual interfaces and classes. This is important because whenever you change a line of code, you need to have some understanding of the impact your change will have, which means you have to understand exactly what the code currently does, what its responsibilities are, which means it has to be a small chunk that has a single responsibility, implementing an interface that doesn't cause clients to be dependent on things they don't need (the S and the I of SOLID). You may find that your application can look like it has two or three simple layers, if you narrow your eyes, but it may not. That isn't really a problem. Of course, a disastrously badly designed application can look like it has layers tiers if you squint as hard as you can. So those "high level" diagrams of an "architecture" can hide a multitude of sins.
208,140
I am trying to delete all the files with a space in their names. I am using following command. But it is giving me an error Command : `ls | egrep '. ' | xargs rm` Here if I am using only `ls | egrep '. '` command it is giving me all the file name with spaces in the filenames. But when I am trying to pass the output to rm, all the spaces (leading or trailing) gets deleted. So my command is not getting properly executed. Any pointers on how to delete the file having atleast one space in their name?
2015/06/07
[ "https://unix.stackexchange.com/questions/208140", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/118444/" ]
From `man xargs` > > xargs reads items from the standard input, **delimited by blanks** (which > can be protected with double or single quotes or a backslash) or > newlines, and executes the command (default is /bin/echo) one or more > times with any initial-arguments followed by items read from standard > input. Blank lines on the standard input are ignored. > > > We can (mostly) fix your initial command by changing the xargs delimiter to a newline: `ls | egrep '. ' | xargs -d '\n' rm` (don't do this... read on) But what if the filename contains a newline? `touch "filename with blanks and newline"` > > Because **Unix filenames can contain blanks and newlines**, this default > behaviour is often problematic; filenames containing blanks and/or > newlines are incorrectly processed by xargs. In these situations it is > better to **use the -0 option**, which prevents such problems. > > > `ls` [is really a tool for direct consumption by a human](https://unix.stackexchange.com/questions/112125/is-there-a-reason-why-ls-does-not-have-a-zero-or-0-option/112126#112126), instead we need to use the `find` command which can separate the filenames with a null character (`-print0`). We also need to tell grep to use null characters to separate the input (`-z`) and output (`-Z`). Finally, we tell xargs to also use null characters (`-0`) `find . -type f -print0 | egrep '. ' -z -Z | xargs -0 rm`
You can use: ``` find . -name '* *' -delete ```
67,391,237
Basically, I have : * An array giving indexes "I", e.g. (1, 2), * And a list of the same length giving the corresponding number of repetitions "N", e.g. [1, 3] And I want to create an array containing the indexes I repeated N times, i.e. (1, 2, 2, 2) here, where 1 is repeated one time and 2 is repeated 3 times. The best solution I've come up with uses the np.repeat and np.concatenate functions : ``` import numpy as np list_index = np.arange(2) list_no_repetition = [1, 3] result = np.concatenate([np.repeat(index, no_repetition) for index, no_repetition in zip(list_index, list_no_repetition)]) print(result) ``` I wonder if there is a "prettier"/"more efficient solution". Thank you for your help.
2021/05/04
[ "https://Stackoverflow.com/questions/67391237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15835738/" ]
Not sure about prettier, but you could solve it completely with list comprehension: ``` [x for i,l in zip(list_index, list_no_repetition) for x in [i]*l] ```
Hello this is the alternative that I propose: ``` import numpy as np list_index = np.arange(2) list_no_repetition = [1, 3] result = np.array([]) for i in range(len(list_index)): tempA=np.empty(list_no_repetition[i]) tempA.fill(list_index[i]) result = np.concatenate([result, tempA]) result ```
4,562,678
In C++, I have a base class A, a sub class B. Both have the virtual method Visit. I would like to redefine 'Visit' in B, but B need to access the 'Visit' function of each A (and all subclass to). I have something like that, but it tell me that B cannot access the protected member of A! But B is a A too :-P So, what can I do? ``` class A { protected: virtual Visit(...); } class B : public class A { protected: vector<A*> childs; Visit(...); } B::Visit(...) { foreach(A* a in childs) { a->Visit(...); } } ``` Thx
2010/12/30
[ "https://Stackoverflow.com/questions/4562678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/346113/" ]
You may access a protected member using your own object but you may not access a protected member using an alternative object unless it is also of your class (not simply the base class). There is a workaround, just as there is a workaround with friendship not being inherited. In any case with this example: ``` class A { protected: virtual void Visit(...); void visitOther( A& other, ... ) { other.Visit(...); } }; class B : public A { Visit(...); vector<A*> childs; }; B::Visit(...) { for( auto a : childs ) { visitOther( *a, ... ); } } ```
A virtual function's essence is exactly which you are escaping from. Here ``` foreach (A * in the Childs) { a-> Visit (...); } ``` all `a` will call it's corresponding Visit function. It is unnecessary to publicly derive from A, you should use protected. In `A` the Visit function is not virtual, and make a protected constructor, to restrict instantiation through inheratinance (and friends, and hax). If you tell more details, we can also help more. **EDIT 1:** if you are playing with virtuals, do not forget virtual destructors. **EDIT 2:** try this: ``` foreach (A * in the Childs) { a->A::Visit(...); } ```
1,410,511
Background: I've got a new eclipse installation and have installed the m2eclipse plugin. After startup m2eclipse generates the message: > > Eclipse is running in a JRE, but a JDK > is required > > > Following the instructions from [here](http://blog.dawouds.com/2008/11/eclipse-is-running-in-jre-but-jdk-is.html) I've changed the eclipse.ini file to use the JDK JVM: ``` -startup plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar --launcher.library plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519 -product org.eclipse.epp.package.jee.product --launcher.XXMaxPermSize 256M -showsplash org.eclipse.platform --launcher.XXMaxPermSize 256m -vmargs -Dosgi.requiredJavaVersion=1.5 -Xms40m -Xmx512m -vm "C:\Program Files\Java\jdk1.6.0_16\bin\javaw.exe" ``` After restarting eclipse however, I still get the message saying its running under the JRE and not the JDK. Looking at the eclipse configuration via *Help -> About Eclipse -> Installation Details -> Configuration* it seems like eclipse is picking up the JVM configuration details from somewhere else: ``` ... -vm C:\Program Files (x86)\Java\jre6\bin\client\jvm.dll eclipse.home.location=file:/C:/Program Files (x86)/eclipse/ eclipse.launcher=C:\Program Files (x86)\eclipse\eclipse.exe eclipse.p2.data.area=@config.dir/../p2/ eclipse.p2.profile=epp.package.jee eclipse.product=org.eclipse.epp.package.jee.product eclipse.startTime=1252669330296 eclipse.vm=C:\Program Files (x86)\Java\jre6\bin\client\jvm.dll eclipse.vmargs=-Dosgi.requiredJavaVersion=1.5 -Xms40m -Xmx512m -vm "C:\Program Files\Java\jdk1.6.0_16\bin\javaw.exe" -XX:MaxPermSize=256m ... ``` My question is where is the first *-vm* argument coming from and how can I remove or change it? Thanks **Update**: I have updated the eclipse.ini file as per VonC's answer. I'm now getting an error when launching eclipse saying: > > A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found after searching the following locations: "C:\Program Files\Java\jdk1.6.0\_16\bin\javaw.exe" > > > I've confirmed that the path is correct and can be executed via the command line. Complete eclipse.ini below: ``` -startup plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar --launcher.library plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519 -product org.eclipse.epp.package.jee.product --launcher.XXMaxPermSize 256M -showsplash org.eclipse.platform --launcher.XXMaxPermSize 256m -vm "C:\Program Files\Java\jdk1.6.0_16\bin\javaw.exe" -vmargs -Dosgi.requiredJavaVersion=1.5 -Xms40m -Xmx512m ``` **Solution:** it seems like there was still something wrong with the eclipse.ini file. I replaced it completely with the settings given by VonC in the post he linked and eclipse is now starting properly and using the correct JVM. Full eclipse.ini below for anyone else with the same problem: ``` -showlocation -showsplash org.eclipse.platform --launcher.XXMaxPermSize 384m -startup plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar --launcher.library plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519 -vm C:\Program Files (x86)\Java\jdk1.6.0_16\jre\bin\client\jvm.dll -vmargs -Dosgi.requiredJavaVersion=1.5 -Xms128m -Xmx384m -Xss4m -XX:PermSize=128m -XX:MaxPermSize=128m -XX:CompileThreshold=5 -XX:MaxGCPauseMillis=10 -XX:MaxHeapFreeRatio=70 -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:+CMSIncrementalPacing -Dcom.sun.management.jmxremote -Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/jv/eclipse/mydropins ```
2009/09/11
[ "https://Stackoverflow.com/questions/1410511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111313/" ]
My issue was that -vm "C:\Program Files\Java\jdk1.7.0\_67\jre\bin\javaw.exe" the path was in quotes, when i removed the quotes it worked: -vm C:\Program Files\Java\jdk1.7.0\_67\jre\bin\javaw.exe
I solve this question. When you create a Maven Project in Eclipse maybe the text file encoding in this project's properties and the `project.build.sourceEncoding` in the `pom.xml` was not the same. When you build this project it would report "Unable to locate the Javac Compiler in:..." error, too. For example, my text file encoding was GBK and `project.build.sourceEncoding` was UTF-8 so this error happened. I just modified the text file encoding to UTF-8.
27,706,201
i want to equal two table column value(dynamic) in where clause, my code is like this ``` array('table1.column1' => 'table2.column2') ``` it shows the sql query like this ``` where `table1`.`column1` = 'table2.column2' ``` but i want to like this: ``` where `table1`.`column1` = `table2`.`column2` ``` i just want to change the comma "'" to this "`", please help me? Thanks in advance.
2014/12/30
[ "https://Stackoverflow.com/questions/27706201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2557878/" ]
When I have to draw text, I usually need to center the text in a bounding rectangle. ``` /** * This method centers a <code>String</code> in * a bounding <code>Rectangle</code>. * @param g - The <code>Graphics</code> instance. * @param r - The bounding <code>Rectangle</code>. * @param s - The <code>String</code> to center in the * bounding rectangle. * @param font - The display font of the <code>String</code> * * @see java.awt.Graphics * @see java.awt.Rectangle * @see java.lang.String */ public void centerString(Graphics g, Rectangle r, String s, Font font) { FontRenderContext frc = new FontRenderContext(null, true, true); Rectangle2D r2D = font.getStringBounds(s, frc); int rWidth = (int) Math.round(r2D.getWidth()); int rHeight = (int) Math.round(r2D.getHeight()); int rX = (int) Math.round(r2D.getX()); int rY = (int) Math.round(r2D.getY()); int a = (r.width / 2) - (rWidth / 2) - rX; int b = (r.height / 2) - (rHeight / 2) - rY; g.setFont(font); g.drawString(s, r.x + a, r.y + b); } ```
I did create a function to keep the text in center of the image ``` private static void setTextCenter(Graphics2D graphics2DImage, String string, BufferedImage bgImage) { int stringWidthLength = (int) graphics2DImage.getFontMetrics().getStringBounds(string, graphics2DImage).getWidth(); int stringHeightLength = (int) graphics2DImage.getFontMetrics().getStringBounds(string, graphics2DImage).getHeight(); int horizontalCenter = bgImage.getWidth() / 2 - stringWidthLength / 2; int verticalCenter = bgImage.getHeight() / 2 - stringHeightLength / 2; graphics2DImage.drawString(string, horizontalCenter, verticalCenter); } ``` where, `graphics2DImage` is. ``` Graphics2D graphics2DImage = bgImage.createGraphics(); graphics2DImage.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2DImage.drawImage(bgImage, 0, 0, null); ```
24,891,476
This is a function for building a binary tree, where the parameters are a list of integers(list) and an empty vector for the tree to be written to(tree). I'm sure it is a very simple error, but for some reason I am overlooking what is causing this to loop. Thanks for the help. ``` void buildTree(vector<int> list, vector<int> tree) { for(int i=0; i<list.size(); i++) { bool placed = false; int source = 1; while(!placed) { if(tree[source] == NULL) { tree[source] = list[i]; placed = true; } else if(list[i] < source) { source = 2*source; } else if(list[i] > source) { source = 2*source+1; } } } } ```
2014/07/22
[ "https://Stackoverflow.com/questions/24891476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3461666/" ]
The problem is that you are comparing the value (i.e. `list[i]`) to an *index* (i.e. `source`) rather than using `tree[source]`: ``` else if(list[i] < tree[source]) { source = 2*source; } else if(list[i] > tree[source]) { source = 2*source+1; } ``` In addition, your program does not specify what happens when `list[i]` is equal to `tree[source]`, which could potentially cause an infinite loop. Another issue that your program has is that it does not check the size of the `tree` before dereferencing one of its elements by index. This could cause undefined behavior. To address this last issue, add this "catch clause" to your `while` loop: ``` if (source >= tree.size()) { cerr << "Tree index exceeds the allocated size. Breaking the loop." << endl; break; } ```
Some problems with your code: -you are receiving the vectors by value, in all the calls to the function the vectors would be copied, and for this, outside the function you could not access to the written `vector tree` and be paying a performance hit. -i am assuming you are using an empty tree (if not erase lines `if (tree.size() < source) { tree.resize(source); }`. This is because the size of the vector to represent the tree could not be predicted, depend of the element in list. This could be enhanced by allocating more space that needed to avoid multiple consecutive allocations, ex: allocating `sources * factor` (factor > 1.0) instead of `source` like vector do -you are comparing the list element with index of `tree`: `else if(list[i] < source)`, this comparative need to with the values. ``` void buildTree(const vector<int>& list, vector<int>& tree) { for (int i = 0; i < list.size(); i++) { bool placed = false; int source = 1; while (!placed) { if (tree.size() < source) { tree.resize(source); } if (tree[source - 1] == 0) { tree[source - 1] = list[i]; placed = true; } else if (list[i] < tree[source - 1]) { source = 2 * source; } else if (list[i] > tree[source - 1]) { source = 2 * source + 1; } } } } std::vector<int> tree; buildTree(std::vector<int>{5, 2, 4, 13, 8, 25, 32}, tree); ```
22,244,182
I have a `Java Application`. I use `Netbeans 7.4` IDE. I want to host some `web service methods` within this application so that other clients can get data provided by this application using web service. I don't want to host this web servis on any web server, i want to host this only within the application itself `like WCF selfhosting in .NET`. I have been developing C# applications and i have knowladge about WCF but i am just a starter of Java world. Is it possible to host web service endpoints within the application itself like happens in .NET?
2014/03/07
[ "https://Stackoverflow.com/questions/22244182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/739228/" ]
The answer accourding to my needs is already [here](https://stackoverflow.com/questions/5595028/add-a-web-service-to-a-already-available-java-project) I see that I just need to add new java class and add xml annoitions like @WebService and @WebMethod to make the class a web service. Then i just need to add following lines to publish this service: ``` public static void main(String[] args) { String address = "http://127.0.0.1:8023/_WebServiceDemo"; Endpoint.publish(address, new MyWebService()); System.out.println("Listening: " + address); } ```
Well it depends on what you mean by "self-hosting". The easiest way to do this is to use an embedded Jetty server in your application. This is typically frowned upon though as it ties up one port for each web service, and if you're going to have more than a handful, it's quickly going to become difficult to manage, as opposed to simply hosting all your webservices in the same container. But if it's just for a small private project, that nobody else is going to use, running as an embedded Jetty or Tomcat will be fine. Be aware that there will be cloud services that may be difficult to use, but again if this is not a concern, go ahead.
353,553
What would be the simplest way to do this?
2013/04/07
[ "https://math.stackexchange.com/questions/353553", "https://math.stackexchange.com", "https://math.stackexchange.com/users/68740/" ]
First, let $z:=x-16$, then this is the same as $\sqrt{16+z}$ at $z=0$. Use the binomial series: $$(1+x)^\alpha=\sum\_{n\ge 0}\binom\alpha n x^n$$ Now we have $$(16+z)^{1/2}=4\cdot\left(1+\frac z{16}\right)^{1/2}=\\ =4\cdot\sum\_{n\ge 0} \binom{1/2}n\frac{z^n}{16^n}\,.$$
note that $f(x)=2^0x^{1/2}$, $f'(x)=-2^1 x^{-1/2}$, $f''(x)=\frac{2^2}{3} x^{-3/2}$,$f'''(x)=-\frac{2^3}{15}x^{-5/2}$ $\cdots$ Then just plug these into the normal formula for a taylor series expansion ![formla for taylor series](https://i.stack.imgur.com/8vtoU.png) here your $a=16$. Then see what patterns you can find to write these in summation notation!
59,650,139
looking for workflow solution. We need something like ad-hoc sharing workflow <https://docs.bit.dev/docs/workflows/projects> with one addition - before the component publishing could happen only after the code review. let me try to describe the short scenario: * there is a repo with the shared components * there are several consumer projects. each one sits in its own repo * there is no dedicated team to maintain the repo with the shared components * the developer of consumer project imports a share component and make changes * the developer wants to create a pull request for a component changes So far I see only one solution - the developer manually applies changes he made locally to a shared library repo and manually creates a pull request. Kind of boring. Does the bit.dev provide an automated solution for such case?
2020/01/08
[ "https://Stackoverflow.com/questions/59650139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390161/" ]
While a PR-like feature is still not available in Bit, you can use Git's PR workflow to set up a code review process for components with some automation. > > **Note** this flow can work regardless of the specific workflow your team implements. In this answer, I'll focus on the ad-hock flow, as your team uses. > > > You'll first need to set up automation on your projects, that when there's a change in component's code, your CI will `bit tag && bit export` the modified components. This should happen only when a PR is approved and merged to `master` branch (in Git). Then using the [Git integration feature](https://blog.bitsrc.io/announcing-auto-github-prs-for-component-version-bumping-74e7768bcd8a) set up your projects to receive PRs on new versions for components. With these two setups, this will be the workflow your team can utilize: 1. Import component to any project and modify. 2. Submit PR to the project. 3. Have a peer do a code review. 4. When change is merged, run `bit tag && bit export --eject` during CI 5. Commit and push back changes to `package.json` to the repo (with a `skip-ci` flag, per your automation infrastructure). 6. All projects that use that component get a PR from Bit with the newly available version. I will update this answer whenever a new feature in Bit improves on this workflow.
as Itay says, you can use the [GitHub integration on bit.dev](https://blog.bitsrc.io/announcing-auto-github-prs-for-component-version-bumping-74e7768bcd8a). But if you want, I create demos projects that show how to use GitHub or Azure CI to integrate the project with Bit, and export new components when code our pushed to master, and also run Bit script on PRs. <https://github.com/teambit/bit-with-github-actions> <https://github.com/teambit/bit-with-azure-devops> I hope it will help you.
20,947,359
Chrome allows us to disable the same origin policy, so we can test cross origin requests. I would like to know if there any possibility to do the same thing in IE
2014/01/06
[ "https://Stackoverflow.com/questions/20947359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014186/" ]
On my computer I am using internet explorer 11 version I also have the same problem. I have done following steps to solve my problem. **Step 1** : Allow Cross domain Access > > > ``` > (Press) Alt -> Tools -> Internet Options -> Security (Tab) -> > Custom Level -> Miscellaneous -> Access data sources across domains -> > Set to Enable > > ``` > > **Step 2**: Disable Protected mode > > > ``` > (Press) Alt -> Tools -> Internet Options -> Security (Tab) -> > uncheck Enable Protected mode for Internet & Local Intranet > > ``` > > **Step 3**: Add localhost/domain to trusted site > > > ``` > (Press) Alt -> Tools -> Internet Options -> Security (Tab) -> > Trusted site -> Sites -> Uncheck Require server verification(https:) -> > enter localhost url & click on add button. > > ``` > >
As decribed at <https://www.webdavsystem.com/ajax/programming/cross_origin_requests/> In FireFox, Safari, Chrome, Edge and IE 10+: To enable cross-origin requests in FireFox, Safari, Chrome and IE 10 and later your server must attach the following headers to all responses: ``` Access-Control-Allow-Origin: http://webdavserver.com Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL Access-Control-Allow-Headers: Overwrite, Destination, Content-Type, Depth, User-Agent, Translate, Range, Content-Range, Timeout, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Location, Lock-Token, If Access-Control-Expose-Headers: DAV, content-length, Allow ``` In Internet Explorer 9 and Earlier: As told at <https://stackoverflow.com/a/20947828/5035343>
31,517,228
I am trying to write a program in VBA at the moment which is to be run in Excel. I am quite stuck right now because I am not very familiar with VBA and doing a search doesn't come up with my specific problem. I have a column in Excel which has 20,000+ hostnames for PC's on our network. What I need to do is be able to start at A2 and get the data in that cell, parse out the 5th and 6th characters only and check if those two characters are in an array called VariantDepartments. If the characters are in the array, I need to move to A3 and do it again. If the characters are not in the array, I need to add them to the end of the VariantDepartments array and then add those two characters plus the word "Workbook" to another array called DepartmentWorkBookNames at which point I index both arrays +1 and move to A3. This is what I am working on right now and it does not work: ``` Sub VulnerabilityMacroFinal() Dim VariantDepartments As Variant Dim departments As Variant Dim Department As String Dim VariantAssetTypes As Variant Dim AssetTypes As Variant Dim AssetType As String Dim Property As String Dim FileName As String Dim PropArray() As String Dim strFile As String 'Opening file & getting property name strFile = Application.GetOpenFilename If strFile <> "False" Then Workbooks.Open strFile FileName = ActiveWorkbook.Name PropArray = Split(FileName, "-") Property = PropArray(0) 'Setting asset types VariantAssetTypes = Array("PC", "Server", "Other Assets") 'Program Start Sheets("AllVulnerabilities").Select 'sorting out unnecessary types ActiveSheet.UsedRange.AutoFilter Field:=5, Criteria1:=Array( _ "01-Adobe", "02-Apache", "06-Chrome", "09-Firefox", "13-Java", "16-Microsoft", _ "38-VNC"), Operator:=xlFilterValues 'Selecting the whole sheet Cells.Select 'Creating sheets for different asset types For Each AssetTypes In VariantAssetTypes 'Making variable a C String to make it easier to check in If statements AssetType = CStr(AssetTypes) If AssetType = "PC" Then 'Parsing out the non local PC assets ActiveSheet.UsedRange.AutoFilter Field:=3, Criteria1:=Property & "D*" ActiveSheet.Range("A:A,B:B,C:C,D:D,E:E,F:F").AutoFilter Field:=1 ElseIf AssetType = "Server" Then 'Selecting original sheet Sheets("AllVulnerabilities").Select 'Parsing out the non local Server assets ActiveSheet.UsedRange.AutoFilter Field:=3, Criteria1:=Property & "*", _ Operator:=xlAnd, Criteria2:="<>" & Property & "D*" ElseIf AssetType = "Other Assets" Then 'Selecting original sheet Sheets("AllVulnerabilities").Select 'Parsing out the non local Server assets ActiveSheet.UsedRange.AutoFilter Field:=3, Criteria1:="<>" & Property & "*" End If 'Copying all info on sheet ActiveSheet.UsedRange.Copy 'Selecting new sheet Sheets.Add.Name = Property & " " & AssetType 'Selecting new sheet Sheets(Property & " " & AssetType).Select 'Pasting data to new sheet ActiveSheet.Paste 'Removing unnecessary colums Range("A:A,B:B,D:D,G:G,H:H,J:J,K:K").Select Application.CutCopyMode = False Selection.Delete Shift:=xlToLeft 'Auto adjusting column widths Range("A:A,B:B,C:C,D:D,E:E,F:F").EntireColumn.AutoFit ActiveWorkbook.Worksheets(Property & " " & AssetType).Copy 'Close Workbook withoutsaving ActiveWorkbook.Close savechanges:=False Next AssetTypes Sheets(Property & " PC").Select 'THIS IS WHERE THE ARRAY SHOULD BE CREATED. For Each departments In VariantDepartments Department = CStr(departments) Sheets(Property & " PC").Select 'Parsing out the non local assets for EH ActiveSheet.UsedRange.AutoFilter Field:=1, Criteria1:=Property & "D" & Department & "*" 'Copying all info on sheet ActiveSheet.UsedRange.Copy 'Selecting new sheet Sheets.Add.Name = Property & Department 'Selecting new sheet Sheets(Property & Department).Select 'Pasting data to new sheet ActiveSheet.Paste 'Auto adjusting column widths Range("A:A,B:B,C:C,D:D,E:E,F:F").EntireColumn.AutoFit ActiveWorkbook.Worksheets(Property & Department).Copy 'Close Workbook withoutsaving ActiveWorkbook.Close savechanges:=False 'Set PC Worksheet to be unfiltered Worksheets(Property & " PC").ShowAllData Next departments 'Completed ActiveWindow.Close savechanges:=False 'Message box which appears when everything is done MsgBox "Done!" ``` End Sub
2015/07/20
[ "https://Stackoverflow.com/questions/31517228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3795599/" ]
Here's a method that allows you to hide cells from the HTML/PDF output by editing the cell metadata only. Versions I'm using: `$ jupyter notebook --version` 4.1.0 `$ jupyter nbconvert --version` 4.2.0 1. Download the ipython notebook extension templates by following install instructions on Github: pip install <https://github.com/ipython-contrib/IPython-notebook-extensions/tarball/master> * This just install files into your local jupyter data directory. [Full details in the readme](https://github.com/ipython-contrib/IPython-notebook-extensions#installpy) 2. run `jupyter notebook` 3. go to `localhost:8888/nbextensions` (or whatever port you started on) and activate `Printview` 4. go back to `localhost:8888/tree`, create a new notebook and go into it 5. create a code cell with some code in it that produces output e.g. `print("You can see me") #but not me` 6. go to `View` > `Cell Toolbar` > `Edit Metadata` 7. click the `Edit Metadata` button now showing to the top right of the cell 8. add `'hide_input':True` to the json e.g. mine looked like `{ "collapsed": false, "hide_input": true, "trusted": true }` after 9. save notebook 10. go back to the terminal and execute `jupyter nbconvert --to pdf --template printviewlatex.tplx notebookname.ipynb` (if your notebook is called `notebookname.ipynb.ipynb`) You should now have a document called notebookname.pdf in the directory. Hopefully it should have just the text `You can see me` in it...fingers crossed.
In case anyone finds excluding all code cells helpful (which is not what is asked here), you can add this flag `nbconvert --TemplateExporter.exclude_code_cell=True`
17,467,331
Big thanks in advance. I want to set up a phantomjs Highcharts export server. It should accept json options as input and output jpeg image files. Here is what I do: 1. I download server side js code from this repo: <https://github.com/highslide-software/highcharts.com/tree/master/exporting-server/phantomjs> 2. I download phantomjs 1.6.0 3. run ``` phantomjs highcharts-convert.js -host 127.0.0.1 -port 3001 ``` Then I tried to use client code in this site: <http://export.highcharts.com/demo> to send request. I changed the form action url from this: ``` <form id="exportForm" action="./" method="POST"> ``` to this: ``` <form id="exportForm" action="http://0.0.0.0:3001" method="POST"> ``` and clicked 'Highcharts config object (JSON)'. All I get is this message: > > Failed rendering: > SyntaxError: Unable to parse JSON string > > > Since the same request can be processed correctly in Highcharts server, the error must be in the Highcharts server side js code I'm using. I also tried following command: ``` phantomjs highcharts-convert.js -infile options.js \ -outfile chart.png -scale 2.5 -width 300 ``` With this code in `options.js`: ``` { infile: { xAxis: { categories:['Jan','Feb','Mar','Apr', 'May','Jun','Jul','Aug', 'Sep','Oct','Nov','Dec'] }, series:[ { data:[29.9,71.5,106.4,129.2, 144.0,176.0,135.6,148.5, 216.4,194.1,95.6,54.4] }] }, callback: function(chart){ chart.renderer .arc(200,150,100,50,-Math.PI,0) .attr({fill:'#FCFFC5',stroke:'black','stroke-width':1}) .add(); }, constr: "Chart", outfile: "//tmp//chart.png" } ``` And it generates the png successfully. I guess Highchart didn't put much work in the exporting functions and I found some typo in the highcharts-convert.js file. Can anyone help me on this? Thanks a lot.
2013/07/04
[ "https://Stackoverflow.com/questions/17467331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1633867/" ]
I got that same error when I tried to send in a JSON string that was longer than what my server hosting the highcharts exporter WAR file would accept. Check your message length parameter in your server. Make sure it is long enough to hold the request sent. Now, since you do not mention what export server you are using (java or PHP) I would imagine you did not actually set up the web front end for the export server and you just have the headless command line export set up (phantomJS + some highcharts js files). To use the exporting server for use in the front end (like when a user clicks on the export buttons on the web page) you also need to set up [Java](https://github.com/highslide-software/highcharts.com/tree/master/exporting-server/java) or [PHP](https://github.com/highslide-software/highcharts.com/tree/master/exporting-server/php).
This is because the Phantoms HTTP server which is started by ``` phantomjs highcharts-convert.js -host ... -port ... ``` expects the parameters send in JSON format. Please read, the [documentation](http://docs.highcharts.com/#render-charts-on-the-server), parapgraph *'start as a webserver'* Out of curiosity... what typo did you found?
4,627,697
I'm putting together a universal app and I have the icons in my project, but I keep getting a warning from the compiler in regards to Icon.png. I followed the instructions at <http://developer.apple.com/library/ios/#qa/qa2010/qa1686.html> but still get the above error. I've tried doing the following: Putting the icons in the Shared group and adding them according to the plist according to the tech note. Changing the icon paths to add Shared/ to them to point to the shared folder. Creating a Resources group (which the tech note fails to point out that XCode doesn't create a Resources Group for a universal app) and moving them into that (I removed the "Shared/" prefixes from the plist.) Moving the icons to the top level of the project. I've also double-checked the icon sizes and they are all correct, as well as the names of each. Anything I might have missed?
2011/01/07
[ "https://Stackoverflow.com/questions/4627697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/272502/" ]
I had the exact same problem. When you build and archive, click show in finder, show the contents of the package of the archive and check if all the files are showing up. For me, the archive was missing Icon.png file for some reason. The archive utility has a bug. I moved the icons out of the resource folder, cleaned and built the project. Then again I moved the icons into the resource folder and cleaned and built it. Then the archive had copied the missing icon files.
This solution worked for me: <http://vawlog.vawidea.com/en/2010/11/icon-specified-in-the-infoplist-not-found-under-the-top-level-app-wrapper-iconpng/>
744,089
So currently my desktop looks like this: [![panel isn't working](https://i.stack.imgur.com/GMHn8.png)](https://i.stack.imgur.com/GMHn8.png) If I use `Ctrl` + `Alt` + `F2` then login and use startx things seem to work perfectly fine but obviously I don't want to have to do this everytime. If I have lightdm running and then I use start-x in a differenty tty then the startx session works fine. However if lightdm isn't running then the startx session will look the same as the screenshots posted. Sorry about the lack of information. Not sure what to describe this problem as but thanks for any help!
2016/03/10
[ "https://askubuntu.com/questions/744089", "https://askubuntu.com", "https://askubuntu.com/users/496443/" ]
In File Manager go to: ``` ~/.cache/sessions/. ``` A couple of `xfce4*` files are there, delete them, reboot.
So, it looks like a video driver issue. But before we troubleshoot that have you attempted to reinstall unity? **Reinstall unity** Just to make sure no processes are running we should do the following: `ALT`+`PrtSc`+`E`. Now go towards the `CTR`+`ALT`+`F2` you used and try the following: `sudo apt-get update && sudo apt-get install --reinstall ubuntu-desktop && sudo apt-get install unity` If this did not resolve the issue, then it really feels like a video driver issue. **Troubleshoot video driver**: To see the current driver that is used: `lspci -nnk | grep -i vga -A3 | grep 'in use'` (for full info remove the grep) In my case: Kernel driver in use: **i915**. Reinstall the video driver, you should first `sudo apt-get purge` the current used driver. To install video driver intel based: ``` sudo apt-get install --reinstall xserver-xorg-video-intel libgl1-mesa-glx libgl1-mesa-dri xserver-xorg-core sudo dpkg-reconfigure xserver-xorg unity --reset ``` If this resolved it, try to get the correct driver for lets say your nvidea card? Also handy to know the output off: `glxinfo | grep -i vendor` (`mesa-utils` is needed for glxinfo)
17,968,565
I am creating a dynamic form using following code, ``` function createForm() { var f = document.createElement("form"); f.setAttribute('method',"post"); f.setAttribute('action',"./Upload"); f.setAttribute('name',"initiateForm"); f.acceptCharset="UTF-8"; var name = document.createElement("input"); name.setAttribute('type',"text"); name.setAttribute('name',"projectname"); name.setAttribute('value',"saket"); f.appendChild(name); f.submit(); } ``` But in Mozilla nothing happens but code works as expected ( in chrome). This code is being called by another function which is invoked by button on click event. After executing this code i am returning false. Please help me out. Thanks in advance :-)
2013/07/31
[ "https://Stackoverflow.com/questions/17968565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2261259/" ]
You need to append the new created form to the document, because it was not there on page load. Try this: ``` function createForm() { var f = document.createElement("form"); f.setAttribute('method',"post"); f.setAttribute('action',"./Upload"); f.setAttribute('name',"initiateForm"); f.acceptCharset="UTF-8"; var name = document.createElement("input"); name.setAttribute('type',"text"); name.setAttribute('name',"projectname"); name.setAttribute('value',"saket"); f.appendChild(name); document.body.appendChild(f); // added this f.submit(); } ```
I had similar error just resolved the same. If you have just used `<form></form>` tag and trying to submit then it gives error in older version of mozill while it works in newer version and other browsers. The form tag should be under `<html><body>` tag. e.g. `<html><body><form></form></body></html>`
4,191,324
How do you make sure that you always have a releasable build? I'm on a Scrum team that is running into the following problem: At the end of the Sprint, the team presents its finished user stories to the Product Owner. The PO will typically accept several user stories but reject one or two. At this point, the team no longer has a releasable build because the build consists of both the releasable stories and the unreleasable stories and there is no simple way to tear out the unreleasable stories. In addition, we do not want to just delete the code associated with the unreleasable stories because typically we just need to add a few bug fixes. How should we solve this problem? My guess is that there is some way to branch the build in such a way that either (a) each user story is on its own branch and the user story branches can be merged or (b) there is a way of annotating the code associated with each user story and creating a build that only has the working user story. But I don't know how to do either (a) or (b). I'm also open to the possibility that there are much easier solutions. I want to stress that the problem is not that the build is broken. The build is not broken -- there are just some user stories in the build that cannot be released. We are currently using svn but are willing to switch to another source control system if this would solve the problem. In addition to answers, I'm also interested in any books or references which address this question.
2010/11/16
[ "https://Stackoverflow.com/questions/4191324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/128807/" ]
As you suggest, one way to approach this is to consider rejection from the outset. Requiring that every user story can be enabled or disabled through a configuration directive guarantees a releasable build without the rejected stories. If you are really serious about excluding the rejected stories, a configuration directive is not enough because it can be edited by the client. You may consider compilation constants in that case. This approach requires some additional code and testing, but saves you the hassle of branching and merging. You can also leave your revision control environment in place. Hope this helps.
> > How do you make sure that you always have a releasable build? > > > I think there are 2 aspects to your question. One is version control plus release management strategies, and the other is how to handle 'Undone' work. As far as the version control part goes, your solution is simpler than you think. With svn each commit creates a tag for the whole project with a tag number. You can do an svn revert on just a particular User Story check in tag. A best practice article suggests that development should always be done on the trunk, and you should only branch for a release. So any unreleasable code should be reverted using svn revert on the tag number on the trunk, and then the release branch should be created. After the branch is created, you can check in the unreleased code back again and continue working on it on the next Sprint. Continue working on bugs or release issues on the branch itself without meddling with the trunk. Offcource do not forget to merge the release branch back to the trunk periodically. And about the undone work goes, first of all it is a good thing that your organisation recognizes the difference between shippable and non shippable, so that is a good step. Secondly you need to investigate why work is left undone, try to facilitate some questions in the Retrospective which will help your Team avoid such situations, using the inspect and adapt principle.
6,088,735
It seems that when I run the following code: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv) { int i=0; setvbuf(stdout, NULL, _IOLBF,0); while (1) printf("%d ",i++); return 0; } ``` it prints in chunks of 1024 chars, no matter the **size** I define for setvbuf(). The question is is if **size** affects somehow in this case and where is the definition for 1024 chars is coming from.
2011/05/22
[ "https://Stackoverflow.com/questions/6088735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/359644/" ]
I don't know how you identified `1024` but it's probably `BUFSIZ`. `BUFSIZ` is defined in `stdio.h`. > > If buf is NULL, then the stdio library > automatically allocates a buffer for > use with stream (unless we select > unbuffered I/O). > > > **EDIT** Here's something `glibc` says: > > Macro: int BUFSIZ > The value of this macro is an integer constant expression that is > good to use for the size argument to > setvbuf. This value is guaranteed to > be **at least 256**. > > > The value of BUFSIZ is chosen on each system so as to make stream I/O > efficient. So it is a good idea to use > BUFSIZ as the size for the buffer when > you call setvbuf. > > > **EDIT 2** @larsmans is right. I looked at how `setvbuf` is implemented and it ignores a call when asking for line buffering and presenting a NULL buf. Now, `stdout` is no ordinary file, it's attached to a terminal. So, heading over to [pixelbeat](http://www.pixelbeat.org/programming/stdio_buffering/) > > * Buffer size only directly affects buffered mode > * The default size like the kernel is based on the page size (4096 bytes on > my system) > * if stdin/stdout are connected to a terminal then default size = 1024; > > else size = 4096 > > >
The size probably doesn't have much effect for a NULL buf pointer. However, you are still requesting buffered output with `_IOLBF` Try `_IONBF` instead. <http://en.wikipedia.org/wiki/Setvbuf>
69,663,301
I am quite new to the docker topics and I have a question of connecting container services with traditional ones. Currently I am thinking of replacing an traditional grafana installation (directly on a linux server) with a grafana docker container. In grafana I have to connect to different data sources like a mysql instance, a Winsows SQL Database and so on. So grafana is doing a pull of data. All these data sources reside (and will still reside) on other hosts and they are not containers. So how can I implement that my container is able to communicate with this data sources? Is it possible by default or do I have to implement a special kind of network? I saw that there is an option called macvlan...is that the correct way? BR Jan
2021/10/21
[ "https://Stackoverflow.com/questions/69663301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211682/" ]
I fixed mine by moving the project directory to the same drive. My project was stored in E:\ so, I moved it to C:. My answer is almost the same as rvr93's answer but I did not add anything to the environment variables.
Create a directory in the same drive as your project and add [PUB\_CACHE](https://dart.dev/tools/pub/environment-variables) environment variable. Run `flutter pub get`. This worked for me.
9,190,792
Suppose portlet X is deployed to Liferay and has a friendly URL mapped. Suppose a user enters the Liferay Portal via a the mapped URL but the portlet is not present in the portal - it's deployed but not added to the page. My problem is that when the user uses the mapped URL nothing happens - the portal gives no visual feedback, that the **target** portlet is not present. How can I change that? I need some kind of an alert / notice to the user... -- edit -- I need not use a second portlet to check the presence of yet another portlet. Kindest regards,
2012/02/08
[ "https://Stackoverflow.com/questions/9190792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000918/" ]
AFAIK, there is no *natual* way to make that happen. A portlet **need not** always be installed on a page. So, the behaviour is quite normal. One rather *hacky* solution I could think of: 1. Get hold of the `ThemeDisplay` object in a JSP using `<liferay-theme:defineObjects />` which would expose the implicit object `themeDisplay` in the JSP scope. 2. Get hold of the type settings string using: ``` String typeSettings = themeDisplay.getLayout().getTypeSettings(); ``` 3. Type settings will have values like the below: ``` layout-template-id=foobar_2column sitemap-include=1 column-1=foo_WAR_barportlet,abc_WAR_barportlet,56_INSTANCE_K4Vv, column-2=baz_WAR_xyzportlet, sitemap-changefreq=daily ``` 4. So if you have a non-instanceable portlet with ID `foo` inside WAR file `bar`, the portlet's unique ID on the layout will be `foo_WAR_barportlet`. 5. Once you know the portlet ID that you're expecting to be present, it's just a matter of string contains check. ``` <% if(!typeSettings.contains("foo_WAR_barportlet")) { %> <h3 style="color: red">Alert! Portlet foo_WAR_barportlet not installed.</h3> <% } %> ``` You can do the above steps even inside a theme, but you'll have to do it in Velocity instead of Java then. Hope that helps. ***EDIT*** You can add this line inside your `portal_normal.vm` ``` #if(!$layout.getTypeSettings().contains("foo_WAR_barportlet")) <h3 style="color: red">Alert! Portlet foo_WAR_barportlet not installed.</h3> #end ```
It would be better if we try this, ``` ThemeDisplay themeDisplay = request.getAttribute(WebKeys.THEME_DISPLAY); Layout layout = LayoutLocalServiceUtil.getLayout(themeDisplay.getLayout().getPlid()); LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet)layout.getLayoutType(); List allPortletIds = layoutTypePortlet.getPortletIds(); ``` If the list is empty then the page doesnt contain any portlets. Gettings the `LayoutTypePortlet` ensures that page the user has been redirected to is layout type portlet.
10,292,001
I have a container that has a % width and height, so it scales depending on external factors. I would like the font inside the container to be a constant size relative to the size of containers. Is there any good way to do this using CSS? The `font-size: x%` would only scale the font according to the original font size (which would be 100%).
2012/04/24
[ "https://Stackoverflow.com/questions/10292001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60893/" ]
You may be able to do this with CSS3 using calculations, however it would most likely be safer to use JavaScript. Here is an example: <http://jsfiddle.net/8TrTU/> Using JS you can change the height of the text, then simply bind this same calculation to a resize event, during resize so it scales while the user is making adjustments, or however you are allowing resizing of your elements.
It **cannot** be accomplished with css [font-size](https://developer.mozilla.org/en/CSS/font-size) Assuming that "external factors" you are referring to could be picked up by media queries, you could use them - adjustments will likely have to be limited to a set of predefined sizes.
45,612
Cancer works by making cells split and reproduce at an accelerated rate, slowly and painfully killing the afflicted. Its true weapon lies in its ability to surpass the immunity system. As far as I can tell, no matter how the cells of an alien work, there is no way to make them immune to this. So I must ask, is the basic premise of cancer universal? How can I design a species whose immunity system is immune to cancer?
2016/06/28
[ "https://worldbuilding.stackexchange.com/questions/45612", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/11049/" ]
Cancer is typically caused by improper [DNA repair](https://en.wikipedia.org/wiki/DNA_repair). The gist of it is that cellular DNA becomes damaged in such a way that a repair to the DNA of the cell fails to restore the original DNA, and also corrupts it in such a way that other cellular mechanics to encourage programmed cell death under these circumstances do not trigger. Now, the human body repairs a *lot* of damage to cellular DNA every day, and the odds of this kind of improper DNA repair happening, and it having the necessary changes in DNA to become cancerous, is fairly rare (otherwise everyone would have cancer from the day they were born). It is a statistics game, however, and unless something else kills us beforehand, statistically speaking, everyone will get cancer. Cancer spreads rapidly by several mechanisms, but one of the key ones is the activation of Telomerase, a Ribonucleic Protein that add a telomere repeating pattern to the end of a DNA chain (typically these patterns naturally limit the number of times a cell can divide, the Telomerase removes this limit). Without a mechanism to limit the number of times a cell can divide, they divide indiscriminately and constantly. Cancer tends to bypass the immune system because it is composed of cells from the same host, and is often recognized as part of the healthy body (one of the research pathways to cancer fighting drugs is aimed at flagging cancer as a foreign body). In theory, a virus or other method could be devised to inflict a cancer-like disease on an alien race. However, depending on how their biology works, it may or may not have the same effect. They could be different enough on a biological level that they would be immune to cancers, and the condition would never occur.
Adding to the answers of @celtschk and @Anne: They both say that cancer is an inevitable consequence of having a multi-cellular organism. One can imagine that other species have more cancer or less cancer than us, but they *will* have cancer. Of course, as medical science gets better, we get better at detecting cancer in an early stage, and we also get better at curing cancer when we find it. We will probably soon reach the point where cancer no longer is a big deal, just a matter of seeing your doctor regularly. Total immunity is probably impossible, but we could certainly be less cancer-prone than we are. Multiple redundant systems for mutation detection leading to repair or cell suicide would help. Actually, we already have that, but they aren't quite redundant *enough*. The problem is that evolution leads to "planned obsolesce". As we age, we accumulate damage from all sorts of sources. From a evolutionary point of view, it is easier to just discard one generation when the next generation is ready, rather than putting lots of effort into repair systems. Any species which is fresh out of their biological evolution era is likely to be in a similar situation. As the species mature and starts modifying their own genome-equivalent, they can get away from this and become more robust. This will not only improve cancer defense but also delay aging in general. Story idea: Write about the one single person on the planet dying from incurable cancer in some distant future. It would have to be somebody who have both skipped their medical controls AND have some complications that makes the cancer incurable. Scientists are working day and night to overcome these complications, but will they succeed in time? Stray thought: A species whose global religion tell them that cancer is a sign of divine wrath, and who always kills the whole family of the diseased. This would give a strong evolutionary pressure to have strong cancer defense. Never totally immune, but far better than us.
1,741,820
What are the differences between the assignment operators `=` and `<-` in R? I know that operators are slightly different, as this example shows ``` x <- y <- 5 x = y = 5 x = y <- 5 x <- y = 5 # Error in (x <- y) = 5 : could not find function "<-<-" ``` But is this the only difference?
2009/11/16
[ "https://Stackoverflow.com/questions/1741820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/203420/" ]
Google's R style guide simplifies the issue by prohibiting the "=" for assignment. Not a bad choice. <https://google.github.io/styleguide/Rguide.xml> The R manual goes into nice detail on all 5 assignment operators. <http://stat.ethz.ch/R-manual/R-patched/library/base/html/assignOps.html>
This may also add to understanding of the difference between those two operators: ``` df <- data.frame( a = rnorm(10), b <- rnorm(10) ) ``` For the first element R has assigned values and proper name, while the name of the second element looks a bit strange. ``` str(df) # 'data.frame': 10 obs. of 2 variables: # $ a : num 0.6393 1.125 -1.2514 0.0729 -1.3292 ... # $ b....rnorm.10.: num 0.2485 0.0391 -1.6532 -0.3366 1.1951 ... ``` R version 3.3.2 (2016-10-31); macOS Sierra 10.12.1
22,008,822
I encountered a strange behavior of mongo and I would like to clarify it a bit... My request is simple as that: I would like to get a size of single document in collection. I found two possible solutions: * Object.bsonsize - some javascript method that should return a size in bytes * db.collection.stats() - where there is a line 'avgObjSize' that produce some "aggregated"(average) size view on the data. It simply represents average size of single document. When I create test collection with only one document, both functions returns different values. How is it possible? Does it exist some other method to get a size of a mongo document? Here, I provide some code I perform testing on: 1. I created new database 'test' and input simple document with only one attribute: type:"auto" ``` db.test.insert({type:"auto"}) ``` 2. output from stats() function call: *db.test.stats()*: ``` { "ns" : "test.test", "count" : 1, "size" : 40, "avgObjSize" : 40, "storageSize" : 4096, "numExtents" : 1, "nindexes" : 1, "lastExtentSize" : 4096, "paddingFactor" : 1, "systemFlags" : 1, "userFlags" : 0, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1 ``` } 3. output from bsonsize function call: *Object.bsonsize(db.test.find({test:"auto"}))* ``` 481 ```
2014/02/25
[ "https://Stackoverflow.com/questions/22008822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1949763/" ]
**MAXIMUM DOCUMENT SIZE 16 MiB ([source](https://docs.mongodb.com/manual/core/document/#document-size-limit))** --- **If you have version >=4.4 (`$bsonSize` [source](https://docs.mongodb.com/upcoming/reference/operator/aggregation/bsonSize/))** ``` db.users.aggregate([ { "$project": { "size_bytes": { "$bsonSize": "$$ROOT" }, "size_KB": { "$divide": [{"$bsonSize": "$$ROOT"}, 1000] }, "size_MB": { "$divide": [{"$bsonSize": "$$ROOT"}, 1000000] } } } ]) ``` --- **If you have version <4.4 (`Object.bsonSize()` [source](https://docs.mongodb.com/manual/reference/mongo-shell/#std-label-shell-quick-ref-misc))** You can use this script for get a real size: ``` db.users.find().forEach(function(obj) { var size = Object.bsonsize(obj); print('_id: '+obj._id+' || Size: '+size+'B -> '+Math.round(size/(1000))+'KB -> '+Math.round(size/(1000*1000))+'MB (max 16MB)'); }); ``` Note: If your IDs are 64-bit integers, the above will truncate the ID value on printing! If that's the case, you can use instead: ``` db.users.find().forEach(function(obj) { var size = Object.bsonsize(obj); var stats = { '_id': obj._id, 'bytes': size, 'KB': Math.round(size/(1000)), 'MB': Math.round(size/(1000*1000)) }; print(stats); }); ``` This also has the advantage of returning JSON, so a GUI like RoboMongo can tabulate it! --- **edit : thanks to [@zAlbee](https://stackoverflow.com/users/2646919/zalbee) for your suggest completion.**
Method `Object.bsonsize()` is available only in legacy `mongo` shell. In new `mongosh` you have to use package [bson](https://github.com/mongodb/js-bson) or [mongocompat snippets](https://github.com/mongodb-labs/mongosh-snippets/tree/main/snippets/mongocompat) ``` const BSON = require("bson"); BSON.calculateObjectSize({field: "value"}) BSON.calculateObjectSize(db.test.findOne()) ```
43,908,131
Can somebody tell me what I am doing wrong please? can't seem to get the expected output, i.e. ignore whitespace and only upper/lowercase a-z characters regardless of the number of whitespace characters my code: ``` var sentence = "dancing sentence"; var charSentence = sentence.ToCharArray(); var rs = ""; for (var i = 0; i < charSentence.Length; i++) { if (charSentence[i] != ' ') { if (i % 2 == 0 && charSentence[i] != ' ') { rs += charSentence[i].ToString().ToUpper(); } else if (i % 2 == 1 && charSentence[i] != ' ') { rs += sentence[i].ToString().ToLower(); } } else { rs += " "; } } Console.WriteLine(rs); ``` Expected output: DaNcInG sEnTeNcE Actual output: DaNcInG SeNtEnCe
2017/05/11
[ "https://Stackoverflow.com/questions/43908131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3849777/" ]
Linq version ``` var sentence = "dancing sentence"; int i = 0; string result = string.Concat(sentence.Select(x => { i += x == ' ' ? 0 : 1; return i % 2 != 0 ? char.ToUpper(x) : char.ToLower(x); })); ``` **Sidenote:** please replace `charSentence[i].ToString().ToUpper()` with `char.ToUpper(charSentence[i])`
Thanks @Dmitry Bychenko. Best Approach. But i thought as per the OP's (might be a fresher...) mindset, what could be the solution. Here i have the code as another solution. Lengthy code. I myself don't like but still representing ``` class Program { static void Main(string[] args) { var sentence = "dancing sentence large also"; string newString = string.Empty; StringBuilder newStringdata = new StringBuilder(); string[] arr = sentence.Split(' '); for (int i=0; i< arr.Length;i++) { if (i==0) { newString = ReturnEvenModifiedString(arr[i]); newStringdata.Append(newString); } else { if(char.IsUpper(newString[newString.Length - 1])) { newString = ReturnOddModifiedString(arr[i]); newStringdata.Append(" "); newStringdata.Append(newString); } else { newString = ReturnEvenModifiedString(arr[i]); newStringdata.Append(" "); newStringdata.Append(newString); } } } Console.WriteLine(newStringdata.ToString()); Console.Read(); } //For Even Test private static string ReturnEvenModifiedString(string initialString) { string newString = string.Empty; var temparr = initialString.ToCharArray(); for (var i = 0; i < temparr.Length; i++) { if (temparr[i] != ' ') { if (i % 2 == 0 && temparr[i] != ' ') { newString += temparr[i].ToString().ToUpper(); } else { newString += temparr[i].ToString().ToLower(); } } } return newString; } //For Odd Test private static string ReturnOddModifiedString(string initialString) { string newString = string.Empty; var temparr = initialString.ToCharArray(); for (var i = 0; i < temparr.Length; i++) { if (temparr[i] != ' ') { if (i % 2 != 0 && temparr[i] != ' ') { newString += temparr[i].ToString().ToUpper(); } else { newString += temparr[i].ToString().ToLower(); } } } return newString; } } ``` OUTPUT [![enter image description here](https://i.stack.imgur.com/ukobS.png)](https://i.stack.imgur.com/ukobS.png)
1,285,690
I am little confused when I set this polynomial to zero what does the result mean? Does the parabola have a minimum point at $4$?
2015/05/17
[ "https://math.stackexchange.com/questions/1285690", "https://math.stackexchange.com", "https://math.stackexchange.com/users/184004/" ]
You have \begin{align} y=\left(x-4\right)^2.\tag{1} \end{align} What we could also do is write it as \begin{align} y&=\left(x-4\right)\left(x-4\right)\\ &=x^2-4x-4x+16\\ &=x^2-8x+16.\tag{2} \end{align} Now, we'll stop and take a look at $\left(2\right)$ for a bit. Notice I have set it $=$ to another variable $y$. I've done this because $\left(2\right)$ varies in the $y$ direction as we change our input $x$ (sometimes called a "free variable"). $y$ is then the *dependent* variable since it *depends* upon our input $x$. We might then write it as \begin{align} y=f\left(x\right)&=x^2-8x+16,\tag{3} \end{align} since $\left(3\right)$ is indeed a *function* of $x$. Now if we set $\left(3\right)$ equal to a definite number, like $0$, we are finding those values of $x$ that result in that fixed value. In this case we can use the quadratic formula to find those values: \begin{align} 0&=x^2-8x+16\\ \implies x&=\frac{8\pm\sqrt{64-4\left(1\right)\left(16\right)}}{2}\\ &=4.\tag{4} \end{align} I would highly recommend you take a look [here](https://math.stackexchange.com/a/49243/167604) to see how I have found $x$. Here is a graph of $\left(1\right)$ for a visual aid before I continue (the blue curve): ![enter image description here](https://i.stack.imgur.com/N5InP.png) In this specific instance, the *roots* of the quadratic are indeed the minimum. You will find that in the quadratic formula, more generally written as \begin{align} x&=\color{red}{\frac{-B}{2A}}\pm\color{blue}{\frac{\sqrt{B^2-4AC}}{2A}}\tag{5} \end{align} for a quadratic \begin{align} y=f\left(x\right)&=Ax^2+Bx+C,\tag{6} \end{align} the red part of $\left(5\right)$ finds the $x$-value of the *vertex* of the parabola, whereas the latter blue portion adds and subtracts the $x$-distance along the $x$-axis our roots are from the $x$ value of the vertex. Notice that in $\left(4\right)$ the "adding and subtracting" blue portion disappeared since the radical was $0$. Hence, the vertex and double-root of $\left(1\right)$, your problem, are at the same point. The parabola thus is sitting directly on the $x$-axis, which is apparent in the above plot. Once you have seen enough functions like $y=\left(x-4\right)^2$ you will notice immediately that the parabola's roots and vertex are at the same point $\left(4,0\right)$ since this is the same as shifting the graph of $y=x^2$ to the right four units by the "substitution" $x=x-4$. If you would like to locate the minimums of a function like $\left(1\right)$ you may use the concept of *derivatives* typically covered in introductory Calculus courses.
What it means is that it just barely touches the x-axis. And as that is the only real root the equation can have it means it doesn't move past or through the x-axis and that it therefore is the minimum point of the parabola.
58,679,774
I'm using **Retrofit 2 and OkHttp3** to data from server and I get error while using **Min\_SDK 17** and my device's API is **17** also I tried this answer :[How to fix Expected Android API level 21+ but was 19 in Android](https://stackoverflow.com/questions/56818660/how-to-fix-expected-android-api-level-21-but-was-19-in-android) Also I tried this answer <https://github.com/square/okhttp/issues/4597#issuecomment-461204144> but I get the same error . **my Gradle.Build class** ``` apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "some" minSdkVersion 17 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/DEPENDENCIES' } compileOptions { targetCompatibility = "8" sourceCompatibility = "8" } lintOptions { checkReleaseBuilds false // Or, if you prefer, you can continue to check for errors in release builds, // but continue the build even when errors are found: } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support:support-v13:28.0.0' implementation 'com.android.support:design:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' implementation 'com.android.support:recyclerview-v7:28.0.0' implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' implementation "com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0" implementation "com.squareup.okhttp3:okhttp:3.11.0" implementation "com.squareup.okhttp3:okhttp-urlconnection:3.11.0" implementation "com.squareup.okhttp3:logging-interceptor:3.11.0" implementation 'com.google.code.gson:gson:2.8.2' implementation 'net.alhazmy13.hijridatepicker:library:2.0.2' implementation group: 'com.github.msarhan', name: 'ummalqura-calendar', version: '1.1.9' implementation 'com.google.android.gms:play-services-maps:16.1.0' implementation 'com.google.android.gms:play-services-location:16.0.0' implementation 'com.google.android.gms:play-services-places:16.1.0' implementation 'com.github.jaiselrahman:FilePicker:1.0.2' implementation 'com.github.bumptech.glide:glide:4.5.0' implementation 'com.squareup.okhttp3:okhttp:3.13.1' implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.loopj.android:android-async-http:1.4.9' implementation 'com.google.android.gms:play-services-auth-api-phone:16.0.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } ``` **my API Client** ``` public class APIClient { private static Retrofit retrofit; private static OkHttpClient okHttpClient; public static Retrofit getInstanceRetrofit(){ if(okHttpClient==null) { initOkHttp(); } if(retrofit==null) { retrofit = new Retrofit.Builder() .baseUrl(Const.URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } private static void initOkHttp() { int REQUEST_TIMEOUT = 60; OkHttpClient.Builder httpClient = new OkHttpClient().newBuilder() .connectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS) .readTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS) .writeTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(interceptor); httpClient.addInterceptor(new Interceptor() { @Override public Response intercept(@NonNull Chain chain) throws IOException { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder() .addHeader("Accept", "application/json") .addHeader("Content-Type", "application/json"); Request request = requestBuilder.build(); return chain.proceed(request); } }); okHttpClient = httpClient.build(); } } ``` **my Logs** ``` 1-03 06:09:07.850 2827-2827/some E/AndroidRuntime: FATAL EXCEPTION: main Process: some, PID: 2827 java.lang.ExceptionInInitializerError at okhttp3.OkHttpClient.newSslSocketFactory(OkHttpClient.java:296) at okhttp3.OkHttpClient.<init>(OkHttpClient.java:262) at okhttp3.OkHttpClient.<init>(OkHttpClient.java:235) at some.Network.APIClient.initOkHttp(APIClient.java:40) at some.Network.APIClient.getInstanceRetrofit(APIClient.java:25) at some.MvpImplementation.DropdownImpInteractor.getDropdowns(DropdownImpInteractor.java:18) at some.MvpImplementation.DropdownImpPresenter.requestDropdowns(DropdownImpPresenter.java:21) at some.Views.LoginActivity.onCreate(LoginActivity.java:87) at android.app.Activity.performCreate(Activity.java:5231) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5001) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.IllegalStateException: Expected Android API level 21+ but was 19 at okhttp3.internal.platform.AndroidPlatform.buildIfSupported(AndroidPlatform.java:238) at okhttp3.internal.platform.Platform.findPlatform(Platform.java:202) at okhttp3.internal.platform.Platform.<clinit>(Platform.java:79) at okhttp3.OkHttpClient.newSslSocketFactory(OkHttpClient.java:296)  at okhttp3.OkHttpClient.<init>(OkHttpClient.java:262)  at okhttp3.OkHttpClient.<init>(OkHttpClient.java:235)  at some.Network.APIClient.initOkHttp(APIClient.java:40)  at some.Network.APIClient.getInstanceRetrofit(APIClient.java:25)  at some.MvpImplementation.DropdownImpInteractor.getDropdowns(DropdownImpInteractor.java:18)  at some.MvpImplementation.DropdownImpPresenter.requestDropdowns(DropdownImpPresenter.java:21)  at some.Views.LoginActivity.onCreate(LoginActivity.java:87)  at android.app.Activity.performCreate(Activity.java:5231)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)  at android.app.ActivityThread.access$800(ActivityThread.java:135)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:136)  at android.app.ActivityThread.main(ActivityThread.java:5001)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:515)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)  at dalvik.system.NativeStart.main(Native Method) ```
2019/11/03
[ "https://Stackoverflow.com/questions/58679774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11567530/" ]
The problem is that you have added `OkHttp` dependency twice. In your `build.gradle` you have: ``` dependencies { ... implementation "com.squareup.okhttp3:okhttp:3.11.0" ... implementation "com.squareup.okhttp3:okhttp:3.13.1" } ``` Starting with version 3.13.0 they removed support for Android < 5. You just need to delete the ``` implementation "com.squareup.okhttp3:okhttp:3.13.1" ``` line and it should work fine
In your gradle file you have: `implementation "com.squareup.okhttp3:okhttp:3.11.0"` The docs say: <https://square.github.io/okhttp/> > > OkHttp works on Android 5.0+ (API level 21+) and on Java 8+. > > > The OkHttp 3.12.x branch supports Android 2.3+ (API level 9+) and Java 7+. These platforms lack support for TLS 1.2 and should not be used. But because upgrading is difficult we will backport critical fixes to the 3.12.x branch through December 31, 2020. So you could try: `implementation "com.squareup.okhttp3:okhttp:3.12.0"`
41,652,029
There are many questions on stackoverflow asking about the error from symfony forms which states that the form's **view data** must an instance of the `data_class` option. e.g: [this one](https://stackoverflow.com/questions/29187899/the-forms-view-data-is-expected-to-be-an-instance-of-class-my-but-is-an) Now the whole point of [transformation](http://symfony.com/doc/2.7/form/data_transformers.html) is to obtain something that can be rendered in the view e.g: a string, and to get the model object in the backend, so it doesn't make sense to require that the **view data** is an instance of the `data_class` option, on the contrary, the **model data** is what is supposed to be an instance of `data_class` So what am I missing here?
2017/01/14
[ "https://Stackoverflow.com/questions/41652029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2268997/" ]
The question you mentioned is about having a **SINGLE** entity expected, but **ARRAY** of entities actual. So expectations about **VIEW** entity transformation result were failed. That means that **VIEW** data does not **represent** the **ENTITY** being instance of **data\_class**. So you either can perform further transformations to fullfil expectations, or relax the expectations by removing `data_class`. The point you are missing is that **VIEW** data is still the **instance of** `data_class`, but it was normalized and serialized.
I think you're not missing anything here. If you check the source code of `Form::getData()` you'll see `return $this->modelData;` there. So basically you're right. It is required that 'model data' is instance of 'data\_class'. Transformers are responsible to transform 'model data' to 'view data' and back. For example Tags objects array to comma separated string and back to objects.
7,237,789
I want to show a car's speeds on iPhone in real time. What can I use? Wouldn't using gps to calculate the car's speed take many seconds?
2011/08/30
[ "https://Stackoverflow.com/questions/7237789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/917725/" ]
``` (db.table.field1==x)&(db.table.field2==y) ``` See the book section on [logical operators](http://web2py.com/book/default/chapter/06#Logical-Operators).
For a more advanced version, you can append a query to a list and use python's reduce function. ``` queries=[] if arg1 == "x": queries.append(db.table.field == x) if arg2 == "y": queries.append(db.table.otherfield == y) # many conditions here.... query = reduce(lambda a,b:(a&b),queries) db(query).select() ```
33,998,688
I'm creating a WebView based Android app that enables the user to login onto a mobile operator. When I run the app the WebView opens the website but I get a message that the WebView doesn't allow cookies. I've tried various codes that I found here but none of them worked. Can anyone help me? Here is the code I'm using: ``` //in oncreate final CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this); final CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); cookieManager.removeSessionCookie(); String[] cookies = getCookie("https://myaccount.ee.co.uk/login-dispatch/?fa=register"); for (String cookie : cookies) { cookieManager.setCookie("https://myaccount.ee.co.uk/login-dispatch/?fa=register", cookie); } cookieSyncManager.sync(); webView.loadUrl("https://myaccount.ee.co.uk/login-dispatch/?fa=register"); ``` and the getCookies method: ``` public String[] getCookie(String siteName) { CookieManager cookieManager = CookieManager.getInstance(); String cookies = cookieManager.getCookie(siteName); String[] cookiesArray = cookies.split(";"); return cookiesArray; } ```
2015/11/30
[ "https://Stackoverflow.com/questions/33998688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892622/" ]
You have to enable javascript and then getting instance of cookie manager accept cookie By using javascriptenable cookie gets stored > > webView.getSettings().setJavaScriptEnabled(true); > CookieManager.getInstance().setAcceptCookie(true); > > >
@Darko. `CookieManager.getInstance()` is the CookieManager instance for your entire application. Hence, you enable or disable cookies for all the webviews in your application. Normally it should work if your webview is already initialized: <http://developer.android.com/reference/android/webkit/CookieManager.html#getInstance()> Maybe you call `CookieManager.getInstance().setAcceptCookie(true);` before you initialize your webview. Thanks,
63,951,583
I tried to implement the following line of code in python script for a telegram bot building using telebot. ``` @bot.message_handler(func=lambda msg:True if msg.text.startswith('/test')) def test_start(message): msg=bot.send_message(message.chat.id,'This feature is under developement') ``` Above code gives me a syntax error. ``` @bot.message_handler(func=lambda msg:True if msg.text.startswith('/test') else False) def test_start(message): msg=bot.send_message(message.chat.id,'This feature is under developement') ``` This code solves the syntax error, but still, it doesn't do what I want it to do. When a user sends '/test some text' I want to identify this and do some actions after that. I am relatively new to python and this is my first time using telebot and lambda functions. So please help me in 1. identifying why the 1st code gave me a syntax error. 2. How to implement this startswith('/test') properly. Thank you so much in advance.
2020/09/18
[ "https://Stackoverflow.com/questions/63951583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12856596/" ]
Because ternary operator has a specific syntax, that has to be followed: ``` <value if True> if <condition> else <value if False> ``` What you did in the first sample is: ``` <value if True> if <condition> ``` Also you don't have to do it like you did ``` True if msg.text.startswith('/test') else False ``` `.startswith()` returns `bool` on its own. It's unclear what decorator does, but why don't you just perform the check inside of the function? ``` @bot.message_handler def test_start(message): if msg.startswith('/test'): msg=bot.send_message(message.chat.id,'This is feature is under developement') ```
I think you are looking for something like that: ``` @bot.message_handler(func=lambda msg: True == msg.text.startswith("/test")) def starts_with_test(message): args = message.text.split(' '); for arg in args: bot.send_message(message.chat.id, "arg = " + arg) ``` It will handle only commands that started with "/test". Then you can use split(' ') to parce arguments. For some types of fields there can be limitaions. For example for "InlineKeyboardButton"->"callback\_data" field. It can be <= 64 bytes. Another handlers will work as intended.
53,822,430
Im searching for an easy way to find which percentage of the data is within certain intervals using python. Consider an array X of float values. I'd like to do something similar to quantiles: ``` X.quantile(np.linspace(0,1,11)) ``` But instead, I'd like to know which percentage of values are within -10 and 10, for example. ``` X.method([-10,10]) ``` I know I can do that with `scipy.stats.percentileofscore` doing ``` percentileofscore(X,10) - percentileofscore(X,-10) ``` I was wondering whether there's a simpler, implemented solution so I could do instead ``` X.method([a,b,c]) ``` Which would give me the percentage of values between the `min(X)` and `a`, `a` and `b`, `b` and `c`, and finally between `c` and `max(X)`
2018/12/17
[ "https://Stackoverflow.com/questions/53822430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2926257/" ]
A simple solution is to use `np.histogram`: ``` import numpy as np X = np.arange(20) values = [5, 13] # these are your a and b freq = np.histogram(X, bins=[-np.inf] + values + [np.inf])[0]/X.size print(freq) >> array([0.25, 0.4 , 0.35]) ```
***Setup*** ``` a = np.linspace(-15,15,1000) ``` --- No builtin method exists, but quite simple to define your own using `np.count_nonzero` and `size`. In general: ``` c = (a > -10) & (a < 10) np.count_nonzero(c) / a.size ``` You can wrap this in a function for convenience and to allow for cases where you want closed intervals: ``` def percent_between(a, lower, upper, closed_left=False, closed_right=False): """ Finds the percentage of values between a range for a numpy array Parameters ---------- a: np.ndarray numpy array to calculate percentage lower: int, float lower bound upper: int, float upper bound closed_left: closed left bound ( > vs >= ) closed_right: closed right bound ( < vs <= ) """ l = np.greater if not closed_left else np.greater_equal r = np.less if not closed_right else np.less_equal c = l(a, lower) & r(a, upper) return np.count_nonzero(c) / a.size ``` ``` percent_between(a, -10, 10) ``` ``` 0.666 ```
88,665
Witness: ``` $ ps f PID TTY STAT TIME COMMAND 31509 pts/3 Ss 0:01 -bash 27266 pts/3 S+ 0:00 \_ mysql -uroot -p 25210 pts/10 Ss+ 0:00 /bin/bash 24444 pts/4 Ss 0:00 -bash 29111 pts/4 S+ 0:00 \_ tmux attach 4833 pts/5 Ss+ 0:00 -bash 9046 pts/6 Ss 0:00 -bash 17749 pts/6 R+ 0:00 \_ ps f 4748 pts/0 Ss 0:00 -bash 14635 pts/0 T 0:02 \_ mysql -uroot -px xxxxxxxxxxxxxxxx 16210 pts/0 S+ 0:01 \_ mysql -uroot -px xxxxxxxxxxxxxxxx ``` How did ps know to hide the `mysql` passwords? Can I incorporate this into my own scripts to hide particular CLI attributes?
2013/08/29
[ "https://unix.stackexchange.com/questions/88665", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/9760/" ]
`ps` does not hide the password. Applications like mysql overwrite arguments list that they got. Please note, that there is a small time frame (possible extendible by high system load), where the arguments are visible to other applications until they are overwritten. [Hiding the process](https://unix.stackexchange.com/a/34224/15241) to other users could help. In general it is much better to pass passwords via files than per command line. In [this article](http://netsplit.com/2007/01/10/hiding-arguments-from-ps/) it is described for C, how to do this. The following example hides/deletes all command line arguments: ``` #include <string.h> int main(int argc, char **argv) { // process command line arguments.... // hide command line arguments if (argc > 1) { char *arg_end; arg_end = argv[argc-1] + strlen (argv[argc-1]); *arg_end = ' '; } // ... } ``` Look also at <https://stackoverflow.com/questions/724582/hide-arguments-from-ps> and <https://stackoverflow.com/questions/3830823/hiding-secret-from-command-line-parameter-on-unix> .
The **mysql** program replaces the password from the command line with `x` in [this line of code](http://bazaar.launchpad.net/~mysql/mysql-server/5.5/view/head:/client/mysql.cc#L1734): ``` while (*argument) *argument++= 'x'; // Destroy argument ```
2,602,133
I want to replace the first context of > > web/style/clients.html > > > with the java String.replaceFirst method so I can get: > > ${pageContext.request.contextPath}/style/clients.html > > > I tried ``` String test = "web/style/clients.html".replaceFirst("^.*?/", "hello/"); ``` And this give me: > > hello/style/clients.html > > > but when I do ``` String test = "web/style/clients.html".replaceFirst("^.*?/", "${pageContext.request.contextPath}/"); ``` gives me java.lang.IllegalArgumentException: Illegal group reference
2010/04/08
[ "https://Stackoverflow.com/questions/2602133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/128237/" ]
My hunch is that it is blowing up as $ is a special character. From [the documentation](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#replaceAll(java.lang.String)) > > Note that backslashes () and dollar > signs ($) in the replacement string > may cause the results to be different > than if it were being treated as a > literal replacement string. Dollar > signs may be treated as references to > captured subsequences as described > above, and backslashes are used to > escape literal characters in the > replacement string. > > > So I believe you would need something like ``` "\\${pageContext.request.contextPath}/" ```
`String test = "web/style/clients.html".replaceFirst("^.*?/", "\\${pageContext.request.contextPath}/");` should do the trick. $ is used for backreferencing in regexes
10,158,495
I have something here: ``` String b = "Test"; String a[] = b; ``` How to solve this problem? Why is wrong? I want to enter values from another string. But how?
2012/04/15
[ "https://Stackoverflow.com/questions/10158495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333938/" ]
Change your code to ``` | v UILabel *label = (UILabel *)[self.view viewWithTag:71]; ``` `UIViewController` does not have `viewWithTag:`, `UIView` does
viewwithTag is a method on UIView not on UIViewController. You'll probably have to call it like this: ``` UILabel *label = (UILabel *)[self.view viewWithTag:71]; ```
56,154,654
I'm trying to evaluate an ANN. I get the accuracies if I use `n_jobs = 1`, however, when I use `n_jobs = - 1` I get the following error. `BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.` I have tried using other numbers but it only works if I use `n_jobs = 1` This is the code I am running: `accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)` This is the error I am getting: ``` Traceback (most recent call last): File "<ipython-input-12-cc51c2d2980a>", line 1, in <module> accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1) File "C:\Users\javie\Anaconda3\lib\site- packages\sklearn\model_selection\_validation.py", line 402, in cross_val_score error_score=error_score) File "C:\Users\javie\Anaconda3\lib\site- packages\sklearn\model_selection\_validation.py", line 240, in cross_validate for train, test in cv.split(X, y, groups)) File "C:\Users\javie\Anaconda3\lib\site- packages\sklearn\externals\joblib\parallel.py", line 930, in __call__ self.retrieve() File "C:\Users\javie\Anaconda3\lib\site- packages\sklearn\externals\joblib\parallel.py", line 833, in retrieve self._output.extend(job.get(timeout=self.timeout)) File "C:\Users\javie\Anaconda3\lib\site- packages\sklearn\externals\joblib\_parallel_backends.py", line 521, in wrap_future_result return future.result(timeout=timeout) File "C:\Users\javie\Anaconda3\lib\concurrent\futures\_base.py", line 432, in result return self.__get_result() File "C:\Users\javie\Anaconda3\lib\concurrent\futures\_base.py", line 384, in __get_result raise self._exception BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.` ``` Spyder should have analyzed each batch in parallel, but even when I use `n_jobs = 1` it only analyzes 10 epochs.
2019/05/15
[ "https://Stackoverflow.com/questions/56154654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11493381/" ]
This always happens when using multiprocessing in an iPython console in Spyder. A workaround is to run the script from the command line instead.
If you use Spyder IDE simply switch to external terminal in settings (run>execute in an external system terminal).
13,252,186
I'm trying to summarize the difference between an "old" and "new" state of the codebase. * I could just do "git log", but sadly the commit messages aren't always sufficient. * I could do "git diff", but I'd like to see some explanations to the differences I'm seeing, or at least commit hashes to save for later * I could do a "git diff --stat" and then "git annotate" for the files that changed, but I don't see how to ask annotate to only show changes since a particular commit. Ideally, I'd like to get the output of "git diff" where all the "+" and "-" lines would be annotated with information about commits which last introduced these changes; ideally, in a git pretty format (e.g. hash, author and date). How can this be achieved?
2012/11/06
[ "https://Stackoverflow.com/questions/13252186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278042/" ]
You could write a small script which does something like ``` git blame before > before git blame after > after diff -u before after ``` :) See `man 1 git` re: `GIT_EXTERNAL_DIFF`.
I worked on a tool (python-based) to do exactly this... even counting for deleted lines doing something *close* to a reverse annotate (a reverse annotate is not exactly what is required because it will show the last revision where a line was *present*, it won't actually point to the revision where the line was deleted so it actually requires a little more analysis to figure out). I hope it suits your needs <https://github.com/eantoranz/difflame>
60,558,610
Is there a way to know when all the widgets are built in Flutter including FutureBuilder widgets. `WidgetsBinding.instance.addPostFrameCallback` is called when build is done, but before FutureBuilder is built. I have a List inside a FutureBuilder whose data is fetched from the server. There is another Text widget outside FutureBuilder which shows the count of list items. I need to update this count widget when the list is populated .Without using a stream is there a callback method triggered when the FutureBuilder is built.
2020/03/06
[ "https://Stackoverflow.com/questions/60558610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12972851/" ]
Just use `WidgetsBinding.instance.addPostFrameCallback` in your futurebuilder when has data and connection is done ``` FutureBuilder<List<Object>>( future: _listFuture, builder: (context, AsyncSnapshot snapshot) { if(snapshot.hasData && snapshot.connectionState == ConnectionState.done){ WidgetsBinding.instance .addPostFrameCallback((_) { }); } return ... } ); ```
There are many ways. If you intend to do this without using state management, you could use ValueNotifier. ``` ValueNotifier<int> total = ValueNotifier(0); FutureBuilder()..future.then((snapshot) { total.value = snapshot.total; }); ValueListenableBuilder( valueListenable: total, builder: (context, value, widget) { return Text(value.toString()); }, ), ``` Bu i suggest you use [provider package](https://pub.dev/packages/provider)
43,194,500
I want give some style to each row of the following UI. It shows simply a list of songs searched in my app but all the rows shown in a the same page without any kind of separation or a kind of line between each row. My idea is to differentiate each song or each row. If there is a nice style or Theme that separate each row with different colors it would be awesome also. This is my code; ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:ads="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:descendantFocusability="blocksDescendants" android:background="@drawable/white_selector" android:paddingTop="20dp" android:paddingBottom="20dp" android:paddingRight="16dp" android:paddingLeft="16dp"> <ImageView android:id="@+id/logo" android:layout_width="40dp" android:layout_height="30dp" android:layout_alignParentLeft="true" android:src="@mipmap/ic_launcher" android:contentDescription="@string/audio_play"/> <LinearLayout android:id="@+id/badges" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="4dp" android:layout_marginStart="4dp" android:layout_centerVertical="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true"> <ImageView android:id="@+id/play" android:layout_width="40dp" android:layout_height="30dp" android:src="@drawable/ic_play" android:contentDescription="@string/audio_play"/> <TextView android:id="@+id/duration" android:layout_width="40dp" android:layout_height="30dp" android:layout_marginLeft="5dp" android:layout_marginStart="5dp" android:textColor="@color/colorPrimaryDark" android:textSize="15sp" android:gravity="center" tools:text="3:05"/> </LinearLayout> <TextView android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/logo" android:layout_toEndOf="@id/logo" android:layout_toLeftOf="@+id/badges" android:layout_toStartOf="@+id/badges" android:textColor="@color/colorAccent" tools:text="Martin Garrix - Animals"/> </RelativeLayout> ```
2017/04/03
[ "https://Stackoverflow.com/questions/43194500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would advise you tu use a [listvew](/questions/tagged/listvew "show questions tagged 'listvew'") not only the design would be better but, as you said, you want to show a LIST of songs. You can still add images to the listview and add automatically a clicklistener to each of the items
Create List dynamically ----------------------- You can use `RecyclerView` to achieve this (It's better than `ListView`, as it reuse the cells while scrolling and other improvements over `ListView`). The easy way to use it, is using android studio to create a Fragment with dummy data and you need then to change the data to your model and do some changes. Right click on your app module -> New -> Fragment -> Fragment (List) [![android](https://i.stack.imgur.com/G4Gd4.png)](https://i.stack.imgur.com/G4Gd4.png) Then in your activity you can show the fragment using `getSupportFragmentManager().beginTransaction().replace(...)` or if you want to use it directly in your activity, then take look at the generated Fragment and adapt your activity to use the `RecyclerView`. Add divider between the items ([reference for details](https://stackoverflow.com/a/27037230/3469686)) ----------------------------------------------------------------------------------------------------- ``` DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), layoutManager.getOrientation()); recyclerView.addItemDecoration(dividerItemDecoration); ```
36,108,377
I want to count the number of times a word is being repeated in the review string I am reading the csv file and storing it in a python dataframe using the below line ``` reviews = pd.read_csv("amazon_baby.csv") ``` The code in the below lines work when I apply it to a single review. ``` print reviews["review"][1] a = reviews["review"][1].split("disappointed") print a b = len(a) print b ``` The output for the above lines were ``` it came early and was not disappointed. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it. ['it came early and was not ', '. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.'] 2 ``` When I apply the same logic to the entire dataframe using the below line. I receive an error message ``` reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1 ``` Error message: ``` Traceback (most recent call last): File "C:/Users/gouta/PycharmProjects/MLCourse1/Classifier.py", line 12, in <module> reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1 File "C:\Users\gouta\Anaconda2\lib\site-packages\pandas\core\generic.py", line 2360, in __getattr__ (type(self).__name__, name)) AttributeError: 'Series' object has no attribute 'split' ```
2016/03/19
[ "https://Stackoverflow.com/questions/36108377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2861976/" ]
You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling [apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) on the data frame: ``` f = lambda x: len(x["review"].split("disappointed")) -1 reviews["disappointed"] = reviews.apply(f, axis=1) ```
pandas 0.20.3 has **pandas.Series.str.split()** which acts on every string of the series and does the split. So you can simply split and then count the number of splits made ``` len(reviews['review'].str.split('disappointed')) - 1 ``` [pandas.Series.str.split](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html)
62,809
Imagine a scenario where a country around the size of New Zealand (in GDP, population, military strength and other areas) decides that it wants to take control of or at least destroy a much larger country (think Russia, USA or China). The following rules apply: * Neither country can call on other countries for help * Either country can take over and hold parts of their opponent (similar to how ISIS has taken over parts of the middle east) * The small country is run a lot like North Korea, with little to no regard for its citizens. They can devote almost all of its resources to the war and citizens (for the most part) actually approve of the war * The small country has even less regard for rules of war than it does for its own citizens. For arguments sake, the large country still has to maintain appearances and not anger the UN * The large country must at least try to keep its citizens happy because they are much more likely to revolt or disapprove of a long war * Both countries are at a similar, modern or near modern technology level * The countries are on the same planet, but can be situated however you like
2016/11/29
[ "https://worldbuilding.stackexchange.com/questions/62809", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/29989/" ]
How about trickery and guile? A clever, ruthless, well-resourced small country might pull this off by tricking the larger country into welcoming (even begging) the smaller country to come in and help them survive the horrible plague-X, when no other country can/will. Plague-X was, of course, artificially created/weaponized in the smaller/attacker for just this purpose. They created an incident on their own soil, as a basis for researching this disease and developing a cure. A cure they have stockpiled and willing to provide (to a fellow nation in need), but insist on administering themselves, to deal with known side effects. The cure does something nasty, like makes the populace (who's already scared and disoriented) highly suggestive and amenable to propaganda. The plague-curers are welcomed as heroes -- and never leave....
What is the nationality of the people in the big country? If there is a huge population from that small country it could be that the big country fails to mobilize because it needs to be paranoid about its own citizens and the guerrilla warfare has already begun. The small country can have naval or aerial overpower. If the big country is not self sufficient the time they can fight before they have to surrender could be fairly short. This would require the small country to be in a strategically vital position for the big country. These two could also explain why the small country gets its way to be a North-Korea without intervention.
14,825,896
Can anybody knows, How to Change Combobox Background Color while Clicked(ComboBox is Open) in WPF?
2013/02/12
[ "https://Stackoverflow.com/questions/14825896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2063564/" ]
Here's a slightly naive approach: ``` <ComboBox ItemsSource="{x:Static Fonts.SystemFontFamilies}" Width="100" > <ComboBox.Style> <Style TargetType="ComboBox"> <Setter Property="Background" Value="Green" /> <Style.Triggers> <Trigger Property="IsDropDownOpen" Value="True"> <Setter Property="Background" Value="Red" /> </Trigger> </Style.Triggers> </Style> </ComboBox.Style> </ComboBox> ``` Initially, this sets the `Background` property to `Green`, but arranges for it to go to `Red` when the drop-down appears. However, there are two problems with this: 1. In some Windows themes (e.g., the Aero theme used in Vista and Windows 7), the green background gets obscured by the bluish colour that theme uses to indicate that the dropdown's button has been pressed. So the button will briefly go green before fading to Cyan. 2. The `ComboBox.Background` property only affects the appearance of the button itself, and not the dropdown list. It's possible that what you actually want to do is change the background colour of the part that pops down. If 2 is what you wanted, this does the trick: ``` <ComboBox ItemsSource="{x:Static Fonts.SystemFontFamilies}" Width="100" > <ComboBox.Resources> <Style TargetType="ComboBoxItem"> <Setter Property="Background" Value="Orange" /> </Style> </ComboBox.Resources> </ComboBox> ``` Strictly speaking, that's actually changing the background colour of the `ComboBoxItem` controls that appear in the dropdown but that will have the desired effect. If you want to fix 1, though, you'll need a custom templates, because the built-in `ComboBox` template doesn't really provide very good support for the `Background` property, because it changes the colour of the button part under various circumstances. The Aero theme's look for a `ComboBox` really isn't designed to support a custom background colour, so you'd need to create your own custom look for the control.
Okay, to answer your question for code behind: Add Items to your Combo box: ``` foreach (String tag in tags) { ComboBoxItem item = new ComboBoxItem(); item.Content = tag; cbTags.Items.Add(item); } ``` Then you can modify the items background color: ``` ((ComboBox)o).Background = GetBrushByRGB(r, g, b); foreach (ComboBoxItem item in ((ComboBox)o).Items) { item.Background = GetBrushByRGB(r, g, b); } ``` So basically you need to change the ComboBoxItem's backcolor.
177,292
I get the category by calling the method from the repository: ``` $category = $this->_categoryRepository->get($id); ``` But I have multiple Store views, one for each language. I saw that the get method takes the store ID as second parameter. The problem is I only have the store view code. How can I get the category details by store code?
2017/06/02
[ "https://magento.stackexchange.com/questions/177292", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/42667/" ]
You need to use Magento 2's dependency injection system. It means in your block class in \_\_construct() method, inject Magento\Store\Model\StoreManagerInterface class as an object. Then you'll be able to get store view id. You need to do something like the following in your block class: ``` protected $storeManager; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Store\Model\StoreManagerInterface $storeManager, array $data = [] ) { $this->storeManager = $storeManager; parent::__construct($context, $data); } /** * Get store identifier * * @return int */ public function getStoreId() { return $this->storeManager->getStore()->getId(); } ``` If your current block class is `Magento\Catalog\Block\Category\View`, then you'd need to use di.xml to extend your own module's block class to this class. More information on extending classes in Magento 2 is [here](http://inchoo.net/magento-2/overriding-classes-magento-2/)
Please try this code- ``` $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface'); $storeid = $storeManager->getStore()->getStoreId(); $storecode = $storeManager->getStore()->getCode(); ```
9,718,116
I'd like some help improving the efficiency of my circular buffer code. I had a look around stackoverflow and found that (nearly) all of the topics on circular buffers are about the uses of such a buffer or the basic implementation of a circular buffer. I really need information about how to make it super efficient. The plan is to use this buffer with the STM32F4 microcontroller which has a single precicion FPU. I plan to make heavy use of especially the write() and readn() functions. We're literally talking a few million calls a second here so shaving of a few clock cycles here and there is really going to make a difference. I'll put the most important bits of code here, the full buffer code is available via <http://dl.dropbox.com/u/39710897/circular%20buffer.rar> Can anyone provide me with a few pointers on how to improve the efficiency of this buffer? ``` #define BUFF_SIZE 3 // buffer size set at compile time typedef struct buffer{ float buff[BUFF_SIZE]; int readIndex; int writeIndex; }buffer; /********************************\ * void write(buffer* buffer, float value) * writes value into the buffer * @param buffer* buffer * pointer to buffer to be used * @param float value * valueto be written in buffer \********************************/ void write(buffer* buffer,float value){ buffer->buff[buffer->writeIndex]=value; buffer->writeIndex++; if(buffer->writeIndex==BUFF_SIZE) buffer->writeIndex=0; } /********************************\ * float readn(buffer* buffer, int Xn) * reads specified value from buffer * @param buffer* buffer * pointer to buffer to be read from * @param int Xn * specifies the value to be read from buffer counting backwards from the most recently written value * i.e. the most recently writen value can be read with readn(buffer, 0), the value written before that with readn(buffer, 1) \********************************/ float readn(buffer* buffer, int Xn){ int tempIndex; tempIndex=buffer->writeIndex-(Xn+1); while(tempIndex<0){ tempIndex+=BUFF_SIZE; } return buffer->buff[tempIndex]; } ```
2012/03/15
[ "https://Stackoverflow.com/questions/9718116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989108/" ]
As "Oli Charlesworth" suggested - you'd be able to simplify things if your buffer size is a power of 2. I'd like to write the read/write function bodies, so that the intent is more clear. ``` #define BUFF_SIZE (4U) #define BUFF_SIZE_MASK (BUFF_SIZE-1U) struct buffer { float buff[BUFF_SIZE]; unsigned writeIndex; }; void write(struct buffer *buffer, float value) { buffer->buff[(++buffer->writeIndex) & BUFF_SIZE_MASK] = value; } float readn(struct buffer *buffer, unsigned Xn){ return buffer->buff[(buffer->writeIndex - Xn) & BUFF_SIZE_MASK]; } ``` Some explanations. Note that there's no branching (`if`) at all. We don't limit the array index to the array bounds, instead we're AND-ing it with the mask.
If you can make your buffer size a power-of-2, then the check against zero can be replaced with unconditional bit-masking. On most processors, this should be faster.
218,861
I already have 6 workflows running in one of my Document Library. If I am adding a new Workflow, it is throwing error as - "The query cannot be completed because the number of lookup columns it contains exceeds the lookup column threshold enforced by the administrator". I have gone through many articles on this. All suggested the default threshold is 8 lookup. [Reference](https://social.technet.microsoft.com/Forums/en-US/ba240e0c-2435-4215-bb70-41b374634172/the-query-cannot-be-completed-because-the-number-of-lookup-columns-it-contains-exceeds-the-lookup?forum=sharepointadminprevious) ... then why I am getting this on adding 7th WF. I don not have any other lookup field in Doc library I am working on Sharepoint Online. Is there any way to modify these default limits? Or If someone can explain about my issue? TIA
2017/06/21
[ "https://sharepoint.stackexchange.com/questions/218861", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/67552/" ]
We have to consider the `Created By` and `Modified By` columns also as lookup columns. Then the total will be 8 in your case and reaches maximum limit.
Remember that you are hitting the **list view** threshold, an actual SharePoint list can hold a lot of columns. But it is weird that you hit limit at 8 columns, as Microsoft states that 12 is the default in Office 365. Sounds like they either lowered it, or you might want to give them a call Do you really need to show all of your SharePoint workflow status columns in the same view/default view? As long as you don't have more than 8 lookup columns in your default view, you will be fine.
68,402,612
I am trying to import a CSV file to a new table in MySql. The file has 1 million rows but MySql is only importing 847 rows. 1. I tried saving the CSV file and importing various formats, utf-8, windows-1205, etc. 2. The CSV file has an INDEX column with sequential numbers that can be used as a primary key. 3. There are no invalid characters, such as commas. 4. I copied the CSV file and deleted the first 847 and imported it again, and it imported the next 26 rows. This shows that there is nothing wrong with the data and it could have imported it originally. Why won't the MySql Workbench import all million rows? [![enter image description here](https://i.stack.imgur.com/eRXkY.png)](https://i.stack.imgur.com/eRXkY.png)
2021/07/16
[ "https://Stackoverflow.com/questions/68402612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6108740/" ]
UPDATE: I tried importing with MSSQL (Using SSMS) and that not only gave me an error but told me what the problem was! I wasn't allocating enough space for the char fields as some values had long strings of text. All I did in SSMS was change it to VARCHAR(max) and SSMS imported all million rows. This might have been a solution for MySql but since MySQL Workbench didn't tell me what the exact problem was, I already uninstalled it and will continue with SSMS and MSSQL.
[![enter image description here](https://i.stack.imgur.com/2sxFa.jpg)](https://i.stack.imgur.com/2sxFa.jpg) Do not use command line, it need set up environment parameter to allow you import from local csv file. Instead use import wizard is much easier for me. [![enter image description here](https://i.stack.imgur.com/Adt9x.png)](https://i.stack.imgur.com/Adt9x.png) However I only import first 100 lines. I solve it by choose latin1 instead of default utf-8 <https://bugs.mysql.com/bug.php?id=89044> [![default utf-8 not work, latin1 works](https://i.stack.imgur.com/BO0pc.jpg)](https://i.stack.imgur.com/BO0pc.jpg)
16,801,396
Basically, when should I use Emacs Lisp's `function` procedure? I haven't found any examples in which there's a difference in behavior if you pass functions as arguments `'like-this` or `#'like-this`. In fact, if I evaluate `(eq 'goto-char #'goto-char)` it returns `t`. The Emacs Lisp code that I've come across *rarely* uses `function`/`#'`; the authors just `quote`/`'` everything. Example: `(add-hook 'emacs-lisp-hook 'turn-on-eldoc-mode)` However, I can find a few counterexamples. Here's one from the source code of Emacs 24.3's `electric.el`: ``` (add-hook 'post-self-insert-hook #'electric-indent-post-self-insert-function 'append) ``` Guesses and further questions: ------------------------------ * Is it just a Lisp-2 stylistic convention? * Does it have to do with byte-compilation? * Does it only matter for library writers? Like, if you intend for your code to be run under a huge number of environments and Emacs versions? (The corollary would be if you're just "dotfile-tinkering" then you don't need to worry about all this.) * When should I quote lambda-expressions? When can I leave them unquoted? E.g., `(do-something '(lambda …` *versus* `(do-something (lambda …` * Was there some limitation in an earlier version of Emacs that gave rise to these facets of elisp? Like, can I mostly ignore the difference between `'` and `#'` as long as I'm using a version of Emacs more recent than **X**?
2013/05/28
[ "https://Stackoverflow.com/questions/16801396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/600510/" ]
`function` (aka `#'`) is used to quote functions, whereas `quote` (aka `'`) is used to quote data. Now, in Emacs-Lisp a symbol whose function cell is a function is itself a function, so `#'symbol` is just the same as `'symbol` in practice (tho the intention is different, the first making it clear that one is not just talking about the symbol "symbol" but about the function named "symbol"). The place where the difference is not just stylistic is when quoting lambdas: `'(lambda ...)` is an expression which evaluates to a *list* whose first element is the symbol `lambda`. You're allowed to apply things like `car` and `cdr` to it, but you should not call it as if it were a function (although in practice it tends to work just fine). On the contrary `#'(lambda ...)` (which can be written just `(lambda ...)`) is an expression which evaluates to a *function*. That means you can't apply `car` to it, but the byte-compiler can look inside `#'(lambda ...)`, perform macro-expansion in it, warn you if what it finds doesn't look kosher, etc...; For lexical-binding it even *has to* look inside in order to find the free variables to which that function refers.
In elisp `#'` is (in effect) purely about byte-compilation (*edit: and since Emacs 24, also lexical closures*); but you'll also probably never need to use it. `#'...` is short-hand for `(function ...)` which is simply a variant of `'...` / `(quote ...)` that also hints to the byte-compiler that it can compile the quoted form as a function. However, in modern Emacs (IIRC this was not always the case), `(lambda ...)` is equivalent to `#'(lambda ...)`, so I believe you would rarely (if ever) *need* to write `#'`. You would also rarely ever want to use `'(lambda ...)`, for the reasons that Stefan has elaborated on (but `'symbol` is fine). This is covered in the manual under `C-h``i``g` `(elisp) Anonymous Functions` `RET` (although there appears to be an error in the last piece of example code, as it is identical to the previous example (in Emacs 24.3.1)). (n.b. Stefan's answer is definitive, but I'll keep this one here as it hopefully complements it.)
37,953,733
I have the following code in php ``` $test = "\151\163\142\156"; echo utf8_decode($test); var_dump($test); ``` and i get the following result: ``` isbn string(4) "isbn" ``` I get some text from a txt file that has the \151\163\142\156 text ``` $all_text = file_get_contents('test.txt'); var_dump($all_text); ``` result: ``` string(16) "\151\163\142\156" ``` I have the following questions: 1. how can i utf8 decode the second text so i get the isbn result? 2. how can i encode the isbn to get \151\163\142\156 ? **EDIT** *(from comments)* I tried everything with iconv and encode but nothing worked. The text from the .txt file is string(16) and not string(4) so i can encode it. The txt file is saved from sublime with Western (ISO 8859-1) encoding
2016/06/21
[ "https://Stackoverflow.com/questions/37953733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2160063/" ]
You need to use resolve in the parent state as $stateparams only contains params registered with that state. ``` state({ name: 'parent', url: '/parent', templateUrl: 'app/parent.html', controller: 'parentController', controllerAs: 'vm', resolve: { regionsCountriesInfo: ['$stateParams', function($stateParams){ return $stateParams.regionsCountriesInfo; }] } ```
i think each child create isolated varibles , did you try to repass it to child in routing ?
10,612,842
I have 5 occurence of UL on a single page. So , when i mouse-over one image then the same effect runs of every instance of UL(i.e. it changes the HTML of all 5 occurences). I want to execute the script on individual UL so that the effect runs on the respective UL where i mouse-hover instead of all of them. Live code example : <http://jsfiddle.net/5FPSc/> Thanks in advance. Any help / pointer would be of great help. / GSA HTML : ``` <ul class="answerOptions"> <li data-score="0" data-answer="A" class="answer-1"> <figure><img src="assets/images/styles/quiz/ques2_A.jpg" alt="" title="" /> <figcaption>Dinner and a movie</figcaption> </figure> </li> <li data-score="1" data-answer="B" class="answer-2"> <figure><img src="assets/images/styles/quiz/ques2_B.jpg" alt="" title="" /> <figcaption>2 words: Laser Tag</figcaption> </figure> </li> <li data-score="0" data-answer="C" class="answer-3"> <figure><img src="assets/images/styles/quiz/ques2_C.jpg" alt="" title="" /> <figcaption>Stroll through the park and a picnic</figcaption> </figure> </li> <li data-score="0" data-answer="D" class="answer-4"> <figure><img src="assets/images/styles/quiz/ques2_D.jpg" alt="" title="" /> <figcaption>Skydiving</figcaption> </figure> </li> <li data-score="4" data-answer="E" class="answer-5"> <figure><img src="assets/images/styles/quiz/ques2_E.jpg" alt="" title="" /> <figcaption>Art gallery and wine tasting</figcaption> </figure> </li> </ul> <div class="answerItem-1"></div> ``` SCRIPT : ``` $('.answerOptions figure').hover(function(){ $(".answerItem-1").html($(this).find("figcaption").html()); },function(){ if($('figure').hasClass('selected') != true){ $(".answerItem-1").html(""); } else { $(".answerItem-1").html($("figure.selected").find("figcaption").html()); } }); $('.answerOptions figure').click(function(){ $('figure').removeClass('selected'); $(this).addClass("selected"); $(".answerItem-1").html($(this).find("figcaption").html()); }); ```
2012/05/16
[ "https://Stackoverflow.com/questions/10612842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1389498/" ]
Your groupId and artifactId are reversed.
After installing maven 3 from a repository and added maven3 home in /etc/environment what I forgot to do is to reboot my machine, after that it worked. My /etc/environment now looks like: ``` M3_HOME="/home/edward/java/apache/maven-3.0.4" MAVEN_HOME="/home/edward/java/apache/maven-3.0.4" M3="home/edward/java/apache/maven-3.0.4" PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/edward/java/apache/maven-3.0.4" ``` Here's how I uninstalled and install maven 3: <http://czetsuya-tech.blogspot.com/2012/05/how-to-install-maven-3-in-ubuntu-1110.html>
17,278,331
Two possibilities come into my mind: * `NUMBER(4)` * `DATE` Pro `NUMBER(4)`: * No duplicate entries possible if specified as UNIQUE * Easy arithmetic (add one, subtract one) Con `NUMBER(4)`: * No Validation (e.g. negative numbers) Pro `DATE`: * Validation Con `DATE`: * Duplicate entries are possible ('2013-06-24', '2013-06-23', ...) * Not so easy arithmetic (add one = ADD\_MONTHS(12)) As additional requirement the column gets compared with the current year `EXTRACT (YEAR FROM SYSDATE)`. In my opinion `NUMBER(4)` ist the better choice. What do you think, is there another option I have missed?
2013/06/24
[ "https://Stackoverflow.com/questions/17278331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/237483/" ]
You can restrict a `date` column to only have one entry per year if you want to, with a function-based index: ``` create unique index uq_yr on <table> (trunc(<column>, 'YYYY')); ``` Trying to insert two dates in the same year would give you an ORA-00001 error. Of course, if you don't want the rest of the date then it may be unhelpful or confusing to hold it, but on the other hand there may be secondary info you want to keep (e.g. if you're recording that an annual audit happened, holding the full date might not hurt anything). You could also have a virtual column (from 11g) that holds the `trunc` value for easier manipulation, perhaps. You could also use an `interval year(4) to month` data type, and insert using `numtoyminterval(2013, 'year')`, etc. You could do interval arithmetic to add and subtract years, and `extract` to get the year back out as a number. That would probably be more painful than using a `date` though, overall. If you're really only interested in the year (and you are not holding the month in a different column!) then a number is probably going to be simplest, with a check constraint to make sure it's a sensible number - `number(4)` doesn't stop you inserting `2.013` when you meant `2,013` (though you need to be converting from a string to hit that, and not have an NLS parameter mismatch), which would be truncated to just `2`.
You've quite well summed up the pros/cons. Provided that you name clearly your field so that it's easy to understand that it contains a year information, I would go with a `NUMBER(4)` for simplicity & storing no more or less than what is necessary. And even if there is no validation, IMO negative years are valid :)
43,868,364
Hi I'm newbie in JSON and Ajax and my question is probably quite stupid but when learning, also the stupid questions are fundamental. I need to pass two parameters via Ajax (giorno and periodo), for example 'giorno' = 2017-05-10 and 'periodo' = 2: ``` $.ajax({ type:'POST', data: JSON.stringify({ giorno: $('#dataselezionata').val(), periodo: $('input:radio[name=periodo]:checked').val() }), contentType: "application/json; charset=utf-8", dataType : 'json', url:'http://www.rinnovipatenti.com/index2.php?a=prenotazione' }); ``` The JSON object passed perfectly and the result in Firebug Console is: ``` {"giorno":"2017-05-10","periodo":"2"} ``` If I try to manually copy and paste the object on the **php page** like this: ``` <? $json = '{"giorno":"2017-05-10","periodo":"2"}'; //pasted manually $json = json_decode($json, TRUE); $giorno = $json['giorno']; $periodo = $json['periodo']; echo"$giorno"; //2017-05-10 echo"$periodo"; //2 ?> ``` the two echoes show me the values. OK! **My problem start and stop here**. I'm not able to bring the JSON object to be decoded. I'm quite sure is a stupid solution but I don't know how to do that. I need to create a function that wrap the Ajax call and then call the function in json\_decode?? PS I also tried to simply get the values with "$\_POST['giorno']" etc.. instead of using JSON but without success. Can someone help me please? Thank you for your patience. **UPDATE 10/05/2017** Hi I've followed your suggestions so I tried one time more to simplify the code like this: ``` $('input:radio[name=periodo]').change(function() { var giorno = document.getElementById("dataselezionata").value; // from datepicker var periodo = $('input:radio[name=periodo]:checked').val(); // from radio button var post_data = ("giorno="+giorno+"&periodo="+periodo); $.ajax({ type:'GET', data: post_data, url:"http://www.rinnovipatenti.com/prenota/prenotazione.php", }); if (this.value == '1') { $('#orario').show(); $('#orari-mattina').show(); $('#orari-pomeriggio').hide(); } else if (this.value == '2') { $('#orario').show(); $('#orari-pomeriggio').show(); $('#orari-mattina').hide(); } ``` using GET method instead of the POST one and in the PHP page **prenotazione.php** the code now is: ``` <? $giorno = $_GET['giorno']; $periodo = $_GET['periodo']; echo"$giorno"; echo"$periodo"; ?> ``` In Firebug console the parameters are ok ``` giorno 2017-05-10 periodo 2 ``` the formatted link is: ``` http://www.rinnovipatenti.com/prenota/prenotazione.php?giorno=2017-05-10&periodo=2 ``` the html console preview works correctly but the page don't. I'm in the corner! Is very strange. I have only one doubt: can I send data by GET/POST method to the same page where the data are collected? In other word can the page foo.php send data to foo.php like a cycle without refresh? And the ajax call could be wrapped inside the .change function or must be outside?
2017/05/09
[ "https://Stackoverflow.com/questions/43868364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7929767/" ]
``` $.post( "http://www.rinnovipatenti.com/index2.php?a=prenotazione", { giorno: $('#dataselezionata').val(), periodo: $('input:radio[name=periodo]:checked').val() } ); ``` you do not need to stringify your JSON on PHP side you just use ``` $giorno = $_POST['giorno']; $periodo = $_POST['periodo']; ``` to get the values you can use the following function. you have it already. it worked fine for me. ``` $('input:radio[name=periodo]').change(function() { var giorno = '2017-05-15'; var periodo = '2'; $.post( 'http://www.rinnovipatenti.com/index2.php?a=prenotazione', { giorno: giorno, periodo: periodo }); /*....*/ }); ```
When you send `application/json` payload to php to access that payload use: ``` $json = json_decode(file_get_contents('php://input'), TRUE); ``` As mentioned in other comments and answers if you stay with `$.ajax` default form encoding and don't json stringify the data then use `$_POST`
42,649,047
I am new to Java (Android Studio), I need to create class and inside this class a method that load anything and after it finish loading, it invoke event on the main instance, which communicate with the main instance, for example in Xcode Swift IOS you can define method with completeHandler: ``` public static func getTheImage( imagePath: String,completeHanlder: @escaping (UIImage)->Void) { completeHanlder(image) } ``` and when you call the method ``` WriteFileHandlingMozeh.getTheImage(imagePath) { (img) in // do something here } ```
2017/03/07
[ "https://Stackoverflow.com/questions/42649047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7564643/" ]
You have copied the code from [Running Windows Service Application without installing it](https://stackoverflow.com/a/21722847), but it was broken by design and you altered it incorrectly. The thought behind it, is that you have a `ServiceBase`-inheriting class containing a public method that performs the actual service logic: ``` public class MyService : ServiceBase { public void DoTheServiceLogic() { // Does its thing } public override void OnStart(...) { DoTheServiceLogic(); } } ``` Then in your application, you can start it like this: ``` class Program { static void Main(string[] args) { ServiceBase[] ServicesToRun = new ServiceBase[] { new MyService() }; ServiceBase.Run(ServicesToRun); } } ``` This provides an executable application that can be installed as a Windows Service. But you don't want to have to install your service and then attach Visual Studio to debug it; that's a horribly inefficient workflow. So what the code you found attempts to do, as many approaches found online do, is to start the application with a certain command line flag, say `/debug`, which then calls the public method on the service logic - **without actually running it as a Windows Service**. That can be implemented like this: ``` class Program { static void Main(string[] args) { if (args.Length == 1 && args[0] == "/debug") { // Run as a Console Application new MyService().DoTheServiceLogic(); } else { // Run as a Windows Service ServiceBase[] ServicesToRun = new ServiceBase[] { new MyService() }; ServiceBase.Run(ServicesToRun); } } } ``` Now you can instruct Visual Studio to pass the `/debug` flag when debugging your application, as explained in [MSDN: How to: Set Start Options for Application Debugging](https://msdn.microsoft.com/en-us/library/1ktzfy9w(v=vs.100).aspx). That's slightly better, but still a bad approach. You should extract the service logic altogether, and write unit tests to be able to test your logic without having to run it inside an application, let alone a Windows Service.
Start with changing your code a bit : ``` static void Main(string[] args) { #if DEBUG // If you are currently in debug mode ClientService service = new ClientService (); // create your service's instance service.Start(args); // start this service Console.ReadLine(); // wait for user input ( enter key ) #else // else you're in release mode ServiceBase[] ServicesToRun; // start service normally ServicesToRun = new ServiceBase[] { new MyService() }; ServiceBase.Run(ServicesToRun); #endif } ``` In your service add this method : ``` public void Start(string[] args) { OnStart(args); } ``` Now all you need to change is in properties change application type from `Windows Application` to `Console Application`.
5,371,761
I installed Postgres on Windows 7, it only asks me for password not for username so what's the default. It is said here: > > When Postgres is installed in your account, there is a default user with the same name as the account (login) name > > > It's not crystal clear. Is it the username of my computer account?
2011/03/20
[ "https://Stackoverflow.com/questions/5371761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310291/" ]
I don't know what installer have you used but when I install it the username is clearly indicated: ![Postres' setup, password step](https://i.stack.imgur.com/ZZMvt.png)
"postgres" is the default user name
43,774,930
``` def highscore(): var = input("Please enter your nickname ") ### And then i want this to be saved within the txt file on my desktop. self.highscoreList.sort() #Sorterar listan man har med highscores (behövs ju inte om den redan är sorterad) if playerScore > self.highscoreList[0]: #Om spelarens poäng högre än lägsta highscore self.highscoreList[0] = playerScore #Byt ut det lägsta mot spelarens #Nånting sånt här iallafall... file = read("/Volumes/me SSD/Users/me/Desktop/Python/highscore.txt", "w") for highscore in self.highscoreList: #Sen skriva till fil! file.write(highscore) #Skriver highscores till filen, en för varje rad file.write("hej") #I have even tried to just have \n file.close() ``` I have made a game (minesweaper) in python 3.5.2 and when the player has played the game, I want him/her to enter his/her nickname so it will save the highscore in a (txt) file on the desktop. I tried to do this, but it won't save anything in the txt file. And also the player doesn't get the input to write down his/her nickname. I tried to have the file.close() in or without the loop, but it didn't work.
2017/05/04
[ "https://Stackoverflow.com/questions/43774930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7661363/" ]
In Python 3, the canonical way to write to a file is e.g., ``` with open("output.txt", "w") as output_file: print("my output", file=output_file) ``` Note that I opened the file inside an `with` block, so that it is automatically closed, and that I printed to the file by supplying a keyword argument `file` to Python 3's `print` function. You can use the extended `print` function in Python 2 by importing it first, ``` from __future__ import print_function ``` and then calling `print` as usual.
``` use this try: fil = open("/Volumes/Melinas SSD/Users/Melina/Desktop/Python/melinas.txt", "w") except: print('the file cannot be opened') for highscore in self.highscoreList: print('hello') file.write(highscore) file.write("hej") ```
160,497
I'm using subversion (TortoiseSVN) and I want to remove the .svn folders from my project for deployment, is there an automated way of doing this using subversion or do I have to create a custom script for this?
2008/10/02
[ "https://Stackoverflow.com/questions/160497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
public static: yes FileZilla has filename filtering. Look under View -> Filename Filters. I checked in v3.1.1 I think most FTP clients have it now.
Do `svn export <url>` to export a clean copy without .svn folders.
51,710,663
Scenario 1: * R1 = 02/08/2018 - 20/08/2018 * R2 = 06/08/2018 - 29/08/2018 ``` R1 |--------------| R2 |---------------------| ``` Scenario 2: * R1 = 02/08/2018 - 20/08/2018 * R2 = 31/08/2018 - 16/09/2018 ``` R1 |--------------| R2 |---------------------| ``` There are two different date ranges, and I need to compare these ranges to find out if they intersect or not. For example, in the first scenario, the ranges intersect and in the second scenario they do not. The dates are in `dd/MM/yyyy` format. What is the best way to determine if they intersect or not using Java? ``` def R1Initial = SDF.parse(u.effectiveStartDate.text()) def R1End = SDF.parse(u.mdfSystemEffectiveEndDate.text()) def R2Initial = SDF.parse(u.effectiveStartDate.text()) def R2End = SDF.parse(u2.mdfSystemEffectiveEndDate.text()) def intersects = ????? ```
2018/08/06
[ "https://Stackoverflow.com/questions/51710663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6460739/" ]
You can create [ranges of `LocalDate` instances in Groovy 2.5](http://groovy-lang.org/groovy-dev-kit.html#_ranges_code_upto_code_and_code_downto_code). Ranges (which extend Iterables) have an [`intersect` method](http://docs.groovy-lang.org/docs/latest/html/groovy-jdk/java/lang/Iterable.html#intersect(java.lang.Iterable)), which returns a collection of the overlapping days between two ranges. If the intersection is non-empty, you know that there is overlap: ``` import java.time.* def r1 = (LocalDate.of(2018, 8, 2)..LocalDate.of(2018, 8, 20)) def r2 = (LocalDate.of(2018, 8, 6)..LocalDate.of(2018, 8, 29)) def overlap = r1.intersect(r2) // returns a list containing August 6th through August 20th ```
The [Answer by bdkosher](https://stackoverflow.com/a/51710748/642706) looks correct, taking advantage of a nifty feature in Groovy. `org.threeten.extra.LocalDateRange` =================================== If doing much work with date-ranges, you may find helpful the [`LocalDateRange`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/LocalDateRange.html) class in the [*ThreeTen-Extra*](http://www.threeten.org/threeten-extra/) project. That class offers several methods for comparison: `abuts`, `contains`, `encloses`, `equals`, `intersection`, `isBefore`, `isAfter`, `isConnected`, [`overlaps`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/LocalDateRange.html#overlaps-org.threeten.extra.LocalDateRange-), `span`, and `union`. ``` LocalDateRange r1 = LocalDateRange.of( LocalDate.of( 2018, 8 , 2 ) , LocalDate.of( 2018 , 8 , 20 ) ) ; LocalDateRange r2 = LocalDateRange.of( LocalDate.of( 2018 , 8 , 6 ) , LocalDate.of( 2018 , 8 , 29 ) ) ; boolean overlaps = r1.overlaps( r2 ) ; ``` --- About *java.time* ================= The [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old [legacy](https://en.wikipedia.org/wiki/Legacy_system) date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), & [`SimpleDateFormat`](http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html). The [*Joda-Time*](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. To learn more, see the [*Oracle Tutorial*](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Specification is [JSR 310](https://jcp.org/en/jsr/detail?id=310). You may exchange *java.time* objects directly with your database. Use a [JDBC driver](https://en.wikipedia.org/wiki/JDBC_driver) compliant with [JDBC 4.2](http://openjdk.java.net/jeps/170) or later. No need for strings, no need for `java.sql.*` classes. Where to obtain the java.time classes? * [**Java SE 8**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8), [**Java SE 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9), [**Java SE 10**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10), and later + Built-in. + Part of the standard Java API with a bundled implementation. + Java 9 adds some minor features and fixes. * [**Java SE 6**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6) and [**Java SE 7**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7) + Much of the java.time functionality is back-ported to Java 6 & 7 in [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/). * [**Android**](https://en.wikipedia.org/wiki/Android_(operating_system)) + Later versions of Android bundle implementations of the *java.time* classes. + For earlier Android (<26), the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project adapts [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) (mentioned above). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). The [**ThreeTen-Extra**](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html).
83,719
As far as I was aware, although Princess Leia was Force sensitive, she hadn't undergone any training to put these powers to use and/or couldn't use any Force powers. > > However, when part of the ship she's on is attacked, she is blown into space. She then uses (I assume) the Force to keep herself alive while in space, and pull herself back to the ship. > > > If that's right, how did she manage to do all this? Before now, she hasn't done anything but 'feel' the Force and people connected to it.
2017/12/15
[ "https://movies.stackexchange.com/questions/83719", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/16624/" ]
**Short answer:** We don't know **Long answer:** That scene was more of tribute to Carrie Fisher's joke about her wishful death. From [vanityfair](https://www.vanityfair.com/hollywood/2017/12/star-wars-the-last-jedi-does-leia-die-carrie-fisher-in-episode-ix): > > The image can’t help but recall the late Fisher’s famous wish for her obituary, from her one-woman show Wishful Drinking. Recalling how Star Wars director George Lucas requested she go bra-less in the original trilogy, Fisher once joked: > > > > > > > George comes up to me the first day of filming and he takes one look at the dress and says, “You can't wear a bra under that dress.” > > So, I say, “Okay, I’ll bite. Why?” > > And he says, “Because . . . there’s no underwear in space.” > > What happens is you go to space and you become weightless. So far so good, right? But then your body expands??? But your bra doesn’t—so you get strangled by your own bra. Now I think that this would make for a fantastic obit—so I tell my younger friends that no matter how I go, I want it reported that I drowned in moonlight, strangled by my own bra. > > > > > > > > > But they later decided to keep her alive. From same source: > > But director Rian Johnson and Lucasfilm president Kathleen Kennedy eventually decided to leave Fisher’s role in The Last Jedi untouched. “We were a little ways into postproduction when she passed away, and so we had it mostly put together,” Johnson said. “We didn’t really end up changing it. And that includes adding lines back in that we had cut out or anything like that.” > > >
So I have an outrageously hidden possibility. What if Ben, as he didn't take the shot at the main bay of the ship, was taken aback that someone else did and used his own force powers to secure Leia and escort her safely back to the ship, untouched? It seems as if ideas of Leia having a last-ditch highly force sensitive move up her sleeve she didn't know about is far-fetched. I would bet money that Leia even knows Ben did that for her, and is further restored that Ben might still come out as an okay guy. Thoughts?
66,501,438
So I want to have a function for my game engine that I am writing in java, where it will return an object of type `T`. My code for the function goes like: ``` public <T> T getComponent(Class<T> tClass) { for(Component component : components) { if(component.getClass() == tClass) { return(T)component; } } return(null); } ``` And this works well and I can call it with `getComponent(Component.class);` However I want to be able to call it like I would with C# (`getComponent<Component>();`) so I am wondering if this is possible. Telling me if its possible or not would be great and giving me code to implement it would be even better, thank you for whatever contribution you make, even if its just reading this so that more people will see it.
2021/03/06
[ "https://Stackoverflow.com/questions/66501438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15281497/" ]
Use reshaping like this, `set_index` with Name and Key creating a multiIndex, then `unstack` the inner most index level to create columns: ``` df.set_index(['Name','Key'])['Val'].unstack() ``` Output: ``` Key A B Name David 1.0 NaN John 3.0 NaN Nat NaN 4.0 Roe NaN 2.0 ```
``` import pandas as pd data = {"Id": ["DA0445EA", "DA0445EA", "DA0445EA", "DA0445EA", "DA0445EA"], "Port" : [1,1,1,1,1], "Lane" :[None,None,None,None,None], "Key" : ["start", "start","case","case_start","end"], "Val":[0.1,0.1,0.3,0.4,0.5] } df = pd.DataFrame(data,columns=['Id', 'Port','Lane','Key','Val']) df1 = df.set_index(['Id', 'Port','Lane','Key'])['Val'].unstack() df1 = df1.reset_index() ``` Below is Error generated. The reason is "*There is two duplicate entry for same id*". Such entry is unavoidable for datatable I'm working on. I was expecting, It will overwrite same line in table and won't throw any error like below. ``` raise ValueError('Index contains duplicate entries, ' ValueError: Index contains duplicate entries, cannot reshape ``` Is there a way to avoid such error during Re-shaping?
24,979
I want to use a laptop which doesn’t save any data, history, passwords anywhere in it. All state information should be destroyed once it is turned off or rebooted, without removing my ability to use the OS or specific applications such as Explorer or some remote desktop apps like Radmin. I am used to Windows OS, but I can use Mac also for such purposes. The aim is that if I'm using the laptop and somebody approaches me, then simply pressing the power button will remove all context of what I've done.
2012/12/04
[ "https://security.stackexchange.com/questions/24979", "https://security.stackexchange.com", "https://security.stackexchange.com/users/16766/" ]
Jeff's answer covers more than I know about, but I can add a few side notes; There is the issue of page files and other non-volatile virtual memory. The general approach is to use an encrypted swap, with a key read from `/dev/random` on boot. On that note, you could just use full disk encryption, and have a 'panic' key combination hooked to a script that pipes some `/dev/random` onto your disk master-salt. Just don't press it by accident.
This is an old question, sorry. But in the context of unattended college computer lab and classroom machines, we used a product called [Deep Freeze](http://www.faronics.com/products/deep-freeze/) that undid any changes on reboot. It supports both Windows and Mac, and whenever we would get a call that someone had installed peer-to-peer software on a classroom machine, we'd just remotely reboot the computer and it'd be gone. Another option along with the excellent LiveCD suggestions everyone else has.
27,435,837
I'm running a node.js server on heroku using the express.js framework. Here is what my server looks like: ``` var express = require('express'); var app = express(); app.use(express.static(__dirname + '/static')); var port = process.env.PORT || 8000; app.listen(port); ``` My index.html file has the following javascript links: ``` <script src="/js/chartview.js"></script> <script src="/js/bootstrap.js"></script> <script src="/js/bootstrap-select.js"></script> ``` My directory system looks like this: ``` server.js /static -index.html -/js -bootstrap.js -bootstrap-select.js -chartview.js -/css -bootstrap.css -bootstrap-select.css -styles.css ``` Chrome displays my html page with the appropriate css styles but the console says: ``` Failed to load resource: the server responded with a status of 404 (Not Found) https://websitename.herokuapp.com/js/chartview.js Failed to load resource: the server responded with a status of 404 (Not Found) https://websitename.herokuapp.com/js/bootstrap.js Failed to load resource: the server responded with a status of 404 (Not Found) https://websitename.herokuapp.com/js/bootstrap-select.js ``` It loads properly when I change my index.html tags to look like this: ``` <script src="chartview.js"></script> <script src="bootstrap.js"></script> <script src="bootstrap-select.js"></script> ``` And I change my directory systems to look like this: ``` server.js /static -index.html -bootstrap.js -bootstrap-select.js -chartview.js -/css -bootstrap.css -bootstrap-select.css -styles.css ``` This is not Ideal, as I would like to have a /js folder. Any suggestions will be greatly appreciated!
2014/12/12
[ "https://Stackoverflow.com/questions/27435837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4166838/" ]
Try Placing your files in the public folder and use the path like this""
Don't use "\_\_dirname" Only using ``` app.use(express.static('static')); ```
410,673
From my understanding, clustering algorithms require complete data. Based on this, if there are missing values in my dataset I have two options: 1. Impute missing information using some sort of imputation method 2. Get rid of observations that contain missing values Sometimes I believe neither approach is appropriate, as ignoring observations can remove a lot of important information (sometimes all information, if there is always 1 missing value per obs for example) - and imputation methods are not 100% accurate. As such, are there any clustering methods that do not require either of these options? In other words, algorithms that use the partial information from observations that don't have complete values, without discarding them? (looking at the information they do have in common) This would allow me to assign these observations to clusters without applying any imputation methods to the data.
2019/05/29
[ "https://stats.stackexchange.com/questions/410673", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/172728/" ]
Some clustering algorithms rely on the [Expectation-Maximisation](https://stats.stackexchange.com/questions/72774/numerical-example-to-understand-expectation-maximization) (EM) algorithm and its variants, e.g. k-means (deterministic- partition clustering), Gaussian mixture models (probabilistic, model-based clustering), etc. In these, the cluster membership of the observations are regarded as the latent variable and a version of the EM algorithm is applied to find maximum likelihood or maximum a posteriori (MAP) estimates in the existence of these latent variables There exist extensions of the EM algorithm that can cater for missing values. Have a look at this [thesis](https://www.math.leidenuniv.nl/scripties/MasterWilson.pdf) for an example of such an extension. As a final note, and as you allude to, it is crucial to examine the reason for the absent values before trying to address the missing data problem. In general we want to discover if the data is missing randomly Missing at Random, (MAR) or Missing Completely at Random, (MCAR), or if the absent values are related to the response data (Not Missing at Random, NMAR). For instance, deleting missing values may give biased results when the MCAR assumption is violated.
Say feature `X1` may be missing. If `X1` is categorical, you could add a `missing` level and proceed. If `X1` is continuous, you could set it to the mean value of non-missing `X1`’s and create a categorical variable `X1_missing` that is True only when `X1` is missing. This assumes a clustering algorithm that can handle categorical variables.
56,381,044
Planning to Migrate the Websphere from 7.0 to 9 and 8.5 to 9. Can anyone help me getting the detailed Process Migration here is "In place". (Migration will be done on the same servers, where the old Installation are in) if at all any migration tools need to be used, please provide the clear info on them. any documental references, or any video references for the questioner is appreciated. OS used : RHEL CUrrent version: WAS 7x and 8.5 Migrating to : WAS 9.0
2019/05/30
[ "https://Stackoverflow.com/questions/56381044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11578878/" ]
Could you please share your PDF document, The issue may be with the PDF document containing different media types.
Just resolved it. Change the Content-Type to 'application/pdf' and in the body, send through the contents of the PDF, it doesn't seem to work with just the path.
6,902,284
I have a class that is handling printing the various messages into the console, lets call this class ConsoleMessages.java. This class is public and abstract and all its methods are public and static. I want to make an interface to this class (lets call it PrintMessages). I mean so, that ConsoleMessages.java will implement PrintMessages. The thing is, JAVA doesn't support static methods in an interface. What would you advise me to do?
2011/08/01
[ "https://Stackoverflow.com/questions/6902284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/861467/" ]
* Create the `PrintMessages` interface with the methods you desire. * Make `ConsoleMessages` a class that implements that interface. Change all methods from static to non static. * Enforce `ConsoleMessages` instantiation as a [singleton](http://es.wikipedia.org/wiki/Singleton). This can be achieved in many ways, either doing it yourself or using a [Dependency Injection framework](http://code.google.com/p/google-guice/).
There is really no strong arguement against static methods in interface. Nothing bad would happen. An interface can have static fields and static member classes though, therefore static methods can be attached through them, albeit with one extra indirection. ``` interface MyService static public class Factory static public MyService get(...) return ...; MyService service = MyService.Factory.get(args); ```
608,786
I am trying to create a script that will count down to 0 from what ever number I give it. Below is my script and basically nothing happens, no error message, I merely get the standard command line prompt back. ``` #!/bin/bash #countdown #counts down to 0 from whatever number you give it #displaying a number each second NUM=${1:-0} if [ $NUM -gt 0 ] then while [ $NUM -gt 0 ] do if [ -f /usr/bin/banner ] then /usr/bin/banner "$NUM" else echo $NUM fi NUM=$(($NUM-1)) sleep 2 done fi ```
2015/04/13
[ "https://askubuntu.com/questions/608786", "https://askubuntu.com", "https://askubuntu.com/users/388100/" ]
``` #!/bin/bash printf "Type an integer number: " && read NUM if [ $NUM -gt 0 ] then while [ $NUM -ge 0 ] do if [ -f /usr/bin/banner ] then /usr/bin/banner "$NUM" else echo $NUM fi NUM=$(($NUM-1)) sleep 2 done fi ``` output: ``` :~$ ./countdown.sh Type an integer number: 10 10 9 8 7 6 5 4 3 2 1 0 ``` explanation: ⠀1. line 3 prompts the user to input an integer number and reads it into the variable NUM. ⠀2. Changed the `-gt` in line 6 to `-ge` so that it counts down to zero. ⠀3. The output is displayed in banner format if sysvbanner is installed or else as text if it isn't.
**Improved and commented code:** ``` #!/bin/bash num=${1:-undefined} # If $1 (the first argument passed to the script) is set, then num=$1, else num=undefined. cmd=$(which {banner,echo} | head -1 | xargs basename) # If banner is installed, then cmd=baner, else cmd=echo. until [[ "$num" =~ ^[0-9]+$ ]]; do # Until $num become a valid number (loop will not be executed if $1 is set): read -p "Type a number: " num # Ask the user for a valid number. done # End of the until loop. for ((num;num>=0;num--)); do # Loop using $num as variable; while $num is greater or equal than zero; num=$num-1. $cmd $num # Runs $cmd (banner or echo) passing $num as argument. sleep 1 # Stop the program execution for one second. done # End of the for loop. ``` The above code will include zero in the countdown, if do you want to stop when the countdown reaches **1**, then you only need to make a few changes: 1. In the 6th line, change `^[0-9]+$` by `^[1-9]+[0-9]*$` so it looks like this: ``` until [[ "$num" =~ ^[1-9]+[0-9]*$ ]]; do # Until $num become a valid number (loop will not be executed if $1 is set): ``` 2. In the 10th line, remove the `=` sign so it looks like this (I've updated also the comment): ``` for ((num;num>0;num--)); do # Loop using $num as variable; while $num is strictly greater than zero; num=$num-1. ``` --- **Your original program doesn't work because:** * You not passed a number as argument to the program. * A example invocation of this command is `./countdown 5` where `5` is the number. * If do you want to handle this, you can add a `else` to your code (look a the five last lines): ``` #!/bin/bash #countdown #counts down to 0 from whatever number you give it #displaying a number each second NUM=${1:-0} if [ $NUM -gt 0 ] then while [ $NUM -gt 0 ] do if [ -f /usr/bin/banner ] then /usr/bin/banner "$NUM" else echo $NUM fi NUM=$(($NUM-1)) sleep 2 done else echo "Error: number not specified." echo "Usage: $0 <number>" exit 1 fi ``` --- `NUM=${1:-0}` **means:** > > `${PARAMETER:-WORD}` > > > If the parameter `PARAMETER` is unset (never was defined) or null > (empty), this one expands to `WORD`, otherwise it expands to the value > of `PARAMETER`, as if it just was `${PARAMETER}`. > > > > ``` > echo "Your home directory is: ${HOME:-/home/$USER}." > echo "${HOME:-/home/$USER} will be used to store your personal data." > > ``` > > If `HOME` is unset or empty, everytime you want to print something > useful, you need to put that parameter syntax in. > > > **Source:** <http://wiki.bash-hackers.org/syntax/pe#use_a_default_value> In your case, it means that, if you passed a argument to the script, `NUM` will be equal to that argument, else, `NUM` will be equal to `0`
24,474,197
I am looking for a very basic example of establishing a data channel using WebRTC. The `peer_connection` examples given are for audio/video and I am not able to run them to understand the code flow and write code for data channel on my own. I have done this using JavaScript for browser, now want to do the same for native application.
2014/06/29
[ "https://Stackoverflow.com/questions/24474197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3136200/" ]
have you tried the glob module? ``` import os, glob def globit(srchDir): srchDir = os.path.join(srchDir, "*") for file in glob.glob(srchDir): print file globit(file) if __name__ == '__main__': dir = r'C:\working' globit(dir) ```
Generators are better solutions as they do lazy computations here is one example of implementation. ``` import os import fnmatch #this may or may not be implemented def list_dir(path): for name in os.listdir(path): yield os.path.join(path, name) #modify this to take some pattern as input def os_walker(top): for root,dlist,flist in os.walk(top): for name in fnmatch.filter(flist, '*.py'): yield os.path.join(root, name) all_dirs = list_dir("D:\\tuts\\pycharm") for l in all_dirs: for name in os_walker(l): print(name) ``` Thanks to [David Beazley](http://www.dabeaz.com)
1,711,566
I am currently extracting data for a research, and I want to automatically copy the data to multiple sheets when a condition is fulfilled, as the data keeps being updated over time. I am aware that this question may be similar to an [earlier question](https://superuser.com/questions/1343583/copy-data-from-one-sheet-to-another-if-criteria-met-relative-rows), but I believe my question is different because I am trying to copy an entire entry rather than a single data cell, hence the `INDEX` and `MATCH` as well as the `VLOOKUP` functions may not be relevant. Below is the illustration of my data (the actual data consist of tens of columns and thousands of rows): [Dataset](https://i.stack.imgur.com/WmtjR.png) From the data in the `Master sheet`, I want to filter out studies which investigates 'Infectious disease' and 'Treatment', and **copy** them to the sheet called `Infectious disease x Treatment`. I want this to be done for each variable (3 unique Topic entries and 3 unique Focus entries, hence a total of 9 sheets). I want the process to be done automatically, meaning that new inputted data which fulfills the condition will be automatically copied to the corresponding sheet. The result should look like this: [Filtered data from the Master sheet](https://i.stack.imgur.com/Et7Rw.png) [Filtered data is then copied to the corresponding sheet](https://i.stack.imgur.com/Uukk7.png) Is this technically possible with Excel without the use of VBA? Any help will be appreciated. Thanks in advance
2022/03/18
[ "https://superuser.com/questions/1711566", "https://superuser.com", "https://superuser.com/users/1677995/" ]
That doesn't say "Windows Server" – it says "**Window** Server". A window server is the OS component which handles the display of application windows on your screen – such as their stacking order, positioning, focus (i.e. delivering input to the right window), and composing individual windows into the single final image. Here's a longer explanation of the macOS 'WindowServer' specifically: * <https://eclecticlight.co/2020/06/08/windowserver-display-compositor-and-input-event-router/> It is also known as "Quartz Compositor" (Quartz being the entire macOS GUI environment): * <https://web.archive.org/web/20040925095929/http://developer.apple.com/documentation/MacOSX/COnceptual/SystemOverview/SystemArchitecture/chapter_3_section_4.html> Similarly, `Xorg` on Linux would be "window server" for the X Window System aka X11 (though it does leave quite a few tasks to a separate window manager program), and `dwm.exe` may be the closest equivalent in Windows.
### I am tempted to just `rm -r` everything in the `SkyLight.framework` directory I don't think you want to do that. > > WindowServer is a core part of macOS, and a liaison of sorts between > your applications and your display. If you see something on your Mac’s > display, WindowServer put it there. Every window you open, every > website you browse, every game you play—WindowServer “draws” it all on > your screen. You can [read more at Apple’s developer guide](https://developer.apple.com/library/content/technotes/tn2083/_index.html#//apple_ref/doc/uid/DTS10003794-CH1-SUBSECTION14) if > you’re technically inclined, but it’s not exactly light reading. > > > For the most part, just know that WindowServer is what macOS, and > every application you run on it, uses in order to display things on > your screen. **It is completely safe**. > > > (Emphasis mine) Source: [What Is the Process WindowServer, and Why Is It Running on My Mac?](https://www.howtogeek.com/312755/what-is-the-process-windowserver-and-why-is-it-running-on-my-mac/)
16,410,340
I am learning structure padding and packing in C. I have this doubt, as I have read padding will depend on architecture, so does it affect inter machine communication?, ie. if data created on one machine is getting read on other machine. How this problem is avoided in this scenario.
2013/05/07
[ "https://Stackoverflow.com/questions/16410340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2333014/" ]
`#pragma pack` is supported by most compilers that I know of. This can allow the programmer to specify their desired padding method for structs. <http://msdn.microsoft.com/en-us/library/2e70t5y1%28v=vs.80%29.aspx> <http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html> <http://clang.llvm.org/docs/UsersManual.html#microsoft-extensions>
In C/C++ a structures are used as data pack. It doesn't provide any data encapsulation or data hiding features (C++ case is an exception due to its semantic similarity with classes). Because of the alignment requirements of various data types, every member of structure should be naturally aligned. The members of structure allocated sequentially increasing order.
37,028,529
Am I still following the Builder pattern with the implementation below? What's confusing me is the protected constructor in the class "myClass". My first thought when it comes to the builder pattern is to hide the object that the builder is supposed to construct. But here we don't. I can't understand if this is just bad design or ok design. ``` public class MyClass{ private final String x; private final String y; protected MyClass(MyBuilder builder){ this.x = builder.getX(); this.y = builder.getY(); } //getters... } public class MyBuilder{ private String X; private String Y; public MyBuilder withX(String x){ this.x = x; return this; } public MyBuilder withY(String y){ this.y = y; return this; } public MyClass build(){ return new MyClass(this); } //getters.... } public class Main{ public static void main(){ //Example 1 MyClass myClass = new MyBuilder().withX("x").withY("y").build(); //Example 2 MyClass myClass2 = new MyClass(new MyBuilder().withX("x").withY("y")); } } ```
2016/05/04
[ "https://Stackoverflow.com/questions/37028529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2565146/" ]
The constructor is `protected` in order to restrict the possibilty of creating new instances of `myClass` outside the protected scope. This looks a bit strange because usually a builder uses `private` constructor to totally avoid the creation of the instance by the client code without using the builder. If you really want to hide the constructor of the class to build, you can create your builder as an inner class of the class to build : ``` public static class MyClass{ private final String x; private final String y; private MyClass(MyBuilder builder){ this.x = builder.x; this.y = builder.y; } public static class MyBuilder{ private String x; private String y; public MyBuilder(){ } public MyClass build() { return new MyClass(this); } public MyBuilder withX(String x){ this.x = x; return this; } public MyBuilder withY(String y){ this.y = y; return this; } } } ``` In this case the only way to create a new instance is using the builder, because the constructor of `MyClass` is now **private**. ``` MyClass myClass = new MyBuilder().withX("xXx").withY("yYy").build(); ```
Different than builder implementations that I've seen (not saying it wouldn't work though). The protected constructor confuses me as well. How would this get called unless you've created another class which extended `myClass`? At which point your builder might function differently for the extended class. I'm used to using fluent builders that return an instance of the object it's building, but maybe that's just my preference. Class to build: ``` public class myClass{ private final String x; private final String y; public myClass(String x, String y){ this.x = x; this.y = y; } } ``` Builder: ``` public class myBuilder{ private String X = "Default X"; private String Y = "Default Y"; public myBuilder withX(String x){ this.x = x; return this; } public myBuilder withY(String y){ this.y = y; return this; } public myClass build(){ return new myClass(y, x); } } ``` Calling: ``` new myBuilder().withX("x").withY("y").build(); ``` returns new `myClass` with `x` = "x" and `y` = "y" ``` new myBuilder().build(); ``` returns new `myClass` with `x` = "Default X" and `y` = "Default Y"
822,247
I'm considering developing an app for Google App Engine, which should not get too much traffic. I'd really rather not pay to exceed the free quotas. However, it seems like it would be quite easy to cause a denial of service attack by overloading the app and exceeding the quotas. Are there any methods to prevent or make it harder to exceed the free quotas? I know I could, for example, limit the number of requests from an IP (making it harder to exceed the CPU quota), but is there any way to make it harder to exceed the requests or bandwidth quotas?
2009/05/04
[ "https://Stackoverflow.com/questions/822247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83871/" ]
There are no built-in tools to prevent DoS. If you are writing Google Apps using java then you can use the `service.FloodFilter` filter. The following piece of code will execute before any of your Servlets do. ``` package service; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; /** * * This filter can protect web server from simple DoS attacks * via request flooding. * * It can limit a number of simultaneously processing requests * from one ip and requests to one page. * * To use filter add this lines to your web.xml file in a <web-app> section. * <filter> <filter-name>FloodFilter</filter-name> <filter-class>service.FloodFilter</filter-class> <init-param> <param-name>maxPageRequests</param-name> <param-value>50</param-value> </init-param> <init-param> <param-name>maxClientRequests</param-name> <param-value>5</param-value> </init-param> <init-param> <param-name>busyPage</param-name> <param-value>/busy.html</param-value> </init-param> </filter> <filter-mapping> <filter-name>JSP flood filter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> * * PARAMETERS * * maxPageRequests: limits simultaneous requests to every page * maxClientRequests: limits simultaneous requests from one client (ip) * busyPage: busy page to send to client if the limit is exceeded * this page MUST NOT be intercepted by this filter * */ public class FloodFilter implements Filter { private Map <String, Integer> pageRequests; private Map <String, Integer> clientRequests; private ServletContext context; private int maxPageRequests = 50; private int maxClientRequests = 10; private String busyPage = "/busy.html"; public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { String page = null; String ip = null; try { if ( request instanceof HttpServletRequest ) { // obtaining client ip and page URI without parameters & jsessionid HttpServletRequest req = (HttpServletRequest) request; page = req.getRequestURI(); if ( page.indexOf( ';' ) >= 0 ) page = page.substring( 0, page.indexOf( ';' ) ); ip = req.getRemoteAddr(); // trying & registering request if ( !tryRequest( page, ip ) ) { // too many requests in process (from one client or for this page) context.log( "Flood denied from "+ip+" on page "+page ); page = null; // forwarding to busy page context.getRequestDispatcher( busyPage ).forward( request, response ); return; } } // requesting next filter or servlet chain.doFilter( request, response ); } finally { if ( page != null ) // unregistering the request releaseRequest( page, ip ); } } private synchronized boolean tryRequest( String page, String ip ) { // checking page requests Integer pNum = pageRequests.get( page ); if ( pNum == null ) pNum = 1; else { if ( pNum > maxPageRequests ) return false; pNum = pNum + 1; } // checking client requests Integer cNum = clientRequests.get( ip ); if ( cNum == null ) cNum = 1; else { if ( cNum > maxClientRequests ) return false; cNum = cNum + 1; } pageRequests.put( page, pNum ); clientRequests.put( ip, cNum ); return true; } private synchronized void releaseRequest( String page, String ip ) { // removing page request Integer pNum = pageRequests.get( page ); if ( pNum == null ) return; if ( pNum <= 1 ) pageRequests.remove( page ); else pageRequests.put( page, pNum-1 ); // removing client request Integer cNum = clientRequests.get( ip ); if ( cNum == null ) return; if ( cNum <= 1 ) clientRequests.remove( ip ); else clientRequests.put( ip, cNum-1 ); } public synchronized void init( FilterConfig config ) throws ServletException { // configuring filter this.context = config.getServletContext(); pageRequests = new HashMap <String,Integer> (); clientRequests = new HashMap <String,Integer> (); String s = config.getInitParameter( "maxPageRequests" ); if ( s != null ) maxPageRequests = Integer.parseInt( s ); s = config.getInitParameter( "maxClientRequests" ); if ( s != null ) maxClientRequests = Integer.parseInt( s ); s = config.getInitParameter( "busyPage" ); if ( s != null ) busyPage = s; } public synchronized void destroy() { pageRequests.clear(); clientRequests.clear(); } } ``` * From: <http://forums.sun.com/thread.jspa?threadID=5125779&tstart=13545> If you are using python, then you may have to roll your own filter.
It's always possible to use a service that provides Denial of Service protection features in front of an App Engine application. For example, Cloudflare provides a well respected service <https://www.cloudflare.com/waf/>, and there are others. It's my understanding (disclaimer: I haven't used the service personally) that these features are available on the free plan. It's also fairly easy to construct a memcache based rate limiting implementation in your application itself. Here's the first hit I got from a google search for this method: <http://blog.simonwillison.net/post/57956846132/ratelimitcache>. This mechanism is sound, and can be cost effective as shared memcache usage may suffice and is free. Furthermore, going this route puts you in control of the knobs. The drawback is that the application itself must handle the HTTP request and decide to allow or deny it, so there may be cost (or [free] quota exhaustion) to deal with. Full Disclosure: I work at Google on App Engine, and have no association with Cloudflare or Simon Willison.
21,980,073
Maybe I'm using git-submodules not on purpose, but if there's any other git feature which satisfies my case, would be nice to find it. After cloning repository, I want submodule to be in master branch, I'll never store any additional files inside of chef-starter submodule. ``` git clone git@github.com:holms/vagrant-starter.git git submodule update --init cd chef-starter git branch * (detached from 0b6a803) master ``` I do understand that it's a nice feature to track that submodule dir tree separately, but it's not my case. After main repository clone, I just want that submodule would be cloned to the latest master stage without any additional fuss. How can I achieve this?
2014/02/24
[ "https://Stackoverflow.com/questions/21980073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310662/" ]
The submodule has a detached head because a submodule means "check out a specific commit from the submodule's repository". The `master` branch may have moved forward (it may point to a commit that descends from commit `0b6a803`), so Git checks out the specific revision instead of checking out a branch. `git-submodule` has the option to record a branch name. When you do this, you can use `git submodule update --remote` to update the submodule with that branch: ``` # Add the submodule with the "master" branch referenced git submodule add -b master https://github.com/holms/chef-starter.git chef-starter # When you want to update the submodule: git submodule update --remote # You'll still need to commit the submodule if you want future checkouts to use the new revision git add chef-starter git commit -m "Update chef-starter submodule" ``` You'll still get a detached head in the submodule when you start checking out different versions of the super project (`vagarant-starter`), but at least now it's easier to update the submodule to the latest version from the remote. You may find it easier to use git-subtree instead of submodules: ``` # First, get rid of the submodule git submodule deinit chef-starter # If you have Git 1.8.3 or later, otherwise edit .gitmodules git rm chef-starter # Remove the directory git commit -m "Removed chef-starter submodule in preparation to add as a subtree" # Now add the subtree git subtree add -P chef-starter https://github.com/holms/chef-starter master --squash ``` This grafts the `chef-starter` repo into the `chef-starter/` directory in your `vagrant-starter` repo. From that point forward, you don't have to do anything special if you choose to edit files in the subtree. For instance, you don't have to run `git submodule update` after cloning.
To ensure my submodules stay synced and undetached, I have the following in a batch file. It relies on adopting the policy of syncing to the submodule's master branch - for me this isn't a problem, I just fork the submodule and ensure it has a master. I find it's much easier to keep track of things with this approach. ``` git pull git submodule sync # Ensure the submodule points to the right place git submodule update # Update the submodule git submodule foreach git checkout master # Ensure subs are on master branch git submodule foreach git pull origin master # Pull the latest master ```
14,174,673
I'm trying to set URL Scheme for my app. I read this [tutorial](http://mobiledevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html) and it works perfectly when I call `myapp://test` from an other app or from Safari app and Mail app (iOS native apps). But how can I do in order to open my app from an other app (Chrome, Gmail, etc...) ? Thanks.
2013/01/05
[ "https://Stackoverflow.com/questions/14174673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1820433/" ]
It's seems to be not possible. It's just possible with the iOS native apps for the moment :)
You can set a secret key like `myapp://test`. You can do this under your project settings -> URL type. In there you need to define your secret key. When entering this key into your safari browser your app is being opened automaticly.
17,831,193
I need to make a plot with only points and tried something like ``` plot(x,y) ``` where `x` and `y` are vectors: collection of points. I do not want matlab to connect these points itself. I want to plot as if plotted with ``` for loop plot;hold on; end ``` I tried ``` plot(x,y,'.'); ``` But this gave me too thick points. I do not want to use forloop because it is time expensive. It takes a lot of time.
2013/07/24
[ "https://Stackoverflow.com/questions/17831193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2178841/" ]
You're almost there, just change the MarkerSize property: ``` plot(x,y,'.','MarkerSize',1) ```
You may try this piece of code that avoid using loops. The plot created does not have lines but markers of different colors corresponding to each column of matrices `x` and `y`. ``` %some data (matrix) x = repmat((2:10)',1,6); y = bsxfun(@times, x, 1:6); set(0,'DefaultAxesColorOrder', jet(6)); %set the default matlab color figure('Color','w'); plot(x,y,'p'); %single call to plot axis([1 11 0 70]); box off; legend(('a':'f')'); ``` This gives ![enter image description here](https://i.stack.imgur.com/j8YvT.png)
16,373,134
I'm currently working (a repo is [here](https://github.com/wishi/blogdev/blob/master/js/example1.js)) on a Hypertree graph, which I want to use from the [JavaScript InfoVis Toolkit](http://philogb.github.io/jit/docs.html). The issue is as follows: I added the specific events to the Hypertree, which are `onClick` and `onRightClick`. ``` Events: { enable: true, onClick: function(node, eventInfo, e) { ht.controller.onComplete(); }, onRightClick: function(node, eventInfo, e) { ht.controller.onComplete(); }, }, ``` Then I simply attached the veent handlers to the Hypertree labels, just modifying [demo-code](http://philogb.github.io/jit/static/v20/Jit/Examples/Hypertree/example1.html) a little: ``` //Attach event handlers and add text to the //labels. This method is only triggered on label //creation onCreateLabel: function(domElement, node){ domElement.innerHTML = node.name; $jit.util.addEvent(domElement, 'click', function () { ht.onRightClick(node.id, { onComplete: function() { ht.controller.onComplete(); } }); }); $jit.util.addEvent(domElement, 'rclick', function () { ht.onClick(node.id, { onComplete: function() { ht.controller.onComplete(); } }); }); }, ``` That's pretty straight forward. The documentation for Hypertree events is in [Options.Events.js](http://philogb.github.io/jit/static/v20/Docs/files/Options/Options-Events-js.html#Options.Events). Now I load the page... and I have the left.clicks. But no right clicks... I want the RightClicks to move the graph and the onClicks to open a link from the DOM Element node. Can someone please give me a pointer here? Best, Marius
2013/05/04
[ "https://Stackoverflow.com/questions/16373134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59300/" ]
Try this `Query` for `MYSQL` ``` select distinct greatest(t1.A, t1.B), least(t1.A, t1.B) from your_table t1 , your_table t2 where t1.B=t2.A and t1.A=t2.B ``` **[SQL Fiddle](http://www.sqlfiddle.com/#!2/96eba/8)** **[Refer my Answer. Only the inner Query](https://stackoverflow.com/questions/16342712/sql-query-how-to-get-items-from-one-col-paired-with-another-but-not-visa-versa/16343404#16343404)** **`Edit`** **SQL SERVER** Version ``` select * from (select case when t1.A>t1.B then t1.A end as A1, case when t1.A>t1.B then t1.B end as B1 from your_table t1 , your_table t2 where t1.B=t2.A and t1.A=t2.B)t where t.A1 is not null ``` **[SQL Fiddle](http://www.sqlfiddle.com/#!3/96eba/5)**
in your query add one more where condition - leftparam<=rightparam. it will eliminate all duplicate reversed pairs. 80|100 ok, 100|80 removed.
60,888,188
I try to get a specific substring out of a string as often as it apears in Python. The substring will be different every time, but the structure will be the same. Example: ``` [{u'style': u'opacity:0.58800001;fill:#0000ff;fill-opacity:1; stroke:none;stroke-width:3.47952747; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none; stroke-dashoffset:0;stroke-opacity:1', u'id': u'rect5231', u'd': u'm 0,1016.9291 35.433071,0 0,35.433 -35.433071,0 z '},{u'style': u'opacity:0.58800001;fill:#0000ff;fill-opacity:1; stroke:none;stroke-width:3.47952747;stroke-linecap:round; stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none; stroke-dashoffset:0;stroke-opacity:1', u'id': u'rect5233', u'd': u'm 70.866142,1016.9291 35.433068,0 0,35.433 -35.433068,0 z '}] ``` Thats the string I have and I only need seperates substring beginning with "m..." I tried str.split but it removes to much an only output the second marked substring.
2020/03/27
[ "https://Stackoverflow.com/questions/60888188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13135805/" ]
You can use [`.flatMap()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) and [`Set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) for this: ```js let data = [ { winner: 'Alishah', loser: 'Bob', loser_points: 3 }, { winner: 'Maria', loser: 'Xu Jin', loser_points: 1 }, { winner: 'Elise', loser: 'Bob', loser_points: 2 }, { winner: 'Elise', loser: 'Maria', loser_points: 4 }, { winner: 'Alishah', loser: 'Maria', loser_points: 2 }, { winner: 'Maria', loser: 'Xu Jin', loser_points: 3 }, { winner: 'Xu Jin', loser: 'Elise', loser_points: 2 } ]; const res = [...new Set(data.flatMap(x=>[x.winner, x.loser]))] console.log( res ) ``` **Explanation:** * Using `.flatMap()` method we will first get an array of arrays. Here the inner array will be array of `winner` & `loser` names. * Then we will flatten the array to get a single array of all player's name. * And finally using `[...new Set(array)]` we will get distinct names in the array to achieve the desired result.
Using map and filter ```js let array = [ { winner: 'Alishah', loser: 'Bob', loser_points: 3 }, { winner: 'Maria', loser: 'Xu Jin', loser_points: 1 }, { winner: 'Elise', loser: 'Bob', loser_points: 2 }, { winner: 'Elise', loser: 'Maria', loser_points: 4 }, { winner: 'Alishah', loser: 'Maria', loser_points: 2 }, { winner: 'Maria', loser: 'Xu Jin', loser_points: 3 }, { winner: 'Xu Jin', loser: 'Elise', loser_points: 2 } ]; let winners = array.map(i => i.winner).filter((x, i, a) => a.indexOf(x) == i) console.log(winners); ```
3,952,539
I'm developing a project for doing **Content Based Image Retrieval** where front end will be in java. The main issue is about choosing tool for performing image processing. Since Matlab provides a lot of functionality for doing CBIR. But the main problem about using Matlab is that you need to have Matlab installed on every computer using the application. Is there any other way in which I can do my project (Using other tools or driver) so that my application will run without using any other tools ??? Or can I develop entire application in Matlab only and deploy it as a standalone application ??? Thank you..
2010/10/17
[ "https://Stackoverflow.com/questions/3952539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1150236/" ]
[Java image utilities](http://sourceforge.net/projects/jiu/) library: A Java library for loading, editing, analyzing and saving pixel image files. It supports various file formats. Provides demo applications for the command line. It has AWT GUI toolkit too.
I think [OpenCV](http://sourceforge.net/projects/opencv/) is one of the best libraries out there for image processing but [Java Advanced Imaging](http://java.sun.com/javase/technologies/desktop/media/jai/) is also quite good but doesn't has as much features and examples. Color similarity would be simple in JAI but shape probably would involve more code. If you choose to use OpenCV I think you have at least two possible binding implementations for Java. The one my group uses is this [one](http://ubaa.net/shared/processing/opencv/). It has some Processing dependencies. Regardless of what library you choose be prepared for some frustration. Matlab users are used to all the nice features it provides and when they have to port their code to other languages end having to write a lot more code.
35,478,969
error: `02-18 10:10:24.260: E/AndroidRuntime(5769): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.opencv.samples.facedetect/activity.CameraTest}: android.view.InflateException: Binary XML file line #33: Error inflating class fragment` Application with face detection camera. * Have a user profile page with a button to test whether face detection camera is working * When click on the button it opens **FaceDetectTest.class** which has the **test\_activity.xml** which includes the **fdActivity.class** fragment. * This has been done so I can have a tool bar at the top of the page to return to the previous screen, so I don't have to make loads of FdActivity classes I have an application where face detection is used. Using open CV I have an fdActivity class which runs the face detection code. I have changed this from an activity to a fragment, so that I can re use it throughout code. For instance I have a user profile page where they can click a button to see whether the face detection works. This opens an activity called TestActivity which view implements the fdActivity fragment to view the face detection camera & also have a toolbar at the top for returning to the previous page. **test\_detec\_activity.xml which is used by TestActivity.class** [![test_detection_activity.xml](https://i.stack.imgur.com/3UfmZ.png)](https://i.stack.imgur.com/3UfmZ.png) ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <RelativeLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/bg_login" android:orientation="vertical" > <Button android:id="@+id/btnReturnProfile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/Profile" /> <TextView android:id="@+id/headingText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="35dp" android:layout_marginStart="35dp" android:layout_toRightOf="@+id/btnReturnProfile" android:layout_toEndOf="@+id/btnReturnProfile" android:text="@string/faceDetetRequir" /> </RelativeLayout> <fragment android:id="@+id/fragment1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/linearLayout1" class="openCV.facedetect.FdActivity" /> ``` **TestActivity.class** ``` package activity; import org.opencv.samples.facedetect.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.View; import android.widget.Button; import helper.SessionManager; public class CameraTest extends FragmentActivity implements View.OnClickListener{ private Button btnReturnProfile; private SessionManager session; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.test_detection_activity); super.onCreate(savedInstanceState); session = new SessionManager(getApplicationContext()); setViewsFromLayout(); setListenersFromLayout(); } @Override public void onClick(View v) { if (v == btnReturnProfile){ launchIntentToProfilePage(); addCheckedCameraToSession(); finish(); } } private void addCheckedCameraToSession(){ session.setCheckedCameraBeforeTest(true); } private void launchIntentToProfilePage(){ Intent intent = new Intent(getApplicationContext(), UserProfile.class); startActivity(intent); } private void setViewsFromLayout(){ btnReturnProfile = (Button) findViewById(R.id.btnRegister); } private void setListenersFromLayout(){ btnReturnProfile = (Button) findViewById(R.id.btnReturnProfile); } } ``` **the fragment code:** (changed fdActivity of openCV) ``` package openCV.facedetect; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame; import org.opencv.android.OpenCVLoader; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfRect; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.android.CameraBridgeViewBase; import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2; import org.opencv.android.LoaderCallbackInterface; import org.opencv.objdetect.CascadeClassifier; import org.opencv.samples.facedetect.R; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; public class FdActivity extends Fragment implements CvCameraViewListener2 { private static final String TAG = "OCVSample::Activity"; private static final Scalar FACE_RECT_COLOR = new Scalar(0, 255, 0, 255); public static final int JAVA_DETECTOR = 0; public static final int NATIVE_DETECTOR = 1; private MenuItem mItemFace50; private MenuItem mItemFace40; private MenuItem mItemFace30; private MenuItem mItemFace20; private MenuItem mItemType; private Mat mRgba; private Mat mGray; private File mCascadeFile; private CascadeClassifier mJavaDetector; private DetectionBasedTracker mNativeDetector; private int mDetectorType = JAVA_DETECTOR; private String[] mDetectorName; private float mRelativeFaceSize = 0.2f; private int mAbsoluteFaceSize = 0; private CameraBridgeViewBase mOpenCvCameraView; private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(getActivity()) { @Override public void onManagerConnected(int status) { switch (status) { case LoaderCallbackInterface.SUCCESS: { Log.i(TAG, "OpenCV loaded successfully"); // Load native library after(!) OpenCV initialization System.loadLibrary("detection_based_tracker"); try { // load cascade file from application resources InputStream is = getResources().openRawResource(R.raw.lbpcascade_frontalface); File cascadeDir = getActivity().getDir("cascade", Context.MODE_PRIVATE); mCascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml"); FileOutputStream os = new FileOutputStream(mCascadeFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } is.close(); os.close(); mJavaDetector = new CascadeClassifier(mCascadeFile.getAbsolutePath()); if (mJavaDetector.empty()) { Log.e(TAG, "Failed to load cascade classifier"); mJavaDetector = null; } else Log.i(TAG, "Loaded cascade classifier from " + mCascadeFile.getAbsolutePath()); mNativeDetector = new DetectionBasedTracker(mCascadeFile.getAbsolutePath(), 0); cascadeDir.delete(); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "Failed to load cascade. Exception thrown: " + e); } mOpenCvCameraView.enableView(); } break; default: { super.onManagerConnected(status); } break; } } }; public FdActivity() { mDetectorName = new String[2]; mDetectorName[JAVA_DETECTOR] = "Java"; mDetectorName[NATIVE_DETECTOR] = "Native (tracking)"; Log.i(TAG, "Instantiated new " + this.getClass()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.face_detect_surface_view, container, false); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { Log.i(TAG, "called onCreate"); super.onCreate(savedInstanceState); getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mOpenCvCameraView = (CameraBridgeViewBase) getView().findViewById(R.id.fd_activity_surface_view); mOpenCvCameraView.setCameraIndex(1); mOpenCvCameraView.setCvCameraViewListener(this); } @Override public void onPause() { super.onPause(); if (mOpenCvCameraView != null) mOpenCvCameraView.disableView(); } @Override public void onResume() { super.onResume(); OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, getActivity(), mLoaderCallback); } public void onDestroy() { super.onDestroy(); mOpenCvCameraView.disableView(); } public void onCameraViewStarted(int width, int height) { mGray = new Mat(); mRgba = new Mat(); } public void onCameraViewStopped() { mGray.release(); mRgba.release(); } public Mat onCameraFrame(CvCameraViewFrame inputFrame) { mRgba = inputFrame.rgba(); mGray = inputFrame.gray(); if (mAbsoluteFaceSize == 0) { int height = mGray.rows(); if (Math.round(height * mRelativeFaceSize) > 0) { mAbsoluteFaceSize = Math.round(height * mRelativeFaceSize); } mNativeDetector.setMinFaceSize(mAbsoluteFaceSize); } MatOfRect faces = new MatOfRect(); if (mDetectorType == JAVA_DETECTOR) { if (mJavaDetector != null) mJavaDetector.detectMultiScale(mGray, faces, 1.1, 2, 2, // TODO: objdetect.CV_HAAR_SCALE_IMAGE new Size(mAbsoluteFaceSize, mAbsoluteFaceSize), new Size()); } else if (mDetectorType == NATIVE_DETECTOR) { if (mNativeDetector != null) mNativeDetector.detect(mGray, faces); } else { Log.e(TAG, "Detection method is not selected!"); } Rect[] facesArray = faces.toArray(); for (int i = 0; i < facesArray.length; i++) Core.rectangle(mRgba, facesArray[i].tl(), facesArray[i].br(), FACE_RECT_COLOR, 3); return mRgba; } @Override public boolean onOptionsItemSelected(MenuItem item) { Log.i(TAG, "called onOptionsItemSelected; selected item: " + item); if (item == mItemFace50) setMinFaceSize(0.5f); else if (item == mItemFace40) setMinFaceSize(0.4f); else if (item == mItemFace30) setMinFaceSize(0.3f); else if (item == mItemFace20) setMinFaceSize(0.2f); else if (item == mItemType) { int tmpDetectorType = (mDetectorType + 1) % mDetectorName.length; item.setTitle(mDetectorName[tmpDetectorType]); setDetectorType(tmpDetectorType); } return true; } private void setMinFaceSize(float faceSize) { mRelativeFaceSize = faceSize; mAbsoluteFaceSize = 0; } private void setDetectorType(int type) { if (mDetectorType != type) { mDetectorType = type; if (type == NATIVE_DETECTOR) { Log.i(TAG, "Detection Based Tracker enabled"); mNativeDetector.start(); } else { Log.i(TAG, "Cascade detector enabled"); mNativeDetector.stop(); } } } } ``` **face\_detect\_surface.xml** ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <org.opencv.android.JavaCameraView android:id="@+id/fd_activity_surface_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" /> ``` I'm new to using fragments, and I'm just looking for a way to reuse the fdActivity rather than make loads of different versions for different screens. Thanks **Edit stack trace** ``` 02-18 11:20:02.315: E/AndroidRuntime(7273): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.opencv.samples.facedetect/activity.CameraActivity}: android.view.InflateException: Binary XML file line #33: Error inflating class fragment 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2049) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2083) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.ActivityThread.access$600(ActivityThread.java:134) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1233) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.os.Handler.dispatchMessage(Handler.java:99) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.os.Looper.loop(Looper.java:137) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.ActivityThread.main(ActivityThread.java:4697) 02-18 11:20:02.315: E/AndroidRuntime(7273): at java.lang.reflect.Method.invokeNative(Native Method) 02-18 11:20:02.315: E/AndroidRuntime(7273): at java.lang.reflect.Method.invoke(Method.java:511) 02-18 11:20:02.315: E/AndroidRuntime(7273): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787) 02-18 11:20:02.315: E/AndroidRuntime(7273): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554) 02-18 11:20:02.315: E/AndroidRuntime(7273): at dalvik.system.NativeStart.main(Native Method) 02-18 11:20:02.315: E/AndroidRuntime(7273): Caused by: android.view.InflateException: Binary XML file line #33: Error inflating class fragment 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.view.LayoutInflater.rInflate(LayoutInflater.java:739) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 02-18 11:20:02.315: E/AndroidRuntime(7273): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:255) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.Activity.setContentView(Activity.java:1879) 02-18 11:20:02.315: E/AndroidRuntime(7273): at activity.CameraActivity.onCreate(CameraActivity.java:25) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.Activity.performCreate(Activity.java:4539) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2013) 02-18 11:20:02.315: E/AndroidRuntime(7273): ... 11 more 02-18 11:20:02.315: E/AndroidRuntime(7273): Caused by: java.lang.NullPointerException 02-18 11:20:02.315: E/AndroidRuntime(7273): at openCV.facedetect.FaceDetectionFragment.onCreateView(FaceDetectionFragment.java:66) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:806) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1010) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1108) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.app.Activity.onCreateView(Activity.java:4317) 02-18 11:20:02.315: E/AndroidRuntime(7273): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:673) 02-18 11:20:02.315: E/AndroidRuntime(7273): ... 21 more ```
2016/02/18
[ "https://Stackoverflow.com/questions/35478969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1860870/" ]
Given: ``` IDictionary<string, object> dict = new Dictionary<string, object>() { { "1", new Dictionary<string, object>() { { "name", "John" }, { "score", 5 } } }, { "2", new Dictionary<string, object>() { { "name", "Pete" }, { "score", 4 } } }, }; ``` You can: ``` var ordered = dict.OrderBy(x => (int)((IDictionary<string, object>)x.Value)["score"]).ToArray(); ``` It is quite ugly, and if the `score` is missing then you'll get an exception. If the `score` could be missing: ``` public static TValue GetValueOrDefault<TKey, TValue>(IDictionary<TKey, TValue> dict, TKey key) { TValue value; dict.TryGetValue(key, out value); return value; } ``` and then ``` var ordered = dict.OrderBy(x => (int?)GetValueOrDefault((IDictionary<string, object>)x.Value, "score")).ToArray(); ```
``` IEnumerable<User> OrderByScore(IDictionary<string,object> firebaseList) { return from user in firebaseList.Values.Cast<IDictionary<string,object>>() let name = (string) user["name"] let score = int.Parse(user["score"].ToString()) orderby score descending select new User { Name = name, Score = score}; } class User { public string Name {get;set;} public int Score {get;set;} } ```
23,866
When you enter a search into [google ngrams](https://books.google.com/ngrams), the graph shows the words/strings down the right hand side. What if you could pick search terms such that reading the right hand side of the graph, from top to bottom, makes an actual sentence... **Challenge** What is the longest sentence you can create in google ngrams by reading the search terms down the right hand side of the graph? **Example** A nice simple one to start you off. I give you, for a score of 4: > > [This sentence scores poorly.](https://books.google.com/ngrams/graph?content=This%2Csentence%2Cscores%2Cpoorly&year_start=1800&year_end=2000&corpus=15&smoothing=3&share=&direct_url=t1%3B%2CThis%3B%2Cc0%3B.t1%3B%2Csentence%3B%2Cc0%3B.t1%3B%2Cscores%3B%2Cc0%3B.t1%3B%2Cpoorly%3B%2Cc0) > > > [![Graph for "This sentence scores poorly."](https://i.stack.imgur.com/G8jYd.png)](https://i.stack.imgur.com/G8jYd.png) > > > **Rules** 1. Each word must be its own ngrams search term (no strings as search terms) 2. The sentence must be in English. You must use the corpus "English". 3. The sentence must make grammatical sense. To achieve this, you are allowed to insert punctuation in your sentence which is not present in your ngrams search. 4. You are not allowed to tick "case insensitive". (Because it spoils the look by adding *(All)* to the end of each word). Capitals are allowed where they make grammatical sense (beginning of sentence, proper nouns) but are not required. 5. You may not string endless adjectives or adverbs together; only one adjective to describe each object and one adverb to describe each verb, *unless you can put a joining word in between*. i.e. "The big red awesome car" would not be acceptable, but "the awesome car which was big and red" would be... although clearly that example isn't going to appear in order! Note that possessive nouns (e.g. "my *sister's* car") are adjectives and hence fall under this rule. 6. You are allowed to change the end year of your search from the default. 7. The maximum score possible is 12, because google ngrams only allows 12 search terms.
2015/11/09
[ "https://puzzling.stackexchange.com/questions/23866", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/9444/" ]
13: Just modifying a previous answer yields higher results: [A,new,man,through,life,without,true,love,today,normally,allows,medicinal,marijuana](https://books.google.com/ngrams/graph?content=A%2Cnew%2Cman%2Cthrough%2Clife%2Cwithout%2Ctrue%2Clove%2Ctoday%2Cnormally%2Callows%2Cmedicinal&year_start=1800&year_end=1972&corpus=15&smoothing=3&share=&direct_url=t1%3B%2CA%3B%2Cc0%3B.t1%3B%2Cnew%3B%2Cc0%3B.t1%3B%2Cman%3B%2Cc0%3B.t1%3B%2Cthrough%3B%2Cc0%3B.t1%3B%2Clife%3B%2Cc0%3B.t1%3B%2Cwithout%3B%2Cc0%3B.t1%3B%2Ctrue%3B%2Cc0%3B.t1%3B%2Clove%3B%2Cc0%3B.t1%3B%2Ctoday%3B%2Cc0%3B.t1%3B%2Cnormally%3B%2Cc0%3B.t1%3B%2Callows%3B%2Cc0%3B.t1%3B%2Cmedicinal%3B%2Cc0) (Though I will point out that google stops showing them after 12. So the answer may just be 12.
10 points --------- A somewhat morbid sentence, perhaps from a proponent of eugenics: *[A new man without true love requires severe anesthesia perfunctorily](https://books.google.com/ngrams/graph?content=A%2Cnew%2Cman%2Cwithout%2Ctrue%2Clove%2Crequires%2Csevere%2Canesthesia%2Cperfunctorily&year_start=1800&year_end=1975&corpus=15&smoothing=3&share=)* (Note that this uses an end year of 1975. After that point, ***love*** overtakes ***true***.)
244,796
I have access to a data node in a Hadoop cluster, and I'd like to find out the identity of the name nodes for the same cluster. Is there a way to do this?
2011/03/08
[ "https://serverfault.com/questions/244796", "https://serverfault.com", "https://serverfault.com/users/1713/" ]
Try the Dedicated Administrator Connection (DAC).
Can you get into SSMS? If so, have you tried running sp\_who2? that should show you what SPID's are eating up the most CPU.
76,128
This is essentially a repeat of [this question](https://wordpress.stackexchange.com/questions/70519/shared-members-between-two-different-wordpress-installations-with-different-data), but it has not been answered. I am trying to create an SSO system between two separate WordPress installs that are on different servers using different databases. The main site has a full database including a users table containing over 300,000 users. Because of the size of the users table, we do not want to replicate each of them on the second site or do a traditional SSO system where each user is created in the database as they login. Ideally, we would like to reference the users table on the main site and use those same users on the second site. So far I have tried using wp\_remote\_post() to send a user object to the second site while overriding the pluggable.php functions and setting the $current\_user global with the posted user object. This, however, isn't working as well as I'd hoped because the methods that are normally available in the WP\_User object are not available in the posted object, which results in fatal errors when methods like $user->exists() are used. I am aware of the CUSTOM\_USER\_TABLE solution, but that obviously won't work in this example as the sites are on separate servers with separate databases. **TL;DR:** Need SSO. Separate servers. Help.
2012/12/14
[ "https://wordpress.stackexchange.com/questions/76128", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/6556/" ]
The main thing I didn't like about most of these solutions is that it was blinking on alot of screens, and if you clicked on **Featured Image** it would revert back to showing all images. After some searching I think found a permanent solution (Thanks to [Ünsal Korkmaz](http://unsalkorkmaz.com/how-to-lock-uploads-to-show-only-uploaded-to-this-post-in-media-panel/)) which looks like it solves these problems. The code: ``` add_action( 'admin_footer-post-new.php', 'media_library_filter' ); add_action( 'admin_footer-post.php', 'media_library_filter' ); function media_library_filter() { ?> <script type="text/javascript"> jQuery(document).on("DOMNodeInserted", function(){ jQuery('select.attachment-filters [value="uploaded"]').attr( 'selected', true ).parent().trigger('change'); }); </script> <?php } ``` which permanently sets the media library to only show "Uploaded To This Post", even if you try and change the view which means no blinking. I've added this code to accompany it to remove the selectbox entirely: ``` add_action( 'admin_head', 'hide_select_ddl' ); function hide_select_ddl() { ?> <style type="text/css"> div.media-menu a.media-menu-item:nth-child(3) {display:none!important;} .media-frame-content .attachment-filters:first-child { display:none; } </style> <?php } ```
This is my solutions to set `dateFilter` to current month, though it triggers AJAX twice. ``` .on('content:render:browse', function(a, b) { var filter = a.toolbar.secondary.get('dateFilter'); if (filter.model) { filter.model.set(filter.filters[1].props); } }) ```
738,989
I opened an Excel file from Internet Explorer, worked on it for 2 hours and saved it. But now I can't find the file. The file was really important. Is there any way I can retrieve it? I'm using Windows 7 Ultimate.
2014/04/08
[ "https://superuser.com/questions/738989", "https://superuser.com", "https://superuser.com/users/313846/" ]
My solution was arrived at indirectly. I noticed that MKV files contained a "date" that couldn't be changed by normal means so that the file would reflect when I got it, as shown in the file properties. In desperation I changed the column in windows file explorer from just "date" to "date created" and then set the view option to make this the default for all folders. Not only did this fix my sorting problem but the GROD was also cured. Not having to dig very deeply into the tagging structure of every file is obviously the reason for this cure.
This is caused by the **Windows Search** service. You could just disable the service by setting the *Windows Search* service to *Disabled* and manually stopping the service (right-click on the service and select *Stop*). Microsoft puts the service there to supposedly speed up Windows (yeah OK, whatever). You can also leave the service running and just disable it for select file types. Once you determine the file types that you want to disable the indexing of (.AVI, .MPEG, .WMV, etc.): 1. Open Control Panel 2. To select Windows Search, enter "Indexing Options" into the search bar and open it. Or you can select it by changing the View to either large or small icons and then opening Indexing Options. Or you can do it using Category View - from the main Control Panel window, select "System and Security" - "Action Center" - "View performance information" - "Adjust indexing options". 3. Click on "Advanced" and then select the "File Types" tab 4. Unselect (remove the check box) next to the extension(s) of the file type(s) that you want to disable the indexing for. Hopefully this helps speed things up for you. Good luck!!
28,994
UPDATE June 21, 2012: --------------------- I purchased a Ferric Chloride, Positive Developer, and positive PCB boards from [MG Chemicals](http://www.mgchemicals.com) and used the photo-etching process. The results were OUTSTANDING! You don't need their sparge tank or exposure kit. I simply exposed my pcb underneath a 20W compact florescent bulb for 10 minutes, developed the pcb in a tupperware dish according to the instructions, and then etched in the same (rinsed out) tupperware dish for 15 minutes while agitating occaisionally with a foam brush. Also, I used an inkjet printer. The instructions say only to use a laser printer, but I found that if I set my printer to print the transparency using very dark, rich dpi settings that I had sufficient contrast. The results were great--super fine and detailed thin traces!! Background ---------- I recently purchased some [Syma brand indoor RC helicopters](https://rads.stackoverflow.com/amzn/click/com/B004L2J7W0) for my nephews. Well, I had so much fun enjoying these with the boys that I have since started a small collection of my own. Although loads of fun and durable, these toys use cheap electronics: * An infrared transmitter/receiver that seems to lose signal quality in a brightly lit room * Single channel so that you and someone else can't fly at the same time without interfering with one another. About me: * Not an electronic engineer, though I am technically minded. * I am very much a novice with soldering and wouldn't be capable of soldering the tiny board inside these little birds. What I would like to do: ------------------------ In an ideal world, I would like to have a custom circuit board made for these little birds that 1. Accepts a non-infrared signal (2.4 GHz? Bluetooth? Wi-Fi? --Remember these are "living room" flyers). 2. Allows for you to choose between 2-3 channels on both the transmitter and receiver so that 2-3 people can fly concurrently. I realize that this might already be available for bigger outdoor birds, but I need the circuit board to be small. Is there a cost-effective way of prototyping this? Is there perhaps a place where I can send them the specifications and they would "print" up the circuit? Software that a semi-layman like myself could use to design it? I realize that the first run would be expensive, but I can see this being an after-market item that those of us bitten by the indoor heli-bug would buy enough of to bring the cost down.
2012/03/30
[ "https://electronics.stackexchange.com/questions/28994", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8970/" ]
PCBs are first designed with a schematic. You can find a large amount of options for schematic editors for the question [Good tools for drawing schematics](https://electronics.stackexchange.com/questions/1024/good-tools-for-drawing-schematics). Once you get the schematic drawn you will need to "transfer" the schematic to a layout program. This is really only ever done with in a single program. For example, eagle is a pretty commonly used program. You create a schematic, and then within eagle you transfer it to a pcb. From this point you will need to place all of the parts in your layout. Once the layout is complete, you can export the layout. A typical format for this is gerber files. You then send those files off to a PCB house who will then fab the board for you. There aren't many cheap options for soldering boards for you in small quantities just because of the large amount of setup time required. One option though is batchpcb.com With all of that said, I think you are taking on a project that might be a little much for you right now. Brainstorming questions are best for the chat room, so I wont go into much detail here. Here are my concerns for you... It is an art to get PCBs very small and you will need pretty small pcbs in order to get them to fit on those small helicopters. Also, people tend to like to make their first PCB in every project a little bigger so that you have room to change things or adding prototyping pins, etc. You would probably be best to buy yourself a development board of some sort, possibly an Arduino with some RF shields. This will allow you to do some prototyping in an environment that is very easy to do things in. This will help to get you up to speed with what all is needed to make something like this. You could then take the step of turning it into a PCB that can fit on to the helicopter. Also, you shouldn't be scared of soldering. In small quantities, you will be able to save money by buying yourself some soldering equipment instead of paying someone else to do it for you.
Last I checked, the most cost-effective place to get small-run PCBS is <http://batchpcb.com/> by the people behind SparkFun. However, you will be waiting a while (for me it was about a month from upload to delivery.)
11,938
I'm updating my resume, and have realized that many programming skills are very brief and abbreviated. My old resumes would list them in a bulleted list, however due to all the new technologies I'm adding, this leads to a rather long list of very short items, with a lot of whitespace to the right of the section. I am wondering if it would be appropriate to list these items in a table instead of a list, or to put them inline in a sentence For example, ``` * C# * WPF * WCF * VB.Net * ASP.Net * HTML * CSS * Javascript * T-SQL ``` versus ``` C# VB.Net HTML WPF ASP.Net CSS WCF T-SQL Javascript ``` versus ``` C#, WPF, WCF, VB.Net, ASP.Net, HTML, CSS, Javascript, T-SQL ``` Is one method preferred over others on my resume to make it easier for employers or recruiters to scan through?
2013/05/23
[ "https://workplace.stackexchange.com/questions/11938", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/316/" ]
I'm no hero when it comes to CVs, but there's a lot of .Net tech in that list. I'd list those in one line. That way you make most of the space available. You could opt to use some kind of matrix style. I'd still make some kind of distinction between the MS tech and the other techniques. Something like: --- .Net technologies and languages: ``` C#, VB.Net, WPF, WCF, ASP.Net. (IIS 7.5?) ``` Web technologies and languages: ``` Javascript, HTML and CSS. ``` I'm familiar with databases. ``` T-SQL. (Maybe MSQL2k8?) ``` --- If the DB stuff is a bit off you could recatagorize the 'web' to 'other' If you catagorize the line with list of skills to fit some kind of structure, like: "languages, API's, markup languages, software stacks", the structure should be apparent to any human reader. The automated resume scanners just look for strings anyways, so I can't imagine that you'd get slammed by those on how you lay them out on the page. I don't know how to do the formatting on SE, but you could even have two columns, each with a title and list the techs in a comma separated format like I just presented. That way you can save space without sacrificing structure.
I want to add that you need to remember that your CV has two audiences: * Recruiters/HR who don't know how the technology is being used, and are possibly just looking for some key buzzwords. * Technical leads who do know how the technology is used, and aren't going to be impressed with just a list of buzzwords, or self-assessed x/10 ratings for technologies. The challenge is - you need to appeal to both people. The way I solve it, is at the start of my CV I have a section that looks like this: ``` SKILL SET Core Skills Some Exposure JavaScript SQL Node ... React ... ``` This is to appeal to the recruiter who just needs to tick some boxes. Later in my experience section, I write it like this: ``` Acme Ltd 2005-2007 Software Engineer I was responsible for creating a frontend with React/Redux, working from designs from a designer, and a REST API spec from the backend team. I also created frontend tests using Jest and Enzyme. Technologies used: Javascript, TypeScript, React, Redux, ImmutableJS, Jest, Enzyme, Git, Jira. ``` The technologies used list is to provide more credibility to the recruiter for the technologies you have used (ie. how recent it is), while the description of the task is to provide credibility to the technical lead (ie. that you're not just listing some technologies), and give them some context for them to ask further questions. You'll note that I include 'git' and 'jira' in the technology list. This is more for the recruiters sake - as this may be one of the things they are looking for, whereas a technical lead really doesn't need a sentence explaining how you used git and jira, unless you were doing something particularly special with it.
76,449
Inspired by [this](https://softwareengineering.stackexchange.com/questions/76415/i-want-to-make-some-programmer-friends-but-dont-know-where-to-really-look) question, I have looked into user groups within my area in England, and there does not seem to be one at all for a few hundred miles. I would like to look into the possibility of setting one up in a local city, but I have no idea what the format should be. My questions are: What is the purpose of a user group? Is it to simply network or are there expectations for presentations, informal learning, etc? How and where does one promote a user group? Is it run as a free enterprise or is there usually a charge to allow for investment back into the meetings? Thanks.
2011/05/15
[ "https://softwareengineering.stackexchange.com/questions/76449", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/24364/" ]
I see from your profile that you're based in Warrington. What type of user group were you looking for .NET, Java, SQL ... general? There's a nice group in Manchester that you might be interested in: <http://www.nxtgenug.net/Region.aspx?RegionID=11> In my experience, user groups derive their focus out of what the co-ordinator (or group of co-ordinators) is interested in. For example, if you are big into Silverlight then your own group would probably have that bias. Similarly, if your focus is more to network with other local devs just to chat, maybe code a little, talk about jobs and share experiences, then you will find that people with similar persuasions will join you. After all, there is not much point to a group where the people attending are not interested in the information that they get from the group :) Depending on what it is that you are looking to get out of spending time with other devs will determine whether you want your group to be an educational group or a networking group. Groups like London's Silverlight user group, London .NET and the regional NxtGen User Groups focus more on education and sharing knowledge. They invite a monthly speaker to come and share their specialities with the group. On the other hand "meetups" (I think there is a fledgling one in Cambridge) have a more social aspect where the attendees participate more to spend leisure time after work with like-minded people rather than to necessarily "learn about" new stuff. If you haven't yet got a feel for what you want your group to focus on, maybe you could arrange an informal meetup to see what others in your area are interested in - educational talks or networking - that may help to determine the expectations of your potential attendees and formulate the best plan. Depending on what type of group you have, there are a lot of places that you can promote your group or meetup. Microsoft operate a list that includes UK events in its Flash newsletter. Twitter is a great way to promote your group, since people in the UK community share links and events like wildfire. You might also try promoting it to local companies that you know have an IT/development department, maybe a printed flyer or a quick call to the company to get the email address of someone who might be interested enough to share the group information with their colleagues. I would offer this advice: don't be put off if you don't get great traction right away. We have a .NET user group in Cambridge and it has taken us a long time (almost 4 years, I think) to get a regular turn out of 30-40 each month. The success and benefits of your group will depend on your commitment to keep pushing on through even if you think you're not getting anywhere. As to the financial side of things, the single biggest pain in the butt is finding a venue who will allow you to make a regular arrangement to hold your meeting there. If you plan to do more of the networking thing, this might not pose such a problem for you as you can arrange to meet at a pub or coffee house where you can usually ask to reserve a little bit of space for no fee. If you are going for the regular education meeting style approach, try asking your company if they might let you have a room in your building one night each month to hold it. Regularity and consistency is one of the keys to hosting a successful educational user group. If you want to organise food and drinks for your attendees, you should try seeking out vendor support from organisations who offer products/services in the field that you are interested in. For example, I help with the Cambridge NxtGen group and I also work for DevExpress. NxtGen is a Microsoft technology focused group for the main part, and DevExpress offer products in this area. NxtGen reached out to us and other vendors like Red Gate, JetBrains, Pluralsight for support in the form of money to pay for pizza and also prizes for monthly raffles to entice more attendees into the group (if they know that they can win valuable stuff and pick up things like shirts and trinkets then it might make them think favourably about coming to your group every time you host a meeting). If you know of vendors who operate in the area that you are interested in then try the same approach and see what they say. I have mostly found .NET vendors to be very forthcoming with their support, so I can't imagine why vendors in other areas might not work the same way. I'd be happy to link you with other user group leaders who can offer you advice. You can find me on Twitter (@RachelHawley) and you can email me at rachelh at the DevExpress domain. Good luck! Rachel.
> > What is the purpose of a user group? > Is it to simply network or are there > expectations for presentations, > informal learning, etc? > > > It is for what ever you want it to be. I help run [Scottish Developers](http://scottishdevelopers.com) and we have a wide scope. We run evening talks, book clubs, geek dinners, conferences, workshops, etc. Each has its own challenges and its own rewards. If all you want to do is network with fellow developers in your local area then I'd suggest activities that encourage discussion: Geek Dinners or a Book Club. (We get people to [vote on a book](http://scottishdevelopers.com/2011/04/26/scottish-developers-book-club-glasgow-july/), when the v[otes are counted we publish that](http://scottishdevelopers.com/2011/05/15/glasgow-book-club-july-results/) and get people to [sign up](http://gla-book-club-july2011-sdblog.eventbrite.com/).) Then on the evening of the meeting we meet in a pub (although a coffee shop may be a good venue for this) and talk about the book. We often talk about other things to that are generaly inspired by the book. Maybe somebody's already done what the book was talking about and it worked well, or maybe it didn't work. Maybe it inspires someone to try something new and they'll tell us at the next meeting how it worked out for them. etc. If you want to bring in speakers to talk about specific subjects then evening talks or conferences work well for that. They are more work to organise, but there is a vibrant community in the UK for that. Just go along to one of the [DDD (Developer!Developer!Developer!) community conferences](http://www.developerdeveloperdeveloper.com/home/) and speak to the speakers and organisers in order to start building a contact list of folks who would be willing to talk at your user group. > > How and where does one promote a user > group? > > > I can't speak for everyone, but Scottish Developers use [twitter](http://twitter.com/#!/scottishdevs), [we have our own blog](http://scottishdevelopers.com), we recently set up [a LinkedIn group](http://www.linkedin.com/groups/Scottish-Developers-3908782), any Microsoft focused events appear in the MSDN Flash Newsletter. > > Is it run as a free enterprise or is > there usually a charge to allow for > investment back into the meetings? > > > It depends on the group. Scottish Developers try not to charge people for things. Obviously, some things like Geek Dinners are charged for, but evening talks and conferences we try not to charge. However, I'm finding that an increasingly difficult proposition. We do have some free venues and we are very grateful for the companies that have helped us in that regard, but unless you have a good relationship with someone that has space to give you will have to pay for it and that money has to come from somewhere.