qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
5,713,653
I'm using a search view in my application. Now i just want to get the text typed in the SearchView text box and display it on another textview. If i typed the text and click a button i can do the same. But i don't want to use any extra buttons. I just want to display the result when i am pressing enter key.
2011/04/19
[ "https://Stackoverflow.com/questions/5713653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669322/" ]
Try to use [setOnQueryTextListener](http://developer.android.com/reference/android/widget/SearchView.html#setOnQueryTextListener%28android.widget.SearchView.OnQueryTextListener%29) of SearchView ``` new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextChange(String newText) { // your text view here textView.setText(newText); return true; } @Override public boolean onQueryTextSubmit(String query) { textView.setText(query); return true; } } ```
The right way to solve this is to use **setOnQueryTextListener** This is a small exmple using Kotlin: ``` txtSearch = rootView.searchView txtSearch.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(newText: String): Boolean { return false } override fun onQueryTextSubmit(query: String): Boolean { return false } }) ```
5,713,653
I'm using a search view in my application. Now i just want to get the text typed in the SearchView text box and display it on another textview. If i typed the text and click a button i can do the same. But i don't want to use any extra buttons. I just want to display the result when i am pressing enter key.
2011/04/19
[ "https://Stackoverflow.com/questions/5713653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669322/" ]
In Kotlin, you can do : ``` searchView.setOnQueryTextListener(object : OnQueryTextListener { override fun onQueryTextChange(newText: String): Boolean { return false } override fun onQueryTextSubmit(query: String): Boolean { // task HERE return false } }) ```
The right way to solve this is to use **setOnQueryTextListener** This is a small exmple using Kotlin: ``` txtSearch = rootView.searchView txtSearch.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(newText: String): Boolean { return false } override fun onQueryTextSubmit(query: String): Boolean { return false } }) ```
5,713,653
I'm using a search view in my application. Now i just want to get the text typed in the SearchView text box and display it on another textview. If i typed the text and click a button i can do the same. But i don't want to use any extra buttons. I just want to display the result when i am pressing enter key.
2011/04/19
[ "https://Stackoverflow.com/questions/5713653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669322/" ]
Try to use [setOnQueryTextListener](http://developer.android.com/reference/android/widget/SearchView.html#setOnQueryTextListener%28android.widget.SearchView.OnQueryTextListener%29) of SearchView ``` new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextChange(String newText) { // your text view here textView.setText(newText); return true; } @Override public boolean onQueryTextSubmit(String query) { textView.setText(query); return true; } } ```
In Kotlin, you can do : ``` searchView.setOnQueryTextListener(object : OnQueryTextListener { override fun onQueryTextChange(newText: String): Boolean { return false } override fun onQueryTextSubmit(query: String): Boolean { // task HERE return false } }) ```
5,713,653
I'm using a search view in my application. Now i just want to get the text typed in the SearchView text box and display it on another textview. If i typed the text and click a button i can do the same. But i don't want to use any extra buttons. I just want to display the result when i am pressing enter key.
2011/04/19
[ "https://Stackoverflow.com/questions/5713653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669322/" ]
It also can be done with RXAndroid and RxBinding by Jake Wharton like this: ``` RxSearchView.queryTextChanges(searchView) .debounce(500, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<CharSequence>() { @Override public void call(CharSequence charSequence) { if(charSequence!=null){ // Here you can get the text System.out.println("SEARCH===" + charSequence.toString()); } } }); ``` Code is subscribing to observe text change with some delay of 500 milliseconds. This is a link to git repo to get RXAndroid: <https://github.com/JakeWharton/RxBinding>
with extension functions, create `SearchViewExtensions.kt` ``` import android.view.View import androidx.appcompat.widget.SearchView inline fun SearchView.onQueryTextChanged(crossinline listener: (String) -> Unit) { this.setOnQueryTextListener(object: SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { return true } override fun onQueryTextChange(newText: String?): Boolean { listener(newText.orEmpty()) return true } }) } ``` and the ***magic*** in your fragment ``` mSearchView.onQueryTextChanged { query: String -> // do whatever } ```
5,713,653
I'm using a search view in my application. Now i just want to get the text typed in the SearchView text box and display it on another textview. If i typed the text and click a button i can do the same. But i don't want to use any extra buttons. I just want to display the result when i am pressing enter key.
2011/04/19
[ "https://Stackoverflow.com/questions/5713653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669322/" ]
The above answer is good but not complete actually you need to set an action listener for your Search view . you can do this in two ways create a class that implements the necessary classes to be an OnQueryTextListener and make a new object of that and use it as your search view query text listener or use the following compact form: ``` SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { callSearch(query); return true; } @Override public boolean onQueryTextChange(String newText) { // if (searchView.isExpanded() && TextUtils.isEmpty(newText)) { callSearch(newText); // } return true; } public void callSearch(String query) { //Do searching } }); ```
It also can be done with RXAndroid and RxBinding by Jake Wharton like this: ``` RxSearchView.queryTextChanges(searchView) .debounce(500, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<CharSequence>() { @Override public void call(CharSequence charSequence) { if(charSequence!=null){ // Here you can get the text System.out.println("SEARCH===" + charSequence.toString()); } } }); ``` Code is subscribing to observe text change with some delay of 500 milliseconds. This is a link to git repo to get RXAndroid: <https://github.com/JakeWharton/RxBinding>
5,713,653
I'm using a search view in my application. Now i just want to get the text typed in the SearchView text box and display it on another textview. If i typed the text and click a button i can do the same. But i don't want to use any extra buttons. I just want to display the result when i am pressing enter key.
2011/04/19
[ "https://Stackoverflow.com/questions/5713653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669322/" ]
The right way to solve this is to use **setOnQueryTextListener** This is a small exmple using Kotlin: ``` txtSearch = rootView.searchView txtSearch.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(newText: String): Boolean { return false } override fun onQueryTextSubmit(query: String): Boolean { return false } }) ```
This is what I have inside the `onCreateOptionsMenu(Menu menu)` function on my main activity: ``` MenuItem searchItem = menu.findItem(R.id.search); SearchView searchView = (SearchView) searchItem.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { // Do whatever you need. This will be fired only when submitting. return false; } @Override public boolean onQueryTextChange(String newText) { // Do whatever you need when text changes. // This will be fired every time you input any character. return false; } }); ```
615,204
I've read the already asked questions on this but I'm still stuck: > > Prove that when 2 perfectly elastic particles collide, with one being at rest, the angle formed is 90° > > > **Attempt.** Given that this is perfectly elastic, the energy and the linear momentum doesn't change, and both particles being A and B, being B the one at rest initially, and being $\vec{p}$ the linear momentum before the collision and $\vec{p'}$ the linear momentum after the collision. $$\begin{cases} \vec{p}=\vec{p'}\\ E\_c(A)=E\_c(A)+E\_c(B)\end{cases}$$ from the first one as the $\vec{p\_B}=0$ because B is at rest: $$\implies \vec{p\_A}=\vec{p'\_A}+\vec{p'\_B}$$ $\vec{p}=m\vec{v}$ and letting both masses being $m\_A$ and $m\_B$ we get $$m\_A\vec{v\_A}=m\_A\vec{v'\_A}+m\_B\vec{v'\_B}$$ isolating $m\_A$ $$m\_A(\vec{v\_A}-\vec{v'\_A})=\vec{v'\_B}m\_B$$ $$m\_A=\frac{\vec{v'\_B}m\_B}{\vec{v\_A}-\vec{v'\_A}}$$ subsituting into the other equation: $$\frac12 m\_Av\_A²=\frac12 m\_Av\_A'²+\frac12 m\_B v\_B'²$$ $$m\_Av\_A²=m\_Av\_A'²+m\_B v\_B'²$$ $$m\_A(v\_A²-v\_A'²)=m\_Bv\_B'²$$ substituting $$\frac{\vec{v'\_B}m\_B}{\vec{v\_A}-\vec{v'\_A}}(v\_A²-v\_A'²)=m\_Bv\_B'²$$ arranging it a bit and cancelling $m\_B$ we get $$\frac{v\_A²-v\_A'²}{\vec{v\_A}-\vec{v\_A'}}=\frac{v\_B'²}{\vec{v'\_B}}$$ but I'm pretty much stuck here, I have also tried with the $\cos(\alpha)=\frac{\vec{v}\cdot\vec{w}}{|\vec{v}||\vec{w}|}$ but anything worked out, anyone can shine a light on this?
2021/02/17
[ "https://physics.stackexchange.com/questions/615204", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/278607/" ]
For an object (mass, m) in the gravitational field of the earth (Mass, M) the potential energy is usually expressed as: U = – GMm/r. (This energy is going up from a negative value towards zero as r gets larger.) If the object is in a circular orbit: F = $GMm/(r^2) = m(v^2)/r$. multiplying by r/2 gives the kinetic energy: Gmm/(2r) = $(1/2)mv^2$. Adding these gives the total energy for a circular orbit: E = -GMm/(2r) (which also goes up toward zero). To move to a larger orbit, the rocket adds energy to make the orbit elliptical (which goes higher on the far side) and adds more energy on the far side to make the orbit a (larger) circle.
> > I learnt that the work done was equal to the change in energy > > > This statement is too ambiguous. We know that the total work due to all forces (conservative or nonconservative) is equal to the change in the **kinetic** energy. However, the work done by external forces (usually just taken to be the nonconservative forces) is equal to the change in the total mechanical energy. This is because if start with $$W\_\text{total}=\Delta K$$ and then utilize potential energy $$W\_\text{cons}=-\Delta U$$ we can split the total work up $$W\_\text{total}=W\_\text{cons}+W\_\text{nc,ext}=-\Delta U+W\_\text{nc,ext}$$ which gives us the relationship we want $$W\_\text{nc,ext}=\Delta K+\Delta U=\Delta E$$ > > I also learnt that work done by conservative forces is equal to change in kinetic energy, whereas work done by non-conservative forces is equal to change in total energy. > > > This is not the case in general.
60,100
I designed a pictures grid in sketch, and wanted to export the hole grid as one jpg or png, and then add it to my website. I am wondering if the quality of the jpg or png would be as good as photoshop? Is there specific settings I should use? What about color management?
2015/09/04
[ "https://graphicdesign.stackexchange.com/questions/60100", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/50455/" ]
Sketch is designed especially for the web/mobile UI design. Therefore, unlike photoshop (older versions) Sketch is optimizing PNG and JPG formats successfully. You don't need to worry about lots of quailty settings as in the photoshop at Sketch. [Here is a tutorial for that](http://webdesign.tutsplus.com/tutorials/understanding-sketchs-export-options--cms-22207) Therefore, go for it!
The answer is no. Photoshop JPG export is far superior to Sketch. This is frustrating as I have to export from Sketch as PNGs. Then open in Photoshop and save the PNGs as JPGs from Photoshop. (This is the case, even if I set a very high jpg export quality when exporting from Sketch). Photoshop's save-for-web creates higher quality jpgs yet with a smaller file size. This is most noticeable around things like logos or areas of flat colour.
7,736,196
> > **Possible Duplicate:** > > [How to get URL of current page in PHP](https://stackoverflow.com/questions/1283327/how-to-get-url-of-current-page-in-php) > > > ive been searching all over and i do not know php too well but all im trying to to do is display:none in php when on a certain page (/site/page/). **basically** `<?php if on this page -->(/page/site/)><?php //echo $this->?><div or span id="dropdown_navigation" style="display:none"></div> <?php endif; ?>` i know that code is all funky but i just wanted to kinda explain what im trying to do in that made up code with no php knowledge. the div id im trying to hide when on a certain page is a drop down menu called **"dropdown\_navigation"** any help would be greatly appreciated. thanks.
2011/10/12
[ "https://Stackoverflow.com/questions/7736196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/990847/" ]
Alright. You can go like so: ``` <?php if($_SERVER['REQUEST_URI']=='/the/page.html'){ echo '<div id="dropdown_navigation"...'; } ?> ``` That should do it. Replace ... with whatever you need. If you need to use a single quote in there, you'll have to escape it by prepending a backslash (i.e. \') This only works with the relative URL.
There are two global arrays which contain the information about the url: 1. `$_SERVER['REQUEST_URI']` : 2. `$_SERVER['QUERY_STRING']` : This will contain the query string something after the ? in the url. The PHP script would be then : ``` <?php if($_SERVER['REQUEST_URI'] == 'your specific page url') { ?> <div or span id="dropdown_navigation" style="display:none"></div> <?php } ?> ```
7,299,618
First, I've searched intensely with Google and Yahoo and I've found several replies on topics like mine, but they all don't really cover what I need to know. I've got several user models in my app, for now it's Customers, Designers, Retailers and it seems there are yet more to come. They all have different data stored in their tables and several areas on the site they're allowed to or not. So I figured to go the devise+CanCan way and to try my luck with polymorphic associations, so I got the following models setup: ``` class User < AR belongs_to :loginable, :polymorphic => true end class Customer < AR has_one :user, :as => :loginable end class Designer < AR has_one :user, :as => :loginable end class Retailer < AR has_one :user, :as => :loginable end ``` For the registration I've got customized views for each different User type and my routes are setup like this: ``` devise_for :customers, :class_name => 'User' devise_for :designers, :class_name => 'User' devise_for :retailers, :class_name => 'User' ``` For now the registrations controller is left as standard (which is "devise/registrations"), but I figured, since I got different data to store in different models I'd have to customize this behaviour as well!? But with this setup I got helpers like `customer_signed_in?` and `designer_signed_in?`, but what I'd really need is a general helper like `user_signed_in?` for the areas on the site that are accessible to all users, no matter which user type. I'd also like a routes helper like `new_user_session_path` instead of the several `new_*type*_session_path` and so on. In fact all I need to be different is the registration process... So I was wondering IF THIS IS THE WAY TO GO for this problem? Or is there a better/easier/less must-customize solution for this?
2011/09/04
[ "https://Stackoverflow.com/questions/7299618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/927573/" ]
Okay, so I worked it through and came to the following solution. I needed to costumize devise a little bit, but it's not that complicated. The User model ``` # user.rb class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :email, :password, :password_confirmation, :remember_me belongs_to :rolable, :polymorphic => true end ``` The Customer model ``` # customer.rb class Customer < ActiveRecord::Base has_one :user, :as => :rolable end ``` The Designer model ``` # designer.rb class Designer < ActiveRecord::Base has_one :user, :as => :rolable end ``` So the User model has a simple polymorphic association, defining if it's a Customer or a Designer. The next thing I had to do was to generate the devise views with `rails g devise:views` to be part of my application. Since I only needed the registration to be customized I kept the `app/views/devise/registrations` folder only and removed the rest. Then I customized the registrations view for new registrations, which can be found in `app/views/devise/registrations/new.html.erb` after you generated them. ``` <h2>Sign up</h2> <% # customized code begin params[:user][:user_type] ||= 'customer' if ["customer", "designer"].include? params[:user][:user_type].downcase child_class_name = params[:user][:user_type].downcase.camelize user_type = params[:user][:user_type].downcase else child_class_name = "Customer" user_type = "customer" end resource.rolable = child_class_name.constantize.new if resource.rolable.nil? # customized code end %> <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> <%= my_devise_error_messages! # customized code %> <div><%= f.label :email %><br /> <%= f.email_field :email %></div> <div><%= f.label :password %><br /> <%= f.password_field :password %></div> <div><%= f.label :password_confirmation %><br /> <%= f.password_field :password_confirmation %></div> <% # customized code begin %> <%= fields_for resource.rolable do |rf| %> <% render :partial => "#{child_class_name.underscore}_fields", :locals => { :f => rf } %> <% end %> <%= hidden_field :user, :user_type, :value => user_type %> <% # customized code end %> <div><%= f.submit "Sign up" %></div> <% end %> <%= render :partial => "devise/shared/links" %> ``` For each User type I created a separate partial with the custom fields for that specific User type, i.e. Designer --> `_designer_fields.html` ``` <div><%= f.label :label_name %><br /> <%= f.text_field :label_name %></div> ``` Then I setup the routes for devise to use the custom controller on registrations ``` devise_for :users, :controllers => { :registrations => 'UserRegistrations' } ``` Then I generated a controller to handle the customized registration process, copied the original source code from the `create` method in the `Devise::RegistrationsController` and modified it to work my way (don't forget to move your view files to the appropriate folder, in my case `app/views/user_registrations` ``` class UserRegistrationsController < Devise::RegistrationsController def create build_resource # customized code begin # crate a new child instance depending on the given user type child_class = params[:user][:user_type].camelize.constantize resource.rolable = child_class.new(params[child_class.to_s.underscore.to_sym]) # first check if child instance is valid # cause if so and the parent instance is valid as well # it's all being saved at once valid = resource.valid? valid = resource.rolable.valid? && valid # customized code end if valid && resource.save # customized code if resource.active_for_authentication? set_flash_message :notice, :signed_up if is_navigational_format? sign_in(resource_name, resource) respond_with resource, :location => redirect_location(resource_name, resource) else set_flash_message :notice, :inactive_signed_up, :reason => inactive_reason(resource) if is_navigational_format? expire_session_data_after_sign_in! respond_with resource, :location => after_inactive_sign_up_path_for(resource) end else clean_up_passwords(resource) respond_with_navigational(resource) { render_with_scope :new } end end end ``` What this all basically does is that the controller determines which user type must be created according to the `user_type` parameter that's delivered to the controller's `create` method by the hidden field in the view which uses the parameter by a simple GET-param in the URL. For example: If you go to `/users/sign_up?user[user_type]=designer` you can create a Designer. If you go to `/users/sign_up?user[user_type]=customer` you can create a Customer. The `my_devise_error_messages!` method is a helper method which also handles validation errors in the associative model, based on the original `devise_error_messages!` method ``` module ApplicationHelper def my_devise_error_messages! return "" if resource.errors.empty? && resource.rolable.errors.empty? messages = rolable_messages = "" if !resource.errors.empty? messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join end if !resource.rolable.errors.empty? rolable_messages = resource.rolable.errors.full_messages.map { |msg| content_tag(:li, msg) }.join end messages = messages + rolable_messages sentence = I18n.t("errors.messages.not_saved", :count => resource.errors.count + resource.rolable.errors.count, :resource => resource.class.model_name.human.downcase) html = <<-HTML <div id="error_explanation"> <h2>#{sentence}</h2> <ul>#{messages}</ul> </div> HTML html.html_safe end end ``` UPDATE: To be able to support routes like `/designer/sign_up` and `/customer/sign_up` you can do the following in your routes file: ``` # routes.rb match 'designer/sign_up' => 'user_registrations#new', :user => { :user_type => 'designer' } match 'customer/sign_up' => 'user_registrations#new', :user => { :user_type => 'customer' } ``` Any parameter that's not used in the routes syntax internally gets passed to the params hash. So `:user` gets passed to the params hash. So... that's it. With a little tweeking here and there I got it working in a quite general way, that's easily extensible with many other User models sharing a common User table. Hope someone finds it useful.
I didn't manage to find any way of commenting for the accepted answer, so I'm just gonna write here. There are a couple of things that don't work exactly as the accepted answer states, probably because it is out of date. Anyway, some of the things that I had to work out myself: 1. For the UserRegistrationsController, `render_with_scope` doesn't exist any more, just use `render :new` 2. The first line in the create function, again in the UserRegistrationsController doesn't work as stated. Just try using ``` # Getting the user type that is send through a hidden field in the registration form. user_type = params[:user][:user_type] # Deleting the user_type from the params hash, won't work without this. params[:user].delete(:user_type) # Building the user, I assume. build_resource ``` instead of simply `build_resource`. Some mass-assignment error was coming up when unchanged. 1. If you want to have all the user information in Devise's current\_user method, make these modifications: `class ApplicationController < ActionController::Base protect_from_forgery` ``` # Overriding the Devise current_user method alias_method :devise_current_user, :current_user def current_user # It will now return either a Company or a Customer, instead of the plain User. super.rolable end end ```
7,299,618
First, I've searched intensely with Google and Yahoo and I've found several replies on topics like mine, but they all don't really cover what I need to know. I've got several user models in my app, for now it's Customers, Designers, Retailers and it seems there are yet more to come. They all have different data stored in their tables and several areas on the site they're allowed to or not. So I figured to go the devise+CanCan way and to try my luck with polymorphic associations, so I got the following models setup: ``` class User < AR belongs_to :loginable, :polymorphic => true end class Customer < AR has_one :user, :as => :loginable end class Designer < AR has_one :user, :as => :loginable end class Retailer < AR has_one :user, :as => :loginable end ``` For the registration I've got customized views for each different User type and my routes are setup like this: ``` devise_for :customers, :class_name => 'User' devise_for :designers, :class_name => 'User' devise_for :retailers, :class_name => 'User' ``` For now the registrations controller is left as standard (which is "devise/registrations"), but I figured, since I got different data to store in different models I'd have to customize this behaviour as well!? But with this setup I got helpers like `customer_signed_in?` and `designer_signed_in?`, but what I'd really need is a general helper like `user_signed_in?` for the areas on the site that are accessible to all users, no matter which user type. I'd also like a routes helper like `new_user_session_path` instead of the several `new_*type*_session_path` and so on. In fact all I need to be different is the registration process... So I was wondering IF THIS IS THE WAY TO GO for this problem? Or is there a better/easier/less must-customize solution for this?
2011/09/04
[ "https://Stackoverflow.com/questions/7299618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/927573/" ]
Okay, so I worked it through and came to the following solution. I needed to costumize devise a little bit, but it's not that complicated. The User model ``` # user.rb class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :email, :password, :password_confirmation, :remember_me belongs_to :rolable, :polymorphic => true end ``` The Customer model ``` # customer.rb class Customer < ActiveRecord::Base has_one :user, :as => :rolable end ``` The Designer model ``` # designer.rb class Designer < ActiveRecord::Base has_one :user, :as => :rolable end ``` So the User model has a simple polymorphic association, defining if it's a Customer or a Designer. The next thing I had to do was to generate the devise views with `rails g devise:views` to be part of my application. Since I only needed the registration to be customized I kept the `app/views/devise/registrations` folder only and removed the rest. Then I customized the registrations view for new registrations, which can be found in `app/views/devise/registrations/new.html.erb` after you generated them. ``` <h2>Sign up</h2> <% # customized code begin params[:user][:user_type] ||= 'customer' if ["customer", "designer"].include? params[:user][:user_type].downcase child_class_name = params[:user][:user_type].downcase.camelize user_type = params[:user][:user_type].downcase else child_class_name = "Customer" user_type = "customer" end resource.rolable = child_class_name.constantize.new if resource.rolable.nil? # customized code end %> <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> <%= my_devise_error_messages! # customized code %> <div><%= f.label :email %><br /> <%= f.email_field :email %></div> <div><%= f.label :password %><br /> <%= f.password_field :password %></div> <div><%= f.label :password_confirmation %><br /> <%= f.password_field :password_confirmation %></div> <% # customized code begin %> <%= fields_for resource.rolable do |rf| %> <% render :partial => "#{child_class_name.underscore}_fields", :locals => { :f => rf } %> <% end %> <%= hidden_field :user, :user_type, :value => user_type %> <% # customized code end %> <div><%= f.submit "Sign up" %></div> <% end %> <%= render :partial => "devise/shared/links" %> ``` For each User type I created a separate partial with the custom fields for that specific User type, i.e. Designer --> `_designer_fields.html` ``` <div><%= f.label :label_name %><br /> <%= f.text_field :label_name %></div> ``` Then I setup the routes for devise to use the custom controller on registrations ``` devise_for :users, :controllers => { :registrations => 'UserRegistrations' } ``` Then I generated a controller to handle the customized registration process, copied the original source code from the `create` method in the `Devise::RegistrationsController` and modified it to work my way (don't forget to move your view files to the appropriate folder, in my case `app/views/user_registrations` ``` class UserRegistrationsController < Devise::RegistrationsController def create build_resource # customized code begin # crate a new child instance depending on the given user type child_class = params[:user][:user_type].camelize.constantize resource.rolable = child_class.new(params[child_class.to_s.underscore.to_sym]) # first check if child instance is valid # cause if so and the parent instance is valid as well # it's all being saved at once valid = resource.valid? valid = resource.rolable.valid? && valid # customized code end if valid && resource.save # customized code if resource.active_for_authentication? set_flash_message :notice, :signed_up if is_navigational_format? sign_in(resource_name, resource) respond_with resource, :location => redirect_location(resource_name, resource) else set_flash_message :notice, :inactive_signed_up, :reason => inactive_reason(resource) if is_navigational_format? expire_session_data_after_sign_in! respond_with resource, :location => after_inactive_sign_up_path_for(resource) end else clean_up_passwords(resource) respond_with_navigational(resource) { render_with_scope :new } end end end ``` What this all basically does is that the controller determines which user type must be created according to the `user_type` parameter that's delivered to the controller's `create` method by the hidden field in the view which uses the parameter by a simple GET-param in the URL. For example: If you go to `/users/sign_up?user[user_type]=designer` you can create a Designer. If you go to `/users/sign_up?user[user_type]=customer` you can create a Customer. The `my_devise_error_messages!` method is a helper method which also handles validation errors in the associative model, based on the original `devise_error_messages!` method ``` module ApplicationHelper def my_devise_error_messages! return "" if resource.errors.empty? && resource.rolable.errors.empty? messages = rolable_messages = "" if !resource.errors.empty? messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join end if !resource.rolable.errors.empty? rolable_messages = resource.rolable.errors.full_messages.map { |msg| content_tag(:li, msg) }.join end messages = messages + rolable_messages sentence = I18n.t("errors.messages.not_saved", :count => resource.errors.count + resource.rolable.errors.count, :resource => resource.class.model_name.human.downcase) html = <<-HTML <div id="error_explanation"> <h2>#{sentence}</h2> <ul>#{messages}</ul> </div> HTML html.html_safe end end ``` UPDATE: To be able to support routes like `/designer/sign_up` and `/customer/sign_up` you can do the following in your routes file: ``` # routes.rb match 'designer/sign_up' => 'user_registrations#new', :user => { :user_type => 'designer' } match 'customer/sign_up' => 'user_registrations#new', :user => { :user_type => 'customer' } ``` Any parameter that's not used in the routes syntax internally gets passed to the params hash. So `:user` gets passed to the params hash. So... that's it. With a little tweeking here and there I got it working in a quite general way, that's easily extensible with many other User models sharing a common User table. Hope someone finds it useful.
I was following the above instructions and found out some gaps and that instructions were just out of date when I was implementing it. So after struggling with it the whole day, let me share with you what worked for me - and hopefully it will save you few hours of sweat and tears * First of all, if you are not that familiar with RoR polymorphism, please go over this guide: <http://astockwell.com/blog/2014/03/polymorphic-associations-in-rails-4-devise/> After following it you will have devise and user users models installed and you will be able to start working. * After that please follow Vapire's great tutorial for generating the views with all the partails. * What I found most frustrating was that dut to using the latest version of Devise (3.5.1), RegistrationController refused to work. Here is the code that will make it work again: ``` def create meta_type = params[:user][:meta_type] meta_type_params = params[:user][meta_type] params[:user].delete(:meta_type) params[:user].delete(meta_type) build_resource(sign_up_params) child_class = meta_type.camelize.constantize child_class.new(params[child_class.to_s.underscore.to_sym]) resource.meta = child_class.new(meta_type_params) # first check if child intance is valid # cause if so and the parent instance is valid as well # it's all being saved at once valid = resource.valid? valid = resource.meta.valid? && valid # customized code end if valid && resource.save # customized code yield resource if block_given? if resource.persisted? if resource.active_for_authentication? set_flash_message :notice, :signed_up if is_flashing_format? sign_up(resource_name, resource) respond_with resource, location: after_sign_up_path_for(resource) else set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format? expire_data_after_sign_in! respond_with resource, location: after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource set_minimum_password_length respond_with resource end end end ``` * and also add these overrides so that the redirections will work fine: ``` protected def after_sign_up_path_for(resource) after_sign_in_path_for(resource) end def after_update_path_for(resource) case resource when :user, User resource.meta? ? another_path : root_path else super end end ``` * In order that devise flash messages will keep working you'll need to update `config/locales/devise.en.yml` instead of the overridden RegistraionsControlloer by UserRegistraionsControlloer all you'll need to do is add this new section: ``` user_registrations: signed_up: 'Welcome! You have signed up successfully.' ``` Hope that will save you guys few hours.
7,299,618
First, I've searched intensely with Google and Yahoo and I've found several replies on topics like mine, but they all don't really cover what I need to know. I've got several user models in my app, for now it's Customers, Designers, Retailers and it seems there are yet more to come. They all have different data stored in their tables and several areas on the site they're allowed to or not. So I figured to go the devise+CanCan way and to try my luck with polymorphic associations, so I got the following models setup: ``` class User < AR belongs_to :loginable, :polymorphic => true end class Customer < AR has_one :user, :as => :loginable end class Designer < AR has_one :user, :as => :loginable end class Retailer < AR has_one :user, :as => :loginable end ``` For the registration I've got customized views for each different User type and my routes are setup like this: ``` devise_for :customers, :class_name => 'User' devise_for :designers, :class_name => 'User' devise_for :retailers, :class_name => 'User' ``` For now the registrations controller is left as standard (which is "devise/registrations"), but I figured, since I got different data to store in different models I'd have to customize this behaviour as well!? But with this setup I got helpers like `customer_signed_in?` and `designer_signed_in?`, but what I'd really need is a general helper like `user_signed_in?` for the areas on the site that are accessible to all users, no matter which user type. I'd also like a routes helper like `new_user_session_path` instead of the several `new_*type*_session_path` and so on. In fact all I need to be different is the registration process... So I was wondering IF THIS IS THE WAY TO GO for this problem? Or is there a better/easier/less must-customize solution for this?
2011/09/04
[ "https://Stackoverflow.com/questions/7299618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/927573/" ]
I didn't manage to find any way of commenting for the accepted answer, so I'm just gonna write here. There are a couple of things that don't work exactly as the accepted answer states, probably because it is out of date. Anyway, some of the things that I had to work out myself: 1. For the UserRegistrationsController, `render_with_scope` doesn't exist any more, just use `render :new` 2. The first line in the create function, again in the UserRegistrationsController doesn't work as stated. Just try using ``` # Getting the user type that is send through a hidden field in the registration form. user_type = params[:user][:user_type] # Deleting the user_type from the params hash, won't work without this. params[:user].delete(:user_type) # Building the user, I assume. build_resource ``` instead of simply `build_resource`. Some mass-assignment error was coming up when unchanged. 1. If you want to have all the user information in Devise's current\_user method, make these modifications: `class ApplicationController < ActionController::Base protect_from_forgery` ``` # Overriding the Devise current_user method alias_method :devise_current_user, :current_user def current_user # It will now return either a Company or a Customer, instead of the plain User. super.rolable end end ```
I was following the above instructions and found out some gaps and that instructions were just out of date when I was implementing it. So after struggling with it the whole day, let me share with you what worked for me - and hopefully it will save you few hours of sweat and tears * First of all, if you are not that familiar with RoR polymorphism, please go over this guide: <http://astockwell.com/blog/2014/03/polymorphic-associations-in-rails-4-devise/> After following it you will have devise and user users models installed and you will be able to start working. * After that please follow Vapire's great tutorial for generating the views with all the partails. * What I found most frustrating was that dut to using the latest version of Devise (3.5.1), RegistrationController refused to work. Here is the code that will make it work again: ``` def create meta_type = params[:user][:meta_type] meta_type_params = params[:user][meta_type] params[:user].delete(:meta_type) params[:user].delete(meta_type) build_resource(sign_up_params) child_class = meta_type.camelize.constantize child_class.new(params[child_class.to_s.underscore.to_sym]) resource.meta = child_class.new(meta_type_params) # first check if child intance is valid # cause if so and the parent instance is valid as well # it's all being saved at once valid = resource.valid? valid = resource.meta.valid? && valid # customized code end if valid && resource.save # customized code yield resource if block_given? if resource.persisted? if resource.active_for_authentication? set_flash_message :notice, :signed_up if is_flashing_format? sign_up(resource_name, resource) respond_with resource, location: after_sign_up_path_for(resource) else set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format? expire_data_after_sign_in! respond_with resource, location: after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource set_minimum_password_length respond_with resource end end end ``` * and also add these overrides so that the redirections will work fine: ``` protected def after_sign_up_path_for(resource) after_sign_in_path_for(resource) end def after_update_path_for(resource) case resource when :user, User resource.meta? ? another_path : root_path else super end end ``` * In order that devise flash messages will keep working you'll need to update `config/locales/devise.en.yml` instead of the overridden RegistraionsControlloer by UserRegistraionsControlloer all you'll need to do is add this new section: ``` user_registrations: signed_up: 'Welcome! You have signed up successfully.' ``` Hope that will save you guys few hours.
1,460,146
I am using Crystal Reports in Visual Studio 2008. I have about 5 pages worth of static text that needs to appear at the top of my report, so I put it in the report header section. I have a page footer section on the page that shows the page number. This does not show, and I suspect it has something to do with the long report header. How can I make the page footer show with a large report header? Edit: The Page Footer is actually appearing once on the last page. The Report Header takes up 5 pages and there isn't a page footer on any of those pages.
2009/09/22
[ "https://Stackoverflow.com/questions/1460146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86191/" ]
Can you split static text between many header (sub)sections (in a way that every section has about pageful of text)? May help.
Ken Hammady has a solution for crosstabs at <http://kenhamady.com/cru/archives/87> It can be adapted to work with long texts in textboxes.
1,460,146
I am using Crystal Reports in Visual Studio 2008. I have about 5 pages worth of static text that needs to appear at the top of my report, so I put it in the report header section. I have a page footer section on the page that shows the page number. This does not show, and I suspect it has something to do with the long report header. How can I make the page footer show with a large report header? Edit: The Page Footer is actually appearing once on the last page. The Report Header takes up 5 pages and there isn't a page footer on any of those pages.
2009/09/22
[ "https://Stackoverflow.com/questions/1460146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86191/" ]
Can you split static text between many header (sub)sections (in a way that every section has about pageful of text)? May help.
I moved all of my text from the Report Header to the Report Footer, and the page numbers will print. I will add a subreport to show my detailed data.
1,460,146
I am using Crystal Reports in Visual Studio 2008. I have about 5 pages worth of static text that needs to appear at the top of my report, so I put it in the report header section. I have a page footer section on the page that shows the page number. This does not show, and I suspect it has something to do with the long report header. How can I make the page footer show with a large report header? Edit: The Page Footer is actually appearing once on the last page. The Report Header takes up 5 pages and there isn't a page footer on any of those pages.
2009/09/22
[ "https://Stackoverflow.com/questions/1460146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86191/" ]
Can you split static text between many header (sub)sections (in a way that every section has about pageful of text)? May help.
I had exactly the same problem. My report header was very long and the page number only was appearing at last page. The problem was that i had my page number in the Report Footer. Then i realize that i had a Page Footer section and moved the page number there. I also changed the section properties (it had the No Drill down option checked). Now i have the same big header with the page number on all pages. Bye
1,460,146
I am using Crystal Reports in Visual Studio 2008. I have about 5 pages worth of static text that needs to appear at the top of my report, so I put it in the report header section. I have a page footer section on the page that shows the page number. This does not show, and I suspect it has something to do with the long report header. How can I make the page footer show with a large report header? Edit: The Page Footer is actually appearing once on the last page. The Report Header takes up 5 pages and there isn't a page footer on any of those pages.
2009/09/22
[ "https://Stackoverflow.com/questions/1460146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86191/" ]
I moved all of my text from the Report Header to the Report Footer, and the page numbers will print. I will add a subreport to show my detailed data.
Ken Hammady has a solution for crosstabs at <http://kenhamady.com/cru/archives/87> It can be adapted to work with long texts in textboxes.
1,460,146
I am using Crystal Reports in Visual Studio 2008. I have about 5 pages worth of static text that needs to appear at the top of my report, so I put it in the report header section. I have a page footer section on the page that shows the page number. This does not show, and I suspect it has something to do with the long report header. How can I make the page footer show with a large report header? Edit: The Page Footer is actually appearing once on the last page. The Report Header takes up 5 pages and there isn't a page footer on any of those pages.
2009/09/22
[ "https://Stackoverflow.com/questions/1460146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86191/" ]
I had exactly the same problem. My report header was very long and the page number only was appearing at last page. The problem was that i had my page number in the Report Footer. Then i realize that i had a Page Footer section and moved the page number there. I also changed the section properties (it had the No Drill down option checked). Now i have the same big header with the page number on all pages. Bye
Ken Hammady has a solution for crosstabs at <http://kenhamady.com/cru/archives/87> It can be adapted to work with long texts in textboxes.
373,876
Which of the following is most correct for the complex numbers Z and W, marked with "x" in the picture of the complex numbers below? (the dashed circle represents the unit circle) a) $Z = W + 3i$ b) $Z = W^2$ c) $W = Z^2$ d) $Z = \dfrac{1}{W}$ e) $Z = 2W$ Picture here: <http://s21.postimg.org/6tt471nd3/problem_complex_numbers.jpg> I think (c). But, I am not sure. What is your opinion?
2013/04/26
[ "https://math.stackexchange.com/questions/373876", "https://math.stackexchange.com", "https://math.stackexchange.com/users/74589/" ]
You are *already* using calculus when you are performing gradient search in the first place. At some point, you have to stop calculating derivatives and start descending! :-) In all seriousness, though: what you are describing is *exact line search*. That is, you actually want to find the minimizing value of $\gamma$, $$\gamma\_{\text{best}} = \mathop{\textrm{arg min}}\_\gamma F(a+\gamma v), \quad v = -\nabla F(a).$$ It is a very rare, and probably manufactured, case that allows you to efficiently compute $\gamma\_{\text{best}}$ analytically. It is far more likely that you will have to perform some sort of gradient or Newton descent on $\gamma$ itself to find $\gamma\_{\text{best}}$. The problem is, if you do the math on this, you will end up *having to compute the gradient $\nabla F$ at every iteration of this line search*. After all: $$\frac{d}{d\gamma} F(a+\gamma v) = \langle \nabla F(a+\gamma v), v \rangle$$ Look carefully: the gradient $\nabla F$ has to be evaluated at each value of $\gamma$ you try. That's an inefficient use of what is likely to be the most expensive computation in your algorithm! If you're computing the gradient *anyway*, the best thing to do is use it to move in the direction it tells you to move---not stay stuck along a line. What you want in practice is a *cheap* way to compute an *acceptable* $\gamma$. The common way to do this is a [backtracking line search](http://en.wikipedia.org/wiki/Backtracking_line_search). With this strategy, you start with an initial step size $\gamma$---usually a small increase on the last step size you settled on. Then you check to see if that point $a+\gamma v$ is of good quality. A common test is the Armijo-Goldstein condition $$F(a+\gamma v) \leq F(a) - c \gamma \|\nabla F(a)\|\_2^2$$ for some $c<1$. If the step passes this test, *go ahead and take it*---don't waste any time trying to tweak your step size further. If the step is too large---for instance, if $F(a+\gamma v)>F(a)$---then this test will fail, and you should cut your step size down (say, in half) and try again. This is generally a lot cheaper than doing an exact line search. I have encountered a couple of specific cases where an exact line search could be computed more cheaply than what is described above. This involved constructing a simplified formula for $F(a+\gamma v)$ , allowing the derivatives $\tfrac{d}{d\gamma}F(a+\gamma v)$ to be computed more cheaply than the full gradient $\nabla F$. One specific instance is when computing the analytic center of a linear matrix inequality. But even in that case, it was generally better overall to just do backtracking.
There is a good discussion of this in chapter 10 of [Numerical Recipes](http://apps.nrbook.com/c/index.html). Old versions are free online. You are right that if you have $F$ in a simple enough form, you can minimize over $\gamma$ by calculus. You might even be able to find the minimum directly, without iteration. Often you don't have it in that form. $x$ and $\bigtriangledown F(x)$ are both vectors and it may not be feasible to compute $\bigtriangledown F(x)$ analytically but you can search for a minimum. What it means to perform a line search is hidden in the symbolism. The value of $G(\gamma)$ is precisely the value of $F$ along a line from the current point $x$ in the direction $\bigtriangledown F(x)$. It should remind you of a parameterized line in three dimensions: a point plus a variable times a direction vector. The reason you do this is because this is the best point along that line. You expect that the value will decrease along that direction (because you have chosen the gradient, which is the direction of greatest decrease) but if you go too far it will start to increase again. Why not stop at the bottom of the valley and try again? Some of the methods in Numerical Recipes don't need any computations of the gradient at all. They come up with directions to minimize over in other ways.
373,876
Which of the following is most correct for the complex numbers Z and W, marked with "x" in the picture of the complex numbers below? (the dashed circle represents the unit circle) a) $Z = W + 3i$ b) $Z = W^2$ c) $W = Z^2$ d) $Z = \dfrac{1}{W}$ e) $Z = 2W$ Picture here: <http://s21.postimg.org/6tt471nd3/problem_complex_numbers.jpg> I think (c). But, I am not sure. What is your opinion?
2013/04/26
[ "https://math.stackexchange.com/questions/373876", "https://math.stackexchange.com", "https://math.stackexchange.com/users/74589/" ]
You are *already* using calculus when you are performing gradient search in the first place. At some point, you have to stop calculating derivatives and start descending! :-) In all seriousness, though: what you are describing is *exact line search*. That is, you actually want to find the minimizing value of $\gamma$, $$\gamma\_{\text{best}} = \mathop{\textrm{arg min}}\_\gamma F(a+\gamma v), \quad v = -\nabla F(a).$$ It is a very rare, and probably manufactured, case that allows you to efficiently compute $\gamma\_{\text{best}}$ analytically. It is far more likely that you will have to perform some sort of gradient or Newton descent on $\gamma$ itself to find $\gamma\_{\text{best}}$. The problem is, if you do the math on this, you will end up *having to compute the gradient $\nabla F$ at every iteration of this line search*. After all: $$\frac{d}{d\gamma} F(a+\gamma v) = \langle \nabla F(a+\gamma v), v \rangle$$ Look carefully: the gradient $\nabla F$ has to be evaluated at each value of $\gamma$ you try. That's an inefficient use of what is likely to be the most expensive computation in your algorithm! If you're computing the gradient *anyway*, the best thing to do is use it to move in the direction it tells you to move---not stay stuck along a line. What you want in practice is a *cheap* way to compute an *acceptable* $\gamma$. The common way to do this is a [backtracking line search](http://en.wikipedia.org/wiki/Backtracking_line_search). With this strategy, you start with an initial step size $\gamma$---usually a small increase on the last step size you settled on. Then you check to see if that point $a+\gamma v$ is of good quality. A common test is the Armijo-Goldstein condition $$F(a+\gamma v) \leq F(a) - c \gamma \|\nabla F(a)\|\_2^2$$ for some $c<1$. If the step passes this test, *go ahead and take it*---don't waste any time trying to tweak your step size further. If the step is too large---for instance, if $F(a+\gamma v)>F(a)$---then this test will fail, and you should cut your step size down (say, in half) and try again. This is generally a lot cheaper than doing an exact line search. I have encountered a couple of specific cases where an exact line search could be computed more cheaply than what is described above. This involved constructing a simplified formula for $F(a+\gamma v)$ , allowing the derivatives $\tfrac{d}{d\gamma}F(a+\gamma v)$ to be computed more cheaply than the full gradient $\nabla F$. One specific instance is when computing the analytic center of a linear matrix inequality. But even in that case, it was generally better overall to just do backtracking.
Not your question, but an *adaptive* step size can beat a constant $\gamma$, and a $\gamma\_i$ per component can beat a single $\gamma$ for all components. See [RmsProp](http://climin.readthedocs.org/en/latest/rmsprop.html) , [rmsprop.py](https://github.com/BRML/climin/blob/master/climin/rmsprop.py) and Zeiler, [ADADELTA: An adaptive learning rate method](http://arxiv.org/abs/1212.5701), 2012, 6p. But be careful with recursive / IIR filters !
12,428
I just learned of Ripple and it still seems a bit fuzzy to grasp the concept, but from what I gathered so far its a decentralized exchange that basically has the potential to overtake Bitpay and Mt.gox. I read that there are Gateway points that do the currency conversions from bitcoin to fiat. Now the other question I have is how does Ripple derive the bitcoin exchange price if everyone starts abandoning traditional exchanges that kind of dictate the price exchanges from fiat to btc. Obviously not everyone is going to abandon those exchanges anytime soon.
2013/07/31
[ "https://bitcoin.stackexchange.com/questions/12428", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/3029/" ]
Ripple supports a distributed currency exchange; anyone can offer to exchange from one currency to another. These offers are taken when a counter offer the same or better is made. Like any exchange between two parties, the price would be based on supply and demand, world events, what the market will bear, etc. The advantage is there’s no single point of failure that would cripple the market. We’ve seen what happens to bitcoin when Mt. Gox goes down or is under a denial of service attack. That’s obviously not a problem with decentralized exchanges. And with the new [Bitcoin Bridge](https://ripple.com/blog/bitcoin-bridge-lets-ripple-users-make-payments-to-bitcoin-accounts/) feature of Ripple, you can pay anyone in Bitcoin from a Ripple wallet. The currency exchange is done by an organization (a.k.a a gateway I believe) running the freely available Bitcoin Bridge protocol, like [Bitstamp](https://www.bitstamp.net). You can see as of this moment, the Bitstamp rate is $98 per Bitcoin. You can see the exchange rates of the exchanges at [Bitcoin Average](http://bitcoinaverage.com).
Bitpay and Mt. Gox (or any other currency exchange) are fundamentally different. Bitpay is not a currency exchange. Bitpay is a service for merchants who wish to take payment in Bitcoin and receive a daily payout in the currency of their choice (including Bitcoin), at an exchange rate that is fixed at the time of the initial transaction. Ripple is something else again, a distributed currency exchange and payment protocol. As a payment protocol, it is a competitor to Bitcoin, but not directly to Bitpay as a company. Ripple labs, the company, provides a different set of services. Looking at their website, it looks like there is space for a hypothetical company "Ripplepay" to provide the same technical support and guaranteed exchange rate that Bitpay offers. *My views do not reflect the views of Bitpay as a company. I just work here.*
12,428
I just learned of Ripple and it still seems a bit fuzzy to grasp the concept, but from what I gathered so far its a decentralized exchange that basically has the potential to overtake Bitpay and Mt.gox. I read that there are Gateway points that do the currency conversions from bitcoin to fiat. Now the other question I have is how does Ripple derive the bitcoin exchange price if everyone starts abandoning traditional exchanges that kind of dictate the price exchanges from fiat to btc. Obviously not everyone is going to abandon those exchanges anytime soon.
2013/07/31
[ "https://bitcoin.stackexchange.com/questions/12428", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/3029/" ]
Ripple supports a distributed currency exchange; anyone can offer to exchange from one currency to another. These offers are taken when a counter offer the same or better is made. Like any exchange between two parties, the price would be based on supply and demand, world events, what the market will bear, etc. The advantage is there’s no single point of failure that would cripple the market. We’ve seen what happens to bitcoin when Mt. Gox goes down or is under a denial of service attack. That’s obviously not a problem with decentralized exchanges. And with the new [Bitcoin Bridge](https://ripple.com/blog/bitcoin-bridge-lets-ripple-users-make-payments-to-bitcoin-accounts/) feature of Ripple, you can pay anyone in Bitcoin from a Ripple wallet. The currency exchange is done by an organization (a.k.a a gateway I believe) running the freely available Bitcoin Bridge protocol, like [Bitstamp](https://www.bitstamp.net). You can see as of this moment, the Bitstamp rate is $98 per Bitcoin. You can see the exchange rates of the exchanges at [Bitcoin Average](http://bitcoinaverage.com).
You derive the exchange price by simulating attempting the exchange and seeing what it cost you. For example, say you have 1 Bitcoin and you want to get the exchange rate to USD: You could look for someone willing to take that Bitcoin and see, among all such offers, who is offering the most USD. You may need to combine several offers if there are people offering to take only a fraction of a Bitcoin. But is that the best you can do? Maybe, maybe not. Perhaps you could trade that Bitcoin for Euros and then use those Euros to buy USD. Perhaps the best rate is to do a little bit of both, taking advantage of the best offers on multiple exchanges. This is precisely what Ripple does using pathfinding. You can think of the Ripple ledger as a giant pool of liquidity. There are balances for each account in whatever assets they hold, and order books containing offers to trade one asset for another. Pathfinding looks at this giant pool of liquidity to perform exchanges or cross-currency payments.
62,562,899
I have nginx directly installed on my server, with a proxy to a Docker container containing a Next.js application. The HTML of the Next.js is being loaded correctly, but all the assets are failing: ``` server { listen 443 ssl http2; listen [::]:443 http2; server_name app.mydomain.ml; include extras.conf; ssl_certificate /etc/letsencrypt/live/app.mydomain.ml/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/app.mydomain.ml/privkey.pem; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_max_temp_file_size 0; proxy_pass http://127.0.0.1:4000; proxy_redirect off; proxy_read_timeout 240s; } } ``` It looks like nginx is trying to open the JS files instead of passing them to the proxy. The files are inside a container. I have a similar setup which works fine on another instance. Below are part of the nginx error log: ``` 2020/06/24 19:39:50 [error] 11172#11172: *482 open() "/etc/nginx/html/_next/static/chunks/75fc9c18.5b5b04c7a1a3ce1f0adc.js" failed (2: No such file or directory), client: xxx.xxx.xxx.xxx, server: app.mydomain.ml, request: "GET /_next/static/chunks/75fc9c18.5b5b04c7a1a3ce1f0adc.js HTTP/2.0", host: "cfcdemo.ml", referrer: "https://app.mydomain.ml/" 2020/06/24 19:39:50 [error] 11172#11172: *482 open() "/etc/nginx/html/_next/static/chunks/22b3a38a.fdf56032c38364c88402.js" failed (2: No such file or directory), client: xxx.xxx.xxx.xx, server: app.mydomain.ml, request: "GET /_next/static/chunks/22b3a38a.fdf56032c38364c88402.js HTTP/2.0", host: "cfcdemo.ml", referrer: "https://app.mydomain.ml/" ```
2020/06/24
[ "https://Stackoverflow.com/questions/62562899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1029654/" ]
Removed all the crap in the location block but the proxy\_pass and suddenly worked. ``` location / { proxy_pass http://127.0.0.1:4000; } ```
Why not create a alias for this ``` location /_next { alias "/etc/nginx/html/_next/; } ```
57,464,592
I have a `while loop` that I feel should run much faster, but it takes up to 50 seconds to go through a maximum of 350 rows in the website. I have tried making separate if statements, but that took the same amount of time. ``` while 'x' not in driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[1]/span').text.strip(): VAR1 = driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr[11]/td[2]').text.strip() if driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[1]/span').text.strip() == 'Y': VAR2 = '' VAR2 = driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[2]/span').text.strip() elif driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[1]/span').text.strip() == 'Z': VAR3 = '' VAR3 = driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[2]/span').text.strip() elif driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[1]/span').text.strip() == 'A': VAR4 = '' VAR4 = driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[2]/span').text.strip() elif driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[1]/span').text.strip() == 'B': VAR5 = '' VAR5 = driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[2]/span').text.strip() elif driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[1]/span').text.strip() == 'C': VAR6 = '' VAR6 = driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[2]/span').text.strip() elif driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[1]/span').text.strip() == 'D': VAR7 = '' VAR7 = driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[2]/span').text.strip() elif driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[1]/span').text.strip() == 'E': VAR8 = '' VAR8 = driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[2]/span').text.strip() else: pass output = VAR1 + '|' + VAR2 + '|' + VAR3 + '|' + VAR4 + '|' + VAR5 + '|' + VAR6 + '|' + VAR7 + '|' + VAR8 print(output) n += 1 else: n += 1 ``` I am getting the proper output, but it is taking a long time. Is there anything that I can do to increase the speed of my loop?
2019/08/12
[ "https://Stackoverflow.com/questions/57464592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11672154/" ]
The main problem is that you're calling a non-trivial function somewhere from 3 to 9 times, and most of those calls simply repeat a search you've already done. Call the function *once* for each line you want to examine, store the result, and compare against that. ``` # This call has no variables; do it only once VAR1 = driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr[11]/td[2]').text.strip() # Let a `for` handle your counter; break the loop when done. for n in range(len(your_table)): row_n = driver.find_element_by_xpath('/html/body/form/table[2]/tbody/tr[2]/th/div/table/tbody/tr['+str(n)+']/td[1]/span').text.strip() if x in row_n: break elif row_n = "Y": ... ``` Also consider handling your series of `VARn` variables with a list; you could index the target strings with a similar list `["Y", "A", ...]` and then build your output line with an inner loop and a `join` call.
I would recommend to use xpath axis for locating elements in different positions. Using loops have a higher cost on the code and it takes unwanted time to reach the specific element. Now with xpath axis you can easily traverse between the xpaths upward or downward in the DOM.
402,268
I want to write a PHP code snippet in the question or answer. I searched that but Stack Overflow can insert only HTML, CSS, JavaScript snippet code. How can I insert a PHP code snippet like below? JavaScript snippet example: ```js console.log('hello world'); ```
2020/10/22
[ "https://meta.stackoverflow.com/questions/402268", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/10770469/" ]
Stack Overflow has no features for executing live demos of PHP code in questions. You should format a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) as a regular code block: ``` ```php <?php echo "123"; ?> ``` ``` You might additionally link to a live demo using a third-party demo hosting service. (Google finds [PHPFiddle](http://phpfiddle.org/), I can't speak to the quality of the service).
There isn't any way to run PHP code. You have to insert an additional link in your question/answer to share your PHP code snippet with fellow members. A PHP code snippet can be shared by using the following websites: <http://www.writephponline.com/> <http://phptester.net/> - [My choice] <https://www.mycompiler.io/online-php-compiler> <https://paiza.io/en/languages/online-php-editor> And many more. You can also google for this using "PHP code snippets online" keywords ;)
402,268
I want to write a PHP code snippet in the question or answer. I searched that but Stack Overflow can insert only HTML, CSS, JavaScript snippet code. How can I insert a PHP code snippet like below? JavaScript snippet example: ```js console.log('hello world'); ```
2020/10/22
[ "https://meta.stackoverflow.com/questions/402268", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/10770469/" ]
Stack Overflow has no features for executing live demos of PHP code in questions. You should format a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) as a regular code block: ``` ```php <?php echo "123"; ?> ``` ``` You might additionally link to a live demo using a third-party demo hosting service. (Google finds [PHPFiddle](http://phpfiddle.org/), I can't speak to the quality of the service).
If you understand the difference between client- and server-side code and the security implications thereof, you will understand why this is not, and probably never will be, a feature on Stack Overflow.
402,268
I want to write a PHP code snippet in the question or answer. I searched that but Stack Overflow can insert only HTML, CSS, JavaScript snippet code. How can I insert a PHP code snippet like below? JavaScript snippet example: ```js console.log('hello world'); ```
2020/10/22
[ "https://meta.stackoverflow.com/questions/402268", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/10770469/" ]
Stack Overflow has no features for executing live demos of PHP code in questions. You should format a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) as a regular code block: ``` ```php <?php echo "123"; ?> ``` ``` You might additionally link to a live demo using a third-party demo hosting service. (Google finds [PHPFiddle](http://phpfiddle.org/), I can't speak to the quality of the service).
No, probably not, you should use code blocks instead as specified in the other answers. Adding to the other answers, here are a few extra points: * The PHP stack snippets would use up all the server CPU/RAM which would make the whole experience slightly slower for everyone * The PHP `mail()` function could be used to send spam email to lots of people, and, again, could overwhelm the server * You can do all sorts of destructive things with PHP, including changing databases, and even deleting files. * Too many requests for PHP could even put Stack Overflow offline. Yikes.
402,268
I want to write a PHP code snippet in the question or answer. I searched that but Stack Overflow can insert only HTML, CSS, JavaScript snippet code. How can I insert a PHP code snippet like below? JavaScript snippet example: ```js console.log('hello world'); ```
2020/10/22
[ "https://meta.stackoverflow.com/questions/402268", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/10770469/" ]
If you understand the difference between client- and server-side code and the security implications thereof, you will understand why this is not, and probably never will be, a feature on Stack Overflow.
There isn't any way to run PHP code. You have to insert an additional link in your question/answer to share your PHP code snippet with fellow members. A PHP code snippet can be shared by using the following websites: <http://www.writephponline.com/> <http://phptester.net/> - [My choice] <https://www.mycompiler.io/online-php-compiler> <https://paiza.io/en/languages/online-php-editor> And many more. You can also google for this using "PHP code snippets online" keywords ;)
402,268
I want to write a PHP code snippet in the question or answer. I searched that but Stack Overflow can insert only HTML, CSS, JavaScript snippet code. How can I insert a PHP code snippet like below? JavaScript snippet example: ```js console.log('hello world'); ```
2020/10/22
[ "https://meta.stackoverflow.com/questions/402268", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/10770469/" ]
No, probably not, you should use code blocks instead as specified in the other answers. Adding to the other answers, here are a few extra points: * The PHP stack snippets would use up all the server CPU/RAM which would make the whole experience slightly slower for everyone * The PHP `mail()` function could be used to send spam email to lots of people, and, again, could overwhelm the server * You can do all sorts of destructive things with PHP, including changing databases, and even deleting files. * Too many requests for PHP could even put Stack Overflow offline. Yikes.
There isn't any way to run PHP code. You have to insert an additional link in your question/answer to share your PHP code snippet with fellow members. A PHP code snippet can be shared by using the following websites: <http://www.writephponline.com/> <http://phptester.net/> - [My choice] <https://www.mycompiler.io/online-php-compiler> <https://paiza.io/en/languages/online-php-editor> And many more. You can also google for this using "PHP code snippets online" keywords ;)
402,268
I want to write a PHP code snippet in the question or answer. I searched that but Stack Overflow can insert only HTML, CSS, JavaScript snippet code. How can I insert a PHP code snippet like below? JavaScript snippet example: ```js console.log('hello world'); ```
2020/10/22
[ "https://meta.stackoverflow.com/questions/402268", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/10770469/" ]
If you understand the difference between client- and server-side code and the security implications thereof, you will understand why this is not, and probably never will be, a feature on Stack Overflow.
No, probably not, you should use code blocks instead as specified in the other answers. Adding to the other answers, here are a few extra points: * The PHP stack snippets would use up all the server CPU/RAM which would make the whole experience slightly slower for everyone * The PHP `mail()` function could be used to send spam email to lots of people, and, again, could overwhelm the server * You can do all sorts of destructive things with PHP, including changing databases, and even deleting files. * Too many requests for PHP could even put Stack Overflow offline. Yikes.
8,937,277
I have this working in C#, but don't know where to go with Objective C (Xcode specifically). I have 8 buttons Stack1, Stack2, etc. I want to choose Stack(variable) and change the image. In C# I used Button Stacks = this.Controls["Stack" + StackNumber.ToString()] as Button; Stacks.BackgroundImage = ..... Can I do this in Objective C also?
2012/01/20
[ "https://Stackoverflow.com/questions/8937277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066553/" ]
``` $('#submit').click(function(e) { var flag = true; $('select').each(function(){ if($(this).val() == "select one"){ alert("please select a value in " + $(this).attr("name")); flag = false; } }); if(flag){ alert('perfect'); }else{ e.preventDefault(); } }); ``` EXAMPLE : <http://jsfiddle.net/raj_er04/3kHVY/1/> Quick note: If you want the alert to only show once rather than once per each 'select one', simply move the alert() into the else{ statement. thanks again for this answer!
Your test fails because `length` is not a method. It is a property. Remove the `()`. If you look in your debugger you should see a warning about this. Also, your selector should be checking the selected option, not the select list itself. <http://jsfiddle.net/7PPs4/> ``` $('#submit').click(function() { $foo = $('#step_1 select option:selected[value="select one"]'); alert($foo.length); }); ```
8,937,277
I have this working in C#, but don't know where to go with Objective C (Xcode specifically). I have 8 buttons Stack1, Stack2, etc. I want to choose Stack(variable) and change the image. In C# I used Button Stacks = this.Controls["Stack" + StackNumber.ToString()] as Button; Stacks.BackgroundImage = ..... Can I do this in Objective C also?
2012/01/20
[ "https://Stackoverflow.com/questions/8937277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066553/" ]
You can do this with $.each(): ``` $('#step_1').find('SELECT').each( function() { if( $(this).val() === 'select one' ) { alert('Please select yes or no!'); return false; } }); ``` Note that returning false will prevent the loop from continuing once a missing field is found.
Your test fails because `length` is not a method. It is a property. Remove the `()`. If you look in your debugger you should see a warning about this. Also, your selector should be checking the selected option, not the select list itself. <http://jsfiddle.net/7PPs4/> ``` $('#submit').click(function() { $foo = $('#step_1 select option:selected[value="select one"]'); alert($foo.length); }); ```
8,937,277
I have this working in C#, but don't know where to go with Objective C (Xcode specifically). I have 8 buttons Stack1, Stack2, etc. I want to choose Stack(variable) and change the image. In C# I used Button Stacks = this.Controls["Stack" + StackNumber.ToString()] as Button; Stacks.BackgroundImage = ..... Can I do this in Objective C also?
2012/01/20
[ "https://Stackoverflow.com/questions/8937277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066553/" ]
``` $('#submit').click(function(e) { var flag = true; $('select').each(function(){ if($(this).val() == "select one"){ alert("please select a value in " + $(this).attr("name")); flag = false; } }); if(flag){ alert('perfect'); }else{ e.preventDefault(); } }); ``` EXAMPLE : <http://jsfiddle.net/raj_er04/3kHVY/1/> Quick note: If you want the alert to only show once rather than once per each 'select one', simply move the alert() into the else{ statement. thanks again for this answer!
You can do this with $.each(): ``` $('#step_1').find('SELECT').each( function() { if( $(this).val() === 'select one' ) { alert('Please select yes or no!'); return false; } }); ``` Note that returning false will prevent the loop from continuing once a missing field is found.
49,633
I'm replacing the wiring from a vintage chandelier and need to know what gauge wire to use. There are five lights on it. This is for the fixture only!
2014/10/02
[ "https://diy.stackexchange.com/questions/49633", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/25713/" ]
18g stranded wire is [quite common on arms](http://www.thisoldhouse.com/toh/photos/0,,20267510_20599803,00.html) 14g stranded is often used to join the 18g arm strands, and to tie into the ceiling. This applies to North America and normal chandeliers with relatively low (<50 each) wattage bulbs.
If you're in the US, NEC likely applies. Article 402 covers fixture wires, and explains what types and sizes are allowed. Type ==== Table 402.3 lists the types of wires allowed to be used as fixture wires. If you're going to rewire the fixture, you'll have to use a type of wire listed in this table. * FFH-2 * HF, HFF * KF-1, KF-2, KFF-1, KFF-2 * PAF, PAFF * PF, PFF * PGF, PGFF * PTF, PTFF * RFH-1, RFH-2, RFHH-2, RFHH-3 * SF-1, SF-2, SFF-1, SFF-2 * TF, TFF * TFN, TFFN * XF, XFF * ZF * ZFF * ZHF Size ==== Table 402.5 lists the allowable ampacity for different sizes of wire. You'll want to use a wire that's sized properly for the load you'll be serving. In most cases, the maximum bulb size you'll have to account for is 100 Watt. Which means you'll likely only be looking at about 833 mA (100 Watts/120 Volts), so you can probably get away with 18 AWG wire. > > ![Table 402.5](https://i.stack.imgur.com/tkY7x.png) > > > 402.6 says that fixture wires cannot be smaller than 18 AWG, so you'll have to use at least that size wire. Overcurrent Protection ====================== 402.12 points to 240.5 for overcurrent protection of fixture wires, which tells you what size overcurrent is required for different sized wires. 240.5(B)(2) lists the size and length of fixture wires, when connected to circuits with various sizes of overcurrent protection. > > National Electrical Code 2014 > ============================= > > > Article 240 Overcurrent Protection > ---------------------------------- > > > ### I. General > > > **240.5 Protection of Flexible Cords, Flexible Cables, and Fixture Wires.** > > > **(B) Branch-Circuit Overcurrent Device.** > > > **(2) Fixture Wire.** Fixture wire shall be permitted to be > tapped to the branch-circuit conductor of a branch circuit in > accordance with the following: > > > (1) 20-ampere circuits — 18 AWG, up to 15 m (50 ft) of run length > > (2) 20-ampere circuits — 16 AWG, up to 30 m (100 ft) of run length > > (3) 20-ampere circuits — 14 AWG and larger > > (4) 30-ampere circuits — 14 AWG and larger > > (5) 40-ampere circuits — 12 AWG and larger > > (6) 50-ampere circuits — 12 AWG and larger > > > Conduit/Tube Fill ================= You may also have to refer to Table 1 of Chapter 9, to determine the maximum number of wires that can be in a conduit or tube.
49,633
I'm replacing the wiring from a vintage chandelier and need to know what gauge wire to use. There are five lights on it. This is for the fixture only!
2014/10/02
[ "https://diy.stackexchange.com/questions/49633", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/25713/" ]
18g stranded wire is [quite common on arms](http://www.thisoldhouse.com/toh/photos/0,,20267510_20599803,00.html) 14g stranded is often used to join the 18g arm strands, and to tie into the ceiling. This applies to North America and normal chandeliers with relatively low (<50 each) wattage bulbs.
Agree 18 awg for the arms and 16 awg is desirable for a splice if needed to feed the ceiling junction box although 18 awg could be used by code as long as the total current stays below 6 amps. House wiring must be at least 14 awg or larger. The thinner gauge 18 and 16 awg is allowed because the wiring is not buried in a wall and is not adjacent to flammable materials. It must be "fixture wire" with quality high temperature insulation; doorbell or speaker wire is not likely to have this type of insulation.
49,633
I'm replacing the wiring from a vintage chandelier and need to know what gauge wire to use. There are five lights on it. This is for the fixture only!
2014/10/02
[ "https://diy.stackexchange.com/questions/49633", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/25713/" ]
If you're in the US, NEC likely applies. Article 402 covers fixture wires, and explains what types and sizes are allowed. Type ==== Table 402.3 lists the types of wires allowed to be used as fixture wires. If you're going to rewire the fixture, you'll have to use a type of wire listed in this table. * FFH-2 * HF, HFF * KF-1, KF-2, KFF-1, KFF-2 * PAF, PAFF * PF, PFF * PGF, PGFF * PTF, PTFF * RFH-1, RFH-2, RFHH-2, RFHH-3 * SF-1, SF-2, SFF-1, SFF-2 * TF, TFF * TFN, TFFN * XF, XFF * ZF * ZFF * ZHF Size ==== Table 402.5 lists the allowable ampacity for different sizes of wire. You'll want to use a wire that's sized properly for the load you'll be serving. In most cases, the maximum bulb size you'll have to account for is 100 Watt. Which means you'll likely only be looking at about 833 mA (100 Watts/120 Volts), so you can probably get away with 18 AWG wire. > > ![Table 402.5](https://i.stack.imgur.com/tkY7x.png) > > > 402.6 says that fixture wires cannot be smaller than 18 AWG, so you'll have to use at least that size wire. Overcurrent Protection ====================== 402.12 points to 240.5 for overcurrent protection of fixture wires, which tells you what size overcurrent is required for different sized wires. 240.5(B)(2) lists the size and length of fixture wires, when connected to circuits with various sizes of overcurrent protection. > > National Electrical Code 2014 > ============================= > > > Article 240 Overcurrent Protection > ---------------------------------- > > > ### I. General > > > **240.5 Protection of Flexible Cords, Flexible Cables, and Fixture Wires.** > > > **(B) Branch-Circuit Overcurrent Device.** > > > **(2) Fixture Wire.** Fixture wire shall be permitted to be > tapped to the branch-circuit conductor of a branch circuit in > accordance with the following: > > > (1) 20-ampere circuits — 18 AWG, up to 15 m (50 ft) of run length > > (2) 20-ampere circuits — 16 AWG, up to 30 m (100 ft) of run length > > (3) 20-ampere circuits — 14 AWG and larger > > (4) 30-ampere circuits — 14 AWG and larger > > (5) 40-ampere circuits — 12 AWG and larger > > (6) 50-ampere circuits — 12 AWG and larger > > > Conduit/Tube Fill ================= You may also have to refer to Table 1 of Chapter 9, to determine the maximum number of wires that can be in a conduit or tube.
Agree 18 awg for the arms and 16 awg is desirable for a splice if needed to feed the ceiling junction box although 18 awg could be used by code as long as the total current stays below 6 amps. House wiring must be at least 14 awg or larger. The thinner gauge 18 and 16 awg is allowed because the wiring is not buried in a wall and is not adjacent to flammable materials. It must be "fixture wire" with quality high temperature insulation; doorbell or speaker wire is not likely to have this type of insulation.
4,491,775
The class $W$ of well-ordered sets is not first-order axiomatizable. However, it does have an associated first-order theory $Th(W)$. I define a pseudo-well-ordered set to be an ordered set $(S;\leq)$ that satisfies $Th(W)$. My question is, is the class of pseudo-well-ordered set closed under taking substructures? If so, I want a proof. If not, I would like an explicit pseudo-well-ordered set $(S;\leq)$ and a suborder $(T;\leq)$ of $(S;\leq)$ such that $(T;\leq)$ is not pseudo-well-ordered.
2022/07/13
[ "https://math.stackexchange.com/questions/4491775", "https://math.stackexchange.com", "https://math.stackexchange.com/users/107952/" ]
$\omega+\zeta$ satisfies all the first-order sentences satisfied by $\omega$, but $\zeta$ does not satisfy "there is a smallest element".
Take any countable non-standard model of $\sf PA$ which is elementarily equivalent to the standard one, it is known that the order type of such model has the form $\Bbb{N+Q\times Z}$, therefore it contains a suborder isomorphic to $\Bbb Q$, which is clearly not satisfying the theory of pseudo-well-orders.
4,491,775
The class $W$ of well-ordered sets is not first-order axiomatizable. However, it does have an associated first-order theory $Th(W)$. I define a pseudo-well-ordered set to be an ordered set $(S;\leq)$ that satisfies $Th(W)$. My question is, is the class of pseudo-well-ordered set closed under taking substructures? If so, I want a proof. If not, I would like an explicit pseudo-well-ordered set $(S;\leq)$ and a suborder $(T;\leq)$ of $(S;\leq)$ such that $(T;\leq)$ is not pseudo-well-ordered.
2022/07/13
[ "https://math.stackexchange.com/questions/4491775", "https://math.stackexchange.com", "https://math.stackexchange.com/users/107952/" ]
Your question has a strong negative answer. Let $S$ be *any* linear order which is not a well-order (for example, any pseudo-well-order which is not a well-order). Then $S$ has an infinite descending chain $s\_0>s\_1>s\_2>\dots$. Let $T=\{s\_i\mid i\in \omega\}$. Then $T$ is a sub-order with no minimal element, so $T$ is not a pseudo-well-order. So we've shown: every sub-order of $S$ is a pseudo-well-order if and only if $S$ is actually a well-order. However, there is a positive answer to a related question. A definable sub-order of $S$ is one of the form $\varphi(S)=\{s\in S\mid S\models \varphi(s)\}$ for some formula $\varphi(x)$ with one free variable. Let $S$ be a pseudo-well-order. Then every definable sub-order of $S$ is a pseudo-well-order. The proof is not hard. Fix a pseudo-well-order $S$ and a formula $\varphi(x)$ with one free variable. Let $\psi\in \mathrm{Th}(W)$. Write $\psi^\varphi$ for the relativization of $\psi$ to $\varphi(x)$. So for any linear order $L$, $L\models \psi^\varphi$ if and only if $\varphi(L)\models \psi$. Now for any well-order $L$, the suborder $\varphi(L)$ is also a well-order, so $\varphi(L)\models \psi$. Thus $L\models \psi^\varphi$, so $\psi^\varphi\in \mathrm{Th}(W)$. Since $S$ is a pseudo-well-order, $S\models \psi^\varphi$, so $\varphi(S)\models \psi$. We've shown that $\varphi(S)\models \mathrm{Th}(W)$, so this definable sub-order is a pseudo-well-order.
Take any countable non-standard model of $\sf PA$ which is elementarily equivalent to the standard one, it is known that the order type of such model has the form $\Bbb{N+Q\times Z}$, therefore it contains a suborder isomorphic to $\Bbb Q$, which is clearly not satisfying the theory of pseudo-well-orders.
47,226,069
A co-worker and I have been working on the same branch for a week, constantly pushing/pulling changes and all of a sudden today, I hit 'pull' to see if there were any changes I needed to pull and I got an error. This is in sourcetree by the way. The error was this: ``` git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken From https://bitbucket.org/colossus ! [new branch] angular_removal -> origin/angular_removal (unable to update local ref) ``` I'm in sourcetree, which has a terminal built in, but I can't seem to find a resolution here.
2017/11/10
[ "https://Stackoverflow.com/questions/47226069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954280/" ]
NOTE: This is the only solution that seems to work for some people, but is also a dangerous operation, that has broken some people's local repos. Please use carefully, and at your own discretion. Here are the steps that fixed it for me: 1. Delete the file `.git/packed_refs` 2. Do a pull. 3. Run `git pack-refs` to recreate the packed\_refs file. For reference, see: <https://git-scm.com/docs/git-pack-refs>
Case 1: Let check branchs from git-server if they are duplicate or not. ``` Example: two branchs below are duplicate: - upper_with_lower - UPPER_with_lower ---> Let consider removing one of them. ``` Case 2: The branch you are pushing are duplicate with other branch.
47,226,069
A co-worker and I have been working on the same branch for a week, constantly pushing/pulling changes and all of a sudden today, I hit 'pull' to see if there were any changes I needed to pull and I got an error. This is in sourcetree by the way. The error was this: ``` git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken From https://bitbucket.org/colossus ! [new branch] angular_removal -> origin/angular_removal (unable to update local ref) ``` I'm in sourcetree, which has a terminal built in, but I can't seem to find a resolution here.
2017/11/10
[ "https://Stackoverflow.com/questions/47226069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954280/" ]
The error text was slightly different for me like: `unable to update local ref it is [hash_code_1] but expected [hash_code_2]`. So the command like `rm -rf .git/refs/remotes/origin/angular_removal` helped me only to do fetch once. Then the message would return again. What actually helped in this situation to fix the issue permanently was: 1. go into .git subfolder of my local repository; 2. open packed-refs file; 3. find the line with branch name from error message; 4. remove it from this file; 5. now you can do fetch or pull all you like.
Just happened to me as well; one of my ref branches under my alias was corrupted. Fix: ``` rm <root of repository>.git/refs/remotes/origin/<your alias> git fetch ``` You can use `rd /s` instead of `rm` on Windows. Here are the detailed steps I took to fix the issue. You may choose to skip some of the steps below: 1. I first committed all my local changes in the local branch that was giving me the issue. 2. Created [git patches](https://robots.thoughtbot.com/send-a-patch-to-someone-using-git-format-patch) for my local branch. 3. Deleted my local branch. 4. Applied the following fix 5. Checked out the remote branch after running git fetch 6. Applied the necessary patch files to the local branch. This made git restore the ref file. After that everything worked as expected again.
47,226,069
A co-worker and I have been working on the same branch for a week, constantly pushing/pulling changes and all of a sudden today, I hit 'pull' to see if there were any changes I needed to pull and I got an error. This is in sourcetree by the way. The error was this: ``` git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken From https://bitbucket.org/colossus ! [new branch] angular_removal -> origin/angular_removal (unable to update local ref) ``` I'm in sourcetree, which has a terminal built in, but I can't seem to find a resolution here.
2017/11/10
[ "https://Stackoverflow.com/questions/47226069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954280/" ]
The accepted solution provides details only about how OP got around the issue and it is not a definitive answer. For the sake of people like me who end up here from Google, Here is the solution that actually works. Lets say, if the error message looks like below, ``` error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken ``` Here, the offending element is a corrupted file named `refs/remotes/origin/angular_removal` which resides in the `.git` hidden folder. Inorder to fix this, run the following commands under your repository root directory. ``` rm .git/refs/remotes/origin/angular_removal git fsck ``` The first command alone should fix the issue as `git` tries to reinitialize the missing references. The command `git fsck` is to there just to check if the repository is in good health. --- > > **NOTE** : The `ref` file would be of different for others. So make sure > you are using the `ref` file name from the error message that you got.\*\* > > >
Multiple solutions didn't quite resolve it but I ended up re-cloning
47,226,069
A co-worker and I have been working on the same branch for a week, constantly pushing/pulling changes and all of a sudden today, I hit 'pull' to see if there were any changes I needed to pull and I got an error. This is in sourcetree by the way. The error was this: ``` git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken From https://bitbucket.org/colossus ! [new branch] angular_removal -> origin/angular_removal (unable to update local ref) ``` I'm in sourcetree, which has a terminal built in, but I can't seem to find a resolution here.
2017/11/10
[ "https://Stackoverflow.com/questions/47226069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954280/" ]
I was able to get this fixed by deleted all the items in the `.git/packed-refs` file. Then I just did a git pull in terminal to get all the references/code from the remote.
``` git pull ``` resulted in the following error. ``` error: cannot lock ref 'refs/remotes/origin/e2e/gb-feedback-test': is at 2962f77c6b4248a82efbd4d3c*******f but expected c3c0af7e310247b4e8dfd94883******5 From https://company.com ! c3c0af7e3..2962f77c6 branch-name -> origin/branch-name (unable to update local ref) ``` It was resolved by ``` git pull origin master ```
47,226,069
A co-worker and I have been working on the same branch for a week, constantly pushing/pulling changes and all of a sudden today, I hit 'pull' to see if there were any changes I needed to pull and I got an error. This is in sourcetree by the way. The error was this: ``` git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken From https://bitbucket.org/colossus ! [new branch] angular_removal -> origin/angular_removal (unable to update local ref) ``` I'm in sourcetree, which has a terminal built in, but I can't seem to find a resolution here.
2017/11/10
[ "https://Stackoverflow.com/questions/47226069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954280/" ]
I had a similar issue, but I couldn't push my commit from my local branch to the remote branch. Looking inside sourcetree under my remote branches, my branch suddenly didn't exist. I tried @Dudar answer, but the branch wasnt mentioned in the packed-refs file. So what I did was: 1. go into .git\refs\remotes\origin\feature subfolder of my local repository; 2. delete the file named as my branch causing the issue; 3. push my changes Note: My branch existed in a subfolder of origin called "feature".
Update ref. ``` $ git update-ref -d refs/remotes/origin/[branchname] ```
47,226,069
A co-worker and I have been working on the same branch for a week, constantly pushing/pulling changes and all of a sudden today, I hit 'pull' to see if there were any changes I needed to pull and I got an error. This is in sourcetree by the way. The error was this: ``` git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken From https://bitbucket.org/colossus ! [new branch] angular_removal -> origin/angular_removal (unable to update local ref) ``` I'm in sourcetree, which has a terminal built in, but I can't seem to find a resolution here.
2017/11/10
[ "https://Stackoverflow.com/questions/47226069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954280/" ]
The accepted solution provides details only about how OP got around the issue and it is not a definitive answer. For the sake of people like me who end up here from Google, Here is the solution that actually works. Lets say, if the error message looks like below, ``` error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken ``` Here, the offending element is a corrupted file named `refs/remotes/origin/angular_removal` which resides in the `.git` hidden folder. Inorder to fix this, run the following commands under your repository root directory. ``` rm .git/refs/remotes/origin/angular_removal git fsck ``` The first command alone should fix the issue as `git` tries to reinitialize the missing references. The command `git fsck` is to there just to check if the repository is in good health. --- > > **NOTE** : The `ref` file would be of different for others. So make sure > you are using the `ref` file name from the error message that you got.\*\* > > >
NOTE: This is the only solution that seems to work for some people, but is also a dangerous operation, that has broken some people's local repos. Please use carefully, and at your own discretion. Here are the steps that fixed it for me: 1. Delete the file `.git/packed_refs` 2. Do a pull. 3. Run `git pack-refs` to recreate the packed\_refs file. For reference, see: <https://git-scm.com/docs/git-pack-refs>
47,226,069
A co-worker and I have been working on the same branch for a week, constantly pushing/pulling changes and all of a sudden today, I hit 'pull' to see if there were any changes I needed to pull and I got an error. This is in sourcetree by the way. The error was this: ``` git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken From https://bitbucket.org/colossus ! [new branch] angular_removal -> origin/angular_removal (unable to update local ref) ``` I'm in sourcetree, which has a terminal built in, but I can't seem to find a resolution here.
2017/11/10
[ "https://Stackoverflow.com/questions/47226069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954280/" ]
NOTE: This is the only solution that seems to work for some people, but is also a dangerous operation, that has broken some people's local repos. Please use carefully, and at your own discretion. Here are the steps that fixed it for me: 1. Delete the file `.git/packed_refs` 2. Do a pull. 3. Run `git pack-refs` to recreate the packed\_refs file. For reference, see: <https://git-scm.com/docs/git-pack-refs>
Locate to the project folder in Terminal ``` git gc --prune=now rm -rf .git/refs/remotes/origin ```
47,226,069
A co-worker and I have been working on the same branch for a week, constantly pushing/pulling changes and all of a sudden today, I hit 'pull' to see if there were any changes I needed to pull and I got an error. This is in sourcetree by the way. The error was this: ``` git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken From https://bitbucket.org/colossus ! [new branch] angular_removal -> origin/angular_removal (unable to update local ref) ``` I'm in sourcetree, which has a terminal built in, but I can't seem to find a resolution here.
2017/11/10
[ "https://Stackoverflow.com/questions/47226069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954280/" ]
Multiple solutions didn't quite resolve it but I ended up re-cloning
Locate to the project folder in Terminal ``` git gc --prune=now rm -rf .git/refs/remotes/origin ```
47,226,069
A co-worker and I have been working on the same branch for a week, constantly pushing/pulling changes and all of a sudden today, I hit 'pull' to see if there were any changes I needed to pull and I got an error. This is in sourcetree by the way. The error was this: ``` git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken From https://bitbucket.org/colossus ! [new branch] angular_removal -> origin/angular_removal (unable to update local ref) ``` I'm in sourcetree, which has a terminal built in, but I can't seem to find a resolution here.
2017/11/10
[ "https://Stackoverflow.com/questions/47226069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954280/" ]
I had a similar issue, but I couldn't push my commit from my local branch to the remote branch. Looking inside sourcetree under my remote branches, my branch suddenly didn't exist. I tried @Dudar answer, but the branch wasnt mentioned in the packed-refs file. So what I did was: 1. go into .git\refs\remotes\origin\feature subfolder of my local repository; 2. delete the file named as my branch causing the issue; 3. push my changes Note: My branch existed in a subfolder of origin called "feature".
Case 1: Let check branchs from git-server if they are duplicate or not. ``` Example: two branchs below are duplicate: - upper_with_lower - UPPER_with_lower ---> Let consider removing one of them. ``` Case 2: The branch you are pushing are duplicate with other branch.
47,226,069
A co-worker and I have been working on the same branch for a week, constantly pushing/pulling changes and all of a sudden today, I hit 'pull' to see if there were any changes I needed to pull and I got an error. This is in sourcetree by the way. The error was this: ``` git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin error: cannot lock ref 'refs/remotes/origin/angular_removal': unable to resolve reference 'refs/remotes/origin/angular_removal': reference broken From https://bitbucket.org/colossus ! [new branch] angular_removal -> origin/angular_removal (unable to update local ref) ``` I'm in sourcetree, which has a terminal built in, but I can't seem to find a resolution here.
2017/11/10
[ "https://Stackoverflow.com/questions/47226069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954280/" ]
I was able to get this fixed by deleted all the items in the `.git/packed-refs` file. Then I just did a git pull in terminal to get all the references/code from the remote.
Case 1: Let check branchs from git-server if they are duplicate or not. ``` Example: two branchs below are duplicate: - upper_with_lower - UPPER_with_lower ---> Let consider removing one of them. ``` Case 2: The branch you are pushing are duplicate with other branch.
12,709,276
I am interested in knowing why static destructors are not allowed in C#. Note that I am not supposing that they exist in any other language. I could have a class like this one. ``` class A { static A() { // here I can load a resource that will be avaliable for all instances // of this class. } } ``` When the application ends I may need to release the resource. So, the semantic of a static destructor could be the following: called when the application ends, for classes that contain it and were initialized in the app.
2012/10/03
[ "https://Stackoverflow.com/questions/12709276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1499972/" ]
I just wrote a tutorial on how You can use the FDT 5.6 AIR for iOS Project Template. Hope is detailed enough to set You on the right path. Here is the link: [.SWFGEEK - Using FDT 5.6 AIR for iOS Project Template](http://www.swfgeek.net/2012/10/17/using-fdt-5-6-air-for-ios-project-template/)
The tutorials on the site are outdated, that is why it will seem a little confusing. To test on device, you simply run an 'FDT AIR Application' configuration, choose the platform and if it's a mobile platform (e.g. Android or iOS) then you will see the option to test on device. ![enter image description here](https://i.stack.imgur.com/jt9r5.jpg) The next screen to pop up.... ![enter image description here](https://i.stack.imgur.com/z5O3q.jpg)
686,889
I open firefox and browse through sites. Sometimes, automatically, the cursor stops moving, I can't use the keyboard too and system is hung. It doesn't go to the command line either. I found out that this may mostly be due to a adobe flash plugin. I don't know which one or which one to remove. Every time this happens I have to manually force shutdown the computer and switch it on again. I know I've been pretty vague in giving details but I don't know how exactly this problem occurs. I'm using Ubuntu 14.04.
2015/10/18
[ "https://askubuntu.com/questions/686889", "https://askubuntu.com", "https://askubuntu.com/users/73204/" ]
> > 2. `#!/bin/bash` & zsh emulate: The first line declare that this script is running in bash. So, why there is a emulate, which is from zsh? > > > The first line, the shebang, only indicates that if the script is executed directly, it would be run using bash. Nothing prevents you from running it using zsh: ``` zsh admin.sh ``` I don't know why the author thought to test for zsh, but they did. This section of code is for zsh, and won't run in bash: ``` emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST ``` > > 3. `alias -g '${1+"$@"}'='"$@"'`: I just input this on another bash and get the error: `-g :invalid option`, I'm confused about the difference of zsh & bash, and how they work together. Could you explain it to me, please? > > > That's a very broad question. I won't explain all the differences of zsh and bash - go read the documentation of both for that. For the specific point of `alias -g`, zsh has *global* aliases. In bash, aliases are only substituted at the start of the line. In zsh, `alias -g` defines global aliases which are substituted everywhere in the line. So, in zsh, if I do: ``` alias -g foo=bar ``` And then run: ``` echo foo ``` The output will be: ``` bar ```
Your questions lacks info, but I'll try to answer it like this: 1. sed regexp demystify ``` s/\([`"$\\]\)/\\\1/g' ^ ^ ^----------------- with The character with a leading \ | | | --- the characters `"$\ | |-- replace ``` So `"` becomes `\"` 2. I have no idea, zsh isn't my cup of tea when you are running scripts. 3. Test if statements like this: ``` if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then echo "Does the if statement run in my shell?"; else echo "The else statement runs in my shell"; fi ```
29,675,159
says it all really in the title I have this javascript ``` <script> $(".tile").click(function(e){ $(this).toggleClass("flipOutX") ; }) </script> ``` I have some html dfined boxes called "tile" and the problem here is that when i click an individual tile the flipoutx function works but only the tile I have clicked.... How can I make this work for all my tiles that are all called "tile" and not just the one tile I have clicked ?
2015/04/16
[ "https://Stackoverflow.com/questions/29675159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3504751/" ]
You need to size the vectors accordingly before accessing elements. You can do that on construction, or using `resize`. `vector<int>values(5/*pre-size for 5 elements*/);` and similar for `values2` would fix your problem. Currently your program behaviour is undefined. If you want to subtract *adjacent* elements, then shouldn't you have `values2[i]=values[i+1]-values[i];`?
The line of code: ``` values2[i]=values[i+1]-values[0]; ``` will take the looked-at element away from the first element each time. Did you mean: ``` values2[i]=values[i+1]-values[i]; ``` ?
352,522
I'm working on a Bash script that makes an SSH connection via git at a given point during the script's actions. I'm trying to gracefully handle some errors that can occur, stopping the script before it ends up failing part of the way through. At one point it runs a command like `git push` which initiates a push over SSH. There's a chance that this will connect to a new host for the first time, which leads to an interactive prompt verifying the validity of the host. ``` RSA key fingerprint is 96:a9:23:5c:cc:d1:0a:d4:70:22:93:e9:9e:1e:74:2f. Are you sure you want to continue connecting (yes/no)? yes ``` I'm looking for ideas on how to either avoid the SSH prompt or fail the script early if the SSH host hasn't been approved by the user before. I took a look at [this question](https://unix.stackexchange.com/q/33271/53923). The argument could be made that this question is a duplicate of that, but the solutions listed there don't apply to my situation. I'd prefer to detect that the SSH connection can't be made without the prompt and fail in that case.
2017/03/20
[ "https://unix.stackexchange.com/questions/352522", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/53923/" ]
So, instead of adding the host to `known_hosts` automatically, you want to fail the connection if it doesn't already exist there. `StrictHostKeyChecking` is still the option to do this (as in the linked question), but instead of setting it to `no`, set it to `yes`. This will cause the connection to fail if the host key isn't known. ``` $ ssh -oStrictHostKeyChecking=yes [email protected] No ECDSA host key is known for somehost.somewhere and you have requested strict checking. Host key verification failed. ``` `ssh` exits with status 255 if an error happens, including this case, so you can test for that in the script with something like ``` if [ "$?" = 255 ] ; then echo "there was an error" fi ``` Of course it could be some other error too, you'd need to check the output from `ssh` to make sure.
The OpenSSH client may prompt the user either through the terminal or through the X11 display. If you want to make sure that the user won't be prompted, arrange to run the client with no controlling terminal and no X display. Getting rid of the X display is easy: unset the `DISPLAY` environment variable or set it to an empty string. To run the process with no controlling terminal, run it in a separate session. There's no POSIX utility for that but Linux has a [`setsid`](http://man7.org/linux/man-pages/man1/setsid.1.html) utility. ``` DISPLAY= setsid ssh … ``` Note that running the SSH client in its own session also runs it in its own process group. The main practical consequence of using `setsid` is that if the script is executed from an interactive shell, `Ctrl`+`C` won't kill the SSH client; you should put a trap for SIGINT in your script that kills the SSH client. ``` ssh_pid= trap INT TERM 'if [ -n "$ssh_pid" ]; then kill "$ssh_pid"; fi' DISPLAY= setsid ssh … & wait "$ssh_pid" unset ssh_pid ``` Beware that `ssh` returns the status code 0 if it can't make the connection because the host key verification failed. You'll need to rely on something else to determine whether the command succeeded.
38,250,261
I have a table of Appointments made by patients. I want to fetch those new patients who came to our medical facility in the current month, but that they were never here before, so we can send a welcome letter to new patients. I am not sure how to select. I want to use NOT IN, but not sure how to hold the ones in the current month, and recheck for past appointments. In this table, I would want only patient\_id 004. ``` Patient_ID Appt_Date time 001 2016-01-01 001 2015-05-09 002 2016-06-01 003 2016-07-01 003 2014-09-03 004 2016-07-02 ```
2016/07/07
[ "https://Stackoverflow.com/questions/38250261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6556651/" ]
I would use aggregation for this: ``` select patient_id from t group by patient_id having min(appt_date_time) > cast(dateadd(day, - day(getdate()), getdate()) as date) ```
I would use group by and min() with the Month() and Year() functions for this. ``` select patient_id from patient_appt -- or whatever your table name is group by patient_id -- groups all visits together for each patient having year(min(appt_date_time)) = year(getdate()) -- checks earliest visit year is current year and month(min(appt_date_time)) = month(getdate()) -- checks earliest visit month is current month ``` This yields the patient whose first ever visit matches the current month and year.
17,104
From *My Face for the World to See* (1958) by Alfred Hayes: > > Ah! she said, triumphantly: the little boy hurts, doesn't it? I said, stonily, it might be a good idea if, instead of a psychiatrist, she stopped off one afternoon at **a delousing station**. > > > Did I (with her eyes widely open) really think so? > > > Yes: I thought so. A delousing station might, after all, be ever so much more helpful than some poor doctor trying, in a scheduled hour, to disentangle that **soul** of hers. > > > **How nice to say she had one.** > > > She had one. Oh stained a little and dirtied a little and cheap a little. But she had one. > > > White and fluttery? > > > White and fluttery and from the hand of God. > > > She was delighted. A **soul**: an actual **soul**. No one, in years, had used the word. Were souls coming back, like **mahjong**? But it was such a waste, wasn't it, to have bothered giving her **one**. so superfluous. It was one of the least necessary things. A **soul**, how silly. Of what possible use could it be, except to get in the way and trip her, at critical moments, like a nightgown that was a bit too long? > > > She was smiling, with her head somewhat to one side, tracing the rim of the martini glass with her finger. > > > That was the trouble: **they** kept giving you things you didn't need. They never gave you quite what you really needed. Enough guts, for example. > > > **Didn't she have her share?** > > > Sadly, no. No she didn't. she didn't have nearly enough. **she could use more and more**. she could use scads of it for what she wanted to do. she'd trade it in: one **soul**, slightly damaged, for its equivalent in **guts**. Did I know a buyer? someone interested in second-hand **souls**? someone who'd care to exchange? Really: she was serious. She was perfectly serious. She'd love to get rid of the damn thing; it was such a nuisance having one, and being expected to take care of it, when really there wasn't time, and there were so many other more important things which needed her constant attention. > > > Was I still brooding about the little boy? > > > I don't get the meaning of the whole context clearly and I think it is because the meaning of the "soul" is unclear to me. Does "soul" in this context mean "one person" or does it mean "her spirits"? it is somehow unclear to me. I think it means "person", but in the phrase: "to disentangle that soul of hers", I thought it means "spirits". The meaning of some other words or phrase in this context that I wrote in bold is also unclear to me and maybe because the meaning of the word "soul" is unclear to me. Does "delousing station" mean "somewhere without bad people"? Does "guts" means "courage" and the writer is saying "some man who the girl become friend with give her courage"? The meaning of "did she have her shire?" is really unclear to me. Does it mean "some courage that she get"? I don't know whom "they" refers to. Could you interpret this for me? (I asked this question in ell.stackexchange with another title and they guide me to ask my question in this forum)
2021/01/09
[ "https://literature.stackexchange.com/questions/17104", "https://literature.stackexchange.com", "https://literature.stackexchange.com/users/11834/" ]
A delousing station would generally be a place that gets rid of your [lice](https://www.lexico.com/en/definition/louse) (small insects that live in your hair). However, in this extract, it seems to means a place that will stop you from being a louse (a contemptible or unpleasant person) yourself. So *delousing station* is wordplay on the meaning of the word *louse.* The same thing is true for [*soul*](https://www.lexico.com/definition/soul) — the various usages of the word *soul* mean different things. One meaning of *soul* is the part of a person that lives on after death, as opposed to their body (and either goes to heaven or to hell). This is often represented as a "white and fluttery thing." In folklore, people sometimes "sell their soul to the devil"; this is a deal where they go to Hell after they die in exchange for getting something they want in this life. Another meaning is a person's emotional nature — this is presumably what the psychiatrist is treating. For a third meaning, if you are [soulless](https://www.lexico.com/definition/soulless), you lack compassion or other human feelings. This is implicit when she talks about getting rid of her soul. And guts means courage here. Mahjongg means the game ... it presumably went out of fashion, and then was coming back into fashion around the time this was written. For some of your other questions, "how nice to say she had one" refers to her soul; "didn't she have her share" refers to guts.
From the excerpt, it seems an argument could be made that "soul" refers to some sort of ethicality - (moral) cleanliness and purity. The mention of a psychiatrist suggests some manner of mental illness. This could be from trauma or psychological disorder. White is a colour that generally represents purity and goodness. Additionally, the mention of God, combined with the talk of a "delousing station," suggests that we might turn to biblical interpretation. In Exo 8:16-19, one of the Plagues of Egypt was lice. On a basic level we can assume this further supports some kind of manifestation of evil. Lice are also small and difficult to find; this suggests that the woman is plagued by some sort of indeterminate evil. It seems overall as though the woman is struggling internally with "good and evil." I wonder if the part about the "gut" has anything to do with biblical sayings related to consumption, gluttony, and material desire.
58,121,048
I know this issue exists already and people have posted before but I can't get this working so sorry for asking this. I am using Heroku to build and deploy, this is not being done locally. I am trying to get MetaMask to get recognized in my Dapp and I am using the code generated by MetaMask to fix their privacy mode breaking change but I cannot get past 'web3' 'Web3' and 'ethereum' undefined compile error. I don't understand where it needs to go within my app. Any assistance would be greatly appreciated. Beyond appreciated. Here is my app.js: ``` import React, { Component } from 'react' import './App.css' import Navbar from './Navbar' import Content from './Content' import { connect } from 'react-redux' import { loadWeb3, loadAccount, loadToken, loadExchange } from '../store/interactions' import { contractsLoadedSelector } from '../store/selectors' window.addEventListener('load', async () => { // Modern dapp browsers... if (window.ethereum) { window.web3 = new Web3(ethereum); try { // Request account access if needed await ethereum.enable(); // Acccounts now exposed web3.eth.sendTransaction({/* ... */}); } catch (error) { // User denied account access... } } // Legacy dapp browsers... else if (window.web3) { window.web3 = new Web3(web3.currentProvider); // Acccounts always exposed web3.eth.sendTransaction({/* ... */}); } // Non-dapp browsers... else { console.log('Non-Ethereum browser detected. You should consider trying MetaMask!'); } }); class App extends Component { componentWillMount() { this.loadBlockchainData(this.props.dispatch) } async loadBlockchainData(dispatch) { const web3 = loadWeb3(dispatch) await web3.eth.net.getNetworkType() const networkId = await web3.eth.net.getId() await loadAccount(web3, dispatch) const token = await loadToken(web3, networkId, dispatch) if(!token) { window.alert('Token smart contract not detected on the current network. Please select another network with Metamask.') return } const exchange = await loadExchange(web3, networkId, dispatch) if(!exchange) { window.alert('Exchange smart contract not detected on the current network. Please select another network with Metamask.') return } } render() { return ( <div> <Navbar /> { this.props.contractsLoaded ? <Content /> : <div className="content"></div> } </div> ); } } export default connect(mapStateToProps)(App) }); ```
2019/09/26
[ "https://Stackoverflow.com/questions/58121048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11588783/" ]
As of January 2021, Metmask has removed their injected `window.web3` If you want to connect your dApp to Metamask, I'd try the following ``` export const connectWallet = async () => { if (window.ethereum) { //check if Metamask is installed try { const address = await window.ethereum.enable(); //connect Metamask const obj = { connectedStatus: true, status: "", address: address } return obj; } catch (error) { return { connectedStatus: false, status: " Connect to Metamask using the button on the top right." } } } else { return { connectedStatus: false, status: " You must install Metamask into your browser: https://metamask.io/download.html" } } }; ``` If you'd like to learn how to also sign transactions with Metamask, I'd recommend you check out this super [beginner-friendly NFT Minter tutorial](https://docs.alchemyapi.io/alchemy/tutorials/nft-minter). You got this!
[over here](https://stackoverflow.com/questions/70371844/random-error-ethereum-is-not-defined-in-vue-development-boilerplate) someone says you can solve "ethereum is not defined" by writing `const { ethereum } = window` This works for me in React 18.1.0
29,196,447
In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5. ``` App::after(function($request, $response) { if($response instanceof Illuminate\Http\Response) { $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); } }); ``` Please how do i make this work in Laravel 5. OR Please provide a better way of compressing HTML in laravel 5 if any. Thanks in advance. NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.
2015/03/22
[ "https://Stackoverflow.com/questions/29196447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772319/" ]
This is almost a copy of [Vahid's](https://stackoverflow.com/a/37510913/2836233) answer but it fixes two problems. 1) It checks if a response is a `BinaryFileResponse` as any attempt to modify this type of response will throw an Exception. 2) It retained newline characters as the complete elimination of newlines will lead to bad Javascript code on lines with single-line comment. For example, the code below ``` var a; //This is a variable var b; //This will be commented out ``` Will become ``` var a; //This is a variable var b; //This will be commented out ``` Note: At the time of this answer I couldn't get my hands on a good regex to match single line comments without complications or rather, ignore newlines on only lines with a single-line comment, so I'm hoping for a better fix. Here's the modified version. ``` <?php namespace App\Http\Middleware; use Closure; class OptimizeMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); if ($response instanceof \Symfony\Component\HttpFoundation\BinaryFileResponse) { return $response; } else { $buffer = $response->getContent(); if (strpos($buffer, '<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n+/" => "\n", "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); ini_set('zlib.output_compression', 'On'); //enable GZip, too! return $response; } } } ``` **Edit** Compressing output for every request using the middleware truly is really a bad idea, I recommend you check out [this solution by Jokerius](https://stackoverflow.com/a/45733044/2836233)
I did it with very simple code. **Example: welcome.blade.php** Add the following code to the beginning of the page ``` <?php ob_start('compress_page');?> ``` Add the following code to the end of the page: ``` <?php ob_end_flush(); function compress_page($buffer) { $search = array("/>[[:space:]]+/", "/[[:space:]]+</"); $replace = array(">","<"); return preg_replace($search, $replace, $buffer); }?> ``` **Full page code example:** ```html <?php ob_start('compress_page');?> <!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> <!-- Styles --> <style> html, body { background-color: #fff; color: #636b6f; font-family: 'Raleway', sans-serif; font-weight: 100; height: 100vh; margin: 0; } .full-height { height: 100vh; } .flex-center { align-items: center; display: flex; justify-content: center; } .position-ref { position: relative; } .top-right { position: absolute; right: 10px; top: 18px; } .content { text-align: center; } .title { font-size: 84px; } .links > a { color: #636b6f; padding: 0 25px; font-size: 12px; font-weight: 600; letter-spacing: .1rem; text-decoration: none; text-transform: uppercase; } .m-b-md { margin-bottom: 30px; } </style> </head> <body> <div class="flex-center position-ref full-height"> @if (Route::has('login')) <div class="top-right links"> @auth <a href="{{ url('/home') }}">Home</a> @else <a href="{{ route('login') }}">Login</a> <a href="{{ route('register') }}">Register</a> @endauth </div> @endif <div class="content"> <div class="title m-b-md"> Laravel </div> <div class="links"> <a href="https://laravel.com/docs">Documentation</a> <a href="https://laracasts.com">Laracasts</a> <a href="https://laravel-news.com">News</a> <a href="https://forge.laravel.com">Forge</a> <a href="https://github.com/laravel/laravel">GitHub</a> </div> </div> </div> </body> </html> <?php ob_end_flush(); function compress_page($buffer) { $search = array("/>[[:space:]]+/", "/[[:space:]]+</"); $replace = array(">","<"); return preg_replace($search, $replace, $buffer); }?> ```
29,196,447
In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5. ``` App::after(function($request, $response) { if($response instanceof Illuminate\Http\Response) { $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); } }); ``` Please how do i make this work in Laravel 5. OR Please provide a better way of compressing HTML in laravel 5 if any. Thanks in advance. NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.
2015/03/22
[ "https://Stackoverflow.com/questions/29196447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772319/" ]
It is not very good solution to minify html in middleware as you can spend a lot of CPU time on it and it runs on every request. Instead it is better to use htmlmin package ( <https://github.com/HTMLMin/Laravel-HTMLMin> ): ``` composer require htmlmin/htmlmin php artisan vendor:publish ``` Minifying HTML on blade template level and caching it in storage should be much more effective.
I have created a webpack plugin to solve same purpose.[MinifyHtmlWebpackPlugin](https://www.npmjs.com/package/minify-html-webpack-plugin) Install the plugin with npm: ```sh $ npm install minify-html-webpack-plugin --save-dev ``` For Laravel Mix Users ===================== Paste below snippets into mix.js file. ```js const MinifyHtmlWebpackPlugin = require('minify-html-webpack-plugin'); const mix = require('laravel-mix'); mix.webpackConfig({ plugins: [ new MinifyHtmlWebpackPlugin({ src: './storage/framework/views', ignoreFileNameRegex: /\.(gitignore)$/, rules: { collapseWhitespace: true, removeAttributeQuotes: true, removeComments: true, minifyJS: true, } }) ] }); ``` It will minify all view files during the Webpack build.
29,196,447
In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5. ``` App::after(function($request, $response) { if($response instanceof Illuminate\Http\Response) { $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); } }); ``` Please how do i make this work in Laravel 5. OR Please provide a better way of compressing HTML in laravel 5 if any. Thanks in advance. NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.
2015/03/22
[ "https://Stackoverflow.com/questions/29196447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772319/" ]
This is almost a copy of [Vahid's](https://stackoverflow.com/a/37510913/2836233) answer but it fixes two problems. 1) It checks if a response is a `BinaryFileResponse` as any attempt to modify this type of response will throw an Exception. 2) It retained newline characters as the complete elimination of newlines will lead to bad Javascript code on lines with single-line comment. For example, the code below ``` var a; //This is a variable var b; //This will be commented out ``` Will become ``` var a; //This is a variable var b; //This will be commented out ``` Note: At the time of this answer I couldn't get my hands on a good regex to match single line comments without complications or rather, ignore newlines on only lines with a single-line comment, so I'm hoping for a better fix. Here's the modified version. ``` <?php namespace App\Http\Middleware; use Closure; class OptimizeMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); if ($response instanceof \Symfony\Component\HttpFoundation\BinaryFileResponse) { return $response; } else { $buffer = $response->getContent(); if (strpos($buffer, '<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n+/" => "\n", "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); ini_set('zlib.output_compression', 'On'); //enable GZip, too! return $response; } } } ``` **Edit** Compressing output for every request using the middleware truly is really a bad idea, I recommend you check out [this solution by Jokerius](https://stackoverflow.com/a/45733044/2836233)
This package is much better option in my opinion [renatomarinho/laravel-page-speed](https://github.com/renatomarinho/laravel-page-speed)
29,196,447
In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5. ``` App::after(function($request, $response) { if($response instanceof Illuminate\Http\Response) { $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); } }); ``` Please how do i make this work in Laravel 5. OR Please provide a better way of compressing HTML in laravel 5 if any. Thanks in advance. NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.
2015/03/22
[ "https://Stackoverflow.com/questions/29196447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772319/" ]
It is not very good solution to minify html in middleware as you can spend a lot of CPU time on it and it runs on every request. Instead it is better to use htmlmin package ( <https://github.com/HTMLMin/Laravel-HTMLMin> ): ``` composer require htmlmin/htmlmin php artisan vendor:publish ``` Minifying HTML on blade template level and caching it in storage should be much more effective.
I did it with very simple code. **Example: welcome.blade.php** Add the following code to the beginning of the page ``` <?php ob_start('compress_page');?> ``` Add the following code to the end of the page: ``` <?php ob_end_flush(); function compress_page($buffer) { $search = array("/>[[:space:]]+/", "/[[:space:]]+</"); $replace = array(">","<"); return preg_replace($search, $replace, $buffer); }?> ``` **Full page code example:** ```html <?php ob_start('compress_page');?> <!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> <!-- Styles --> <style> html, body { background-color: #fff; color: #636b6f; font-family: 'Raleway', sans-serif; font-weight: 100; height: 100vh; margin: 0; } .full-height { height: 100vh; } .flex-center { align-items: center; display: flex; justify-content: center; } .position-ref { position: relative; } .top-right { position: absolute; right: 10px; top: 18px; } .content { text-align: center; } .title { font-size: 84px; } .links > a { color: #636b6f; padding: 0 25px; font-size: 12px; font-weight: 600; letter-spacing: .1rem; text-decoration: none; text-transform: uppercase; } .m-b-md { margin-bottom: 30px; } </style> </head> <body> <div class="flex-center position-ref full-height"> @if (Route::has('login')) <div class="top-right links"> @auth <a href="{{ url('/home') }}">Home</a> @else <a href="{{ route('login') }}">Login</a> <a href="{{ route('register') }}">Register</a> @endauth </div> @endif <div class="content"> <div class="title m-b-md"> Laravel </div> <div class="links"> <a href="https://laravel.com/docs">Documentation</a> <a href="https://laracasts.com">Laracasts</a> <a href="https://laravel-news.com">News</a> <a href="https://forge.laravel.com">Forge</a> <a href="https://github.com/laravel/laravel">GitHub</a> </div> </div> </div> </body> </html> <?php ob_end_flush(); function compress_page($buffer) { $search = array("/>[[:space:]]+/", "/[[:space:]]+</"); $replace = array(">","<"); return preg_replace($search, $replace, $buffer); }?> ```
29,196,447
In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5. ``` App::after(function($request, $response) { if($response instanceof Illuminate\Http\Response) { $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); } }); ``` Please how do i make this work in Laravel 5. OR Please provide a better way of compressing HTML in laravel 5 if any. Thanks in advance. NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.
2015/03/22
[ "https://Stackoverflow.com/questions/29196447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772319/" ]
The recommended way to do this in Larvel 5 is to rewrite your function as [middleware](http://laravel.com/docs/5.0/middleware). As stated in the docs: ..this middleware would perform its task **after** the request is handled by the application: ``` <?php namespace App\Http\Middleware; class AfterMiddleware implements Middleware { public function handle($request, Closure $next) { $response = $next($request); // Perform action return $response; } } ```
This is almost a copy of [Vahid's](https://stackoverflow.com/a/37510913/2836233) answer but it fixes two problems. 1) It checks if a response is a `BinaryFileResponse` as any attempt to modify this type of response will throw an Exception. 2) It retained newline characters as the complete elimination of newlines will lead to bad Javascript code on lines with single-line comment. For example, the code below ``` var a; //This is a variable var b; //This will be commented out ``` Will become ``` var a; //This is a variable var b; //This will be commented out ``` Note: At the time of this answer I couldn't get my hands on a good regex to match single line comments without complications or rather, ignore newlines on only lines with a single-line comment, so I'm hoping for a better fix. Here's the modified version. ``` <?php namespace App\Http\Middleware; use Closure; class OptimizeMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); if ($response instanceof \Symfony\Component\HttpFoundation\BinaryFileResponse) { return $response; } else { $buffer = $response->getContent(); if (strpos($buffer, '<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n+/" => "\n", "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); ini_set('zlib.output_compression', 'On'); //enable GZip, too! return $response; } } } ``` **Edit** Compressing output for every request using the middleware truly is really a bad idea, I recommend you check out [this solution by Jokerius](https://stackoverflow.com/a/45733044/2836233)
29,196,447
In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5. ``` App::after(function($request, $response) { if($response instanceof Illuminate\Http\Response) { $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); } }); ``` Please how do i make this work in Laravel 5. OR Please provide a better way of compressing HTML in laravel 5 if any. Thanks in advance. NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.
2015/03/22
[ "https://Stackoverflow.com/questions/29196447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772319/" ]
This package is much better option in my opinion [renatomarinho/laravel-page-speed](https://github.com/renatomarinho/laravel-page-speed)
this is best way.. we don't need to use laravel packeges .Thanks.. ```html <?php namespace App\Http\Middleware; use Closure; class OptimizeMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); ini_set('zlib.output_compression', 'On'); // If you like to enable GZip, too! return $response; } } ```
29,196,447
In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5. ``` App::after(function($request, $response) { if($response instanceof Illuminate\Http\Response) { $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); } }); ``` Please how do i make this work in Laravel 5. OR Please provide a better way of compressing HTML in laravel 5 if any. Thanks in advance. NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.
2015/03/22
[ "https://Stackoverflow.com/questions/29196447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772319/" ]
I have created a webpack plugin to solve same purpose.[MinifyHtmlWebpackPlugin](https://www.npmjs.com/package/minify-html-webpack-plugin) Install the plugin with npm: ```sh $ npm install minify-html-webpack-plugin --save-dev ``` For Laravel Mix Users ===================== Paste below snippets into mix.js file. ```js const MinifyHtmlWebpackPlugin = require('minify-html-webpack-plugin'); const mix = require('laravel-mix'); mix.webpackConfig({ plugins: [ new MinifyHtmlWebpackPlugin({ src: './storage/framework/views', ignoreFileNameRegex: /\.(gitignore)$/, rules: { collapseWhitespace: true, removeAttributeQuotes: true, removeComments: true, minifyJS: true, } }) ] }); ``` It will minify all view files during the Webpack build.
This package is much better option in my opinion [renatomarinho/laravel-page-speed](https://github.com/renatomarinho/laravel-page-speed)
29,196,447
In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5. ``` App::after(function($request, $response) { if($response instanceof Illuminate\Http\Response) { $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); } }); ``` Please how do i make this work in Laravel 5. OR Please provide a better way of compressing HTML in laravel 5 if any. Thanks in advance. NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.
2015/03/22
[ "https://Stackoverflow.com/questions/29196447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772319/" ]
Complete code is this (with custom GZip enabled) : ``` <?php namespace App\Http\Middleware; use Closure; class OptimizeMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); ini_set('zlib.output_compression', 'On'); // If you like to enable GZip, too! return $response; } } ``` Please check your browser network inspector for `Content-Length` header before/after implement this code. enjoy it ... :).. .
this is best way.. we don't need to use laravel packeges .Thanks.. ```html <?php namespace App\Http\Middleware; use Closure; class OptimizeMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $response = $next($request); $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); ini_set('zlib.output_compression', 'On'); // If you like to enable GZip, too! return $response; } } ```
29,196,447
In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5. ``` App::after(function($request, $response) { if($response instanceof Illuminate\Http\Response) { $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); } }); ``` Please how do i make this work in Laravel 5. OR Please provide a better way of compressing HTML in laravel 5 if any. Thanks in advance. NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.
2015/03/22
[ "https://Stackoverflow.com/questions/29196447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772319/" ]
I have created a webpack plugin to solve same purpose.[MinifyHtmlWebpackPlugin](https://www.npmjs.com/package/minify-html-webpack-plugin) Install the plugin with npm: ```sh $ npm install minify-html-webpack-plugin --save-dev ``` For Laravel Mix Users ===================== Paste below snippets into mix.js file. ```js const MinifyHtmlWebpackPlugin = require('minify-html-webpack-plugin'); const mix = require('laravel-mix'); mix.webpackConfig({ plugins: [ new MinifyHtmlWebpackPlugin({ src: './storage/framework/views', ignoreFileNameRegex: /\.(gitignore)$/, rules: { collapseWhitespace: true, removeAttributeQuotes: true, removeComments: true, minifyJS: true, } }) ] }); ``` It will minify all view files during the Webpack build.
I did it with very simple code. **Example: welcome.blade.php** Add the following code to the beginning of the page ``` <?php ob_start('compress_page');?> ``` Add the following code to the end of the page: ``` <?php ob_end_flush(); function compress_page($buffer) { $search = array("/>[[:space:]]+/", "/[[:space:]]+</"); $replace = array(">","<"); return preg_replace($search, $replace, $buffer); }?> ``` **Full page code example:** ```html <?php ob_start('compress_page');?> <!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> <!-- Styles --> <style> html, body { background-color: #fff; color: #636b6f; font-family: 'Raleway', sans-serif; font-weight: 100; height: 100vh; margin: 0; } .full-height { height: 100vh; } .flex-center { align-items: center; display: flex; justify-content: center; } .position-ref { position: relative; } .top-right { position: absolute; right: 10px; top: 18px; } .content { text-align: center; } .title { font-size: 84px; } .links > a { color: #636b6f; padding: 0 25px; font-size: 12px; font-weight: 600; letter-spacing: .1rem; text-decoration: none; text-transform: uppercase; } .m-b-md { margin-bottom: 30px; } </style> </head> <body> <div class="flex-center position-ref full-height"> @if (Route::has('login')) <div class="top-right links"> @auth <a href="{{ url('/home') }}">Home</a> @else <a href="{{ route('login') }}">Login</a> <a href="{{ route('register') }}">Register</a> @endauth </div> @endif <div class="content"> <div class="title m-b-md"> Laravel </div> <div class="links"> <a href="https://laravel.com/docs">Documentation</a> <a href="https://laracasts.com">Laracasts</a> <a href="https://laravel-news.com">News</a> <a href="https://forge.laravel.com">Forge</a> <a href="https://github.com/laravel/laravel">GitHub</a> </div> </div> </div> </body> </html> <?php ob_end_flush(); function compress_page($buffer) { $search = array("/>[[:space:]]+/", "/[[:space:]]+</"); $replace = array(">","<"); return preg_replace($search, $replace, $buffer); }?> ```
29,196,447
In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5. ``` App::after(function($request, $response) { if($response instanceof Illuminate\Http\Response) { $buffer = $response->getContent(); if(strpos($buffer,'<pre>') !== false) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\r/" => '', "/>\n</" => '><', "/>\s+\n</" => '><', "/>\n\s+</" => '><', ); } else { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/<\?php/" => '<?php ', "/\n([\S])/" => '$1', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', ); } $buffer = preg_replace(array_keys($replace), array_values($replace), $buffer); $response->setContent($buffer); } }); ``` Please how do i make this work in Laravel 5. OR Please provide a better way of compressing HTML in laravel 5 if any. Thanks in advance. NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.
2015/03/22
[ "https://Stackoverflow.com/questions/29196447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772319/" ]
Just in case you are rendering the view manually: ```php echo view('example.site')->render(function($view, $content) { return preg_replace( ['/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s'], ['>', '<', '\\1'], $content ); } ); ```
This package is much better option in my opinion [renatomarinho/laravel-page-speed](https://github.com/renatomarinho/laravel-page-speed)
39,156,762
``` <li class ="block" ng-repeat="i in items | searchFor:searchString" id={{i.title}}> <a><img class="gallery" id={{i.title}} ng-src="{{i.image}}" title="{{i.title}}" /></a> <a href="{{i.image}}" download><button id="eye" title="Preview"></button></a> <p>{{i.title}}</p> </li> ``` **Items list** ``` $scope.items = [ { url: '#', title: 'Mountain', image: 'https://images.unsplash.com/photo-1443890923422-7819ed4101c0' }]; ``` This throws an error > > jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: <https://images.unsplash.com/photo-1443890923422-7819ed4101c0> > > >
2016/08/26
[ "https://Stackoverflow.com/questions/39156762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6584514/" ]
Different fonts have different "aspect values" which is the size difference between a lowercase x and uppercase X for instance. You could try to use something like "font-size adjust" in your css to make all fonts have the same aspect value regardless of the font family.
I know it's an old post but try ``` -webkit-text-size-adjust:none; -ms-text-size-adjust:none; -moz-text-size-adjust:none; text-size-adjust:none; ```
9,160
I have seen a ticket opened about this on tor bug tracker, but no progress for over a year on the Tor Browser being available on arm processors. I have setup firefox with a proxy to use Tor but that is not safe because the browser itself leaks to much info. So I am asking for help if this is the right place to ask how to compile the Tor Browser on RasPi 2 on Debian/Ubuntu. Just some simple instructions for me to follow so I can compile from source, or is there an easier way?
2015/12/03
[ "https://tor.stackexchange.com/questions/9160", "https://tor.stackexchange.com", "https://tor.stackexchange.com/users/10106/" ]
Speaking from experience, this is not currently possible. During the compiling process, the make script will download some binaries that are only built for X86 and not for ARM and therefore the compilation wil fail every time. The Tor developers plan on releasing a version for Tor Browser for ARM in the future, but there is no ETA. Your best option at the current time is to download the Tor application and apply it to Firefox/Iceweasel.
On all raspberry pi's, I have found that downloading the source and then running the following commands ``` cd your/source/directory sudo ./configure && sudo make ``` If all goes well, this will install TOR from source. Note: You may need some external libraries in order for this to work. I needed libevent and libopenssh Then just run tor from the command line like so ``` tor ```
9,160
I have seen a ticket opened about this on tor bug tracker, but no progress for over a year on the Tor Browser being available on arm processors. I have setup firefox with a proxy to use Tor but that is not safe because the browser itself leaks to much info. So I am asking for help if this is the right place to ask how to compile the Tor Browser on RasPi 2 on Debian/Ubuntu. Just some simple instructions for me to follow so I can compile from source, or is there an easier way?
2015/12/03
[ "https://tor.stackexchange.com/questions/9160", "https://tor.stackexchange.com", "https://tor.stackexchange.com/users/10106/" ]
Tor Browser does not work on ARM as of this time. <https://trac.torproject.org/projects/tor/ticket/12631> TOR ticket tracker for porting to ARM hasn't had much traction at all. I wouldn't expect this project to be ported to arm anytime soon. Note: tor is available on raspberry pi. This is for running a relay. This is different from the tor browser.
On all raspberry pi's, I have found that downloading the source and then running the following commands ``` cd your/source/directory sudo ./configure && sudo make ``` If all goes well, this will install TOR from source. Note: You may need some external libraries in order for this to work. I needed libevent and libopenssh Then just run tor from the command line like so ``` tor ```
10,686,209
I am trying to attach a PDF file called download.pdf to an email in my Android App. I am copying the file first to the SDCard and then attaching it the email. I'm not if relevant, but I am testing on a galaxy tab device. The external storage path returns mnt/sdcard/ My code is as follows : ``` public void sendemail() throws IOException { CopyAssets(); String emailAddress[] = {""}; File externalStorage = Environment.getExternalStorageDirectory(); Uri uri = Uri.fromFile(new File(externalStorage.getAbsolutePath() + "/" + "download.pdf")); Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.putExtra(Intent.EXTRA_EMAIL, emailAddress); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Text"); emailIntent.setType("application/pdf"); emailIntent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(emailIntent, "Send email using:")); } public void CopyAssets() { AssetManager assetManager = getAssets(); String[] files = null; try { files = assetManager.list(""); } catch (IOException e) { Log.e("tag", e.getMessage()); } for(String filename : files) { InputStream in = null; OutputStream out = null; if (filename.equals("download.pdf")) { try { System.out.println("Filename is " + filename); in = assetManager.open(filename); File externalStorage = Environment.getExternalStorageDirectory(); out = new FileOutputStream(externalStorage.getAbsolutePath() + "/" + filename); System.out.println("Loacation is" + out); copyFile(in, out); in.close(); in = null; out.flush(); out.close(); out = null; } catch(Exception e) { Log.e("tag", e.getMessage()); } } } } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while((read = in.read(buffer)) != -1){ out.write(buffer, 0, read); } } } ``` The problem is that the file that is attached is 0 bytes in size. Can anyone spot what might be wrong ? **EDIT** I can see that the file has been saved onto the device if I look in settings, therefore this must be a problem around how I am attaching the file to the email. In the error log I am seeing : ``` gMail Attachment URI: file:///mnt/sdcard/download.pdf gMail type: application/pdf gmail name: download.pdf gmail size: 0 ``` **EDIT** Wondering if this is a bug on the galaxy tab ? If I open the file via a pdf viewer (from my app) then try to attach to a gmail email, the size is again 0. Can anyone verify ? Thank you.
2012/05/21
[ "https://Stackoverflow.com/questions/10686209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441717/" ]
``` String[] mailto = {""}; Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/CALC/REPORTS/",pdfname )); Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.putExtra(Intent.EXTRA_EMAIL, mailto); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Calc PDF Report"); emailIntent.putExtra(Intent.EXTRA_TEXT, ViewAllAccountFragment.selectac+" PDF Report"); emailIntent.setType("application/pdf"); emailIntent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(emailIntent, "Send email using:")); ```
If your download.pdf file exists in SDCard. So the problem should be get Uri from File. Try this, it works for me. ``` Uri uri = Uri.fromFile(new File("/sdcard/", "download.pdf")); ```
10,686,209
I am trying to attach a PDF file called download.pdf to an email in my Android App. I am copying the file first to the SDCard and then attaching it the email. I'm not if relevant, but I am testing on a galaxy tab device. The external storage path returns mnt/sdcard/ My code is as follows : ``` public void sendemail() throws IOException { CopyAssets(); String emailAddress[] = {""}; File externalStorage = Environment.getExternalStorageDirectory(); Uri uri = Uri.fromFile(new File(externalStorage.getAbsolutePath() + "/" + "download.pdf")); Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.putExtra(Intent.EXTRA_EMAIL, emailAddress); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Text"); emailIntent.setType("application/pdf"); emailIntent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(emailIntent, "Send email using:")); } public void CopyAssets() { AssetManager assetManager = getAssets(); String[] files = null; try { files = assetManager.list(""); } catch (IOException e) { Log.e("tag", e.getMessage()); } for(String filename : files) { InputStream in = null; OutputStream out = null; if (filename.equals("download.pdf")) { try { System.out.println("Filename is " + filename); in = assetManager.open(filename); File externalStorage = Environment.getExternalStorageDirectory(); out = new FileOutputStream(externalStorage.getAbsolutePath() + "/" + filename); System.out.println("Loacation is" + out); copyFile(in, out); in.close(); in = null; out.flush(); out.close(); out = null; } catch(Exception e) { Log.e("tag", e.getMessage()); } } } } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while((read = in.read(buffer)) != -1){ out.write(buffer, 0, read); } } } ``` The problem is that the file that is attached is 0 bytes in size. Can anyone spot what might be wrong ? **EDIT** I can see that the file has been saved onto the device if I look in settings, therefore this must be a problem around how I am attaching the file to the email. In the error log I am seeing : ``` gMail Attachment URI: file:///mnt/sdcard/download.pdf gMail type: application/pdf gmail name: download.pdf gmail size: 0 ``` **EDIT** Wondering if this is a bug on the galaxy tab ? If I open the file via a pdf viewer (from my app) then try to attach to a gmail email, the size is again 0. Can anyone verify ? Thank you.
2012/05/21
[ "https://Stackoverflow.com/questions/10686209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441717/" ]
``` String[] mailto = {""}; Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/CALC/REPORTS/",pdfname )); Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.putExtra(Intent.EXTRA_EMAIL, mailto); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Calc PDF Report"); emailIntent.putExtra(Intent.EXTRA_TEXT, ViewAllAccountFragment.selectac+" PDF Report"); emailIntent.setType("application/pdf"); emailIntent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(emailIntent, "Send email using:")); ```
The same problem happens for me also. I've cleared that using some method from examples. I've already [answered](https://stackoverflow.com/a/9273051/940096) a question similar to your query. Maybe that can be helps you.
10,686,209
I am trying to attach a PDF file called download.pdf to an email in my Android App. I am copying the file first to the SDCard and then attaching it the email. I'm not if relevant, but I am testing on a galaxy tab device. The external storage path returns mnt/sdcard/ My code is as follows : ``` public void sendemail() throws IOException { CopyAssets(); String emailAddress[] = {""}; File externalStorage = Environment.getExternalStorageDirectory(); Uri uri = Uri.fromFile(new File(externalStorage.getAbsolutePath() + "/" + "download.pdf")); Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.putExtra(Intent.EXTRA_EMAIL, emailAddress); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Text"); emailIntent.setType("application/pdf"); emailIntent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(emailIntent, "Send email using:")); } public void CopyAssets() { AssetManager assetManager = getAssets(); String[] files = null; try { files = assetManager.list(""); } catch (IOException e) { Log.e("tag", e.getMessage()); } for(String filename : files) { InputStream in = null; OutputStream out = null; if (filename.equals("download.pdf")) { try { System.out.println("Filename is " + filename); in = assetManager.open(filename); File externalStorage = Environment.getExternalStorageDirectory(); out = new FileOutputStream(externalStorage.getAbsolutePath() + "/" + filename); System.out.println("Loacation is" + out); copyFile(in, out); in.close(); in = null; out.flush(); out.close(); out = null; } catch(Exception e) { Log.e("tag", e.getMessage()); } } } } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while((read = in.read(buffer)) != -1){ out.write(buffer, 0, read); } } } ``` The problem is that the file that is attached is 0 bytes in size. Can anyone spot what might be wrong ? **EDIT** I can see that the file has been saved onto the device if I look in settings, therefore this must be a problem around how I am attaching the file to the email. In the error log I am seeing : ``` gMail Attachment URI: file:///mnt/sdcard/download.pdf gMail type: application/pdf gmail name: download.pdf gmail size: 0 ``` **EDIT** Wondering if this is a bug on the galaxy tab ? If I open the file via a pdf viewer (from my app) then try to attach to a gmail email, the size is again 0. Can anyone verify ? Thank you.
2012/05/21
[ "https://Stackoverflow.com/questions/10686209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441717/" ]
``` String[] mailto = {""}; Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/CALC/REPORTS/",pdfname )); Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.putExtra(Intent.EXTRA_EMAIL, mailto); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Calc PDF Report"); emailIntent.putExtra(Intent.EXTRA_TEXT, ViewAllAccountFragment.selectac+" PDF Report"); emailIntent.setType("application/pdf"); emailIntent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(emailIntent, "Send email using:")); ```
``` File externalStorage = Environment.getExternalStorageDirectory(); String PDFpath = externalStorage.toString(); String pdfpath =path.replace("/mnt",""); Uri uri = Uri.parse(new File("file://" + pdfpath)); ```
35,271,838
Trying to delete `<shipmentIndex Name=\"shipments\">whatever...</shipmentIndex>` if it appear more then 1 time, keeping only one. I have surrounded the item i want to delete here with \*\*\*.. The code i am using worked before, but then i added `.Value == "shipments"` and now it fail. How can i keep this code and only fix `.Value == "shipments"` to work? ``` class Program { static void Main(string[] args) { string renderedOutput = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<RootDTO xmlns:json='http://james.newtonking.com/projects/json'>" + "<destination>" + "<name>xxx</name>" + "</destination>" + "<orderData>" + "<items json:Array='true'>" + "<shipmentIndex Name=\"items\" >111</shipmentIndex>" + "<barcode>12345</barcode>" + "</items>" + "<items json:Array='true'>" + "<shipmentIndex Name=\"items\">222</shipmentIndex>" + "<barcode>12345</barcode>" + "</items>" + "<items json:Array='true'>" + "<shipmentIndex Name=\"items\">222</shipmentIndex>" + "<barcode>12345</barcode>" + "</items>" + "<misCode>9876543210</misCode>" + "<shipments>" + "<sourceShipmentId></sourceShipmentId>" + "<shipmentIndex shipments=\"shipments\">111</shipmentIndex>" + "</shipments>" + "<shipments>" + "<sourceShipmentId></sourceShipmentId>" + "<shipmentIndex Name=\"shipments\">222</shipmentIndex>" + **** "<shipmentIndex Name=\"shipments\">222</shipmentIndex>" + **** "</shipments>" + "</orderData>" + "</RootDTO>"; var xml = XElement.Parse(renderedOutput); xml.Element("orderData").Descendants("shipments") .SelectMany(s => s.Elements("shipmentIndex") .GroupBy(g => g.Attribute("Name").Value == "shipments") .SelectMany(m => m.Skip(1))).Remove(); } } ```
2016/02/08
[ "https://Stackoverflow.com/questions/35271838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1454961/" ]
Not sure I understand the question 100% but here goes: I am thinking you want to filter the results to only include those elements where the name attribute is equal to 'shipments', although not all of the shipmentIndex elements have a 'Name' attribute so you are probably getting a null reference exception. You need to add a check to ensure that the 'Name' attribute exists. ``` xml.Element("orderData").Descendants("shipments") .SelectMany(s => s.Elements("shipmentIndex") .GroupBy(g => g.Attribute("Name") != null && g.Attribute("Name").Value == "shipments") .SelectMany(m => m.Skip(1))).Remove(); ```
If you want to delete the duplicate from the renderedOutput string: ``` Match match = Regex.Match(renderedOutput, "<shipmentIndex Name=\"shipments\">([^<]*)</shipmentIndex>"); int index = renderedOutput.IndexOf(match.ToString()); renderedOutput = renderedOutput.Remove(index, match.ToString().Length); ```
532,590
A Windows10 / debian system with a shared ntfs drive: ``` # lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 931.5G 0 disk ├─sda1 8:1 0 9.3G 0 part [SWAP] ├─sda2 8:2 0 83.8G 0 part /home └─sda3 8:3 0 100G 0 part /media/share nvme0n1 259:0 0 465.8G 0 disk ├─nvme0n1p1 259:1 0 100M 0 part /boot/efi ├─nvme0n1p2 259:2 0 435.7G 0 part └─nvme0n1p4 259:3 0 27.9G 0 part / ``` The share used to work well up until recently, when it became read-only on the linux part. I think I have the appropriate drivers for write access. The line in fstab: ``` $ cat /etc/fstab | grep share UUID=2786FC7C74DF871D /media/share ntfs defaults 0 3 ``` If I unmount it and then mount again: ``` # mount /dev/sda3 share The disk contains an unclean file system (0, 0). Metadata kept in Windows cache, refused to mount. Falling back to read-only mount because the NTFS partition is in an unsafe state. Please resume and shutdown Windows fully (no hibernation or fast restarting.) Could not mount read-write, trying read-only ``` In windows I checked the disk for errors and defragmented it, then used Shut down. No upgrades started during shutting down. How to proceed?
2019/07/28
[ "https://unix.stackexchange.com/questions/532590", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/20506/" ]
Modern windows has something called fast startup that causes trouble for dual booting. If you are using a modern windows (8 or 10) and dual booting you should keep it [turned off](https://www.windowscentral.com/how-disable-windows-10-fast-startup)
1. Open the terminal and write the command ``` sudo fdisk -l ``` It will show your file system 2. Identify the partition you want permission for read and write, then type the command and give the partition name like this to your specific `sda` ``` sudo ntfsfix /dev/sda3 ``` Credits: <https://askubuntu.com/a/1187649>
532,590
A Windows10 / debian system with a shared ntfs drive: ``` # lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 931.5G 0 disk ├─sda1 8:1 0 9.3G 0 part [SWAP] ├─sda2 8:2 0 83.8G 0 part /home └─sda3 8:3 0 100G 0 part /media/share nvme0n1 259:0 0 465.8G 0 disk ├─nvme0n1p1 259:1 0 100M 0 part /boot/efi ├─nvme0n1p2 259:2 0 435.7G 0 part └─nvme0n1p4 259:3 0 27.9G 0 part / ``` The share used to work well up until recently, when it became read-only on the linux part. I think I have the appropriate drivers for write access. The line in fstab: ``` $ cat /etc/fstab | grep share UUID=2786FC7C74DF871D /media/share ntfs defaults 0 3 ``` If I unmount it and then mount again: ``` # mount /dev/sda3 share The disk contains an unclean file system (0, 0). Metadata kept in Windows cache, refused to mount. Falling back to read-only mount because the NTFS partition is in an unsafe state. Please resume and shutdown Windows fully (no hibernation or fast restarting.) Could not mount read-write, trying read-only ``` In windows I checked the disk for errors and defragmented it, then used Shut down. No upgrades started during shutting down. How to proceed?
2019/07/28
[ "https://unix.stackexchange.com/questions/532590", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/20506/" ]
Modern windows has something called fast startup that causes trouble for dual booting. If you are using a modern windows (8 or 10) and dual booting you should keep it [turned off](https://www.windowscentral.com/how-disable-windows-10-fast-startup)
I had a similar issue. But in my case, there were issues with accessing the Hard Drive because Windows crashed (instead of properly shutting down), so it's possible Windows didn't properly unmount the HDD, and so Linux couldn't have proper access to it. The fix for me was just to go into Windows, make sure the HDD is connected, and shutdown properly.
532,590
A Windows10 / debian system with a shared ntfs drive: ``` # lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 931.5G 0 disk ├─sda1 8:1 0 9.3G 0 part [SWAP] ├─sda2 8:2 0 83.8G 0 part /home └─sda3 8:3 0 100G 0 part /media/share nvme0n1 259:0 0 465.8G 0 disk ├─nvme0n1p1 259:1 0 100M 0 part /boot/efi ├─nvme0n1p2 259:2 0 435.7G 0 part └─nvme0n1p4 259:3 0 27.9G 0 part / ``` The share used to work well up until recently, when it became read-only on the linux part. I think I have the appropriate drivers for write access. The line in fstab: ``` $ cat /etc/fstab | grep share UUID=2786FC7C74DF871D /media/share ntfs defaults 0 3 ``` If I unmount it and then mount again: ``` # mount /dev/sda3 share The disk contains an unclean file system (0, 0). Metadata kept in Windows cache, refused to mount. Falling back to read-only mount because the NTFS partition is in an unsafe state. Please resume and shutdown Windows fully (no hibernation or fast restarting.) Could not mount read-write, trying read-only ``` In windows I checked the disk for errors and defragmented it, then used Shut down. No upgrades started during shutting down. How to proceed?
2019/07/28
[ "https://unix.stackexchange.com/questions/532590", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/20506/" ]
1. Open the terminal and write the command ``` sudo fdisk -l ``` It will show your file system 2. Identify the partition you want permission for read and write, then type the command and give the partition name like this to your specific `sda` ``` sudo ntfsfix /dev/sda3 ``` Credits: <https://askubuntu.com/a/1187649>
I had a similar issue. But in my case, there were issues with accessing the Hard Drive because Windows crashed (instead of properly shutting down), so it's possible Windows didn't properly unmount the HDD, and so Linux couldn't have proper access to it. The fix for me was just to go into Windows, make sure the HDD is connected, and shutdown properly.
66,629,543
I want to create an AWS IAMS account that has various permissions with CloudFormation. I understand there are policies that would let a user change his password and let him get his account to use MFA [here](https://security.stackexchange.com/questions/124786/aws-cloudformation-enable-mfa?newreg=9d07e7c9d733438b82b483b8a6afe541) How could I enforce the user to use MFA at first log in time when he needs to change the default password? This is what I have: The flow I have so far is: 1. User account is created 2. When user tries to log in for the first time is asked to change the default password. 3. User is logged in the AWS console. Expected behavior: 1. User account is created 2. When user tries to log in for the first time is asked to change the default password and set MFA using Authenticator app. 3. User is logged in the AWS console and has permissions. A potential flow is shown [here](https://pomeroy.me/2020/09/solved-first-time-login-problems-when-enforcing-mfa-with-aws/). Is there another way? Update: This [blog](https://aws.amazon.com/blogs/security/how-to-delegate-management-of-multi-factor-authentication-to-aws-iam-users/) explains the flow Again, is there a better way? Like an automatic pop up that would enforce the user straight away? Update2: I might have not been explicit enough. What we have so far it is an ok customer experience. This flow would be fluid 1. User tries to log in 2. Console asks for password change 3. Colsole asks for scanning the code and introducing the codes 4. User logs in with new password and the code from authenticator 5.User is not able to deactivate MFA
2021/03/14
[ "https://Stackoverflow.com/questions/66629543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15234088/" ]
From [official documentation](https://flutter.dev/docs/development/accessibility-and-localization/internationalization) By default, Flutter only provides US English localizations. To add support for other languages, an application must specify additional MaterialApp (or CupertinoApp) properties, and include a package called flutter\_localizations. As of November 2020, this package supports 78 languages. To use flutter\_localizations, add the package as a dependency to your pubspec.yaml file: ``` dependencies: flutter: sdk: flutter flutter_localizations: # Add this line sdk: flutter # Add this line ``` Next, run pub get packages, then import the flutter\_localizations library and specify localizationsDelegates and supportedLocales for MaterialApp: ``` import 'package:flutter_localizations/flutter_localizations.dart'; // TODO: uncomment the line below after codegen // import 'package:flutter_gen/gen_l10n/app_localizations.dart'; // ... MaterialApp( localizationsDelegates: [ // ... app-specific localization delegate[s] here // TODO: uncomment the line below after codegen // AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: [ const Locale('en', ''), // English, no country code const Locale('ar', ''), // Arabic, no country code const Locale.fromSubtags(languageCode: 'zh'), // Chinese *See Advanced Locales below* // ... other locales the app supports ], // ... ) ``` After introducing the flutter\_localizations package and adding the code above, the Material and Cupertino packages should now be correctly localized in one of the 78 supported locales. Widgets should be adapted to the localized messages, `along with correct left-to-right and right-to-left layout`. Try switching the target platform’s locale to Arabic (ar) and notice that the messages should be localized and widgets are laid out with right-to-left layout in mind.
Try using langdetect (if you use tkinter) ``` from langdetect import detect from tkinter import * from tkinter.constants import * arabictext = "مرحبا" root = Tk() text = Text(root) lang = detect(arabictext) if lang == "ar": text.tag_configure('tag-right', justify='right') text.insert('end', arabictext, 'tag-right') text.grid() root.mainloop() ```
66,629,543
I want to create an AWS IAMS account that has various permissions with CloudFormation. I understand there are policies that would let a user change his password and let him get his account to use MFA [here](https://security.stackexchange.com/questions/124786/aws-cloudformation-enable-mfa?newreg=9d07e7c9d733438b82b483b8a6afe541) How could I enforce the user to use MFA at first log in time when he needs to change the default password? This is what I have: The flow I have so far is: 1. User account is created 2. When user tries to log in for the first time is asked to change the default password. 3. User is logged in the AWS console. Expected behavior: 1. User account is created 2. When user tries to log in for the first time is asked to change the default password and set MFA using Authenticator app. 3. User is logged in the AWS console and has permissions. A potential flow is shown [here](https://pomeroy.me/2020/09/solved-first-time-login-problems-when-enforcing-mfa-with-aws/). Is there another way? Update: This [blog](https://aws.amazon.com/blogs/security/how-to-delegate-management-of-multi-factor-authentication-to-aws-iam-users/) explains the flow Again, is there a better way? Like an automatic pop up that would enforce the user straight away? Update2: I might have not been explicit enough. What we have so far it is an ok customer experience. This flow would be fluid 1. User tries to log in 2. Console asks for password change 3. Colsole asks for scanning the code and introducing the codes 4. User logs in with new password and the code from authenticator 5.User is not able to deactivate MFA
2021/03/14
[ "https://Stackoverflow.com/questions/66629543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15234088/" ]
you can use this <https://pub.dev/packages/auto_direction> This package changes the direction of a widget from ltr direction into rtl direction and vice versa based on the language of the text provided.
Try using langdetect (if you use tkinter) ``` from langdetect import detect from tkinter import * from tkinter.constants import * arabictext = "مرحبا" root = Tk() text = Text(root) lang = detect(arabictext) if lang == "ar": text.tag_configure('tag-right', justify='right') text.insert('end', arabictext, 'tag-right') text.grid() root.mainloop() ```
66,629,543
I want to create an AWS IAMS account that has various permissions with CloudFormation. I understand there are policies that would let a user change his password and let him get his account to use MFA [here](https://security.stackexchange.com/questions/124786/aws-cloudformation-enable-mfa?newreg=9d07e7c9d733438b82b483b8a6afe541) How could I enforce the user to use MFA at first log in time when he needs to change the default password? This is what I have: The flow I have so far is: 1. User account is created 2. When user tries to log in for the first time is asked to change the default password. 3. User is logged in the AWS console. Expected behavior: 1. User account is created 2. When user tries to log in for the first time is asked to change the default password and set MFA using Authenticator app. 3. User is logged in the AWS console and has permissions. A potential flow is shown [here](https://pomeroy.me/2020/09/solved-first-time-login-problems-when-enforcing-mfa-with-aws/). Is there another way? Update: This [blog](https://aws.amazon.com/blogs/security/how-to-delegate-management-of-multi-factor-authentication-to-aws-iam-users/) explains the flow Again, is there a better way? Like an automatic pop up that would enforce the user straight away? Update2: I might have not been explicit enough. What we have so far it is an ok customer experience. This flow would be fluid 1. User tries to log in 2. Console asks for password change 3. Colsole asks for scanning the code and introducing the codes 4. User logs in with new password and the code from authenticator 5.User is not able to deactivate MFA
2021/03/14
[ "https://Stackoverflow.com/questions/66629543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15234088/" ]
you can use this <https://pub.dev/packages/auto_direction> This package changes the direction of a widget from ltr direction into rtl direction and vice versa based on the language of the text provided.
From [official documentation](https://flutter.dev/docs/development/accessibility-and-localization/internationalization) By default, Flutter only provides US English localizations. To add support for other languages, an application must specify additional MaterialApp (or CupertinoApp) properties, and include a package called flutter\_localizations. As of November 2020, this package supports 78 languages. To use flutter\_localizations, add the package as a dependency to your pubspec.yaml file: ``` dependencies: flutter: sdk: flutter flutter_localizations: # Add this line sdk: flutter # Add this line ``` Next, run pub get packages, then import the flutter\_localizations library and specify localizationsDelegates and supportedLocales for MaterialApp: ``` import 'package:flutter_localizations/flutter_localizations.dart'; // TODO: uncomment the line below after codegen // import 'package:flutter_gen/gen_l10n/app_localizations.dart'; // ... MaterialApp( localizationsDelegates: [ // ... app-specific localization delegate[s] here // TODO: uncomment the line below after codegen // AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: [ const Locale('en', ''), // English, no country code const Locale('ar', ''), // Arabic, no country code const Locale.fromSubtags(languageCode: 'zh'), // Chinese *See Advanced Locales below* // ... other locales the app supports ], // ... ) ``` After introducing the flutter\_localizations package and adding the code above, the Material and Cupertino packages should now be correctly localized in one of the 78 supported locales. Widgets should be adapted to the localized messages, `along with correct left-to-right and right-to-left layout`. Try switching the target platform’s locale to Arabic (ar) and notice that the messages should be localized and widgets are laid out with right-to-left layout in mind.
23,135
1. Go to this website: <http://parts-of-speech.info/> 2. Now go to this Wikipedia article: <https://en.wikipedia.org/wiki/Evolutionary_psychology> 3. Grab the first paragraph and feed it into POS tagger to see the tags. This is an image of the result: [![parts of speech tagging result](https://i.stack.imgur.com/9cgNz.png)](https://i.stack.imgur.com/9cgNz.png) However, as human beings, to understand this text, we need to understand some concepts that are denoted by more than one word: * Evolutionary psychology * Natural science * Natural selection * ... These are technical terms that mean more than simply a bunch of words and they are not tagged. For example, if you know **natural** and **selection**, you don't necessarily know **natural selection**. Is there a technical term to refer to concepts which are composed of more than one word? Also, is there a way to identify them in a given text? In other words, what is the name for technical terms in Linguistics, and how does find technical terms using NLP algorithms and techniques?
2017/06/09
[ "https://linguistics.stackexchange.com/questions/23135", "https://linguistics.stackexchange.com", "https://linguistics.stackexchange.com/users/141/" ]
There are several terminologies for such words. Here are their definitions found in Wikipedia: **Multi-word Expressions (MWEs):** *A multiword expression (MWE), also called phraseme, is a lexeme made up of a sequence of two or more lexemes that has properties that are not predictable from the properties of the individual lexemes or their normal mode of combination.* [[URL]](https://en.wikipedia.org/wiki/Multiword_expression) **Terminology:** *the study of terms and their use. Terms are words and compound words or multi-word expressions that in specific contexts are given specific meanings—these may deviate from the meanings the same words have in other contexts and in everyday language.* [[URL]](https://en.wikipedia.org/wiki/Terminology) **Collocations:** *In corpus linguistics, a collocation is a sequence of words or terms that co-occur more often than would be expected by chance.* [[URL]](https://en.wikipedia.org/wiki/Collocation) Note that all of these are similar. Both "collocations" and "terms" are "MWEs". The terms are usually MWEs that are specific for a given topic, while collocations are MWEs which co-occur together in a corpus more frequently than by chance. Collocations and terms often coincide (you can always use a predefined MWE dictionary with terms/collocations). If you want to discover MWEs in an unsupervised manner by using the corpus statistics - you should use [collocation extraction](https://en.wikipedia.org/wiki/Collocation_extraction) techniques. There have been plenty of work on collocation extraction, so it should be easy for you to find software or some APIs. Here's a list of tools (feel free to edit the list): * Software: + [Collocation extraction software: Collocate](https://www.athel.com/colloc.html) + [Collocation Extract](http://en.freedownloadmanager.org/Windows-PC/Collocation-Extract-FREE.html) + [Collocation Extract (other source)](http://pioneer.chula.ac.th/~awirote/resources/collocation-extract.html) * APIs: + [Java] Stanford's CoreNLP [CollocationFinder](https://nlp.stanford.edu/nlp/javadoc/javanlp/edu/stanford/nlp/trees/CollocationFinder.html) (predifined, uses WordNet) + [Java] Mahout's [collocation extraction](https://mahout.apache.org/users/basics/collocations.html) * Resources (all of its MWEs can be seen as collocations/terms) + [WordNet](https://wordnet.princeton.edu/) + [Wiktionary](https://www.wiktionary.org/) In my opinion, a nice reading resource is the paper ["50-something years of work on collocations"](http://www.linguistics.ucsb.edu/faculty/stgries/research/2013_STG_DeltaP&H_IJCL.pdf).
You are dealing with **[terminology](https://en.wikipedia.org/wiki/Terminology)** (a discipline of applied linguistics) and **[term extraction](https://en.wikipedia.org/wiki/Terminology_extraction)**. You are looking for **terms**. The quoted wikipedia articles will give you some starters for further reading.
23,135
1. Go to this website: <http://parts-of-speech.info/> 2. Now go to this Wikipedia article: <https://en.wikipedia.org/wiki/Evolutionary_psychology> 3. Grab the first paragraph and feed it into POS tagger to see the tags. This is an image of the result: [![parts of speech tagging result](https://i.stack.imgur.com/9cgNz.png)](https://i.stack.imgur.com/9cgNz.png) However, as human beings, to understand this text, we need to understand some concepts that are denoted by more than one word: * Evolutionary psychology * Natural science * Natural selection * ... These are technical terms that mean more than simply a bunch of words and they are not tagged. For example, if you know **natural** and **selection**, you don't necessarily know **natural selection**. Is there a technical term to refer to concepts which are composed of more than one word? Also, is there a way to identify them in a given text? In other words, what is the name for technical terms in Linguistics, and how does find technical terms using NLP algorithms and techniques?
2017/06/09
[ "https://linguistics.stackexchange.com/questions/23135", "https://linguistics.stackexchange.com", "https://linguistics.stackexchange.com/users/141/" ]
You are dealing with **[terminology](https://en.wikipedia.org/wiki/Terminology)** (a discipline of applied linguistics) and **[term extraction](https://en.wikipedia.org/wiki/Terminology_extraction)**. You are looking for **terms**. The quoted wikipedia articles will give you some starters for further reading.
You may also want to look into **Idioms**. An Idiom is a phrase (series of words, usually) whose meaning is not composed of its parts, at least not without a layer of metaphorical or (usually lost) historical meaning. For example, * The fly [kicked the bucket] (to mean the fly died) is an idiom since knowing what [kick] and [the bucket] mean does not allow one to derive what [kick the bucket] means. It may be productive to look into whether or not [natural science] can be derived from what [natural] and [science] means in the technical sense.
23,135
1. Go to this website: <http://parts-of-speech.info/> 2. Now go to this Wikipedia article: <https://en.wikipedia.org/wiki/Evolutionary_psychology> 3. Grab the first paragraph and feed it into POS tagger to see the tags. This is an image of the result: [![parts of speech tagging result](https://i.stack.imgur.com/9cgNz.png)](https://i.stack.imgur.com/9cgNz.png) However, as human beings, to understand this text, we need to understand some concepts that are denoted by more than one word: * Evolutionary psychology * Natural science * Natural selection * ... These are technical terms that mean more than simply a bunch of words and they are not tagged. For example, if you know **natural** and **selection**, you don't necessarily know **natural selection**. Is there a technical term to refer to concepts which are composed of more than one word? Also, is there a way to identify them in a given text? In other words, what is the name for technical terms in Linguistics, and how does find technical terms using NLP algorithms and techniques?
2017/06/09
[ "https://linguistics.stackexchange.com/questions/23135", "https://linguistics.stackexchange.com", "https://linguistics.stackexchange.com/users/141/" ]
There are several terminologies for such words. Here are their definitions found in Wikipedia: **Multi-word Expressions (MWEs):** *A multiword expression (MWE), also called phraseme, is a lexeme made up of a sequence of two or more lexemes that has properties that are not predictable from the properties of the individual lexemes or their normal mode of combination.* [[URL]](https://en.wikipedia.org/wiki/Multiword_expression) **Terminology:** *the study of terms and their use. Terms are words and compound words or multi-word expressions that in specific contexts are given specific meanings—these may deviate from the meanings the same words have in other contexts and in everyday language.* [[URL]](https://en.wikipedia.org/wiki/Terminology) **Collocations:** *In corpus linguistics, a collocation is a sequence of words or terms that co-occur more often than would be expected by chance.* [[URL]](https://en.wikipedia.org/wiki/Collocation) Note that all of these are similar. Both "collocations" and "terms" are "MWEs". The terms are usually MWEs that are specific for a given topic, while collocations are MWEs which co-occur together in a corpus more frequently than by chance. Collocations and terms often coincide (you can always use a predefined MWE dictionary with terms/collocations). If you want to discover MWEs in an unsupervised manner by using the corpus statistics - you should use [collocation extraction](https://en.wikipedia.org/wiki/Collocation_extraction) techniques. There have been plenty of work on collocation extraction, so it should be easy for you to find software or some APIs. Here's a list of tools (feel free to edit the list): * Software: + [Collocation extraction software: Collocate](https://www.athel.com/colloc.html) + [Collocation Extract](http://en.freedownloadmanager.org/Windows-PC/Collocation-Extract-FREE.html) + [Collocation Extract (other source)](http://pioneer.chula.ac.th/~awirote/resources/collocation-extract.html) * APIs: + [Java] Stanford's CoreNLP [CollocationFinder](https://nlp.stanford.edu/nlp/javadoc/javanlp/edu/stanford/nlp/trees/CollocationFinder.html) (predifined, uses WordNet) + [Java] Mahout's [collocation extraction](https://mahout.apache.org/users/basics/collocations.html) * Resources (all of its MWEs can be seen as collocations/terms) + [WordNet](https://wordnet.princeton.edu/) + [Wiktionary](https://www.wiktionary.org/) In my opinion, a nice reading resource is the paper ["50-something years of work on collocations"](http://www.linguistics.ucsb.edu/faculty/stgries/research/2013_STG_DeltaP&H_IJCL.pdf).
These are called multi-word expressions (MWEs). Before we put things into a POS tagger, we need to perform another process known as *tokenisation* to separate characters into words. This is especially important in Chinese, where there are no whitespaces at all, but is also needed in English, where strings surrounded by word boundaries (in the sense of regex) are not always words either. For solutions, you can [search on Google scholar](https://scholar.google.com.hk/scholar?q=multiword%20expressions&btnG=&hl=zh-TW&as_sdt=0%2C5); there is a huge literature on that. :)
23,135
1. Go to this website: <http://parts-of-speech.info/> 2. Now go to this Wikipedia article: <https://en.wikipedia.org/wiki/Evolutionary_psychology> 3. Grab the first paragraph and feed it into POS tagger to see the tags. This is an image of the result: [![parts of speech tagging result](https://i.stack.imgur.com/9cgNz.png)](https://i.stack.imgur.com/9cgNz.png) However, as human beings, to understand this text, we need to understand some concepts that are denoted by more than one word: * Evolutionary psychology * Natural science * Natural selection * ... These are technical terms that mean more than simply a bunch of words and they are not tagged. For example, if you know **natural** and **selection**, you don't necessarily know **natural selection**. Is there a technical term to refer to concepts which are composed of more than one word? Also, is there a way to identify them in a given text? In other words, what is the name for technical terms in Linguistics, and how does find technical terms using NLP algorithms and techniques?
2017/06/09
[ "https://linguistics.stackexchange.com/questions/23135", "https://linguistics.stackexchange.com", "https://linguistics.stackexchange.com/users/141/" ]
These are called multi-word expressions (MWEs). Before we put things into a POS tagger, we need to perform another process known as *tokenisation* to separate characters into words. This is especially important in Chinese, where there are no whitespaces at all, but is also needed in English, where strings surrounded by word boundaries (in the sense of regex) are not always words either. For solutions, you can [search on Google scholar](https://scholar.google.com.hk/scholar?q=multiword%20expressions&btnG=&hl=zh-TW&as_sdt=0%2C5); there is a huge literature on that. :)
You may also want to look into **Idioms**. An Idiom is a phrase (series of words, usually) whose meaning is not composed of its parts, at least not without a layer of metaphorical or (usually lost) historical meaning. For example, * The fly [kicked the bucket] (to mean the fly died) is an idiom since knowing what [kick] and [the bucket] mean does not allow one to derive what [kick the bucket] means. It may be productive to look into whether or not [natural science] can be derived from what [natural] and [science] means in the technical sense.
23,135
1. Go to this website: <http://parts-of-speech.info/> 2. Now go to this Wikipedia article: <https://en.wikipedia.org/wiki/Evolutionary_psychology> 3. Grab the first paragraph and feed it into POS tagger to see the tags. This is an image of the result: [![parts of speech tagging result](https://i.stack.imgur.com/9cgNz.png)](https://i.stack.imgur.com/9cgNz.png) However, as human beings, to understand this text, we need to understand some concepts that are denoted by more than one word: * Evolutionary psychology * Natural science * Natural selection * ... These are technical terms that mean more than simply a bunch of words and they are not tagged. For example, if you know **natural** and **selection**, you don't necessarily know **natural selection**. Is there a technical term to refer to concepts which are composed of more than one word? Also, is there a way to identify them in a given text? In other words, what is the name for technical terms in Linguistics, and how does find technical terms using NLP algorithms and techniques?
2017/06/09
[ "https://linguistics.stackexchange.com/questions/23135", "https://linguistics.stackexchange.com", "https://linguistics.stackexchange.com/users/141/" ]
There are several terminologies for such words. Here are their definitions found in Wikipedia: **Multi-word Expressions (MWEs):** *A multiword expression (MWE), also called phraseme, is a lexeme made up of a sequence of two or more lexemes that has properties that are not predictable from the properties of the individual lexemes or their normal mode of combination.* [[URL]](https://en.wikipedia.org/wiki/Multiword_expression) **Terminology:** *the study of terms and their use. Terms are words and compound words or multi-word expressions that in specific contexts are given specific meanings—these may deviate from the meanings the same words have in other contexts and in everyday language.* [[URL]](https://en.wikipedia.org/wiki/Terminology) **Collocations:** *In corpus linguistics, a collocation is a sequence of words or terms that co-occur more often than would be expected by chance.* [[URL]](https://en.wikipedia.org/wiki/Collocation) Note that all of these are similar. Both "collocations" and "terms" are "MWEs". The terms are usually MWEs that are specific for a given topic, while collocations are MWEs which co-occur together in a corpus more frequently than by chance. Collocations and terms often coincide (you can always use a predefined MWE dictionary with terms/collocations). If you want to discover MWEs in an unsupervised manner by using the corpus statistics - you should use [collocation extraction](https://en.wikipedia.org/wiki/Collocation_extraction) techniques. There have been plenty of work on collocation extraction, so it should be easy for you to find software or some APIs. Here's a list of tools (feel free to edit the list): * Software: + [Collocation extraction software: Collocate](https://www.athel.com/colloc.html) + [Collocation Extract](http://en.freedownloadmanager.org/Windows-PC/Collocation-Extract-FREE.html) + [Collocation Extract (other source)](http://pioneer.chula.ac.th/~awirote/resources/collocation-extract.html) * APIs: + [Java] Stanford's CoreNLP [CollocationFinder](https://nlp.stanford.edu/nlp/javadoc/javanlp/edu/stanford/nlp/trees/CollocationFinder.html) (predifined, uses WordNet) + [Java] Mahout's [collocation extraction](https://mahout.apache.org/users/basics/collocations.html) * Resources (all of its MWEs can be seen as collocations/terms) + [WordNet](https://wordnet.princeton.edu/) + [Wiktionary](https://www.wiktionary.org/) In my opinion, a nice reading resource is the paper ["50-something years of work on collocations"](http://www.linguistics.ucsb.edu/faculty/stgries/research/2013_STG_DeltaP&H_IJCL.pdf).
You may also want to look into **Idioms**. An Idiom is a phrase (series of words, usually) whose meaning is not composed of its parts, at least not without a layer of metaphorical or (usually lost) historical meaning. For example, * The fly [kicked the bucket] (to mean the fly died) is an idiom since knowing what [kick] and [the bucket] mean does not allow one to derive what [kick the bucket] means. It may be productive to look into whether or not [natural science] can be derived from what [natural] and [science] means in the technical sense.
17,529,012
For far too long I've been stumbling around trying to make a simple .click jquery method work in my c# site. I just want it to call to a function in my controller, but I can't seem to get any button click to register. The calls in it are very similar to a .change() function for another control that works just fine. JQuery method in question: ``` $('#addUserButton').click(function () { var e = document.getElementById('searchDDL'); var itemText = e.options[e.selectedIndex].text; var url = encodeURI('@Url.Action("AddUser")' + "?User=" + itemText); }); ``` HTML of button that is intended to trigger the above function: ``` <button id="addUserButton" type="button" value="addUser">&gt;</button> ``` Some things I've researched and tried already: * Changing from a .click() method to a .live("click", etc) method made no difference. * I saw that setting the button type="submit" would be a problem, so I changed it to "button." * I made sure to include it in document.ready() - I was already doing this before researching other problems. I have created a jsfiddle for the problem [here](http://jsfiddle.net/MQLB4/). I had to remove a lot of sensitive information so the page is not fully fleshed out. It is for an internal application and only has to work with IE. **EDIT:** Below I am adding the function I am trying to call in my controller; other posters have verified that the jquery is working as expected, so I'm inclined to believe it is something to do with my c#. ``` public ActionResult AddUser(string User) { //numUsers = App.NumberUsers + 1; selectedUsers.Add(User); return RedirectToAction("ApplicationForm"); } ```
2013/07/08
[ "https://Stackoverflow.com/questions/17529012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547781/" ]
Did you try debugging your function or even putting alerts in it to flesh out whats happening. ``` $('#addUserButton').click(function () { alert("FUNCTION IS GETTING CALLED ON CLICK EVENT"); var e = document.getElementById('searchDDL'); alert(e); var itemText = e.options[e.selectedIndex].text; alert(itemText); var url = encodeURI('@Url.Action("AddUser")' + "?User=" + itemText); alert(url); }); ``` Doesn't look like your function makes an AJAX request after getting the URL.
It's not something silly like the extra closing `>` bracket on this? ``` <button id="addUserButton" type="button" value="addUser">></button> ```
17,529,012
For far too long I've been stumbling around trying to make a simple .click jquery method work in my c# site. I just want it to call to a function in my controller, but I can't seem to get any button click to register. The calls in it are very similar to a .change() function for another control that works just fine. JQuery method in question: ``` $('#addUserButton').click(function () { var e = document.getElementById('searchDDL'); var itemText = e.options[e.selectedIndex].text; var url = encodeURI('@Url.Action("AddUser")' + "?User=" + itemText); }); ``` HTML of button that is intended to trigger the above function: ``` <button id="addUserButton" type="button" value="addUser">&gt;</button> ``` Some things I've researched and tried already: * Changing from a .click() method to a .live("click", etc) method made no difference. * I saw that setting the button type="submit" would be a problem, so I changed it to "button." * I made sure to include it in document.ready() - I was already doing this before researching other problems. I have created a jsfiddle for the problem [here](http://jsfiddle.net/MQLB4/). I had to remove a lot of sensitive information so the page is not fully fleshed out. It is for an internal application and only has to work with IE. **EDIT:** Below I am adding the function I am trying to call in my controller; other posters have verified that the jquery is working as expected, so I'm inclined to believe it is something to do with my c#. ``` public ActionResult AddUser(string User) { //numUsers = App.NumberUsers + 1; selectedUsers.Add(User); return RedirectToAction("ApplicationForm"); } ```
2013/07/08
[ "https://Stackoverflow.com/questions/17529012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547781/" ]
Did you try debugging your function or even putting alerts in it to flesh out whats happening. ``` $('#addUserButton').click(function () { alert("FUNCTION IS GETTING CALLED ON CLICK EVENT"); var e = document.getElementById('searchDDL'); alert(e); var itemText = e.options[e.selectedIndex].text; alert(itemText); var url = encodeURI('@Url.Action("AddUser")' + "?User=" + itemText); alert(url); }); ``` Doesn't look like your function makes an AJAX request after getting the URL.
From your [JSFiddle](http://jsfiddle.net/MQLB4/), **it seems you're not including the `jQuery`.** ***Which is at the top-left corner of JSFiddle.*** I've [updated fiddle](http://jsfiddle.net/MQLB4/4/) working fine. Remember you're including `jQuery`, so try to make use of its feature and leave Javascript.
60,886,431
I have a section of html that needs to be displayed in a certain way but some elements may be optional and I'm not sure if I can do it with `display:grid`. I need to have 3 columns, but the first and last one are optional and I need to remove the gap when they are not present. Note that the markup needs to be this one without extra wrapper : ```css .grid { display: grid; grid-template-columns: auto 1fr auto; grid-gap: 0 20px; align-items: center; background-color: lightgrey; } .grid > .image { grid-column: 1; grid-row: 1 / span 2; background-color: red; } .grid > .title { grid-column: 2; background-color: blue; } .grid > .description { grid-column: 2; background-color: purple; } .grid > .button { grid-column: 3; grid-row: 1 / span 2; background-color: green; } ``` ```html <div class="grid"> <div class="image">image</div> <div class="title">title</div> <div class="description">description</div> <div class="button">button</div> </div> <p>&nbsp;</p> <p>Unwanted gap when no image :</p> <div class="grid"> <div class="title">title</div> <div class="description">description</div> <div class="button">button</div> </div> <p>&nbsp;</p> <p>Unwanted gap when no image or button :</p> <div class="grid"> <div class="title">title</div> <div class="description">description</div> </div> ```
2020/03/27
[ "https://Stackoverflow.com/questions/60886431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1458442/" ]
Rely on implicit column creation and keep only one explicit column ```css .grid { display: grid; grid-template-columns: 1fr; /* one column here */ grid-gap: 0 20px; align-items: center; background-color: lightgrey; } .grid > .image { grid-column: -3; /* this will create an implicit column at the start */ grid-row: span 2; background-color: red; } .grid > .title { background-color: blue; } .grid > .description { background-color: purple; } .grid > .button { grid-column: 2; /* this will create an implicit column at the end */ grid-row:1/ span 2; background-color: green; } ``` ```html <div class="grid"> <div class="image">image</div> <div class="title">title</div> <div class="description">description</div> <div class="button">button</div> </div> <p>&nbsp;</p> <div class="grid"> <div class="title">title</div> <div class="description">description</div> <div class="button">button</div> </div> <p>&nbsp;</p> <div class="grid"> <div class="image">image</div> <div class="title">title</div> <div class="description">description</div> </div> <p>&nbsp;</p> <div class="grid"> <div class="title">title</div> <div class="description">description</div> </div> ```
Instead of using grid gaps, **use margins** on the individual elements. ```css .grid { display: grid; grid-auto-columns: auto 1fr auto; /* grid-gap: 0 20px; */ align-items: center; background-color: lightgrey; } .grid > .image { margin-right: 20px; /* new */ grid-column: 1; grid-row: 1 / span 2; background-color: red; } .grid > .button { margin-left: 20px; /* new */ grid-column: 3; grid-row: 1 / span 2; background-color: green; } .grid > .title { grid-column: 2; background-color: blue; } .grid > .description { grid-column: 2; background-color: purple; } ``` ```html <div class="grid"> <div class="image">image</div> <div class="title">title</div> <div class="description">description</div> <div class="button">button</div> </div> <p>&nbsp;</p> <p>NO unwanted gap when no image :</p> <div class="grid"> <div class="title">title</div> <div class="description">description</div> <div class="button">button</div> </div> <p>&nbsp;</p> <p>NO unwanted gap when no image or button :</p> <div class="grid"> <div class="title">title</div> <div class="description">description</div> </div> ```
35,611,371
I tried everything I can find, but I am unable to get the result I'm looking for. I am taking two txt files, combining them together in every possible way with no duplicates and saving the output to a CSV file. Everything works, except I can't get it to remove the middle space. For example: list1.txt: ``` 1 2 ``` list2.txt: ``` dog cat ``` The result I get is: ``` dog 1, dog 2, cat 1, cat 2, 1 dog, 2 dog, 1 cat, 2 cat ``` But I need (see spaces): ``` dog1, dog2, cat1, cat2, 1dog, 2dog, 1cat, 2cat ``` Code: ``` <?php $array1 = file('list1.txt'); $array2 = file('list2.txt'); $array3 = array(); $array4 = array(); foreach ($array1 as $key1) { foreach ($array2 as $key2) { $array3[] = $key1 . $key2; { $array4[] = $key2 . $key1; } } } print_r($array3); print_r($array4); $fp = fopen('combined.csv', 'w'); fputcsv($fp, $array3); fputcsv($fp, $array4); fclose($fp); ?> ```
2016/02/24
[ "https://Stackoverflow.com/questions/35611371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3526961/" ]
Use the below code ``` foreach ($array1 as $key1){ foreach ($array2 as $key2){ $array3[] = trim($key1).trim($key2); $array4[] = trim($key2).trim($key1); } } ``` Or Use array\_map function to trim all the elements of an array ``` $array = array_map('trim', $array); ```
As Ravinder and Rizier stated, use trim(). So for example: ``` <?php $array1 = file('list1.txt'); $array2 = file('list2.txt'); $array3 = array(); $array4 = array(); foreach ($array1 as $key1) { foreach ($array2 as $key2) { $array3[] = trim($key1) . trim($key2); $array4[] = trim($key2) . trim($key1); } } print_r($array3); print_r($array4); $fp = fopen('combined.csv', 'w'); fputcsv($fp, $array3); fputcsv($fp, $array4); fclose($fp); ?> ``` As a side note, it looks like you have a couple stray `{` and `}` in your code. You'll need to remove those for the code to complete successfully.
35,611,371
I tried everything I can find, but I am unable to get the result I'm looking for. I am taking two txt files, combining them together in every possible way with no duplicates and saving the output to a CSV file. Everything works, except I can't get it to remove the middle space. For example: list1.txt: ``` 1 2 ``` list2.txt: ``` dog cat ``` The result I get is: ``` dog 1, dog 2, cat 1, cat 2, 1 dog, 2 dog, 1 cat, 2 cat ``` But I need (see spaces): ``` dog1, dog2, cat1, cat2, 1dog, 2dog, 1cat, 2cat ``` Code: ``` <?php $array1 = file('list1.txt'); $array2 = file('list2.txt'); $array3 = array(); $array4 = array(); foreach ($array1 as $key1) { foreach ($array2 as $key2) { $array3[] = $key1 . $key2; { $array4[] = $key2 . $key1; } } } print_r($array3); print_r($array4); $fp = fopen('combined.csv', 'w'); fputcsv($fp, $array3); fputcsv($fp, $array4); fclose($fp); ?> ```
2016/02/24
[ "https://Stackoverflow.com/questions/35611371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3526961/" ]
Use the below code ``` foreach ($array1 as $key1){ foreach ($array2 as $key2){ $array3[] = trim($key1).trim($key2); $array4[] = trim($key2).trim($key1); } } ``` Or Use array\_map function to trim all the elements of an array ``` $array = array_map('trim', $array); ```
Try this `foreach` loop instead: ``` foreach ($array1 as $key1) { foreach ($array2 as $key2) { $key1 = trim($key1); $key2 = trim($key2); /* If the above doesn't work, try this method: (If you use this method, you should delete your $array3 and $array4 assignments) $arrangement['array3'] = $key1.$key2; $arrangement2['array4'] = $key2.$key1; foreach($arrangements as $arrayName=>$str) { $str = preg_replace('#^([^ ]+) ([^ ]+)$#', '', $str); $$arrayName[] = $str; } */ $array3[] = $key1 . $key2; { $array4[] = $key2 . $key1; } } } ```
35,611,371
I tried everything I can find, but I am unable to get the result I'm looking for. I am taking two txt files, combining them together in every possible way with no duplicates and saving the output to a CSV file. Everything works, except I can't get it to remove the middle space. For example: list1.txt: ``` 1 2 ``` list2.txt: ``` dog cat ``` The result I get is: ``` dog 1, dog 2, cat 1, cat 2, 1 dog, 2 dog, 1 cat, 2 cat ``` But I need (see spaces): ``` dog1, dog2, cat1, cat2, 1dog, 2dog, 1cat, 2cat ``` Code: ``` <?php $array1 = file('list1.txt'); $array2 = file('list2.txt'); $array3 = array(); $array4 = array(); foreach ($array1 as $key1) { foreach ($array2 as $key2) { $array3[] = $key1 . $key2; { $array4[] = $key2 . $key1; } } } print_r($array3); print_r($array4); $fp = fopen('combined.csv', 'w'); fputcsv($fp, $array3); fputcsv($fp, $array4); fclose($fp); ?> ```
2016/02/24
[ "https://Stackoverflow.com/questions/35611371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3526961/" ]
Thanks to the help from Rizier123, I solved the problem by simply changing lines 3 and 4 as follows: ``` $array1 = file('list1.txt'**, FILE\_IGNORE\_NEW\_LINES**); $array2 = file('list2.txt'**, FILE\_IGNORE\_NEW\_LINES**); ``` The problem was due to the line breaks in my two list files, as each keyword used in the arrays are on a separate line.
Use the below code ``` foreach ($array1 as $key1){ foreach ($array2 as $key2){ $array3[] = trim($key1).trim($key2); $array4[] = trim($key2).trim($key1); } } ``` Or Use array\_map function to trim all the elements of an array ``` $array = array_map('trim', $array); ```
35,611,371
I tried everything I can find, but I am unable to get the result I'm looking for. I am taking two txt files, combining them together in every possible way with no duplicates and saving the output to a CSV file. Everything works, except I can't get it to remove the middle space. For example: list1.txt: ``` 1 2 ``` list2.txt: ``` dog cat ``` The result I get is: ``` dog 1, dog 2, cat 1, cat 2, 1 dog, 2 dog, 1 cat, 2 cat ``` But I need (see spaces): ``` dog1, dog2, cat1, cat2, 1dog, 2dog, 1cat, 2cat ``` Code: ``` <?php $array1 = file('list1.txt'); $array2 = file('list2.txt'); $array3 = array(); $array4 = array(); foreach ($array1 as $key1) { foreach ($array2 as $key2) { $array3[] = $key1 . $key2; { $array4[] = $key2 . $key1; } } } print_r($array3); print_r($array4); $fp = fopen('combined.csv', 'w'); fputcsv($fp, $array3); fputcsv($fp, $array4); fclose($fp); ?> ```
2016/02/24
[ "https://Stackoverflow.com/questions/35611371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3526961/" ]
Thanks to the help from Rizier123, I solved the problem by simply changing lines 3 and 4 as follows: ``` $array1 = file('list1.txt'**, FILE\_IGNORE\_NEW\_LINES**); $array2 = file('list2.txt'**, FILE\_IGNORE\_NEW\_LINES**); ``` The problem was due to the line breaks in my two list files, as each keyword used in the arrays are on a separate line.
As Ravinder and Rizier stated, use trim(). So for example: ``` <?php $array1 = file('list1.txt'); $array2 = file('list2.txt'); $array3 = array(); $array4 = array(); foreach ($array1 as $key1) { foreach ($array2 as $key2) { $array3[] = trim($key1) . trim($key2); $array4[] = trim($key2) . trim($key1); } } print_r($array3); print_r($array4); $fp = fopen('combined.csv', 'w'); fputcsv($fp, $array3); fputcsv($fp, $array4); fclose($fp); ?> ``` As a side note, it looks like you have a couple stray `{` and `}` in your code. You'll need to remove those for the code to complete successfully.
35,611,371
I tried everything I can find, but I am unable to get the result I'm looking for. I am taking two txt files, combining them together in every possible way with no duplicates and saving the output to a CSV file. Everything works, except I can't get it to remove the middle space. For example: list1.txt: ``` 1 2 ``` list2.txt: ``` dog cat ``` The result I get is: ``` dog 1, dog 2, cat 1, cat 2, 1 dog, 2 dog, 1 cat, 2 cat ``` But I need (see spaces): ``` dog1, dog2, cat1, cat2, 1dog, 2dog, 1cat, 2cat ``` Code: ``` <?php $array1 = file('list1.txt'); $array2 = file('list2.txt'); $array3 = array(); $array4 = array(); foreach ($array1 as $key1) { foreach ($array2 as $key2) { $array3[] = $key1 . $key2; { $array4[] = $key2 . $key1; } } } print_r($array3); print_r($array4); $fp = fopen('combined.csv', 'w'); fputcsv($fp, $array3); fputcsv($fp, $array4); fclose($fp); ?> ```
2016/02/24
[ "https://Stackoverflow.com/questions/35611371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3526961/" ]
Thanks to the help from Rizier123, I solved the problem by simply changing lines 3 and 4 as follows: ``` $array1 = file('list1.txt'**, FILE\_IGNORE\_NEW\_LINES**); $array2 = file('list2.txt'**, FILE\_IGNORE\_NEW\_LINES**); ``` The problem was due to the line breaks in my two list files, as each keyword used in the arrays are on a separate line.
Try this `foreach` loop instead: ``` foreach ($array1 as $key1) { foreach ($array2 as $key2) { $key1 = trim($key1); $key2 = trim($key2); /* If the above doesn't work, try this method: (If you use this method, you should delete your $array3 and $array4 assignments) $arrangement['array3'] = $key1.$key2; $arrangement2['array4'] = $key2.$key1; foreach($arrangements as $arrayName=>$str) { $str = preg_replace('#^([^ ]+) ([^ ]+)$#', '', $str); $$arrayName[] = $str; } */ $array3[] = $key1 . $key2; { $array4[] = $key2 . $key1; } } } ```
4,167,419
> > Let $f(x)=a(x-2)(x-b)$, where $a,b\in R$ and $a\ne0$. Also, $f(f(x))=a^3\left(x^2-(2+b)x+2b-\frac2a\right)\left(x^2-(2+b)x+2b-\frac ba\right)$, $a\ne0$ has exactly one real zeroes $5$. Find the minima and maxima of $f(x)$. > > > $f(f(x))$ is a quartic equation. So, it would have $4$ roots. Its real root should occur in pair because complex roots occur in pair. So, I failed to understand the meaning of 'exactly one real zero' in the question. Does that mean its real roots are equal and they are equal to $5$? Since $f(x)$ has a zero at $2$, $f(f(2))=f(0)=2ab$. But even RHS of $f(f(x))$ is coming out to be $2ab$ at $x=2$. Putting $x=5$ in $f(f(x))$ gives an equation in $a^2$ and $b^2$. Don't know what to do with it. Also, $f(x)=a(x^2-(2+b)x+2b)$ $f'(x)=a(2x-2-b)=0\implies x=\frac{2+b}2$ is the minima or maxima. How to proceed next? Do the critical points of $f(x)$ tell us anything about $f(f(x))$?
2021/06/08
[ "https://math.stackexchange.com/questions/4167419", "https://math.stackexchange.com", "https://math.stackexchange.com/users/87430/" ]
Let $q>3$. Then there exists a nonzero element $a\in \Bbb F\_q$ with $a^2-1\neq 0$. Let $A=\begin{pmatrix} 1 & -x \cr 0 & 1 \end{pmatrix}$ and $B=\begin{pmatrix} a & 0 \cr 0 & a^{-1} \end{pmatrix}$ in $SL(2,q)$. Then \begin{align\*} [A,B] & = ABA^{-1}B^{-1} \\ & =\begin{pmatrix} 1 & (a^2-1)x \cr 0 & 1 \end{pmatrix} \end{align\*} So every element of the corresponding transvection group is a commutator. Since the transvections generate $SL(2,q)$, this is enough to show that $SL(2,q)$ is perfect.
I might approach it via Bruhat decomposition. Let $B$ be the group of upper triangular matrices in $G$. It is the semidirect product of the group $T$ of diagonal matrices in $G$ and the group $N$ of upper triangular matrices with $1$s on the diagonal. First, show that every element of $B$ is a product of commutators in $G$. Next, use the fact that $G$ is the disjoint union of the double cosets $BwB$, where $w$ ranges through a set of permutation matrices in $G$. This is called the *Bruhat decomposition*. For example, $G = \operatorname{SL}\_2$ is the disjoint union of $B = B1B$ and $BwB$, where $$w = \begin{pmatrix} & 1 \\ -1 \end{pmatrix}.$$ Thus you just have to show that $B$ and every such $w$ is a product of commutators.
73,334,904
I've got a .showGuesses block which max-height is set to 100px. When its height goes over its maximum I want a vertical scroll bar to appear. But, unfortunately, for some reason I never get the scroll bar. **How to make the scrollbar to appear?** Here's the code and the result: <https://liveweave.com/hyo1ut> HTML ``` <!DOCTYPE html> <form class="order-form" method="POST" action="insert_data.php"> <legend>Insert your address</legend> <div class="input-area-wrap"> <div class="input-area"> <label>street/avenue</label> <input type="text" name="street" required> </div> <div class="showGuesses"> <div class="showGuess">Street 1</div> <div class="showGuess">Street 2</div> <div class="showGuess">Street 3</div> <div class="showGuess">Street 4</div> </div> </div> </form> ``` CSS ``` * { -webkit-box-sizing: border-box!important; box-sizing: border-box!important; } .order-form { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; width: 80%; max-width: 800px; margin: 0 auto; border: 1px solid #222; border-radius: 15px; padding: 20px; margin-top: 25px; position: unset!important; overflow: hidden; } legend { text-align: center; margin-bottom: 25px!important; } .input-area-wrap { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; } .input-area { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: baseline; -ms-flex-align: baseline; align-items: baseline; position: relative; } .input-area label { width: 150px; } input[type="text"] { width: 250px!important; outline: none; } input[type="text"]:focus { border: 2px solid darkred!important; outline: none; } input[type="submit"] { width: 100px; margin: 25px auto 0; border-radius: 25px; background: rgb(255, 74, 74); color: #fff; border: none; padding: 10px; font-size: 16px; } .showGuesses { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; z-index: 3; /* top: 25px; */ margin-left: 150px; font-size: 14px; width: 100%; max-height: 100px; overflow: -moz-scrollbars-vertical; overflow-y: scroll; } .showGuess { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; border: 1px solid #222; padding: 5px; width: 250px; min-height: 45px; text-align: center; background: #fff; border-bottom: none; } ``` **UPD 0:** Due to help of @EssXTee I now get the scrollbar, but it doesn't disappear if the content of showGuesses block doesn't overflow it. It's just there all the time for some reason. **How to fix that?**
2022/08/12
[ "https://Stackoverflow.com/questions/73334904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19712456/" ]
Pattern matching and regular expressions are two different things. In pattern matching `*` means *any string*. In regular expressions it means *zero or more of what precedes*. In pattern matching `(.+)` means... the literal `(.+)` string. In regular expressions it represents a capture group with at least one character. For your simple renaming scheme you can try: ```bash for f in *.fq.gz; do g="${f/_DKDL220005480-2a-*_HHJ2MCCX2_L8_/_R}" printf 'mv "%s" "%s"\n' "$f" "${g%.fq.gz}.fastq.gz" # mv "$f" "${g%.fq.gz}.fastq.gz" done ``` Once satisfied with the output uncomment the `mv` line.
To use regular expressions in `bash` you need to use `[[ $x =~ regex ]]`, and you can use groups with `$BASH_REMATCH`, so: ``` for x in *; do [[ $x =~ ^(S2EC[0-9]+)_.*_([0-9]+).fq.gz$ ]] && mv $x ${BASH_REMATCH[1]}_R${BASH_REMATCH[2]}.fastq.gz done ```
34,190,609
``` Page A Page B Page C ``` If the user is coming from `page A` do something on `page C` (within the same website) If the user is coming from `page B` do something else on `page C` (within the same website) What would be the best approach to do that in JS? (dont use `document.referrer`)
2015/12/09
[ "https://Stackoverflow.com/questions/34190609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3195927/" ]
In my opinion, there are two decent solutions: 1. When Page A loads Page C, include a variable in the URL that essentially says "*loaded from page A*". (Same applies to Page B.) 2. When Page A is loaded, set either a cookie, `localStorage`, or `sessionStorage` variable that says "*loaded from page A*". (Same applies for Page B.) Then when Page C is loaded, check the variable to see if either Page A or Page B was the most recently opened page. (You may also want to set a timeout/expiration-time on the cookie, localStorage, or sessionStorage.)
What you can do is have a global variable that will hold the location. When you load a page. assign that variable the location ``` window.location.href ``` or ``` document.URL; ``` Another option would be using cookies.
34,190,609
``` Page A Page B Page C ``` If the user is coming from `page A` do something on `page C` (within the same website) If the user is coming from `page B` do something else on `page C` (within the same website) What would be the best approach to do that in JS? (dont use `document.referrer`)
2015/12/09
[ "https://Stackoverflow.com/questions/34190609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3195927/" ]
In my opinion, there are two decent solutions: 1. When Page A loads Page C, include a variable in the URL that essentially says "*loaded from page A*". (Same applies to Page B.) 2. When Page A is loaded, set either a cookie, `localStorage`, or `sessionStorage` variable that says "*loaded from page A*". (Same applies for Page B.) Then when Page C is loaded, check the variable to see if either Page A or Page B was the most recently opened page. (You may also want to set a timeout/expiration-time on the cookie, localStorage, or sessionStorage.)
Your description doesnt make a lot of sense (to me), especially because you havent included any framework/stack you're using (which this responsibility would likely fall on). That said, I would use a variable with session getters and setters. You can parse the query string or URL, set that equal to a session variable, then get that session variable when you're ready to use it. Here's [how to use](https://stackoverflow.com/questions/18076013/setting-session-variable-using-javascript?answertab=active#tab-top) session getters and setters in javascript
34,190,609
``` Page A Page B Page C ``` If the user is coming from `page A` do something on `page C` (within the same website) If the user is coming from `page B` do something else on `page C` (within the same website) What would be the best approach to do that in JS? (dont use `document.referrer`)
2015/12/09
[ "https://Stackoverflow.com/questions/34190609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3195927/" ]
In my opinion, there are two decent solutions: 1. When Page A loads Page C, include a variable in the URL that essentially says "*loaded from page A*". (Same applies to Page B.) 2. When Page A is loaded, set either a cookie, `localStorage`, or `sessionStorage` variable that says "*loaded from page A*". (Same applies for Page B.) Then when Page C is loaded, check the variable to see if either Page A or Page B was the most recently opened page. (You may also want to set a timeout/expiration-time on the cookie, localStorage, or sessionStorage.)
You can have `page A` and `page B` set a cookie that indicates which page they are. Then `page C` can check the cookie value.
1,441,686
I am planning to use PHP's autoload function to dynamicly load only class files that are needed. Now this could create a huge mess if every single function has a seperate file, So I am hoping and asking is there a way to have related classes remain in 1 class file and still be auto-loaded ``` function __autoload($class_name){ include('classes/' . $class_name . '.class.php'); } ``` Let's say there is a class name animals and then another class named dogs. Dogs class extends animals class, now if I were to call the dogs class but NOT call the animals class, would the animals class file still be loaded?
2009/09/17
[ "https://Stackoverflow.com/questions/1441686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143030/" ]
> > if I were to call the dogs class but > NOT call the animals class, would the > animals class file still be loaded? > > > Yes. When you load an class that extends another class, PHP must load the base class so it knows what it's extending. re: the idea of storing multiple classes per file: This will not work with the autoload function you provided. One class per file is really the best practice, especially for autoloaded classes. If you have more than one class in a file, you really shouldn't attempt to autoload any classes from that file.
Yes it will load unless you don't include/require the class file. You have to always import any files that contain needed PHP code. PHP itself can't guess the name you gave to your class file. Unlike Java for instance, PHP doesn't have any file naming requirements for classes. The common way so solve this problem is to group related classes in one single file. Creating a "module".
1,441,686
I am planning to use PHP's autoload function to dynamicly load only class files that are needed. Now this could create a huge mess if every single function has a seperate file, So I am hoping and asking is there a way to have related classes remain in 1 class file and still be auto-loaded ``` function __autoload($class_name){ include('classes/' . $class_name . '.class.php'); } ``` Let's say there is a class name animals and then another class named dogs. Dogs class extends animals class, now if I were to call the dogs class but NOT call the animals class, would the animals class file still be loaded?
2009/09/17
[ "https://Stackoverflow.com/questions/1441686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143030/" ]
Have you considered explicit definitions of your class locations? Sometimes it makes a lot of sense to group related classes. Here is a proven way of handling it. This code is placed in an `auto_prepend_file` (or included first) ``` class Import { public static $_AutoLoad = array(); public static $_Imported = array(); public static function Load($sName) { if(! isset(self::$_AutoLoad[$sName])) throw new ImportError("Cannot import module with name '$sName'."); if(! isset(self::$_Imported[$sName])) { self::$_Imported[$sName] = True; require(self::$_AutoLoad[$sName]); } } public static function Push($sName, $sPath) { self::$_AutoLoad[$sName] = $sPath; } public static function Auto() { function __autoload($sClass) { Import::Load($sClass); } } } ``` And in your bootstrap file, define your classes, and what file they are in. ``` //Define autoload items Import::Push('Admin_Layout', App::$Path . '/PHP/Admin_Layout.php'); Import::Push('Admin_Layout_Dialog', App::$Path . '/PHP/Admin_Layout.php'); Import::Push('FileClient', App::$Path . '/PHP/FileClient.php'); ``` And lastly, enable AutoLoad by calling ``` Import::Auto() ``` --- One of the nice things is that you can define "Modules": ``` Import::Push('MyModule', App::$Path . '/Module/MyModule/Init.php'); ``` And then load them explicitly when needed: ``` Import::Load('MyModule'); ``` And one of the best parts is you can have additional `Import::Push` lines in the module, which will define all of its classes at runtime.
Yes it will load unless you don't include/require the class file. You have to always import any files that contain needed PHP code. PHP itself can't guess the name you gave to your class file. Unlike Java for instance, PHP doesn't have any file naming requirements for classes. The common way so solve this problem is to group related classes in one single file. Creating a "module".
1,441,686
I am planning to use PHP's autoload function to dynamicly load only class files that are needed. Now this could create a huge mess if every single function has a seperate file, So I am hoping and asking is there a way to have related classes remain in 1 class file and still be auto-loaded ``` function __autoload($class_name){ include('classes/' . $class_name . '.class.php'); } ``` Let's say there is a class name animals and then another class named dogs. Dogs class extends animals class, now if I were to call the dogs class but NOT call the animals class, would the animals class file still be loaded?
2009/09/17
[ "https://Stackoverflow.com/questions/1441686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143030/" ]
> > if I were to call the dogs class but > NOT call the animals class, would the > animals class file still be loaded? > > > Yes. When you load an class that extends another class, PHP must load the base class so it knows what it's extending. re: the idea of storing multiple classes per file: This will not work with the autoload function you provided. One class per file is really the best practice, especially for autoloaded classes. If you have more than one class in a file, you really shouldn't attempt to autoload any classes from that file.
Have you considered explicit definitions of your class locations? Sometimes it makes a lot of sense to group related classes. Here is a proven way of handling it. This code is placed in an `auto_prepend_file` (or included first) ``` class Import { public static $_AutoLoad = array(); public static $_Imported = array(); public static function Load($sName) { if(! isset(self::$_AutoLoad[$sName])) throw new ImportError("Cannot import module with name '$sName'."); if(! isset(self::$_Imported[$sName])) { self::$_Imported[$sName] = True; require(self::$_AutoLoad[$sName]); } } public static function Push($sName, $sPath) { self::$_AutoLoad[$sName] = $sPath; } public static function Auto() { function __autoload($sClass) { Import::Load($sClass); } } } ``` And in your bootstrap file, define your classes, and what file they are in. ``` //Define autoload items Import::Push('Admin_Layout', App::$Path . '/PHP/Admin_Layout.php'); Import::Push('Admin_Layout_Dialog', App::$Path . '/PHP/Admin_Layout.php'); Import::Push('FileClient', App::$Path . '/PHP/FileClient.php'); ``` And lastly, enable AutoLoad by calling ``` Import::Auto() ``` --- One of the nice things is that you can define "Modules": ``` Import::Push('MyModule', App::$Path . '/Module/MyModule/Init.php'); ``` And then load them explicitly when needed: ``` Import::Load('MyModule'); ``` And one of the best parts is you can have additional `Import::Push` lines in the module, which will define all of its classes at runtime.
1,441,686
I am planning to use PHP's autoload function to dynamicly load only class files that are needed. Now this could create a huge mess if every single function has a seperate file, So I am hoping and asking is there a way to have related classes remain in 1 class file and still be auto-loaded ``` function __autoload($class_name){ include('classes/' . $class_name . '.class.php'); } ``` Let's say there is a class name animals and then another class named dogs. Dogs class extends animals class, now if I were to call the dogs class but NOT call the animals class, would the animals class file still be loaded?
2009/09/17
[ "https://Stackoverflow.com/questions/1441686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143030/" ]
> > if I were to call the dogs class but > NOT call the animals class, would the > animals class file still be loaded? > > > Yes. When you load an class that extends another class, PHP must load the base class so it knows what it's extending. re: the idea of storing multiple classes per file: This will not work with the autoload function you provided. One class per file is really the best practice, especially for autoloaded classes. If you have more than one class in a file, you really shouldn't attempt to autoload any classes from that file.
There's a workaround, I've just used it and it seems to work: Let's assume we have an autoloaded class called animals stored in animals.class.php. In the same file you could have other classes that extends animals ``` class animals{ static function load(){ return true; } } class dogs extends animals{ } class cats extends animals{ } ``` Now... when you need to use your class `dogs` you need PHP autoload it's parent class (and doing this you're sure it will parse also all the extendend classes inside the same file) so you just have to write: ``` animals::load(); $fuffy = new dogs(); ```
1,441,686
I am planning to use PHP's autoload function to dynamicly load only class files that are needed. Now this could create a huge mess if every single function has a seperate file, So I am hoping and asking is there a way to have related classes remain in 1 class file and still be auto-loaded ``` function __autoload($class_name){ include('classes/' . $class_name . '.class.php'); } ``` Let's say there is a class name animals and then another class named dogs. Dogs class extends animals class, now if I were to call the dogs class but NOT call the animals class, would the animals class file still be loaded?
2009/09/17
[ "https://Stackoverflow.com/questions/1441686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143030/" ]
Have you considered explicit definitions of your class locations? Sometimes it makes a lot of sense to group related classes. Here is a proven way of handling it. This code is placed in an `auto_prepend_file` (or included first) ``` class Import { public static $_AutoLoad = array(); public static $_Imported = array(); public static function Load($sName) { if(! isset(self::$_AutoLoad[$sName])) throw new ImportError("Cannot import module with name '$sName'."); if(! isset(self::$_Imported[$sName])) { self::$_Imported[$sName] = True; require(self::$_AutoLoad[$sName]); } } public static function Push($sName, $sPath) { self::$_AutoLoad[$sName] = $sPath; } public static function Auto() { function __autoload($sClass) { Import::Load($sClass); } } } ``` And in your bootstrap file, define your classes, and what file they are in. ``` //Define autoload items Import::Push('Admin_Layout', App::$Path . '/PHP/Admin_Layout.php'); Import::Push('Admin_Layout_Dialog', App::$Path . '/PHP/Admin_Layout.php'); Import::Push('FileClient', App::$Path . '/PHP/FileClient.php'); ``` And lastly, enable AutoLoad by calling ``` Import::Auto() ``` --- One of the nice things is that you can define "Modules": ``` Import::Push('MyModule', App::$Path . '/Module/MyModule/Init.php'); ``` And then load them explicitly when needed: ``` Import::Load('MyModule'); ``` And one of the best parts is you can have additional `Import::Push` lines in the module, which will define all of its classes at runtime.
There's a workaround, I've just used it and it seems to work: Let's assume we have an autoloaded class called animals stored in animals.class.php. In the same file you could have other classes that extends animals ``` class animals{ static function load(){ return true; } } class dogs extends animals{ } class cats extends animals{ } ``` Now... when you need to use your class `dogs` you need PHP autoload it's parent class (and doing this you're sure it will parse also all the extendend classes inside the same file) so you just have to write: ``` animals::load(); $fuffy = new dogs(); ```