qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
83,521
I can't think of the word and it's driving me nuts. I'm looking for a word that can be used when some technology is discovered, way of thinking, or even event happening that causes a big change in society. Examples might be: discovery of electricity, industrial revolution, nuclear power / bomb, the internet. Some similar terms I can think of are: dawn of a new era, a new age, or paradigm shift. EDIT: I just want to add that I'm thinking of a lesser used word, although *revolutionary* fits it's not specific enough nor the word that I'm looking for.
2012/09/23
[ "https://english.stackexchange.com/questions/83521", "https://english.stackexchange.com", "https://english.stackexchange.com/users/26429/" ]
Pivotal. All the energy of the change comes to bear on one pivotal point, the tipping point, past which the accumulated effort of generations can be seen to have an irrevocable effect.
The first part of the question (“… a word that can be used when some technology is discovered, …”) made me think of [***eureka moment***](http://www.oxfordlearnersdictionaries.com/us/definition/english/eureka-moment), which is comparable to a *breakthrough*: > > the moment when you suddenly understand something important, > have a great idea, or find the answer to a problem > > > But then you go on to talk about “event … that causes a big change in society,” and people suggested *sea change*, *watershed*, and *the beginning of a new era*, so I’ll suggest [***game changer***](http://www.oxforddictionaries.com/us/definition/american_english/game-changer) (optionally hyphenated): > > an event, idea, or procedure > that effects a significant shift in the current manner > of doing or thinking about something > > >
4,117,483
I've got an abstract C++ base class CPlugin. From it, there are many classes derived directly and indirectly. Now given CPlugin \*a,\*b I need to find out, if a's real class is derived from b's real class. I.e. I'd like to do something like this: ``` void checkInheritance(CPlugin *a, CPlugin *b){ if (getClass(a).isDerivedFrom(getClass(b)){ std::cout << "a is a specialization from b's class" << std::endl; } } ``` But how do I implement the "getClass" and "isDerivedFrom" in C++?
2010/11/07
[ "https://Stackoverflow.com/questions/4117483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436308/" ]
You can use dynamic cast to test whether an object belongs to a subtype of a type known at compile time. The mechanism for changing behaviour depending on the runtime type of an object is a virtual function, which gives you a scope where the type of the receiver is known at compile time. So you can achieve the same effect by a virtual function so you have the type at compile time on one side, and then dynamic cast to check the other side against that type: ``` #include <iostream> class Plugin { public: virtual bool objectIsDerivedFromMyClass ( const Plugin & object ) const = 0; }; template <typename T, typename BasePlugin = Plugin> class TypedPlugin : public BasePlugin { public: virtual bool objectIsDerivedFromMyClass ( const Plugin & object ) const { return dynamic_cast<const T*> ( &object ) != 0; } private: int CheckMe(const T*) const; }; class PluginA : public TypedPlugin<PluginA> {}; class PluginB : public TypedPlugin<PluginB, PluginA> {}; class PluginC : public TypedPlugin<PluginC> {}; int main () { PluginA a; PluginB b; PluginC c; std::cout << std::boolalpha << "type of a is derived from type of a " << a.objectIsDerivedFromMyClass ( a ) << '\n' << "type of a is derived from type of b " << b.objectIsDerivedFromMyClass ( a ) << '\n' << "type of b is derived from type of a " << a.objectIsDerivedFromMyClass ( b ) << '\n' << "type of c is derived from type of a " << a.objectIsDerivedFromMyClass ( c ) << '\n' ; return 0; } ``` (You also may want to add a check that `T` extends `TypedPlugin<T>`) It's not quite double dispatch, though `dynamic_cast` is runtime polymorphic on its argument so it is pretty close. Though for anything much more complicated (or if you want to stick with your original style of comparing the objects which represent the runtime types of the objects you have), you need to start create metaclasses, or use an existing framework which supplies metaclasses. Since you're talking about plugins, you may already have somewhere to specify configuration properties or dependencies, and that could be used for this too.
I don't really understand what you are after, but you can always use virtual methods in the following manner: ``` template <typename Derived> struct TypeChecker { virtual bool ParentOf(CPlugin const& c) const { return dynamic_cast<Derived const*>(&c); } }; ``` Now, augment the `CPlugin` class with the following pure virtual method: ``` virtual bool ParentOf(CPlugin const& c) const = 0; ``` And make each class deriving from `CPlugin` inherit from `TypeChecker` as well: ``` class SomePlugin: public CPlugin, private TypeChecker<SomePlugin> {}; ``` And finally use it like such: ``` void checkInheritance(CPlugin const& lhs, CPlugin const& rhs) { if (!rhs.ParentOf(lhs)) return; std::cout << "lhs is derived from rhs' class\n"; } ``` This does not detect if it is a specialization though, since both could perfectly be of the exact same class, this can be detected by using the `typeid` operator. Note the requirement to implement it for every single class deriving from `CPlugin` and you'll understand why it is so complicated and error-prone...
38,956,760
I am trying to print the channel a message was posted to in slack with the python SlackClient. After running this code I only get an ID and not the channel name. ``` import time import os from slackclient import SlackClient BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN') def main(): # Creates a slackclient instance with bots token sc = SlackClient(BOT_TOKEN) #Connect to slack if sc.rtm_connect(): print "connected" while True: # Read latest messages for slack_message in sc.rtm_read(): message = slack_message.get("text") print message channel = slack_message.get("channel") print channels time.sleep(1) if __name__ == '__main__': main() ``` This is the output: ``` test U1K78788H ```
2016/08/15
[ "https://Stackoverflow.com/questions/38956760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3850443/" ]
This will always produce a channel id and not channel name. You must call **channels.info** to get the channel name. ``` import time import os from slackclient import SlackClient BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN') def main(): # Creates a slackclient instance with bots token sc = SlackClient(BOT_TOKEN) #Connect to slack if sc.rtm_connect(): print "connected" while True: # Read latest messages for slack_message in sc.rtm_read(): message = slack_message.get("text") print message channel = slack_message.get("channel") print channel channel_info=sc.api_call("channels.info",channel=channel) print channel_info["channel"]["name"] time.sleep(1) if __name__ == '__main__': main() ``` This will also print channel Name. Another way is that you can store names of all the channels with their channel\_id in a dictionary beforehand. And then get the channel name with id as key.
I'm not sure what you are outputting. Shouldn't "channels" be "channel" ? Also, I think this output is the "user" field. The "Channel" field should yield an id starting with C or G ([doc](https://api.slack.com/events/message)). ``` { "type": "message", "channel": "C2147483705", "user": "U2147483697", "text": "Hello world", "ts": "1355517523.000005" } ``` Then, use either the python client to retrieve the channel name, if it stores it (I don't know the Python client), or use the web API method [channels.info](https://api.slack.com/methods/channels.info) to retrieve the channel name.
60,842
I'm super new to Blender and I hope I'm not offending others asking this. I am baking physics using the method described [here](https://blender.stackexchange.com/questions/6249/setting-the-context-for-cloth-bake) and then do the rendering using the code below. However, it takes a while for the simulation to take place and I only care about the final status of the system/simulation. So I was wondering, is there a way to shortcut the simulation and only get the final status/scene? ``` self.scene.render.filepath = output_name logfile = '/dev/null' open(logfile, 'a').close() old = os.dup(1) sys.stdout.flush() os.close(1) os.open(logfile, os.O_WRONLY) # do the rendering if simulate: bpy.ops.render.render(animation=True) else: bpy.ops.render.render(write_still=True) # disable output redirection os.close(1) os.dup(old) os.close(old) ``` Thanks
2016/08/12
[ "https://blender.stackexchange.com/questions/60842", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/29301/" ]
No, it needs to calculate each step through the animation to make sure that the physics are correct. There is no way to "cut in line." Think about it in terms of a stream of marbles across a plane in Blender. If (theoretically) you could calculate the end frame, you would image a line of marbles moving along. But due to calculating the end frame, you missed the fact that a cube slid across the path, pushing marbles out of the way. Blender *needs* to calculate every frame to make sure physics are correct. If you already know the locations of the objects you want on the end frame, then I recommend just placing the objects there.
No and if you think about it, it really does make sense. Blender does not "calculate" the result. The results are based on the events that are simulated by Blender's realtime physics engine and they can be different every time you run the simulation.
61,266,601
Does anyone know why I'm still receiving a deprecation warning even though I've already specified `useUnifiedTopoology: true` in my `MongoClient` constructor? Thank you in advance! ```js const mongodb = require('mongodb') const MongoClient = mongodb.MongoClient const connectionURL = 'connectionurl' const databaseName = 'db' const client = new MongoClient(connectionURL, { useNewUrlParser: true, useUnifiedTopology: true}); const insertHandler = async(data, collectionName) => { await client.connect().then(async() => { const collection = client.db(databaseName).collection(collectionName) await collection.insertOne(data) }).catch(error => { console.log("Failed to insert:", error) }) } module.exports = { insertHandler: insertHandler } ``` And I'm getting the following error: ``` DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor. ``` [![enter image description here](https://i.stack.imgur.com/TZP9j.png)](https://i.stack.imgur.com/TZP9j.png) [![enter image description here](https://i.stack.imgur.com/QKW2Z.png)](https://i.stack.imgur.com/QKW2Z.png)
2020/04/17
[ "https://Stackoverflow.com/questions/61266601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11839249/" ]
This is what I used and it worked for me: ``` const mongoServer = require('mongodb'); const mongoClient = mongoServer.MongoClient; const dbName = 'tconnect'; const serverUrl = 'mongodb://localhost:27017/'; // Create a database const dbUrl = serverUrl + dbName; const client = new mongoClient(dbUrl, { useUnifiedTopology: true }); client.connect( (err, db) => { if (err) { console.log(err); return; } else { console.log('Database successfully created!'); db.close(); } }); ```
I use it this way, and I don't see that warning anymore. ``` const run = async () => { await mongoose.connect(keys.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }); }; run().catch(error => console.error(error); ```
1,952,817
I am running into an issue with running javascript from an external javascript file inside of an UpdatePanel. I am trying to get a color picker working inside of a ListView. The ListView is inside of an UpdatePanel. I am using [this color picker](http://jscolor.com/). Here is what I have narrowed it down to: * If I use the color picker on a textbox outside of an `UpdatePanel`, it works perfectly fine through all postbacks. * If I use the color picker on a textbox inside of an `UpdatePanel`, it works, until I do an async postback(clicking on an "EDIT" button in the ListView). Once the `UpdatePanel` has done the postback, the textbox will no longer show the color picker when clicked. The same occurs when the textbox is in either the `InsertItemTemplate` or `EditItemTemplate` of the ListView. If you would like to replicate it, simply download the color picker(it's free), then add this to a webpage... ``` <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <div> <asp:UpdatePanel ID="panel1" runat="server"> <ContentTemplate> <asp:TextBox runat="server" ID="textbox" CssClass="color" /> <asp:Button ID="Button1" runat="server" Text="Button" /> </ContentTemplate> </asp:UpdatePanel> </div> ``` When the page loads, the color picker works fine. When you click on the button(which does a postback), the color picker will no longer work. Any ideas?
2009/12/23
[ "https://Stackoverflow.com/questions/1952817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137825/" ]
After an asynchronous roundtrip, any startup scripts will not be run, which is likely why it doesn't work after the AJAX callback. The color picker likely has functions which need to be executed on page load. I've run into this so many times that I wrote a small method to register my scripts in the code-behind, which handles both async and non-async round trips. Here's the basic outline: ``` private void RegisterClientStartupScript(string scriptKey, string scriptText) { ScriptManager sManager = ScriptManager.GetCurrent(this.Page); if (sManager != null && sManager.IsInAsyncPostBack) { //if a MS AJAX request, use the Scriptmanager class ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), scriptKey, scriptText, true); } else { //if a standard postback, use the standard ClientScript method scriptText = string.Concat("Sys.Application.add_load(function(){", scriptText, "});"); this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), scriptKey, scriptText, true); } } ``` I actually baked the above into a base page class so that any page I'm working with can call `this.RegisterClientStartupScript(...)`. To do that, simply create a base page class and include it there (making sure to mark protected not private or your inheriting page classes won't be able access it). With the above code, I can confidently register client scripts regardless of whether the page is doing a postback or callback. Realizing you are using external script files, you could probably modify the above method to register external scripts rather than inline. Consult the [ScriptManager](http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.aspx) class for more details, as there are several script registering methods...
After looking at the jscolor source code, I noticed that it initializes everything on window load. So, you will probably need to re-init with something like this (inside the UpdatePanel): ``` function yourInit(){ /* keep in mind that the jscolor.js file has no way to determine that the script has already been initialized, and you may end up initializing it twice, unless you remove jscolor.install(); */ if (typeof(jscolor) !== 'undefined'){ jscolor.init(); } } if (typeof(Sys) !== 'undefined'){ Sys.UI.DomEvent.addHandler(window, "load", yourInit); } else{ // no ASP.NET AJAX, use your favorite event // attachment method here } ``` If you decide to put the jscolor script inside the UpdatePanel, you will also need to add something like this to the end of the jscolor.js: ``` if(Sys && Sys.Application){ Sys.Application.notifyScriptLoaded(); } ```
63,100,064
I want a card image to change to another card image when I press a button. This is my current code: ```swift import SwiftUI var leftCard = "green_back" var rightCard = "blue_back" func dealCards() { leftCard = "1C" print("deal") } struct GameView: View { var body: some View { VStack { HStack(alignment: .center, spacing: 20) { Image(leftCard) .resizable() .aspectRatio(contentMode: .fit) Image(rightCard) .resizable() .aspectRatio(contentMode: .fit) } .padding(.all, 25) Button(action: dealCards) { Text("Deal Cards") .fontWeight(.bold) .font(.title) .padding(10) .background(Color.blue) .foregroundColor(.white) .padding(10) .border(Color.blue, width: 5) } } } } struct GameView_Previews: PreviewProvider { static var previews: some View { GameView() } } ``` This code prints "deal" when I press the button, but it doesn't change the image. I am using MacOS Big Sur beta 3 and Xcode 12 beta 2. Edit: I just had to move my variables into the GameView struct and add a `@State` modifier to them. Thanks to everyone who answered. :D
2020/07/26
[ "https://Stackoverflow.com/questions/63100064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11396448/" ]
You can even remove the function and add the code directly to button ```swift struct GameView: View { @State var leftCard = "green_back" @State var rightCard = "blue_back" var body: some View { VStack { HStack(alignment: .center, spacing: 20) { Image(leftCard) .resizable() .aspectRatio(contentMode: .fit) Image(rightCard) .resizable() .aspectRatio(contentMode: .fit) } .padding(.all, 25) Button(action: { self.leftCard = "1C" }) { Text("Deal Cards") .fontWeight(.bold) .font(.title) .padding(10) .background(Color.blue) .foregroundColor(.white) .padding(10) .border(Color.blue, width: 5) } } } } ```
You can move your variables to the `GameView` and add `@State` modifier: ``` struct GameView: View { @State var leftCard = "green_back" @State var rightCard = "blue_back" var body: some View { ... } func dealCards() { leftCard = "1C" print("deal") } } ``` This way SwiftUI will refresh the view when your `@State` variables change.
63,030
I have tried to create bootnode by using the following command, but I cannot start the node. bootnode -genkey boot.key ``` bootnode -nodekey boot.key -verbosity 9 -addr :30310 INFO [11-20|18:06:05.376] New local node record seq=1 id=14a0c68dfe9d6ca2 ip=<nil> udp=0 tcp=0 ``` I know how to get the enode, and I had tried to enter it directly. it does not work as well. ``` geth -bootnodes "enode://3ec4fef2d726c2c01f16f0a0030f15dd5a81e274067af2b2157cafbf76aa79fa9c0be52c6664e80cc5b08162ede53279bd70ee10d024fe86613b0b09e1106c40@[::]:30310" ``` Had spent more than 2 days. Any help will be appreciated!
2018/11/26
[ "https://ethereum.stackexchange.com/questions/63030", "https://ethereum.stackexchange.com", "https://ethereum.stackexchange.com/users/48426/" ]
You may produce the enode from nodekey by using option of `--writeaddress` Refer to [how to produce enode from node key?](https://ethereum.stackexchange.com/questions/28970/how-to-produce-enode-from-node-key)
Try to `-writeaddress` Example: `bootnode -nodekey boot.key -verbosity 9 -addr :30310 -writeaddress` Maybe it help you
5,357,716
I'm using expressionengine to create a documentation site, using the weblog module. I have a number of categories, which contain subcategories. Categories and subcategories contain entries. I want to create a page for each category that outputs a nested list of all the child entries and subcategories within in that parent category. There should be a breadcrumb at the top that shows the category hierarchy with links to the parent categories. Here is my code: ``` <!-- url /docs/category/category_id --> <!-- Breadcrumb --> <!-- This works on the page template, but on the category template it shows all the categories --> {exp:weblog:entries weblog="docs" } {categories} <a href="{path='/category'}?category_id={category_id}&category_name={category_name}&category_description={category_description}">{category_name}</a> > {/categories} {title} {/exp:weblog:entries} <!-- List of Categories --> <!-- This shows ALL of the categories. I want it to only show the parent category and its children --> {exp:weblog:categories style="nested"} <h1><a href="{path='weblog/category'}"{category_name}</a></h1> {exp:weblog:entries category="{category_id}"} <a href="{path='weblog/page'}">{title}</a> {/exp:weblog:entries} {/exp:weblog:categories} ```
2011/03/18
[ "https://Stackoverflow.com/questions/5357716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362871/" ]
To go from: ``` Year,Make,Model,Description,Price 1997,Ford,E350,"ac, abs, moon",3000.00 1999,Chevy,"Venture ""Extended Edition""","",4900.00 1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00 1996,Jeep,Grand Cherokee,"MUST SELL! air, moon roof, loaded",4799.00 ``` To ``` [ {:year => 1997, :make => 'Ford', :model => 'E350', :description => 'ac, abs, moon', :price => 3000.00}, {:year => 1999, :make => 'Chevy', :model => 'Venture "Extended Edition"', :description => nil, :price => 4900.00}, {:year => 1999, :make => 'Chevy', :model => 'Venture "Extended Edition, Very Large"', :description => nil, :price => 5000.00}, {:year => 1996, :make => 'Jeep', :model => 'Grand Cherokee', :description => "MUST SELL!\nair, moon roof, loaded", :price => 4799.00} ] ``` Do this: ``` csv = CSV.new(body, :headers => true, :header_converters => :symbol, :converters => :all) csv.to_a.map {|row| row.to_hash } #=> [{:year=>1997, :make=>"Ford", :model=>"E350", :description=>"ac, abs, moon", :price=>3000.0}, {:year=>1999, :make=>"Chevy", :model=>"Venture \"Extended Edition\"", :description=>"", :price=>4900.0}, {:year=>1999, :make=>"Chevy", :model=>"Venture \"Extended Edition, Very Large\"", :description=>nil, :price=>5000.0}, {:year=>1996, :make=>"Jeep", :model=>"Grand Cherokee", :description=>"MUST SELL!\nair, moon roof, loaded", :price=>4799.0}] ``` Credit: <https://technicalpickles.com/posts/parsing-csv-with-ruby>
If you're in a Rails project ``` CSV.parse(csv_string, {headers: true}) csv.map(&:to_h).to_json ```
69,511,294
Update ------- Since `onSaveInstanceState` & `onRestoreInstanceState` can't be used to store/restore values after closed the app, I tried to use dataStore to solve it, but it dosen't work, here's my trying **`DataStoreRepository`** ``` @ActivityRetainedScoped public static class DataStoreRepository { RxDataStore<Preferences> dataStore; public static Preferences.Key<Integer> CURRENT_DESTINATION = PreferencesKeys.intKey("CURRENT_DESTINATION"); public final Flowable<Integer> readCurrentDestination; @Inject public DataStoreRepository(@ApplicationContext Context context) { dataStore = new RxPreferenceDataStoreBuilder(Objects.requireNonNull(context), /*name=*/ "settings").build(); readCurrentDestination = dataStore.data().map(preferences -> { if (preferences.get(CURRENT_DESTINATION) != null) { return preferences.get(CURRENT_DESTINATION); } else { return R.id.nav_home; } }); } public void saveCurrentDestination(String keyName, int value){ CURRENT_DESTINATION = PreferencesKeys.intKey(keyName); dataStore.updateDataAsync(prefsIn -> { MutablePreferences mutablePreferences = prefsIn.toMutablePreferences(); Integer currentKey = prefsIn.get(CURRENT_DESTINATION); if (currentKey == null) { saveCurrentDestination(keyName,value); } mutablePreferences.set(CURRENT_DESTINATION, currentKey != null ? value : R.id.nav_home); return Single.just(mutablePreferences); }).subscribe(); } } ``` **read and save in ViewModel** ``` public final MutableLiveData<Integer> currentDestination = new MutableLiveData<>(); @Inject public PostViewModel(Repository repository, Utils.DataStoreRepository dataStoreRepository) { this.repository = repository; getAllItemsFromDataBase = repository.localDataSource.getAllItems(); this.dataStoreRepository = dataStoreRepository; dataStoreRepository.readCurrentDestination .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new FlowableSubscriber<Integer>() { @Override public void onSubscribe(@NonNull Subscription s) { s.request(Long.MAX_VALUE); } @Override public void onNext(Integer integer) { } @Override public void onError(Throwable t) { Log.e(TAG, "onError: " + t.getMessage()); } @Override public void onComplete() { } }); } public void saveCurrentDestination(int currentDestination) { dataStoreRepository .saveCurrentDestination("CURRENT_DESTINATION", currentDestination); } ``` **and finally MainActivity** ``` @AndroidEntryPoint public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @SuppressWarnings("unused") private AppBarConfiguration mAppBarConfiguration; private NavHostFragment navHostFragment; private NavController navController; NavGraph navGraph; private PostViewModel postViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); postViewModel = new ViewModelProvider(this).get(PostViewModel.class); setSupportActionBar(binding.appBarMain.toolbar); mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_home, R.id.nav_accessory, R.id.nav_arcade, R.id.nav_fashion, R.id.nav_food, R.id.nav_heath, R.id.nav_lifestyle, R.id.nav_sports, R.id.about) .setOpenableLayout(binding.drawerLayout) .build(); navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment); if(navHostFragment !=null) { navController = navHostFragment.getNavController(); } NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration); NavigationUI.setupWithNavController(binding.navView, navController); navGraph = navController.getNavInflater().inflate(R.navigation.mobile_navigation); postViewModel.currentDestination.observe(this,currentDestination -> { Log.d(TAG, "currentDestination: " + currentDestination); Toast.makeText(this,"currentDestination" + currentDestination,Toast.LENGTH_SHORT).show(); navGraph.setStartDestination(currentDestination); navController.setGraph(navGraph); }); navController.addOnDestinationChangedListener((controller, destination, arguments) -> { Log.d(TAG, "addOnDestinationChangedListener: " + destination.getId()); postViewModel.saveCurrentDestination(destination.getId()); }); } @Override public boolean onSupportNavigateUp() { return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp(); } } ``` **Problem in detail** In this app I have 9 menu items and fragments in navigation drawer, I want to save the last opened fragment in `savedInstanceState` or `datastore` and after the user closed the app and re open it again display the last opend fragment, but I don't know which method I'll use **`Navigation.findNavController(activity,nav_graph).navigate();`** or **`binding.navView.setNavigationItemSelectedListener(item -> false);`** **activity\_main.xml** ``` <?xml version="1.0" encoding="utf-8"?> <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"> <include android:id="@+id/app_bar_main" layout="@layout/app_bar_main" android:layout_width="match_parent" android:layout_height="match_parent" /> <com.google.android.material.navigation.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" android:background="@color/color_navigation_list_background" app:headerLayout="@layout/nav_header_main" app:menu="@menu/activity_main_drawer" /> </androidx.drawerlayout.widget.DrawerLayout> ``` **activity\_main\_drawer.xml** ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:showIn="navigation_view"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_home" android:title="@string/home" android:icon="@drawable/home" /> <item android:id="@+id/nav_accessory" android:title="@string/accessory" android:icon="@drawable/necklace" /> <item android:id="@+id/nav_arcade" android:title="@string/arcade" android:icon="@drawable/arcade_cabinet" /> <item android:id="@+id/nav_fashion" android:title="@string/fashion" android:icon="@drawable/fashion_trend" /> <item android:id="@+id/nav_food" android:title="@string/food" android:icon="@drawable/hamburger" /> <item android:id="@+id/nav_heath" android:title="@string/heath" android:icon="@drawable/clinic" /> <item android:id="@+id/nav_lifestyle" android:title="@string/lifestyle" android:icon="@drawable/yoga" /> <item android:id="@+id/nav_sports" android:title="@string/sports" android:icon="@drawable/soccer" /> <item android:id="@+id/nav_favorites" android:title="@string/favorites_posts" android:icon="@drawable/ic_favorite" /> <item android:id="@+id/about" android:title="@string/about" android:icon="@drawable/about" /> </group> </menu> ``` **nav\_graph.xml** ``` <?xml version="1.0" encoding="utf-8"?> <navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/mobile_navigation" app:startDestination="@id/nav_home"> <fragment android:id="@+id/nav_home" android:name="com.blogspot.abtallaldigital.ui.HomeFragment" android:label="@string/home" tools:layout="@layout/fragment_home"> <action android:id="@+id/action_nav_home_to_detailsFragment" app:destination="@id/detailsFragment" app:popUpTo="@id/nav_home" /> </fragment> <fragment android:id="@+id/nav_accessory" android:name="com.blogspot.abtallaldigital.ui.AccessoryFragment" android:label="@string/accessory" tools:layout="@layout/fragment_accessory" > <action android:id="@+id/action_nav_Accessory_to_detailsFragment" app:destination="@id/detailsFragment" /> </fragment> <fragment android:id="@+id/nav_arcade" android:name="com.blogspot.abtallaldigital.ui.ArcadeFragment" android:label="@string/arcade" tools:layout="@layout/fragment_arcade" > <action android:id="@+id/action_nav_Arcade_to_detailsFragment" app:destination="@id/detailsFragment" /> </fragment> <fragment android:id="@+id/nav_fashion" android:name="com.blogspot.abtallaldigital.ui.FashionFragment" android:label="@string/fashion" tools:layout="@layout/fragment_fashion" > <action android:id="@+id/action_nav_Fashion_to_detailsFragment" app:destination="@id/detailsFragment" /> </fragment> <fragment android:id="@+id/nav_food" android:name="com.blogspot.abtallaldigital.ui.FoodFragment" android:label="@string/food" tools:layout="@layout/food_fragment" > <action android:id="@+id/action_nav_Food_to_detailsFragment" app:destination="@id/detailsFragment" /> </fragment> <fragment android:id="@+id/nav_heath" android:name="com.blogspot.abtallaldigital.ui.HeathFragment" android:label="@string/heath" tools:layout="@layout/heath_fragment" > <action android:id="@+id/action_nav_Heath_to_detailsFragment" app:destination="@id/detailsFragment" /> </fragment> <fragment android:id="@+id/nav_lifestyle" android:name="com.blogspot.abtallaldigital.ui.LifestyleFragment" android:label="@string/lifestyle" tools:layout="@layout/lifestyle_fragment" > <action android:id="@+id/action_nav_Lifestyle_to_detailsFragment" app:destination="@id/detailsFragment" /> </fragment> <fragment android:id="@+id/nav_sports" android:name="com.blogspot.abtallaldigital.ui.SportsFragment" android:label="@string/sports" tools:layout="@layout/sports_fragment" > <action android:id="@+id/action_nav_Sports_to_detailsFragment" app:destination="@id/detailsFragment" /> </fragment> <dialog android:id="@+id/about" android:name="com.blogspot.abtallaldigital.ui.AboutFragment" android:label="about" tools:layout="@layout/about" /> <fragment android:id="@+id/detailsFragment" android:name="com.blogspot.abtallaldigital.ui.DetailsFragment" android:label="Post details" tools:layout="@layout/fragment_details" > <argument android:name="postItem" app:argType="com.blogspot.abtallaldigital.pojo.Item" /> </fragment> <fragment android:id="@+id/nav_favorites" android:name="com.blogspot.abtallaldigital.ui.FavoritesFragment" android:label="Favorites posts" tools:layout="@layout/fragment_favorites" > <action android:id="@+id/action_favoritesFragment_to_detailsFragment" app:destination="@id/detailsFragment" /> </fragment> </navigation> ``` **MainActivity class** ``` @AndroidEntryPoint public class MainActivity extends AppCompatActivity { @SuppressWarnings("unused") private AppBarConfiguration mAppBarConfiguration; public static Utils.DataStoreRepository DATA_STORE_REPOSITORY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); setSupportActionBar(binding.appBarMain.toolbar); mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_home, R.id.nav_accessory, R.id.nav_arcade, R.id.nav_fashion, R.id.nav_food, R.id.nav_heath, R.id.nav_lifestyle, R.id.nav_sports, R.id.about) .setOpenableLayout(binding.drawerLayout) .build(); NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment); assert navHostFragment != null; NavController navController = navHostFragment.getNavController(); NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration); NavigationUI.setupWithNavController(binding.navView, navController); } @Override public boolean onSupportNavigateUp() { NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp(); } } ```
2021/10/09
[ "https://Stackoverflow.com/questions/69511294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7639296/" ]
#### Disclaimer: As the `SharedPreference` will be deprecated soon or later, there is an Update below using `DataStore`. --- Using `SharedPreference` ------------------------ `onSaveInstanceState` & `onRestoreInstanceState` can't be used to store/restore values after the app is closed/shut. Even if the app is not closed, you can't rely on them for storing large objects or storing objects for a long time. Instead of that you can use `SharedPreference` to store a value that maps to last open fragment before the app exists. Here I store some arbitrary value, as it's recommended not to store application IDs, as they can vary from app launch to another. So, you can store arbitrary values and map them to the generated IDs in the current app launch. I picked those values as array indices: ``` // Array of fragments private Integer[] fragments = { R.id.nav_home, R.id.nav_accessory, R.id.nav_arcade, R.id.nav_fashion, R.id.nav_food, R.id.nav_heath, R.id.nav_lifestyle, R.id.nav_sports, R.id.about }; ``` Then for every launch of the app; i.e. in `onCreate()` method, you can pick the current index from the `SharedPreference`, and call `graph.setStartDestination()`: ``` // Getting the last fragment: SharedPreferences mSharedPrefs = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE); int fragIndex = mSharedPrefs.getInt(LAST_FRAGMENT, -1); // The last fragment index // Check if it's a valid index if (fragIndex >= 0 && fragIndex < fragments.length) { // Navigate to this fragment int currentFragment = fragments[fragIndex]; graph.setStartDestination(currentFragment); // Change the current navGraph navController.setGraph(graph); } ``` And you can register new values to the sharedPreference once the destination is changed using `OnDestinationChangedListener` of the `navController`: ``` // Listener to the change in fragments, so that we can updated the shared preference navController.addOnDestinationChangedListener((controller, destination, arguments) -> { int fragmentIndex = Arrays.asList(fragments).indexOf(destination.getId()); SharedPreferences.Editor editor = mSharedPrefs.edit(); editor.putInt(LAST_FRAGMENT, fragmentIndex).apply(); }); ``` Integrating this into your code with: ``` @AndroidEntryPoint public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @SuppressWarnings("unused") private AppBarConfiguration mAppBarConfiguration; private NavHostFragment navHostFragment; private NavController navController; NavGraph navGraph; // Array of fragments private Integer[] fragments = { R.id.nav_home, R.id.nav_accessory, R.id.nav_arcade, R.id.nav_fashion, R.id.nav_food, R.id.nav_heath, R.id.nav_lifestyle, R.id.nav_sports, R.id.about }; // Key for saving the last fragment in the Shared Preferences private static final String LAST_FRAGMENT = "LAST_FRAGMENT"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); setSupportActionBar(binding.appBarMain.toolbar); mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_home, R.id.nav_accessory, R.id.nav_arcade, R.id.nav_fashion, R.id.nav_food, R.id.nav_heath, R.id.nav_lifestyle, R.id.nav_sports, R.id.about) .setOpenableLayout(binding.drawerLayout) .build(); navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment); if(navHostFragment !=null) { navController = navHostFragment.getNavController(); } NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration); NavigationUI.setupWithNavController(binding.navView, navController); navGraph = navController.getNavInflater().inflate(R.navigation.mobile_navigation); // Getting the last fragment: SharedPreferences mSharedPrefs = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE); int fragIndex = mSharedPrefs.getInt(LAST_FRAGMENT, -1); // The last fragment index // Check if it's a valid index if (fragIndex >= 0 && fragIndex < fragments.length) { // Navigate to this fragment int currentFragment = fragments[fragIndex]; graph.setStartDestination(currentFragment); // Change the current navGraph navController.setGraph(graph); } // Listener to the change in fragments, so that we can updated the shared preference navController.addOnDestinationChangedListener((controller, destination, arguments) -> { int fragmentIndex = Arrays.asList(fragments).indexOf(destination.getId()); SharedPreferences.Editor editor = mSharedPrefs.edit(); editor.putInt(LAST_FRAGMENT, fragmentIndex).apply(); }); } @Override public boolean onSupportNavigateUp() { return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp(); } } ``` --- Using DataStore --------------- > > Since I migrated from sharedpreferences to dataStore in this project, I tried to do the same as your solution but it doesn't work, I'll post my try and you can look at it to see what's wrong, then you can edit your answer with dataStore soultion > > > So, I am going to use the same approach but with the DataStore (same fragment array, store indices instead of fragment destination IDs). So, you need to add the array of fragment IDs so that it can be read in the DataStore process: ``` // Array of fragment IDs private Integer[] fragments = { R.id.nav_home, R.id.nav_accessory, R.id.nav_arcade, R.id.nav_fashion, R.id.nav_food, R.id.nav_heath, R.id.nav_lifestyle, R.id.nav_sports, R.id.about }; ``` Then in the Repository change the logic to use the indices instead of the fragment IDs: ``` @Inject public DataStoreRepository(@ApplicationContext Context context) { dataStore = new RxPreferenceDataStoreBuilder(Objects.requireNonNull(context), /*name=*/ "settings").build(); readCurrentDestination = dataStore.data().map(preferences -> { Integer fragIndex = preferences.get(CURRENT_DESTINATION); if (fragIndex == null) fragIndex = 0; if (fragIndex >= 0 && fragIndex <= fragments.length) { // Navigate to the fragIndex return fragments[fragIndex]; } else { return R.id.nav_home; } }); } ``` And in the `ViewModel`, you should not subscribe a permanent Observable to the `Flowable` because this will submit any change to the observed data permanently, but instead you can convert the `Flowable` to a `Single` so that you can just get a single (first) value of the fragment ID only once at the app launch, and no more observers are registered. [Check Documentation](http://reactivex.io/RxJava/3.x/javadoc/io/reactivex/rxjava3/core/Single.html) for more details. Applying that in your `ViewModel`: ``` @Inject public PostViewModel(Repository repository, Utils.DataStoreRepository dataStoreRepository) { this.repository = repository; getAllItemsFromDataBase = repository.localDataSource.getAllItems(); this.dataStoreRepository = dataStoreRepository; dataStoreRepository.readCurrentDestination.firstOrError().subscribeWith(new DisposableSingleObserver<Integer>() { @Override public void onSuccess(@NotNull Integer destination) { // Must be run at UI/Main Thread runOnUiThread(() -> { currentDestination.setValue(destination); }); } @Override public void onError(@NotNull Throwable error) { error.printStackTrace(); } }).dispose(); } ``` Then as you observe the `currentDestination` MutableLiveData in the activity: change the current destination there (You already did that well): ``` postViewModel.currentDestination.observe(this,currentDestination -> { Log.d(TAG, "currentDestination: " + currentDestination); Toast.makeText(this,"currentDestination" + currentDestination,Toast.LENGTH_SHORT).show(); navGraph.setStartDestination(currentDestination); navController.setGraph(navGraph); }); ``` Saving the current fragment to the `DataStore` whenever the destination changes: In the `ViewModel`: ``` public void saveCurrentDestination(int value){ int fragmentIndex = Arrays.asList(fragments).indexOf(value); CURRENT_DESTINATION = PreferencesKeys.intKey(keyName); dataStore.updateDataAsync(prefsIn -> { MutablePreferences mutablePreferences = prefsIn.toMutablePreferences(); mutablePreferences.set(CURRENT_DESTINATION, fragmentIndex); return Single.just(mutablePreferences); }).subscribe(); } ```
How you store the current location within the navigation graph doesn't matter much (we are actually talking about storing a single one `long` value and eventually some argument values). The preconditions by themselves should already explain how it works: * being able to navigate to each destination with a [global](https://developer.android.com/guide/navigation/navigation-global-action) `NavAction`. * being able to resolve the stored destination ID to a [global](https://developer.android.com/guide/navigation/navigation-global-action) `NavAction`. * not to forget about navigation arguments (eg. alike an `itemId`). Alike this one may loose the back-stack entries, but one can navigate directly. If this shouldn't suffice, store the `NavController` back-stack entries and them play them back (not suggested).
7,181,534
I would like to make a simple HTTP POST using JSON in Java. Let's say the URL is `www.site.com` and it takes in the value `{"name":"myname","age":"20"}` labeled as `'details'` for example. How would I go about creating the syntax for the POST? I also can't seem to find a POST method in the JSON Javadocs.
2011/08/24
[ "https://Stackoverflow.com/questions/7181534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/910485/" ]
You can use the following code with Apache HTTP: ``` String payload = "{\"name\": \"myname\", \"age\": \"20\"}"; post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON)); response = client.execute(request); ``` Additionally you can create a json object and put in fields into the object like this ``` HttpPost post = new HttpPost(URL); JSONObject payload = new JSONObject(); payload.put("name", "myName"); payload.put("age", "20"); post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON)); ```
For Java 11 you can use the new [HTTP client](https://openjdk.java.net/groups/net/httpclient/intro.html): ``` HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost/api")) .header("Content-Type", "application/json") .POST(ofInputStream(() -> getClass().getResourceAsStream( "/some-data.json"))) .build(); client.sendAsync(request, BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept(System.out::println) .join(); ``` You can use publishers from `InputStream`, `String`, `File`. Converting JSON to a `String` or `IS` can be done with Jackson.
67,145,283
I have wrote the code ``` import os from webdriver_manager.chrome import ChromeDriverManager import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC options = Options() options.add_argument('--ignore-certificate-errors') options.add_argument('--start-maximized') options.page_load_strategy = 'eager' driver = webdriver.Chrome(options=options) url = "https://www.moneycontrol.com/india/stockpricequote/chemicals/tatachemicals/TC" driver.get(url) try: wait = WebDriverWait(driver, 10) except Exception: driver.send_keys(Keys.CONTROL +'Escape') driver.find_element_by_link_text("Bonus").click() try: wait = WebDriverWait(driver, 5) except Exception: driver.send_keys(Keys.CONTROL +'Escape') for i in range(0, 50): bonus_month = driver.find_element_by_xpath ("//*[@class= 'mctable1.thborder.frtab']/tbody/tr[%s]/td[1]"%(i)) print(bonus_month.text) bonus = driver.find_element_by_xpath ("//*[@class= 'mctable1.thborder.frtab']/tbody/tr[%s]/td[1]"%(i)) print(bonus.text) ``` This gives me error ``` no such element: Unable to locate element: {"method":"xpath","selector":"//*[@class= 'mctable1.thborder.frtab']/tbody/tr[0]/td[1]"} ``` Element on the page: [![enter image description here](https://i.stack.imgur.com/8I6D1.png)](https://i.stack.imgur.com/8I6D1.png) Where I am making mistake in finding Exbonus and Ratio?
2021/04/18
[ "https://Stackoverflow.com/questions/67145283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
There is a strange bit of history to `bit_width`. The function that would eventually become known as `bit_width` started life as `log2`, as part of a proposal [adding integer power-of-two functions](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0556r0.html). `log2` was specified to produce UB when passed 0. Because that's how logarithms work. But then, things changed. The function later became `log2p1`, and [for reasons that are not specified was given a wider contract](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0556r1.html) ("wide contract" in C++ parlance means that more stuff is considered valid input). Specifically, 0 is valid input, and yields the value of 0. Which is *not* how logarithms work, but whatever. As C++20 neared standardization, a [name conflict was discovered (PDF)](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2019/n4844.pdf#page=94). The name `log2p1` happens to correspond to the name of an IEEE-754 algorithm, but it's a radically different one. Also, functions in other languages with similar inputs and results use a name like `bit_length`. So it [was renamed to `bit_width`](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1956r0.pdf). And since it's not pretending to do a logarithm anymore, the behavior at 0 can be whatever we want. Indeed, [the Python function `int.bit_length` has the exact same behavior](https://docs.python.org/3/library/stdtypes.html#additional-methods-on-integer-types). Leading zeros are not considered part of the bit length, and since a value of `0` contains all leading zeros...
Because mathematically it makes sense: ``` bit_width(x) = log2(round_up_to_nearest_integer_power_of_2(x + 1)) bit_width(0) = log2(round_up_to_nearest_integer_power_of_2(0 + 1)) = log2(1) = 0 ```
67,191,045
I am trying to Check for the NAN values for 2 columns, if both the columns are blank so need to update the col3 with "All Blanks" I have tried working with it but its not working. Input Data: ``` S.no col1 col2 col3 1. 2. 9786543628 AZ256hy 3. 4. 9784533930 AZ256hc 5. 9778934593 AZ256py ``` **Code i have been using** ``` df['col3']=df.apply(lambda x:'All Blanks' if (x['col1'] == " ") and (x['col2'] == " ")) print(df['col3']) ``` But it's Not working. Please Suggest.
2021/04/21
[ "https://Stackoverflow.com/questions/67191045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7735179/" ]
Using `apply` here is not recommended, because it is loops under the hoods and always try avoit it if exist some vectorized alternatives. So use: Missing values are not spaces (or empty strings), so for test use [`Series.isna`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isna.html) and for new column [`numpy.where`](https://numpy.org/doc/stable/reference/generated/numpy.where.html): ``` df['col3']=np.where(df['col1'].isna() & df['col2'].isna(), 'All Blanks' , df['col3']) ``` Or test columns selected by list with [`DataFrame.all`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.all.html) for all `True`s per rows: ``` df['col3']=np.where(df[['col1', 'col2']].isna().all(axis=1), 'All Blanks' , df['col3']) ```
You can also use boolean mask, `assign()` method and `fillna()` method: ``` mask=(df['col1'].isna()) & (df['col2'].isna()) df=df.assign(col3=df.loc[mask]['col3'].fillna('All Blanks')) ``` Now if you print `df` you will get your desired output
248,293
Cant rewrite `Mage_Review_Block_Product_View` for some reason. In my config file I have: ``` <?xml version="1.0"?> <config> <modules> <NameSpace_ModuleName> <version>0.0.1</version> </NameSpace_ModuleName> </modules> <admin> <routers> <adminhtml> <args> <modules> <NameSpace_ModuleName before="Mage_Adminhtml">NameSpace_ModuleName_Adminhtml</NameSpace_ModuleName> </modules> </args> </adminhtml> </routers> </admin> <adminhtml> <layout> <updates> <Review> <file>namespace/review.xml</file> </Review> </updates> </layout> </adminhtml> <frontend> <routers> <review> <args> <modules> <NameSpace_ModuleName before="Mage_Review">NameSpace_ModuleName</NameSpace_ModuleName> </modules> </args> </review> </routers> <layout> <updates> <Review> <file>namespace/product-review-extended.xml</file> </Review> </updates> </layout> </frontend> <global> <helpers> <Review> <class>NameSpace_ModuleName_Helper</class> </Review> </helpers> <blocks> <Review> <class>NameSpace_ModuleName_Block</class> </Review> <review> <rewrite> <product_view>NameSpace_ModuleName_Block_Product_View</product_view> </rewrite> </review> <adminhtml> <rewrite> <review_edit_form>NameSpace_ModuleName_Block_Review_Edit_Form</review_edit_form> </rewrite> <rewrite> <review_add_form>NameSpace_ModuleName_Block_Review_Add_Form</review_add_form> </rewrite> </adminhtml> <page> <rewrite> <html_pager>NameSpace_ModuleName_Block_Page_Html_Pager</html_pager> </rewrite> </page> </blocks> <models> <review_resource> <rewrite> <review>NameSpace_ModuleName_Model_Resource_Review</review> </rewrite> </review_resource> <review_resource> <rewrite> <review_collection>NameSpace_ModuleName_Model_Resource_Review_Collection</review_collection> </rewrite> </review_resource> <Review> <class>NameSpace_ModuleName_Model</class> </Review> </models> <events> <review_save_after> <observers> <NameSpace_ModuleName> <type>singleton</type> <class>NameSpace_ModuleName_Model_Observer</class> <method>notifyRecipient</method> </NameSpace_ModuleName> </observers> </review_save_after> </events> <template> <email> <review_email_notification_optionamespace_email_template tranamespacelate="label" module="review"> <label>Product Review Notification</label> <file>product_review_notification.html</file> <type>html</type> </review_email_notification_optionamespace_email_template> </email> </template> </global> </config> ``` And I place file the following path: `Local/Namespace/ModuleName/Block/Product/View.php` with class name extended like this: `class Namespace_ModuleName_Block_Product_View extends Mage_Catalog_Block_Product_View` But it would not extend it for some reason. Its not cache, and the rest of the module works fine. Please help dont know what to try. Thanks,
2018/10/29
[ "https://magento.stackexchange.com/questions/248293", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/73183/" ]
You can use CSS instead of script. ``` .success { -webkit-animation: cssAnimation 5s forwards; animation: cssAnimation 5s forwards; } @keyframes cssAnimation { 0% {opacity: 1;} 90% {opacity: 1;} 100% {opacity: 0;} } @-webkit-keyframes cssAnimation { 0% {opacity: 1;} 90% {opacity: 1;} 100% {opacity: 0;} } ``` Its work for me.
Try the following way: **File:** Vendor/Module/view/frontend/requirejs-config.js ``` var config = { "map": { "*": { "Magento_Theme/js/view/messages": "Vendor_Module/js/view/messages", } } } ``` **File:** Vendor/Module/view/frontend/web/js/view/messages.js ``` define([ 'jquery', 'uiComponent', 'underscore', 'Magento_Customer/js/customer-data', 'jquery/jquery-storageapi' ], function ($, Component, _, customerData) { 'use strict'; return Component.extend({ defaults: { cookieMessages: [], messages: [] }, /** @inheritdoc */ initialize: function () { this._super(); this.cookieMessages = $.cookieStorage.get('mage-messages'); this.messages = customerData.get('messages').extend({ disposableCustomerData: 'messages' }); if (!_.isEmpty(this.messages().messages)) { customerData.set('messages', {}); } $.cookieStorage.set('mage-messages', ''); setTimeout(function() { $(".messages").hide('blind', {}, 500) }, 5000); } }); }); ``` Now, clear cache, deploy static content and check again.
30,945,769
How can we pass an arraylist as value from the mapper to the reducer. My code basically has certain rules to work with and would create new values(String) based on the rules.I am maintaining all the outputs(generated after the rule execution) in a list and now need to send this output(Mapper value) to the Reducer and do not have a way to do so. Can some one please point me to a direction Adding Code ``` package develop; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs; import utility.RulesExtractionUtility; public class CustomMap{ public static class CustomerMapper extends Mapper<Object, Text, Text, Text> { private Map<String, String> rules; @Override public void setup(Context context) { try { URI[] cacheFiles = context.getCacheFiles(); setupRulesMap(cacheFiles[0].toString()); } catch (IOException ioe) { System.err.println("Error reading state file."); System.exit(1); } } public void map(Object key, Text value, Context context) throws IOException, InterruptedException { // Map<String, String> rules = new LinkedHashMap<String, String>(); // rules.put("targetcolumn[1]", "ASSIGN(source[0])"); // rules.put("targetcolumn[2]", "INCOME(source[2]+source[3])"); // rules.put("targetcolumn[3]", "ASSIGN(source[1]"); // Above is the "rules", which would basically create some list values from source file String [] splitSource = value.toString().split(" "); List<String>lists=RulesExtractionUtility.rulesEngineExecutor(splitSource,rules); // lists would have values like (name, age) for each line from a huge text file, which is what i want to write in context and pass it to the reducer. // As of now i havent implemented the reducer code, as m stuck with passing the value from mapper. // context.write(new Text(), lists);---- I do not have a way of doing this } private void setupRulesMap(String filename) throws IOException { Map<String, String> rule = new LinkedHashMap<String, String>(); BufferedReader reader = new BufferedReader(new FileReader(filename)); String line = reader.readLine(); while (line != null) { String[] split = line.split("="); rule.put(split[0], split[1]); line = reader.readLine(); // rules logic } rules = rule; } } public static void main(String[] args) throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException, URISyntaxException { Configuration conf = new Configuration(); if (args.length != 2) { System.err.println("Usage: customerMapper <in> <out>"); System.exit(2); } Job job = Job.getInstance(conf); job.setJarByClass(CustomMap.class); job.setMapperClass(CustomerMapper.class); job.addCacheFile(new URI("Some HDFS location")); URI[] cacheFiles= job.getCacheFiles(); if(cacheFiles != null) { for (URI cacheFile : cacheFiles) { System.out.println("Cache file ->" + cacheFile); } } // job.setReducerClass(Reducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ```
2015/06/19
[ "https://Stackoverflow.com/questions/30945769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5029282/" ]
To pass an arraylist from mapper to reducer, it's clear that objects must implement Writable interface. Why don't you try this library? ``` <dependency> <groupId>org.apache.giraph</groupId> <artifactId>giraph-core</artifactId> <version>1.1.0-hadoop2</version> </dependency> ``` It has an abstract class: ``` public abstract class ArrayListWritable<M extends org.apache.hadoop.io.Writable> extends ArrayList<M> implements org.apache.hadoop.io.Writable, org.apache.hadoop.conf.Configurable ``` You could create your own class and source code filling the abstract methods and implementing the interface methods with your code. For instance: ``` public class MyListWritable extends ArrayListWritable<Text>{ ... } ```
You should send `Text` objects instead `String` objects. Then you can use `object.toString()` in your Reducer. Be sure to config your driver properly. If you post your code we will help you further.
35,167,776
I was wondering if there is a quick way to parse the first line of a HTTP get request to just grab the directory information? For example, if I have: GET /test.txt HTTP/1.1, what would be the easiest way to get just test.txt or whatever the request might be. The file might change so hard coding is out. Is string.split() the easiest way. If so what would the best way to split it be. I can't split it by "/", because there could be more than one I need. Is it possible to just split it an grab everything after the first "/" and then stop at the first space. Thanks. EDIT: Would it be better to just remove GET and HTTP/1.1 since I won't need them, and then just grab everything else?
2016/02/03
[ "https://Stackoverflow.com/questions/35167776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5808314/" ]
With `bool([''])` you're checking if the list `['']` has any contents, *which it does*, the contents just happen to be the empty string `''`. If you want to check whether *all* the elements in the list aren't 'empty' (so if the list contains the string `''` it will return `False`) you can use the built-in function **[`all()`](https://docs.python.org/2.7/library/functions.html#all)**: ``` all(v for v in l) ``` This takes every element `v` in list `l` and checks if it has a `True` value; if **all** elements do it returns `True` if at least one doesn't it returns `False`. As an example: ``` l = ''.split(',') all(v for v in l) Out[75]: False ``` You can substitute this with **[`any()`](https://docs.python.org/2.7/library/functions.html#any)** to perform a partial check and see if *any of the items* in the list `l` have a value of `True`. A more comprehensive example\* with both uses: ``` l = [1, 2, 3, ''] all(l) # '' doesn't have a True value Out[82]: False # 1, 2, 3 have a True value any(l) Out[83]: True ``` --- \*As *[@ShadowRanger](https://stackoverflow.com/users/364696/shadowranger)* pointed out in the comments, the same exact thing can be done with `all(l)` or `any(l)` since they both just accept an iterable in the end.
In your case it truly isnt empty If you want to check if the element within that list is empty you can do: ``` string = ''.split(',') if not string[0]: print "empty" ```
8,253,091
I remember a few years ago writing an emulator for an 8 bit processor, which IIRC, never really existed. It was thought up by someone in order to write a emulator, and was referenced a lot for beginners in the field of emulation. I lost the code that I had and I wanted to look it up again. (bummer really. It had a nice debugger, with register, stack, and memory views and break points. Full screen, sound, saved states. I liked it a lot D: ) I've been googling with no luck. The name in my head was Z80, but I quickly realized that that was the processor for the Gameboys xD hahaha
2011/11/24
[ "https://Stackoverflow.com/questions/8253091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1031401/" ]
try this, <https://github.com/valums/ajax-upload> It has multiple file upload support for old browsers too
You could try jQuery uploadify <http://www.uploadify.com/>
54,259,911
A user enters a String and method draws a square. For example: * For input= `ram` method draws: `r r r` `- a -` `m m m` * For input= `code` method draws: `c c c c` `- o o -` `- d d -` `e e e e` * For input = `coder` method draws: `c c c c c` `- o o o -` `- - d - -` `- e e e -` `r r r r r` So far I have managed to draw something like this: `c - - - c` `- o - o -` `- - d - -` `- e - e -` `r - - - r` Using this code: ``` static void pattern(String n) { int len = n.length(); for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { if((i==j)||(i==len-j-1)) { System.out.printf("%c ", n.charAt(i)); } else { System.out.printf("- "); } } System.out.printf("%n"); } } ``` I have only managed to print diagonally using `if((i==j)||(i==len-j-1))`, but I do not know how I would be able to make it look like example above. How could I upgrade my code to draw the square properly?
2019/01/18
[ "https://Stackoverflow.com/questions/54259911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7248976/" ]
``` static void pattern(String n) { int len = n.length(); for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { if((i<j)&&(i>len-j-1) || (i>j)&&(i<len-j-1)) { System.out.printf("- "); } else { System.out.printf("%c ", n.charAt(i)); } } System.out.printf("%n"); } ``` The first condition ``` (i>j)&&(i<len-j-1) ``` selects the following part ``` x x x x x x x - x x x x x x - - x x x x x - - - x x x x - - x x x x x - x x x x x x x x x x x x x ``` and the ``` (i>j)&&(i<len-j-1) ``` selects the following parts ``` x x x x x x x x x x x x x - x x x x x - - x x x x - - - x x x x x - - x x x x x x - x x x x x x x ```
You could use double for loop to print 2D array. Just count amount of `-` at the beginning and end of the raw depending on the raw's index. ``` public static void pattern(String str) { for (int i = 0, last = str.length() - 1; i <= last; i++) { for (int j = 0, dash = last; j <= last; j++, dash--) System.out.print(i < j && i > dash || i > j && i < dash ? '-' : str.charAt(i)); System.out.println(); } } ```
2,911,721
I wanted to know if that has any ill effects under any circumsatnce. For ex: ``` Ex1: void* func1() { void* p_ref = NULL; //function scope static variable static int var1 = 2; p_ref = &var1; return p_ref; } Ex2: //file scope static variable static int var2 = 2; void* func2() { void* p_ref = NULL; var2 = 3; p_ref = &var2; return p_ref; } ``` So in the above two cases what is the difference apart from the fact that var1 is function scope and var2 is file scope. Thanks in advance.
2010/05/26
[ "https://Stackoverflow.com/questions/2911721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95880/" ]
I'm guessing you just need to break this down into a couple of steps rather than trying to do it all in one, something like: ``` // First get the customer group Property... CustomerGroup customerGroup = getValue<Customer>(customer, "Group"); // Then get the name of the group... if(customerGroup != null) { string customerGroupName = getValue<CustomerGroup>(customerGroup, "name"); } ```
Since Group is the property of the customer, which itself hosts the property name, you have to go this way too. But since '.' cant be part of the name of the property you can easyly use String.Substring to remove the first property name from string and call your method recursively.
32,643,393
Does anyone know why the file isn't opening? I also tried just putting "infile.txt" and placing it in the folder of the program and also the debug folder but the ways I used to check for open error both triggered meaning that it could not open. I know I can hard code the location but I don't want to. I heard you should do `stringobj.c_str()` but I don't know if that's accurate? ``` #include "stdafx.h" #include <iostream> #include <string> #include <fstream> using namespace std; int main() { ifstream infile; ofstream outfile; string fileloc = "infile.txt"; infile.open(fileloc); if (!infile) { cout << "open fail 1" << endl; } bool fail = infile.fail(); if (fail) { cout << "open fail 2"; } return 0; } ```
2015/09/18
[ "https://Stackoverflow.com/questions/32643393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3822749/" ]
Check your working directory in Project Settings -> Debugging. Make your file available there.
with ``` string fileloc = "infile.txt"; ``` if you put infile.txt in the same folder of the cpp file, it should be fine. btw I delete your first line ``` #include "stdafx.h" ``` I use cygwin console, may have minor diff
130,415
In *Minecraft*, you can only build up to a certain height limit (which is something around 256). However, if a player uses mods/hacks to go above the limit (Or simply goes into Creative Mode), then they can go above the height limit. How high is the player height limit in *Minecraft*? Is there even a limit to it? I've tried testing this myself, but my thumb started hurting when I reached Y= 1000.
2013/09/09
[ "https://gaming.stackexchange.com/questions/130415", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/49961/" ]
The answer to your question can easily be found on the [Minecraft wiki](http://www.minecraftwiki.net/wiki/Altitude). > > **The maximum height (coordinates) a player can reach is displayed as "6.7108E7" (6.7E7 is 6.7 times 10^7th, or 67 million, approximately > 2^26th)** > > >
There is no limit to a player's height. The Y coordinate is tracked with the same size of variable as the X and Z, so you can go as infinitely\* high as you can travel infinitely\* far. There is no extra limitation placed on player height, so the only limitation is *how* to get there. With cheats on, you can use `/tp` to experiment with how high you can go, and you can see your position by toggling on the debug screen with `F3`. \* Not actually infinite, but it takes many days of real time to walk that far.
349
I have a sliding screen door that leads out to a porch/deck. The door continually sticks and is just doesn't slide open cleanly. Otherwise the screen and everything is fine. Is there something I can do to fix this or do I need to replace the entire screen door?
2010/07/22
[ "https://diy.stackexchange.com/questions/349", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/38/" ]
Have you tried lubricating it? [Seems worth a shot for the price](http://www.shopgetorganized.com/item/PATIO_DOOR_LUBE_AND_SLIDE/29338?src=GOFRGL08&CAWELAID=281651816) before replacing the whole door.
Take your screen to a glass company. They usually have or can get replacement rollers.
49,967,724
I have an element on the page ``` <a data-cke-saved-name name></a> ``` and I want to check does this element exist on the page? I tried this way ``` WebElement link = null; try { link = Main.s_driver.findElement(By.tagName("data-cke-saved-name name")); System.out.println("OK"); } catch (NoSuchElementException e) { System.out.println("Something went wrong"); } ``` But it doesn't work. Is there any other way to check this element?
2018/04/22
[ "https://Stackoverflow.com/questions/49967724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9496492/" ]
I will provide an answer for those who can't use a third party. The output of the format is **04 || X || Y [ || K]** without the EC header identifier that many outside systems expect. You'll need to add that header when exporting it for other platforms. Here's an example: ``` let fullKeyData = CFDataCreateMutable(kCFAllocatorDefault, CFIndex(0)) if fullKeyData != nil { //Fixed schema header per key size in bits //var headerBytes256r1: [UInt8] = [0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00] //uncomment if you use 256 bit EC keys var header384r1: [UInt8] = [0x30, 0x76, 0x30, 0x10, 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, 0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22, 0x03, 0x62, 0x00] //384 bit EC keys //var header521r1: [UInt8] = [0x30, 0x81, 0x9B, 0x30, 0x10, 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, 0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23, 0x03, 0x81, 0x86, 0x00] // For 521 bit EC keys let headerSize = CFIndex(header384r1.count) CFDataAppendBytes(fullKeyData, &header384r1, headerSize) CFDataAppendBytes(fullKeyData, CFDataGetBytePtr(pub), CFDataGetLength(pub)) //pub = data you got from SecKeyCopyExternalRepresentation var pem = "" //pem.append("-----BEGIN PUBLIC KEY-----\n") //uncomment if needed pem.append((fullKeyData as Data?)?.base64EncodedString() ?? "") //pem.append("\n-----END PUBLIC KEY-----\n") //uncomment if needed //do something with pem } ```
> > BJSCZtBatd2BYEHtyLB0qTZNlphKf3ZTGI6Nke3dSxIDpyP9FWMZbG0zcdIXWENyndskfxV0No/yz369ngL2EHZYw6ggNysOnZ5IQSPOLFFl44m1aAk0o0NdaRXTVAz4jQ== > > > The key appears to be malformed. It appears to be an EC key. I suspect it is the public one detailed as `04 || X || Y`, but I could be wrong. Do you know what field the key is over? The field tells you how many bytes are in `X` and `Y`. ```none $ cat key.dat BJSCZtBatd2BYEHtyLB0qTZNlphKf3ZTGI6Nke3dSxIDpyP9FWMZbG0zcdIXWENyndskfxV0No/yz369ngL2EHZYw6ggNysOnZ5IQSPOLFFl44m1aAk0o0NdaRXTVAz4jQ== $ base64 -d key.dat | hexdump -C 00000000 04 94 82 66 d0 5a b5 dd 81 60 41 ed c8 b0 74 a9 |...f.Z...`A...t.| 00000010 36 4d 96 98 4a 7f 76 53 18 8e 8d 91 ed dd 4b 12 |6M..J.vS......K.| 00000020 03 a7 23 fd 15 63 19 6c 6d 33 71 d2 17 58 43 72 |..#..c.lm3q..XCr| 00000030 9d db 24 7f 15 74 36 8f f2 cf 7e bd 9e 02 f6 10 |..$..t6...~.....| 00000040 76 58 c3 a8 20 37 2b 0e 9d 9e 48 41 23 ce 2c 51 |vX.. 7+...HA#.,Q| 00000050 65 e3 89 b5 68 09 34 a3 43 5d 69 15 d3 54 0c f8 |e...h.4.C]i..T..| 00000060 8d |.| 00000061 ```
43,127,159
I'm working on a personal project to do with computational geometry. The question in the title is an abstraction of one of the small subproblems that I am trying, but struggling, to solve efficiently. Hopefully it's general enough to maybe be of use of more than just me! --- The problem ----------- Imagine we have a set S of rectangles in the plane, all of which have edges parallel to the coordinate axes (no rotations). For my problem we'll assume that rectangle intersections are **very common**. But they are also very nice: If two rectangles intersect, we can assume one of them *always* completely contains the other. So there's no "partial" overlaps. I want to store these rectangles in a way that: * We can efficiently add new rectangles. * Given a query point (x,y) we can efficiently report back the rectangle of smallest area that contains the point. The illustration provides the motivation for the latter. We always want to find the most deeply nested rectangle that contains the query point, so that's always the one of smallest area. [![.](https://i.stack.imgur.com/QXN9J.png)](https://i.stack.imgur.com/QXN9J.png) --- My thoughts ----------- So I know that both R-Trees and Quad-Trees are often used for spatial indexing problems, and indeed both can work well in some cases. The problem with R-Trees is that they can degrade to linear performance in the worst case. I thought about building a set of balanced binary trees based on nestedness. The left subtree of node r contains all the rectangles that are inside rectangle r. The right subtree contains all the rectangles that r is inside of. The illustrated example would have three trees. But what if none of the rectangles are nested? Then you need O(n) trees of 1 element and again we have something that performs just as poorly as a linear scan through the boxes. --- How could I solve this in a way that we have asymptotically sub linear time in the worst case? Even if that means sacrificing some performance in the best cases or storage requirements. (I assume for a problem like this, there may be a need to maintain two data structures and that's cool) I am certain that the very specific way in which rectangles are allowed to intersect should help make this problem possible. In fact, it looks like a candidate for logarithmic performance to me but I'm just not getting anywhere. Thanks in advance for any ideas you have!
2017/03/30
[ "https://Stackoverflow.com/questions/43127159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4310120/" ]
I'd suggest storing the rectangles per nesting level, and tackling the rectangle-finding per level. Once you've found which top-level rectangle the point is in, you can then look at the second-level rectangles that are inside that rectangle, find the rectangle the point is in using the same method, then look at the third-level, and so on. To avoid a worst-case of O(n) to find the rectangle, you could use a sort of ternary spatial tree, where you repeatedly draw a vertical line across the space and divide the rectangles into three groups: those to the left (blue), those intersected by (red), and those to the right (green) of the line. For the group of intersected rectangles (or once a vertical line would intersect most or all of the rectangles), you switch to a horizontal line and divide the rectangles into groups above, intersected by, and below the line. [![ternary spatial tree](https://i.stack.imgur.com/oZ1Rl.png)](https://i.stack.imgur.com/oZ1Rl.png) You would then repeatedly check whether the point is to the left/right or above/below the line, and go on to check the rectangles on the same side and those intersected by the line. In the example, only four rectangles would actually need to be checked to find which rectangle contains the point. --- If we use the following numbering for the rectangles in the example: [![rectangle numbering](https://i.stack.imgur.com/Ddi0k.png)](https://i.stack.imgur.com/Ddi0k.png) then the ternary spatial tree would be something like this: [![ternary spatial tree](https://i.stack.imgur.com/8pB2G.png)](https://i.stack.imgur.com/8pB2G.png)
How about a [PH-Tree](http://www.phtree.org)? The PH-Tree is a essentially quadtree shaped like a quadtree, but with some unique properties that may be ideal for your case, such as very efficient updates and a high likelihood of locality of small rectangles. Basics: * The PH-Tree is a bit-level try, that means it splits in all dimensions at every bit position. This means, for 64bit floating point data, the maximum depth of the tree is 64. * The tree is implicitly z-ordered * Query speed is usually comparable to R\*Tree or STR-Tree, for your case it may be considerably faster, see below. * Insertion/deletion speed is equal to or better that STR-Trees and better than any other R-Tree type that I am aware of. * Tree shape is determined only by the data, not by insertion order. That means there will never be any costly rebalancing. In fact, the tree guarantees that any insertion or deletion will never affect more than two nodes (with child/parent relationship). Storing rectangles: The PH-Tree can only store vectors of data, ie. points. In order to store (axis aligned) rectangles, it takes by default the 'lower left' and 'upper right' corner and but these into single vector. For example, a 2D rectangle (2,2)-(4,5) is stored as a 4-dim vector (2,2,4,5). It may not be obvious, but this representation still allows for efficient queries, such as window queries and nearest neighbor queries, see some results [here](https://github.com/tzaeschke/TinSpin/blob/master/doc/benchmark-2017-01/Diagrams.pdf) and some more explanation [here](https://github.com/tzaeschke/phtree/blob/master/PhTreeRevisited.pdf). The tree cannot directly store the same rectangle twice. Instead you would have associate a counter with each 'key'. For the special case with 'n' identical rectangles, this actually has the advantage that the resulting tree would contain only one key, so overlap with the smallest rectangle could be determined in almost constant time. Query performance: As can be seen from the performance results, the PH-Tree is (depending on the dataset) fastest with small query windows that return few results ([here](https://github.com/tzaeschke/TinSpin/blob/master/doc/benchmark-2017-01/Diagrams.pdf), Figure 16). I'm not sure whether the performance benefit is connected to the small query window size or the small result size. But if it is connected to the first, then your queries should be very fast, because essentially your query window is a point. Optimising for small rectangle size: Due to the encoding of rectangles into a single vector, the smallest rectangle is likely (guaranteed??) to be in the same leaf node that would also contain your search point. Usually, queries are traversed in z-order, so to exploit locality of small rectangles, you would need to write a special query. This should not be hard, I think I could simply use the PH-Tree k-nearest-neighbor implementation and provide a custom distance function. The current kNN starts with locating the node with the search point and then extends the search area until it found all nearest neighbors. I do believe that using a custom distance function should be sufficient, but you may have to do some research to prove it. The complete code (Java) of the PH-Tree is available in the link above. For comparison, you may want to check out my other index implementations [here](https://github.com/tzaeschke/tinspin-indexes) (R\*Tree, quadtrees, STR-Tree).
49,968,581
I have tried to run this code over and over and cannot figure out the problem. When you add a name the results can be displayed just fine. When I edit the name and then try to display the roster I get an error. The error is: ``` Traceback (most recent call last): File "Z:/Grantham University/programming essentials/Week 5 Cody Pillsbury.py", line 88, in <module> DisplayTeamRoster(teamRoster) File "Z:/Grantham University/programming essentials/Week 5 Cody Pillsbury.py", line 39, in DisplayTeamRoster teamRoster[x].displayTeamRoster() AttributeError: 'tuple' object has no attribute 'displayTeamRoster' ``` Below is the code: ``` import sys; class Roster: name = "" phoneNumber = "" jersyNumber = 0 def __init__(self, name, phoneNumber, jersyNumber): self.name = name self.phoneNumber = phoneNumber self.jersyNumber = jersyNumber def setname(self, name): self.name = name def setphoneNumber(self, phoneNumber): self.phoneNumber = phoneNumber def setjersyNumber(self, jersyNumber): self.jersyNumber = jersyNumber def getname(self): return self.name def getphoneNumber(self): return self.phoneNumber def getjersyNumber(self): return self.jersyNumber def displayTeamRoster(self): print("Member information:") print("-------------------") print("Name:", self.name) print("Phone Number:", self.phoneNumber) print("Jersy Number:", self.jersyNumber) def DisplayTeamRoster(teamRoster): if len(teamRoster) == 0: print("There are no players on this team!") else: for x in teamRoster.keys(): teamRoster[x].displayTeamRoster() def addPlayer(teamRoster): playerName = input("Please Enter Player\'s Name:") playerPhoneNumber = input("Please Enter Player\'s Phone Number:") playerJersyNumber = int(input("Please Enter Player\'s Jersy Number:")) teamRoster[playerName] = Roster(playerName, playerPhoneNumber, playerJersyNumber) print(playerName, "is now on the Team Roster!") return teamRoster def removePlayer(teamRoster): removed = input("Please Enter Player You Would Like To Remove:") if removed in teamRoster: del teamRoster[removed] print(removed, "is no longer on in the team roster!") else: print(removed, "was not found in the team roster!") return teamRoster def editPlayer(teamRoster): oldName = input("Please enter the player\'s name you would like to change:") if oldName in teamRoster: playerName = input("What is the player\'s new name:") playerPhoneNumber = input("What is the player\'s new phone number:") playerJersyNumber = input("What is the player\'s new jersey number:") teamRoster[oldName] = (playerName, playerPhoneNumber, playerJersyNumber) else: print(oldName, "was not found in the team roster!") return teamRoster def exitProgram(): print("Exiting Program......") sys.exit() def mainApp(): print("---------Main Menu---------") print("(1) Display Team Roster") print("(2) Add Player") print("(3) Remove Player") print("(4) Edit Player") print("(9) Exit Program") try: test = int(input("Please choose a menu option:")) except ValueError: print("invalid input, you must use corresponding number in menu") else: return test print("Welcome to the Team Manager") teamRoster = {} options = mainApp() while options != 9: if options == 1: DisplayTeamRoster(teamRoster) elif options == 2: teamRoster = addPlayer(teamRoster) elif options == 3: teamRoster = removePlayer(teamRoster) elif options == 4: teamRoster = editPlayer(teamRoster) elif options == 9: exitProgram() else: print("invalid selection") options = mainApp() ```
2018/04/22
[ "https://Stackoverflow.com/questions/49968581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3728126/" ]
In IEEE-754 basic 32-bit binary floating-point, every finite value has the form: > > ± x.xxxxxxxxxxxxxxxxxxxxxxx • 2*e* > > > where x.xxxxxxxxxxxxxxxxxxxxxxx is a binary numeral and −126 ≤ *e* ≤ +127. For normal numbers, the first x is 1, and *e* may be any value in −126 ≤ *e* ≤ +127. Since the first x is always 1, it is not explicitly stored—the floating-point format contains one bit for the sign, 23 bits for the other x's, and 8 bits for the exponent. The exponent is stored as the binary for *e*+127. So, for *e* from −126 to +127, the stored value is 1 to 254. That leaves 0 and 255. 0 in the exponent field is a code for subnormal numbers. For subnormal numbers, the exponent *e* is the same as the lowest normal exponent, −126, but the first x is 0. So a subnormal value has the form: > > ± 0.xxxxxxxxxxxxxxxxxxxxxxx • 2−126 > > > Thus the smallest positive value that can be represented is: > > + 0.00000000000000000000001 • 2−126 > > > which is 2−149. (255 in the exponent field is used to represent infinity and NaNs.)
It is quite simple: -126 was chosen for denormals so there is no step between the smallest normal and the largest denormal. The lowest normal is > > 1.0000...bin × 2-126 > > > One "ULP" below that is > > 0.1111...bin × 2-126 > > > If it were 2-127, there would be a step of several "ULP" (or even many "ULP") between those two values.
24,652,297
I m new to JSON and I'm getting this error .. Actually I'm pulling wallpapers from cloud using JSON file .. Please let me know what mistake I have done .. Please .. Blow arre the details .. ``` org.json.JSONException: Unterminated array at character 5995 ``` this is my JSON ``` { "wallpapers": { "category": [ { "name": "Blur", "wallpaper": [ { "author": "Musaddiq", "url": "http://i.imgur.com/Zq3oJXF.png", "thumbUrl": "http://i.imgur.com/Zq3oJXFm.png", "name": "Blur-1" }, { "author": "Musaddiq", "url": "http://i.imgur.com/Dri3Q3k.png", "thumbUrl": "http://i.imgur.com/Dri3Q3km.png", "name": "Blur-2" }, { "author": "Musaddiq", "url": "http://i.imgur.com/HQLf2B2.png", "thumbUrl": "http://i.imgur.com/HQLf2B2m.png", "name": "Blur-3" }, { "author": "Musaddiq", "url": "http://i.imgur.com/kk4Dbeo.png", "thumbUrl": "http://i.imgur.com/kk4Dbeom.png", "name": "Blur-4" }, { "author": "Musaddiq", "url": "http://i.imgur.com/lEuPZYO.png", "thumbUrl": "http://i.imgur.com/lEuPZYOm.png", "name": "Blur-5" } ] }, { "name": "Meteor Style", "wallpaper": [ { "author": "Musaddiq", "url": "http://i.imgur.com/tRkX4P5.png", "thumbUrl": "http://i.imgur.com/tRkX4P5m.png", "name": "Avengers" }, { "author": "Musaddiq", "url": "http://i.imgur.com/QCp7W7j.png", "thumbUrl": "http://i.imgur.com/QCp7W7jm.png", "name": "Batman" }, { "author": "Musaddiq", "url": "http://i.imgur.com/plaD66v.png", "thumbUrl": "http://i.imgur.com/plaD66vm.png", "name": "C America" }, { "author": "Musaddiq", "url": "http://i.imgur.com/hAfX42z.png", "thumbUrl": "http://i.imgur.com/hAfX42zm.png", "name": "Flash" }, { "author": "Musaddiq", "url": "http://i.imgur.com/MQaAGUi.png", "thumbUrl": "http://i.imgur.com/MQaAGUim.png", "name": "Green Lantern" }, { "author": "Musaddiq", "url": "http://i.imgur.com/x1GBhD1.png", "thumbUrl": "http://i.imgur.com/x1GBhD1m.png", "name": "Iron Man" }, { "author": "Musaddiq", "url": "http://i.imgur.com/LCSmsc8.png", "thumbUrl": "http://i.imgur.com/LCSmsc8m.png", "name": "Meteor" }, { "author": "Musaddiq", "url": "http://i.imgur.com/icM5MfS.png", "thumbUrl": "http://i.imgur.com/icM5MfSm.png", "name": "Super Man" } ] }, { "name": "Outer Space", "wallpaper": [ { "author": "PartimusPrime", "url": "http://i.imgur.com/6DFACmh.jpg", "thumbUrl": "http://i.imgur.com/6DFACmhm.jpg", "name": "Outer Space-1" }, { "author": "edisile", "url": "http://i.imgur.com/RCMXDzE.png", "thumbUrl": "http://i.imgur.com/RCMXDzEm.png", "name": "Outer Space-2" }, { "author": "edisile", "url": "http://i.imgur.com/CvXSj5Q.png", "thumbUrl": "http://i.imgur.com/CvXSj5Qm.png", "name": "Outer Space-3" }, { "author": "edisile", "url": "http://i.imgur.com/BjwtOgc.png", "thumbUrl": "http://i.imgur.com/BjwtOgcm.png", "name": "Outer Space-4" } ] }, { "name": "Triangulate", "wallpaper": [ { "author": "Musaddiq", "url": "http://i.imgur.com/rxhJBpb.png", "thumbUrl": "http://i.imgur.com/rxhJBpbm.png", "name": "Triangulate-1" }, { "author": "Musaddiq", "url": "http://i.imgur.com/XfN47N3.png", "thumbUrl": "http://i.imgur.com/XfN47N3m.png", "name": "Triangulate-2" }, { "author": "Musaddiq", "url": "http://i.imgur.com/FQrOMK8.png", "thumbUrl": "http://i.imgur.com/FQrOMK8m.png", "name": "Triangulate-3" }, { "author": "Musaddiq", "url": "http://i.imgur.com/u1FLHgz.png", "thumbUrl": "http://i.imgur.com/u1FLHgzm.png", "name": "Triangulate-4" }, "author": "Musaddiq", "url": "http://i.imgur.com/q1vAuoO.png", "thumbUrl": "http://i.imgur.com/q1vAuoOm.png", "name": "Triangulate-5" }, "author": "Musaddiq", "url": "http://i.imgur.com/1IOAQbl.png", "thumbUrl": "http://i.imgur.com/1IOAQblm.png", "name": "Triangulate-6" } ] } ] } ] } ``` } Any Solution ? Thanks :)
2014/07/09
[ "https://Stackoverflow.com/questions/24652297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3447597/" ]
You have syntax errors on your JSON Object near the end: ``` }, <-- Missing new object declaractor '{' "author": "Musaddiq", "url": "http://i.imgur.com/q1vAuoO.png", "thumbUrl": "http://i.imgur.com/q1vAuoOm.png", "name": "Triangulate-5" }, <-- Missing new object declaractor '{' "author": "Musaddiq", "url": "http://i.imgur.com/1IOAQbl.png", "thumbUrl": "http://i.imgur.com/1IOAQblm.png", "name": "Triangulate-6" } ] } ] <-- Typographical error, remove this token } <-- Typographical error, remove this token ] } } ```
You have an extra closing bracket and curly bracket in the end
57,891,570
what do you think, is it permissible to use logic in a class marked as @Configuration, given that this logic is applied only 1 time at the start of the application. For example: We want to configure Caches and for this, we need to do a couple of injections in the class marked as @Configuration, write some methods to create caches and add @PostConstract. How legal is it to write such a thing not in @Service or @Component, but in @Configuration? And if it's bad, then why? ``` @Configuration public class SomeClass { @Resource private SomeCacheManager someCacheManager; @Resource private SomeCacheEvictor someCacheEvictor; @PostConstruct public void init(){ createCache("Some cache"); createCache("Other"); createCache("More"); ... } public void createCache(String cacheName){ /* Some code to create cache */ } ``` }
2019/09/11
[ "https://Stackoverflow.com/questions/57891570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10231106/" ]
I was messing up with tabindex value and missing title attribute on headings. This heading is navigable with tab hotkeys and reproduces audio title for screen readers: ``` <h2 tabindex="0" title="List of our services">List of our services</h2> ```
Screen reader users can navigating heading without the need of the `tabindex="0"`. This is a build in feature for screen readers. That is pressing the h key in form modes off. Will navigate to all heading. Pressing the number 1 will navigate to `<h1>` and 2 will navigate to `<h2>` and so on if these elements exist on a webpage Adding the `tabindex="0"` to heading will not impove the screen reader users experience but will help keyboard users that are not able to navigate heading with the tab key to now access the headings on you page. I would not advice adding a custome message on your heading elements `<h1> <h2>` and `<h3>`. If you want to customise the heading contect I will ask why. Would other uses also find the information provide. Providing a custome message that only screen reader users can see but no other users can cause more harm than good as it could confuse screen reader users who can see. Examples would be 1. People with low vision 2. People with cognitive disability 3. People with other reading disabilities that use screen readers to help them read the content on a webpage page.
801,962
(I've come here from [this question](https://math.stackexchange.com/questions/801505/shall-remainder-always-be-positive).) What's the difference between modulus and remainder? (Bearing in mind until 5 minutes ago I thought they were the same :P )
2014/05/19
[ "https://math.stackexchange.com/questions/801962", "https://math.stackexchange.com", "https://math.stackexchange.com/users/25334/" ]
Let's say we have integers $a $ and $b$. The $remainder$ of $a$ divided by $b$ is the number $r$ such that $a = qb +r$ for some $q\in\mathbb{Z}$ (here $\mathbb{Z}$ is the set of integers), and $0\leq r <b$. In this situation, $r$ is uniquely determined. That is, there is only one value of $r$ which satisfies these requirements, and so we say that $r$ is $the$ remainder of $a$ divided by $b$. Modulus, in this situation, refers to the number $b$. However, given the context, I think what you meant to refer to was "$a$ mod $b$", or the class of $a$ modulo $b$, which is actually an infinite set of integers. Precisely, the class of $a$ modulo $b$ is the set \begin{equation\*} a+b\mathbb{Z} = \left\{a+bn\;|\;n\in\mathbb{Z}\right\}.\end{equation\*} Every number in this set yields the same remainder after division by $b$. So, for example, $5$ mod $7$ is the same as $12$ mod $7$, because we have the equality of sets \begin{equation\*} 5+7\mathbb{Z} = 12 + 7\mathbb{Z}. \end{equation\*} Often, people say "$12 $ mod $7 = 5$," which is technically incorrect. What we should say is "the class of 12 mod 7 is equal to the class of 5 mod 7", or "5 and 12 are equivalent modulo 7". When working modulo $n$, we have a preferred set of representatives for each class modulo $n$, which is usually \begin{equation\*} \{0,1,...n-1\}.\end{equation\*}That means that every number is equivalent to one of these numbers modulo $n$. When we use this particular set of class representatives, they just so happen to coincide with the usual notion of remainder.
The modulus in a modular equation $\pmod{n}$ is the number $n$. That is exactly what "mod n" refers to. The set of integers with the same remainder forms an equivalence class that's sometimes called "the residue modulo $n$." For and integer $a$ and a positive integer $b$, the division algorithm says that there exists unique integers $q,r$ such that $a=bq+r$ and $0\leq r<b$. They are related in the sense that $a\equiv a'\pmod b$ iff $a$ and $a'$ have the same remainder after division by the modulus $b$.
294,535
I'm on a GoDaddy shared hosting Linux server ("unlimited" hosting). I have a folder with product images for an e-commerce store that contains over 7000 images. GoDaddy told me I'm not *allowed* to have over 1024 files in a single directory and that I need to reformat the folder structure, which isn't possible as this software is maintained and run by a Point-of-Sale system at my client's brick and mortar store. I've SSH'd in and changed permissions on the folder I'm moving the image to and the image itself to 777 and issued the following command: ``` mv img.gif product_images/img.gif ``` and I get the following error: ``` mv: cannot move 'img.gif' to 'product_images/img.gif': File too large ``` The file is not "too large"; it is only 49 bytes (its a 1x1 gif)! If I try drag+drop upload from Windows into the directory via FTP I get the following errors: ``` An error occurred copying a file to the FTP Server. Make sure you have permission to put files on the server. Details: 200 TYPE is now 8-bit binary 227 Entering Passive Mode (184,168,167,92,197,60) 553-Can't open that file: File too large 553 Rename/move failure: no such file or directory ``` I DO have permission to put files on the server...its how I put the img.gif file there in the first place. The directory does exist. I can `ls` its contents just fine. The previous support guy (who is not longer available) could do it - I just don't know how. How can I go about moving files into this very stubborn directory? Any ideas?
2011/06/08
[ "https://superuser.com/questions/294535", "https://superuser.com", "https://superuser.com/users/31266/" ]
GoDaddy has directly told you that it doesn't allow what you want to do. [The GoDaddy help pages tell you that what you want to do is not allowed.](http://help.godaddy.com./topic/306/article/4261) They even tell you that you'll get these sorts of error messages if you try to do what you are not allowed to do. And here you are, asking, "How, despite being told that I cannot by GoDaddy itself, do I do this?". **GoDaddy does not allow you to do this.** Find someone else who does, or keep below the 1024 directory entries limit.
Get around the issue by creating a [CSS sprite-sheet](http://css-tricks.com/css-sprites/) for the product images. You'll reduce your number of files exponentially.
2,493,232
I've this brief snippet: ``` String target = baseFolder.toString() + entryName; target = target.substring(0, target.length() - 1); File targetdir = new File(target); if (!targetdir.mkdirs()) { throw new Exception("Errore nell'estrazione del file zip"); } ``` doesn't mattere if I leave the last char (that is usually a slash). It's done this way to work on both unix and windows. The path is actually obtained from the URI of the base folder. As you can see from baseFolder.toString() (baseFolder is of type URI and is correct). The base folder actually exists. I can't debug this because all I get is true or false from mkdir, no other explanations.The weird thing is that baseFolder is created as well with mkdir and in that case it works. Now I'm under windows. --- the value of target just before the creation of targetdir is "file:/C:/Users/dario/jCommesse/jCommesseDB" if I cut and paste it (without the last entry) in windows explore it works...
2010/03/22
[ "https://Stackoverflow.com/questions/2493232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138606/" ]
The path you provide is not a file path, but a URI. I suggest you try the following : ``` URI uri = new URI("file://c:/foo/bar"); File f = new File(uri). ```
The [`File` constructor taking a `String`](http://java.sun.com/javase/6/docs/api/java/io/File.html#File(java.lang.String)) expects a path name. A path name is **not** an URI. Remove the `file:/` from the front of the String (or better yet, use [`getPath()`](http://java.sun.com/javase/6/docs/api/java/net/URI.html#getPath()) instead of `toString()`) to get to the path you need.
555,292
What is the common theory behind thread communication? I have some primitive idea about how it should work but something doesn't settle well with me. Is there a way of doing it with interrupts?
2009/02/17
[ "https://Stackoverflow.com/questions/555292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/63166/" ]
Really, it's just the same as *any* concurrency problem: you've got multiple threads of control, and it's indeterminate which statements on which threads get executed when. That means there are a large number of POTENTIAL execution paths through the program, and your program must be correct under all of them. In general the place where trouble can occur is when state is shared among the threads (aka "lightweight processes" in the old days.) That happens when there are shared memory areas, To ensure correctness, what you need to do is ensure that these data areas get updated in a way that can't cause errors. To do this, you need to identify "critical sections" of the program, where sequential operation must be guaranteed. Those can be as little as a single instruction or line of code; if the language and architecture ensure that these are *atomic*, that is, can't be interrupted, then you're golden. Otherwise, you idnetify that section, and put some kind of guards onto it. The classic way is to use a *semaphore*, which is an atomic statement that only allows one thread of control past at a time. These were invented by Edsgar Dijkstra, and so have names that come from the Dutch, *P* and *V*. When you come to a *P*, only one thread can proceed; all other threads are queued and waiting until the executing thread comes to the associated *V* operation. Because these primitives are a little primitive, and because the Dutch names aren't very intuitive, there have been some ther larger-scale approaches developed. Per Brinch-Hansen invented the *monitor*, which is basically just a data structure that has operations which are guaranteed atomic; they can be implemented with semaphores. Monitors are pretty much what Java `synchronized` statements are based on; they make an object or code block have that particular behavir -- that is, only one thread can be "in" them at a time -- with simpler syntax. There are other modeals possible. Haskell and Erlang solve the problem by being functional languages that never allow a variable to be modified once it's created; this means they naturally don't need to wory about synchronization. Some new languages, like Clojure, instead have a structure called "transactional memory", which basically means that when there *is* an assignment, you're guaranteed the assignment is atomic and reversible. So that's it in a nutshell. To really learn about it, the best places to look at Operating Systems texts, like, eg, [Andy Tannenbaum's text](https://rads.stackoverflow.com/amzn/click/com/0136006639).
The two most common mechanisms for thread communication are shared state and [message passing](http://lambda-the-ultimate.org/node/193).
6,017,673
I dont have much experience of using these 2 ways to extend a class or create extension methods against a class. By looking others work, I have a question here. I saw people using a partial class to extend an entity class in a project. Meanwhile, in the same project, there is another folder containing a lot extension methods to the entity class. Is it right to do so? I mean these 2 ways both work well. Could you give me some real idea of how to pick one or the other when I want extend a class?
2011/05/16
[ "https://Stackoverflow.com/questions/6017673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407183/" ]
Partial classes should be used in code generation scenarios. Since the generated file might get overwritten at any time, one uses partial classes to write into the non-generated file. Additionally, partials will only work if they are part of the same assembly - they cannot cross assembly boundaries. If these are not your constraints, you can and should use extension methods - of course, after considering other possibilities such as inheritance and composition for suitability.
Partial works only if both files are in the same project, and you can access private and protected members of that class. Extension methods are just static methods, and can't access private members. So if you want to access private and protected members, only way you have is partial, if no, answer to the question, should the method you want to add be visible everywhere you want to use class? if yes, use partial, if no, it's some kind of extension, use extension methods. By the way, if the first class is not generated by some tool, you can write your function there except of using partial ;) hope this helps
18,531,537
I am trying to put overlay image over whole iPhone screen (over **navigation** and **tabbar** also) from `viewDidLoad` but nothing happens. ``` self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"overlayimage.png"]]; UIWindow* window = [[UIApplication sharedApplication] keyWindow]; [window.rootViewController.view addSubview: imageView]; UITapGestureRecognizer * recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; recognizer.delegate = self; [imageView addGestureRecognizer:recognizer]; imageView.userInteractionEnabled = YES; self.imageView = imageView; ``` This is the result that I am trying to get: ![enter image description here](https://i.stack.imgur.com/cJWIy.jpg)
2013/08/30
[ "https://Stackoverflow.com/questions/18531537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/480231/" ]
Since `UIWindow` is a subclass of `UIView`, you can also add subviews to the key window. These subviews will appear above any view controller. ``` UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window]; [keyWindow addSubview:imageView]; ```
``` imageView.frame = [[UIScreen mainScreen] applicationFrame]; [self.navigationController.view addSubview: imageView]; ```
11,168,687
I'm not familiar with beautifulsoup's encoding. when I tackle with some pages,some attribute is chinese, and I want to use this chinese attribute to extract tags. for example,a html like below: ``` <P class=img_s> <A href="/pic/93/b67793.jpg" target="_blank" title="查看大图"> <IMG src="/pic/93/s67793.jpg"> </A> </P> ``` I want to extract the '/pic/93/b67793.jpg' so what I done is: ``` img_urls = form_soup.findAll('a',title='查看大图') ``` and encounter: ``` UnicodeDecodeError: 'ascii' codec can't decode byte 0xb2 in position 0: ordinalnot in range(128) ``` to tackle with this,I have done two method,both failed: one way is : ``` import sys reload(sys) sys.setdefaultencoding("utf-8") ``` another way is: ``` response = unicode(response, 'gb2312','ignore').encode('utf-8','ignore') ```
2012/06/23
[ "https://Stackoverflow.com/questions/11168687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448607/" ]
You need to pass in unicode to the findAll method: ``` # -*- coding: utf-8 ... img_urls = form_soup.findAll('a', title=u'查看大图') ``` Note the [`u` unicode literal marker](http://docs.python.org/reference/lexical_analysis.html#string-literals) in front of the title value. You do need to [specify an encoding on your source file](http://www.python.org/dev/peps/pep-0263/) for this to work (the `coding` comment at the top of the file), or switch to unicode escape codes instead: ``` img_urls = form_soup.findAll('a', title=u'\u67e5\u770b\u5927\u56fe') ``` Internally, BeautifulSoup uses unicode, but you are passing it a byte-string with non-ascii characters in them. BeautifulSoup tries to decode that to unicode for you and fails as it doesn't know what encoding you used. By providing it with ready-made unicode instead you side-step the issue. Working example: ``` >>> from BeautifulSoup import BeautifulSoup >>> example = u'<P class=img_s>\n<A href="/pic/93/b67793.jpg" target="_blank" title="<A href="/pic/93/b67793.jpg" target="_blank" title="\u67e5\u770b\u5927\u56fe"><IMG src="/pic/93/s67793.jpg"></A></P>' >>> soup = BeautifulSoup(example) >>> soup.findAll('a', title=u'\u67e5\u770b\u5927\u56fe') [<a href="/pic/93/b67793.jpg" target="_blank" title="查看大图"><img src="/pic/93/s67793.jpg" /></a>] ```
Beautiful Soup 4.1.0 [will automatically convert attribute values from UTF-8](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-string), which solves this problem:
2,023,837
I have a base class with an attribute and I want to hide it in a derived class. Is there any way to do this other than using reflection? ``` [Authorize(Roles = "User,Admin,Customs")] public abstract class ApplicationController : Controller { } // hide the Authorize attribute public class ErrorController : ApplicationController { } ```
2010/01/07
[ "https://Stackoverflow.com/questions/2023837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215732/" ]
Removing features inherited from a base class violates the [Liskov Substitution Principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle). *Breaking inheritance* in this way usually rears its ugly head with unintended and unexpected consequences—after it's too late to change the root problem. So even if there is a way, I'll answer that you shouldn't use it the vast majority of the time. Alternatives to inheritance may apply, such as containment (*has-a* instead of inheritance's *is-a*) or refactoring the base into a separate interface which both can then implement; or even combine both of these.
Depends a bit on what you mean by 'Hide'. You should be able to revoke the authorization like this: ``` // hide the Authorize attribute [Authorize(Roles = "")] public class ErrorController : ApplicationController { } ```
6,838,593
Palm's Enyo framework uses a DSL-ish "Kind" system to create objects based on prototypes. Unfortunately, this results in, what I believe to be, untidier code. Does anyone have any experience using/hacking Enyo with native-javascript prototypes / constructors? ``` enyo.kind name: 'SimpleTimer' kind: "RowGroup" caption: "Simple Timer" published: timerDuration: 30 ``` vs… ``` class SimpleTimer extends RowGroup caption: "SimpleTimer" published: timerDuration: 30 ``` Hoping to know if anyone else has accomplished/attempted this.
2011/07/27
[ "https://Stackoverflow.com/questions/6838593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/142474/" ]
I was trying to accomplish the same thing you are, using a different method of compiled Javascript (Haxe JS) I was able to get this to work ... extending kinds like base classes, but I had to wrap the framework in my own files to get it to work. I don't wish that on anyone else, but feel free to take a peek at what I have working: <http://www.joshuagranick.com/blog/2011/08/08/enyo-with-code-completion-yes/> Have a great day!
You can alternatively use a more functional, rather than object-oriented, style. Maybe something like: ``` simpleTimer = (timerDuration) -> new RowGroup caption: 'Simple Timer', timerDuration: timerDuration ``` And then instead of creating a timer by doing ``` new SimpleTimer timerDuration:99 ``` you can do ``` simpleTimer 99 ```
3,534,360
Ok, so here's the thing. I have a UIViewController that contains a UITabBarController. That tab bar has a UIViewController for each tab button. Now, inside one of the tab buttons is an MPMoviePlayerController that is playing a stream from over the network. Playing the stream works just fine and you can see the video and hear the audio. The problem is when you navigate to another tab. The audio still plays, which is good, but when you go back to the stream, the video is black. The audio is still playing, but the video needs to be playing too. Has anyone run into this problem before? I'm currently using iOS 4.0 to build against and an iPhone 3GS. If more information is needed, just ask and I'll do my best to answer. Thanks, Robbie
2010/08/20
[ "https://Stackoverflow.com/questions/3534360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138145/" ]
The real question is why create an array when you don't need one. If you use $arg = array(), there will be a specific instruction to create an array, even if it's PHP an instruction still consumes CPU cycles. If you just do $arg = NULL, then nothing will be done.
This is a couple of years old I know, but I can't help but say the wrong answer was chosen and nobody clearly answered the full question. So for others that are looking at this and want to know what's really going on here: ``` function foo(array $arg = NULL) { ... } ``` When you call foo() the first thing that will happen is PHP will test $arg to see if it's an array. That's right, array $arg is a test. If $arg is not an array you will see this error: If $arg is a string: ``` Catchable fatal error: Argument 1 passed to foo() must be an array, string given ``` Ok, then NULL just means that in case $arg is not passed we will set it to NULL. It's just a way to make $arg optional, or preset its value. And just to be clear, there's no such thing as type casting function parameters without using the RFC patch, [here](https://wiki.php.net/rfc/parameter_type_casting_hints). If you use the RFC patch you can do: ``` function foo((array)$arg){ ... } ```
1,215,055
When I compile this code in Visual Studio 2005: ``` template <class T> class CFooVector : public std::vector<CFoo<T>> { public: void SetToFirst( typename std::vector<CFoo<T>>::iterator & iter ); }; template <class T> void CFooVector<T>::SetToFirst( typename std::vector<CFoo<T>>::iterator & iter ) { iter = begin(); } ``` I get these errors: ``` c:\home\code\scantest\stltest1\stltest1.cpp(33) : error C2244: 'CFooVector<T>::SetToFirst' : unable to match function definition to an existing declaration c:\home\code\scantest\stltest1\stltest1.cpp(26) : see declaration of 'CFooVector<T>::SetToFirst' definition 'void CFooVector<T>::SetToFirst(std::vector<CFoo<T>>::iterator &)' existing declarations 'void CFooVector<T>::SetToFirst(std::_Vector_iterator<_Ty,_Alloc::rebind<_Ty>::other> &)' ``` If I add a typedef to the CFooVector template, I can get the code to compile and work: ``` template <class T> class CFooVector : public std::vector<CFoo<T>> { public: typedef typename std::vector<CFoo<T>>::iterator FooVIter; void SetToFirst( FooVIter & iter ); }; template <class T> void CFooVector<T>::SetToFirst( FooVIter & iter ) { iter = begin(); } ``` My question is, why does the typedef work when using the bare `'typename std::vector>::iterator'` declaration did not work?
2009/07/31
[ "https://Stackoverflow.com/questions/1215055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118058/" ]
The question isn't really about typedef but typename. Whenever the compiler encounters a name that is dependent on a template (basically, anything using `::` after a template, it is unable to determine if that is a type or a value (it could be a static int, for example), so it needs a hint. When you add `typename` you're specifying that the dependent member is actually a type. In your typedef example, you still have the typename in the typedef declaration, but once the typedef is declared, that is not a dependent name. It's just a type, so the `typename` isn't necessary when referring to the typedef. Basically, the compiler can't be sure that `std::vector<CFoo<T>>::iterator` is a type. But it knows that `FooVIter` is a type, because it's a typedef. Typedefs are always types.
Another interesting bit: VS2008 compiles your second attempt if you don't use the `std::` name qualification on the `vector` in the definition of `SetToFirst()`: ``` template <class T> class CFooVector : public std::vector< CFoo<T> > { public: void SetToFirst( typename std::vector< CFoo<T> >::iterator & iter ); }; template <class T> void CFooVector<T>::SetToFirst( typename /*std::*/vector< CFoo<T> >::iterator & iter ) { iter = begin(); }; ``` Note that it only seemed to matter on the defintion, not the declaration. Also interesting to me was that it didn't matter if there was a "`using namespace std;`" or not... I don't really know what to make of this.
696,872
If a magnetic material such as an iron bar is placed near a magnet, the former becomes an *induced magnet* with the end closest to the north pole of the magnet becoming a south pole and vice-versa for the other end. But why does this happen? **Why does a magnet always induce a pole such that it attracts?** Or to put it in another way: what causes magnets to **always attract** magnetic materials such as iron? [![enter image description here](https://i.stack.imgur.com/nkHbw.png)](https://i.stack.imgur.com/nkHbw.png)[1](https://i.stack.imgur.com/nkHbw.png) --- 1. “Induced Magnetism.” Untitled Document, University of Leicester, <https://www.le.ac.uk/se/centres/sci/selfstudy/mam6.htm>. Accessed 28 February 2022. *Note: By magnetic materials, I mean metals such as iron, cobalt, nickel and others that can be "turned" into a magnet.* (OK, a "why" question, I know, but I'm interested in reading through possible explanations anyway—if there are any.)
2022/02/28
[ "https://physics.stackexchange.com/questions/696872", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/297028/" ]
Explaining what happens is comparatively easy but how it happens is much more difficult although you can always say that a system tries to move to its lowest energy state and is the simple answer to your question. The origin of magnetism is the fact that electrons have *spin angular momentum* and as a result they behave as though they are microscopic bar magnets. If the total spin of an atom is zero ie all the electrons are paired, then a phenomena called paramagnetism is exhibited which means that the material actually repels an external magnetic field. [How to levitate pencil lead](https://www.youtube.com/watch?v=yeIizmhzPQc) is a nice do it home type video showing this for graphite. Although all atoms could exhibit diamagnetism that effect is very often swamped by an effect due to unpaired electrons in an atom called paramagnetism. In this instants the atomic scale magnets due to unpaired electrons line up when in an external magnetic field because that is a lower energy state than if then not lining up. However removal of the external state means that due to thermal agitation the material reverts back to an demagnetised state. For the magnetic materials you are asking about even without a magnetic field neighbouring atoms in a region become aligned within a region called a domain. If the magnetism of the domains within the substance are randomly align the substance overall is not magnetised. Applying an external field tends to align the domains to produce a magnetic field in the same direction as the external field and this is a a lower energy state. The material is magnetised. The alignment of the atomic bar magnets is always battling with the thermal vibrations of the atoms and so for some ferromagnetic materials, eg iron, removal of the external magnetic field rests in the thermal processes randomising the magnetism due to the domains and the material ceases to be magnetised. However for something like steel the thermal agitation is not enough to change the orientation of the magnetism due to the domains and with the external field removed the material stays magnetised. There is a nice diagram in @annav's answer to the question [Direction of electric dipole moment and magnetic dipole moment](https://physics.stackexchange.com/questions/290585/direction-of-electric-dipole-moment-and-magnetic-dipole-moment) which illustrates my point about lowering the energy state. [![enter image description here](https://i.stack.imgur.com/N0ZF9m.jpg)](https://i.stack.imgur.com/N0ZF9m.jpg) Imagine an atomic scale bar magnet in an external field as shown in the left hand diagram. That bar magnet has a torque applied on it which will try and rotate the bar magnet so that it is orientated more in the direction of the external field with the torque being zero when the bar magnet is parallel to the external field. In moving closer to being parallel to the external field the torque can do work which means in undergoing that reorientation the system (bar magnet and external field) has less potential energy ie moved to a more stable state.
Electrons are not only electric charges, they are also magnetic dipoles. For the electron see its intrinsic value [here](https://physics.nist.gov/cgi-bin/cuu/Value?muem)). BTW, it does not matter at all for the explanation of the magnetic properties of the magnetic materials whether the observation of the magnetic dipole of the electron is considered as an intrinsic property per se or as a consequence of a relativistic self-rotation of the particle. It is observable that (any) substance becomes magnetic itself under the influence of an external (enough strong) magnetic field, for example your bar magnet. This is simply based on the influence of the previously more or less chaotic orientation of the magnetic dipoles of the subatomic particles in your iron bar.
24,497
I am looking for the way of building a Table of pairs of numbers in a fast way. My true table evaluates huge functions, and I see no way and reason to show those cumbersome expressions here. Let us for simplicity consider this: ``` Table[{10 - x - y^2, 1/x - y}, {x, 0.1, 15, 0.5}] ``` In addition my real table is very long, but for the sake of shortness in this example it has a small amount of terms. Here y is a parameter taking several values. For example, y may be 0.1 and 0.5. Now, I only need the part of the table in which each term in the pair {a, b} is positive and real. In my example here, if y=0.1 one gets ``` {{9.89, 9.9}, {9.39, 1.56667}, {8.89, 0.809091}, {8.39, 0.525}, {7.89, 0.37619}, {7.39, 0.284615}, {6.89, 0.222581}, {6.39, 0.177778}, {5.89, 0.143902}, {5.39, 0.117391}, {4.89, 0.0960784}, {4.39, 0.0785714}, {3.89, 0.0639344}, {3.39, 0.0515152}, {2.89, 0.0408451}, {2.39, 0.0315789}, {1.89, 0.0234568}, {1.39, 0.0162791}, {0.89, 0.00989011}, {0.39, 0.00416667}, {-0.11, -0.000990099}, {-0.61, -0.00566038}, {-1.11, \ -0.00990991}, {-1.61, -0.0137931}, {-2.11, -0.0173554}, {-2.61, \ -0.0206349}, {-3.11, -0.0236641}, {-3.61, -0.0264706}, {-4.11, \ -0.029078}, {-4.61, -0.0315068}} ``` but I only need its first 20 terms, which have the both figures positive. It is easy to sort it after the table is build. The problem is that the expressions entering the real table are huge, and the table is long. In addition the table is a part of a complex demonstration, which is immensely slowed down by the process of the table evaluation. As soon as I change the parameter y from one value to another, it takes about a minute to evaluate everything. Changing to ParallelTable makes the things even worse. My question: is there a way to instruct Table to stop evaluating as soon as any of the figures in the pair becomes negative? This might considerably shorten its evaluation time. The Menu/Help/Table mentions a possibility of some specifications in the Table operator, but I have found no examples of such specifications and cannot see, if that would be of help.
2013/05/02
[ "https://mathematica.stackexchange.com/questions/24497", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/788/" ]
If speed is an issue, I think testing for the halting condition is likely to be counterproductive, unless a small proportion of elements of the list fit the condition. The suggestion by @b.gatessucks seems more on target. Whether it works depends on how easy and fast it is to solve for the first point at which the "huge functions" become zero. Here I make the step size much smaller to illustrate the timings. ``` tab1 = Module[{y = 0.1, x0, x1, x2}, x1 = Min[x /. NSolve[First@{10 - x - y^2, 1/x - y} == 0, x]]; x2 = Min[x /. NSolve[Last@{10 - x - y^2, 1/x - y} == 0, x]]; x0 = Min[x1, x2, 15]; Table[{10 - x - y^2, 1/x - y}, {x, 0.1, x0, 0.001}]]; // Timing // First (* 0.009297 *) ``` **Comparisons** First, to get a sense of the limit speed, here is how long it takes to generate the whole table: ``` With[{y = 0.1}, Table[{10 - x - y^2, 1/x - y}, {x, 0.1, 15, 0.001}]]; // Timing // First (* 0.002527 *) ``` Here we compute the whole table and take the initial positive segment: ``` tab2 = With[{y = 0.1}, Take[#, Position[#, _?NonPositive, {2}, 1][[1, 1]] - 1] &@ Table[{10 - x - y^2, 1/x - y}, {x, 0.1, 15, 0.001}]]; // Timing // First (* 0.022767 *) ``` *Edit*: Here's another method that takes the initial positive segment: ``` tabFn = Compile[{{y, _Real}}, Module[{flag = 1.}, Table[If[ flag > 0. && 10 - x - y^2 > 0. && 1/x - y > 0., {10 - x - y^2, 1/x - y}, flag = 0.; {0., 0.}], {x, 0.1, 15, 0.001}] ] ]; tab5 = Cases[#, Except[{0., 0.}]] &@ tabFn[0.1]; // Timing // First (* 0.011772 *) ``` @J.M.'s solution: ``` tab3 = With[{y = 0.1}, Reap[Do[If[And @@ Positive[temp = {10 - x - y^2, 1/x - y}], Sow[temp], Break[]], {x, 0.1, 15, 0.001}]][[-1, 1]]]; // Timing // First (* 0.057492 *) ``` @LeonidShifrin's solution: ``` tab4 = With[{y = 0.1}, conditionalTable[{10 - x - y^2, 1/x - y}, 10 - x - y^2 > 0 && 1/x - y > 0, {x, 0.1, 15, 0.001}]]; // Timing // First (* 0.066421 *) ``` **Check** ``` tab1 == tab2 == tab3 == tab4 (* True *) ``` **Caveat** First, note that all the methods tested are slower than generating the whole table. Next, in the first method, being able to efficiently find the point at which to stop the `Table` is going to be crucial for speed. The sample equations are particularly easy to deal with, but not all equations will be so easy. Also, if most of the table is generated anyway, the desired speedup may be hard to achieve (depending on how efficient the OP's actual method is). That generating the whole table and selecting the initial positive segment is as fast as it is deserves attention. It suggests that testing the elements might not ever be made fast enough. (Ok, that's going out on a limb -- I'd love to find out I'm wrong.)
If you somehow don't like Do, Table, Reap and Sow (I don't know where you'd get that idea ;) ), you can also use Fold in the following way ``` Clear[collector] y = 0.1; kkkk = 20; xRange = Table[x, {x, 0.1, 15, 0.5}]; Module[{group}, With[{kkkk = kkkk}, collector[{list_, n_}, elem_] := If[n == kkkk, Throw[list], If[And @@ Positive[elem], {group[list, elem], n + 1}]] ]; With[{y = y}, {DeleteCases[ Catch[Fold[ Function[collector[#, {10 - #2 - y^2, 1/#2 - y}]], {group, 0}, xRange]], group, Infinity, Heads -> True]} ] ] ``` The answer is similar to that of J.M., but here I use Throw to exit Fold and I use Catch to catch the value. A function collector that takes a linkedlist as its first arguments maintains the positive pairs we have found so far. collector also remembers how many such values we have found. The use of DeleteCases to go from a linked list to a normal list is perhaps a bit strange. But I think it is efficient this way. Feedback is welcome! **Remark** I could also have written ``` Clear[collector] SetAttributes[llToken, HoldAll]; fromJLinkedList[ll_] := List@DeleteCases[ll, llToken, Infinity, Heads -> True]; y = 0.1; kkkk = 20; xRange = Table[x, {x, 0.1, 15, 0.5}]; collector[{list_, n_}, elem_] := If[n == kkkk, Throw[list], If[And @@ Positive[elem], {llToken[list, elem], n + 1}]] fromJLinkedList@ Catch[Fold[ Function[collector[#, {10 - #2 - y^2, 1/#2 - y}]], {llToken, 0}, xRange]] ```
156,402
My roommate who studies physics once showed me the leftovers of an interesting experiment: ![enter image description here](https://i.stack.imgur.com/CfRI2.jpg) They filled up those metal balls with water and then froze it. The water expanded and with all of its power blasted away the metal shells. Amazing stuff. But I came up with a question he couldn't answer with confidence when I saw that. All of these "balls" are imperfect. They have different materials all over the place. Let's say they're mostly some metal $m$, but at no point is there exclusively any $m$, there are always other things (oxygen, hydrogenparts out of the air, ...), therefore those spheres can sustain different pressure levels at different parts and in one part or another, they will crack first and release all the energy. At least I imagine it that way and I cannot think of any other way. But now imagine you had a perfect ball of metal like those. Every nm² and smaller is exactly as durable as any other one. And then you did the same experiment: at which point would the metal first start to crack? Would it crack at all without any differences in structure? Wouldn't a perfect children's balloon then be able to stand any pressure from the inside without breaking? That seems paradoxical to me, but logical if my assumption is true that the balls only break at a certain point because that point cannot handle as much pressure as the other points Does anybody know the answer? It would really interest me.
2015/01/03
[ "https://physics.stackexchange.com/questions/156402", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/68957/" ]
Well I think the problem won't be in the sphere no matter how perfect it is. It will probably brake relatively random. That would be caused the way the water freezes, because it can't freeze "perfectly". some areas will freeze faster than others be that to gravity, temperature layering of the freezing liquid, or the movement of molecules in it.
According to classical non-statistical mechanics, if such a perfectly symmetric sphere existed (I think such symmetry might not be possible even in theory because every material consists of particles), the sphere would not break. In practice, however, the sphere would at some point become unstable to deformations. Micro-scale deviations of symmetry, caused by effects such as non-zero temperature or even quantum effects (as pointed out by Phoenix87), would amplify almost instantaneously to macro-scale breaking of the sphere.
3,738,239
I do mean the `???` in the title because I'm not exactly sure. Let me explain the situation. I'm not a computer science student & I never did any compilers course. Till now I used to think that compiler writers or students who did compilers course are outstanding because they had to write Parser component of the compiler in whatever language they are writing the compiler. It's not an easy job right? I'm dealing with Information Retrieval problem. My desired programming language is Python. **Parser Nature:** <http://ir.iit.edu/~dagr/frDocs/fr940104.0.txt> is the sample corpus. This file contains around 50 documents with some XML style markup. (You can see it in above link). I need to note down other some other values like `<DOCNO> FR940104-2-00001 </DOCNO>` & `<PARENT> FR940104-2-00001 </PARENT>` and I only need to index the `<TEXT> </TEXT>` portion of document which contains some varying tags which I need to strip down and a lot of `<!-- -->` comments that are to be neglected and some `&hyph; &space; &amp;` character entities. I don't know why corpus has things like this when its know that it's neither meant to be rendered by browser nor a proper XML document. I thought of using any Python XML parser and extract desired text. But after little searching I found [JavaCC parser source code (Parser.jj)](http://www.ir.iit.edu/~dagr/IRCourse/Project/Parser.jj) for the same corpus I'm using [here](http://www.ir.iit.edu/~dagr/cs529/project.html). A quick look up on [JavaCC](http://en.wikipedia.org/wiki/JavaCC) followed by [Compiler-compiler](http://en.wikipedia.org/wiki/Parser_generator) revealed that after all compiler writers aren't as great as I thought. They use Compiler-compiler to generate parser code in desired language. Wiki says input to compiler-compiler is input is a grammar (usually in BNF). This is where I'm lost. 1. Is [Parser.jj](http://www.ir.iit.edu/~dagr/IRCourse/Project/Parser.jj) the grammar (Input to compiler-compiler called JavaCC)? It's definitely not BNF. What is this grammar called? Why is this grammar has Java language? Isn't there any universal grammar language? 2. I want python parser for parsing the corpus. Is there any way I can translate Parser.jj to get python equivalent? If yes, what is it? If no, what are my other options? 3. By any chance does any one know what is this corpus? Where is its original source? I would like to see some description for it. It is distributed on internet with name `frDocs.tar.gz`
2010/09/17
[ "https://Stackoverflow.com/questions/3738239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193653/" ]
Why do you call this "XML-style" markup? - this looks like pretty standard/basic XML to me. Try elementTree or lxml. Instead of writing a parser, use one of the stable, well-hardened libraries that are already out there.
You can't build a parser - let alone a whole compiler - from a(n E)BNF grammar - it's just the grammar, i.e. syntax (and some syntax, like Python's indentation-based block rules, can't be modeled in it at all), not the semantics. Either you use seperate tools for these aspects, or use a more advances framework (like Boost::Spirit in C++ or Parsec in Haskell) that unifies both. JavaCC (like yacc) is responsible for generating a parser, i.e. the subprogram that makes sense of the tokens read from the source code. For this, they mix a (E)BNF-like notation with code written in the language the resulting parser will be in (for e.g. building a parse tree) - in this case, Java. Of course it would be possible to make up another language - but since the existing languages can handle those tasks relatively well, it would be rather pointless. And since other parts of the compiler might be written by hand in the same language, it makes sense to leave the "I got ze tokens, what do I do wit them?" part to the person who will write these other parts ;) I never heard of "PythonCC", and google didn't either (well, theres a "pythoncc" project on google code, but it's describtion just says "pythoncc is a program that tries to generate optimized machine Code for Python scripts." and there was no commit since march). Do you mean [any of these python parsing libraries/tools?](http://wiki.python.org/moin/LanguageParsing) But I don't think there's a way to automatically convert the javaCC code to a Python equivalent - but the whole thing looks rather simple, so if you dive in and learn a bit about parsing via javaCC and [python library/tool of your choice], you might be able to translate it...
49,807,307
I am trying to parse the output log of unit tests using a regular expression. My goal is to print only the details of the error cases. Here is an example of the output: ```none [ RUN ] testname 1 Success log [ OK ] testname 1 [ RUN ] testname 2 Failure details 1 Failure details 1 [ FAILED ] testname 2 [ RUN ] testname 3 Success log [ OK ] testname 3 [ RUN ] testname 4 Failure details 2 Failure details 2 [ FAILED ] testname 4 [ RUN ] testname Success log [ OK ] testname ``` The output should be: ```none [ RUN ] testname 2 Failure details 1 Failure details 1 [ FAILED ] testname 2 [ RUN ] testname 4 Failure details 2 Failure details 2 [ FAILED ] testname 4 ``` Here is what I tried so far: ```sh grep -Pzo "(?s)^\[ RUN \].*?^\[ FAILED \].*?$" test.log ``` However, the output is not correct because the sequence `.*?` does not exclude the `[ OK ]`. In practice, I get two matches: 1. ```none [ RUN ] testname 1 Success log [ OK ] testname 1 [ RUN ] testname 2 Failure details 1 Failure details 1 [ FAILED ] testname 2 ``` 2. ```none [ RUN ] testname 3 Success log [ OK ] testname 3 [ RUN ] testname 4 Failure details 2 Failure details 2 [ FAILED ] testname 4 ``` I think I should use something called Negative Lookahead, but I wasn't able to get it working. Do you have any suggestion?
2018/04/12
[ "https://Stackoverflow.com/questions/49807307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556141/" ]
```sh $ perl -ne 'BEGIN{$/="[ RUN "} chomp; print $/,$_ if /FAILED/' ip.txt [ RUN ] testname 2 Failure details 1 Failure details 1 [ FAILED ] testname 2 [ RUN ] testname 4 Failure details 2 Failure details 2 [ FAILED ] testname 4 ``` * `BEGIN{$/="[ RUN "}` change input record separator from newline to `[ RUN` * `chomp` remove record separator from each record * `print $/,$_ if /FAILED/` print record separator and the record if it contains `FAILED` This is similar to ```sh gawk -v RS='\\[ RUN ' -v ORS= '/FAILED/{print "[ RUN " $0}' ip.txt ```
With Perl ``` perl -0777 -ne'print grep /Failure/, split /^(?=\[ RUN)/m' test.log ``` This prints the desired output with the provided example in `test.log` The [`-0777`](https://perldoc.perl.org/perlrun.html#Command-Switches) enables "slurp" mode so the whole file is read into [`$_`](https://perldoc.perl.org/perlvar.html#General-Variables). This is [split](https://perldoc.perl.org/functions/split.html) on `^`, matching line beginning with [`/m`](https://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators), with a [lookahead](https://perldoc.perl.org/perlretut.html#Looking-ahead-and-looking-behind) for the pattern `[ RUN`. The list returned by `split` is passed through [grep](http://perldoc.perl.org/functions/grep.html), which passes blocks with `Failure`, and this output list is printed.
21,024,608
If you have a function like this in a module: ``` dbHandler.js exports.connectSQL = function(sql, connStr, callback){ ////store a connection to MS SQL Server----------------------------------------------------------------------------------- sql.open(connStr, function(err, sqlconn){ if(err){ console.error("Could not connect to sql: ", err); callback(false); //sendback connection failure } else{ callback(sqlconn); //sendback connection object } }); } ``` Can you call this from inside the same module it's being defined? I want to do something like this: ``` later on inside dbHandler.js connectSQL(sql, connStr, callback){ //do stuff }); ```
2014/01/09
[ "https://Stackoverflow.com/questions/21024608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1948845/" ]
Declare the function like a regular old function: ``` function connectSQL(sql, connStr, callback){ ////store a connection to MS SQL Server------------------------------------ sql.open(connStr, function(err, sqlconn){ // ... ``` and then: ``` exports.connectSQL = connectSQL; ``` Then the function will be available by the name "connectSQL".
There are any number of ways to accomplish this, with Pointy's being my preferred method in most circumstances, but several others depending on the situation may be appropriate. One thing you will see often is something like this: ``` var connectSQL = exports.connectSQL = function(sql, connStr, callback) { /*...*/ }; ``` Technically, though I've never actually seen someone do this, you could use the exports object inside your module without issue: ``` // later on inside your module... exports.connectSQL('sql', 'connStr', function() {}); ``` Beyond that, it comes down to whether it matters whether you have a named function, like in Pointy's example, or if an anonymous function is ok or preferred.
33,342,344
[screen shot of network panel](http://i.stack.imgur.com/XMuiy.png) [screen shot of console panel](http://i.stack.imgur.com/uCrMo.png) i want to send form details to node.js server by using ajax function i am able see in console whatever i am sending But i am not able to get any response from node.js server to html ajax function server.js ``` var http = require('http'); http.createServer(function(request, response) { request.on('data', function (chunk) { var res=chunk.toString('utf8'); var obj=JSON.parse(res); var region=obj.region; var os=obj.os; console.log(region); console.log(os); }); //var data="hi"; //how to send data //response.send(data); }).listen(8088); ``` client.html ``` <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> function myFunction() { var region = document.getElementById("region").value; var os = document.getElementById("os").value; var data = {}; data.region = region; data.os = os; $.ajax({ type: 'POST', jsonpCallback: "callback", datatype: 'jsonp', data: JSON.stringify(data), //contentType: 'application/json', url: 'http://127.0.0.1:8088/', //node.js server is running success: function(data) { alert("success"); console.log(JSON.stringify(data)); }, error: function (xhr, status, error){ console.log('Failure'); alert("failure"); }, }); } </script> </head> <body> <form> <input type="text" id="region" name="region"/> <input type="text" id="os" name="os"/> <input type="button" value="search" class="fil_search" onclick="myFunction()"/> </form> </body> </html> ``` help me out from this how get response from node.js server. just i want see the alert box of success message in html page
2015/10/26
[ "https://Stackoverflow.com/questions/33342344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5260379/" ]
Your main slowdown here is that Console.Read() and Console.ReadLine() both "echo" your text on the screen - and the process of writing the text slows you WAY down. What you want to use, then, is Console.Readkey(true), which does not echo the pasted text. Here's an example that writes 100,000 characters in about 1 second. It may need some modification for your purposes, but I hope it's enough to give you the picture. Cheers! ``` public void begin() { List<string> lines = new List<string>(); string line = ""; Console.WriteLine("paste text to begin"); int charCount = 0; DateTime beg = DateTime.Now; do { Chars = Console.ReadKey(true); if (Chars.Key == ConsoleKey.Enter) { lines.Add(line); line = ""; } else { line += Chars.KeyChar; charCount++; } } while (charCount < 100000); Console.WriteLine("100,000 characters ("+lines.Count.ToString("N0")+" lines) in " + DateTime.Now.Subtract(beg).TotalMilliseconds.ToString("N0")+" milliseconds"); } ``` I'm pasting a 5 MB file with long lines of text on a machine with all cores active doing other things (99% CPU load) and getting 100,000 characters in 1,600 lines in 1.87 seconds.
I don't see that you need to preserve order? If so, use Parallel in combination with partitioner class since you're executing small tasks: See [When to use Partitioner class?](https://stackoverflow.com/questions/4031820/when-to-use-partitioner-class) for example This means you have to change datatype to `ConcurrentBag` or `ConcurrentDictionary`
72,317
I mountain bike about 4 times a week. I like to do jumps, but I wear a water backpack (water bladder, camelbak, whatever you'd like to call it). I wear it because I find that a water bottle doesn't hold enough water for me to do a long ride without having to stop to refill. My backpack holds about 100 oz of water, plus a multi tool, sunscreen, bug spray, my phone and keys, and maybe a snack or two. This means that it is heavy. I would guess that when full it is about 20 pounds. My friends tell me to take it off when doing jumps, but I find that it feels a bit awkward to take it off because I lose a significant amount of weight from doing so. I haven't noticed any sort of difference in how easy it is to clear a given jump when my backpack is on/off, but the technique I use definitely is different when I am wearing a backpack because it adds 20 pounds hanging off my back. Does NOT wearing a backpack actually make jumping easier, or does it just make it more comfortable? Does anyone know of a different solution to carry both a good amount of water and tools without needing a backpack? EDIT: I forgot to say that my backpack has two straps, one that buckles at chest level and one that buckles at waist level, although no matter how tight I make it the bag still flops around due to all the tools and just stuff in general that I store in it.
2020/09/25
[ "https://bicycles.stackexchange.com/questions/72317", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/53029/" ]
You have more control over weight on you than on the bike, so long as the pack is fitted nicely and doesn't bounce around too much. This doesn't just apply to jumps but all the time, as your bodyweight is part of your control but weight on the bike is passive. Imagine rolling over a tree root on a hardtail or even rigid forks. Weight attached to the bike must lift over the bump, but if you're off the saddle and riding properly your body and backpack float over the obstacle, barely rising. Moving a few kg/10-20lbs between frame and body is noticeable. I'm a perpetual mountain bike novice but ride a lot on road. On the MTB (hardtail) I either use a hydration pack similar to you, or copy my road kit: a litre bottle of water, tool bottle in a 2nd cage, and saddlebag on the bike. Even at my level (no big jumps, but the effect holds even for bunny-hops) bike handling is easier with the weight on my back, though it's fatiguing on a very long ride. This makes sense. When your weight is on your feet and hands rather than your saddle (i.e. most of the time when riding technically) your bodyweight is sprung on your legs - so is the backpack. When you jump, you launch your body into the air and the bike follows you. You launch a backpack with you, but extra weight on the bike has to follow you. Note that flopping around can be reduced with good packing (but not eliminated if you're jumping when the whole backpack will shift vertically. ). Extra layers of clothing can be used to wedge loose tools into place. You can also borrow an idea from big trekking backpacks - straps to compress the contents. These don't have to be integrated, and could be webbing, paracord, or bungee cord, pulled tight around the packed bag and tied (or more conveniently buckled). Some elastic in the chest strap helps too.
You tagged “dirt jumping” in the question. At a jump park, I would definitely remove the backpack. At the very least, you won’t risk blowing up the water bag or breaking a tool in the (inevitable) event of a crash. For normal trail riding, it goes either way. Some people prefer the backpack, others prefer the on-bike solution. It’s really all up to you. It’s best to pick one solution and stick to it though; as you described, the difference in weight balance really does mess with your skills and technique. If you want to carry stuff on the bike, it is common to use normal bottles and cages for water. Tools and supplies would normally be held with elastic or Velcro straps. Contrary to what Chris suggested, I would not recommend the use of a saddle bag: they flop around all over the place and sound like your bike is falling apart. They also make it harder to use a dropper post. A fanny pack is a common solution where I live: water goes in a bottle and cage, bike tools go in Velcro straps, and soft goods (keys, phone, snacks...) go in the fanny pack. You can pick a variety of sizes of fanny packs to suit your needs.
4,652,084
How to get the previous URL in Rails? Not the URL that you got a request from, but the one before that? Because I'm getting an AJAX request, and I need the URL for the page they are currently on (or the URL before the AJAX).
2011/01/10
[ "https://Stackoverflow.com/questions/4652084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356849/" ]
Use ``` <%= url_for(:back) %> # if request.env["HTTP_REFERER"] is set to "http://www.example.com" # => http://www.example.com ``` [here is more details.](http://api.rubyonrails.org/v3.2.14/classes/ActionView/Helpers/UrlHelper.html#method-i-url_for)
In a web application there is no such thing as a previous url. The http protocol is stateless, so each request is independent of each other. You could have the Javascript code, that sends a request back, send the current url with the request.
36,176,700
I am getting three different roles from server like this- ``` ["ROLE_USER", "ROLE_MODERATOR", "ROLE_ADMIN"] ``` or ``` ["ROLE_USER","ROLE_ADMIN"] ``` If the user is not a moderator i don't want to access some pages to that user in my angular js application.What should i do.?
2016/03/23
[ "https://Stackoverflow.com/questions/36176700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5384141/" ]
[angular-permission](https://github.com/Narzerus/angular-permission) is a third party module, Check this [angular-permission](https://github.com/Narzerus/angular-permission) it may help you
The Simple solution is check the user role and hide/show the pages based on the user role.. Did all those things during login redirect.
58,931,099
Does anyone know how to convert a Hex color to HSL in PHP? I've searched but the functions that I’ve found don’t convert precisely the color.
2019/11/19
[ "https://Stackoverflow.com/questions/58931099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7722662/" ]
I think the mistake in the second answer is using integer division rather than fmod() when calculating the hue when red is the maximum colour value `$hue = (($green - $blue) / $delta) % 6;` I think the mistake in the first answer is in the saturation calculation - for me `$s = $l > 0.5 ? $diff / (2 - $max - $min) : $diff / ($max + $min);` is a bit confusing to unpick Since usually when I want to convert RGB to HSL I want to adjust the lightness value to make a lighter or darker version of the same colour, I have built that into the function below by adding an optional $ladj percent value. The $hex parameter can be either a hex string (with or without the '#') or an array of RGB values (between 0 and 255) The return value is an HSL string ready to drop straight in to a CSS colour. ie the values are from 0 to 359 for hue and 0 to 100% for saturation and lightness. I think this works correctly (based on <https://gist.github.com/brandonheyer/5254516>) ``` function hex2hsl($RGB, $ladj = 0) { //have we got an RGB array or a string of hex RGB values (assume it is valid!) if (!is_array($RGB)) { $hexstr = ltrim($RGB, '#'); if (strlen($hexstr) == 3) { $hexstr = $hexstr[0] . $hexstr[0] . $hexstr[1] . $hexstr[1] . $hexstr[2] . $hexstr[2]; } $R = hexdec($hexstr[0] . $hexstr[1]); $G = hexdec($hexstr[2] . $hexstr[3]); $B = hexdec($hexstr[4] . $hexstr[5]); $RGB = array($R,$G,$B); } // scale the RGB values to 0 to 1 (percentages) $r = $RGB[0]/255; $g = $RGB[1]/255; $b = $RGB[2]/255; $max = max( $r, $g, $b ); $min = min( $r, $g, $b ); // lightness calculation. 0 to 1 value, scale to 0 to 100% at end $l = ( $max + $min ) / 2; // saturation calculation. Also 0 to 1, scale to percent at end. $d = $max - $min; if( $d == 0 ){ // achromatic (grey) so hue and saturation both zero $h = $s = 0; } else { $s = $d / ( 1 - abs( (2 * $l) - 1 ) ); // hue (if not grey) This is being calculated directly in degrees (0 to 360) switch( $max ){ case $r: $h = 60 * fmod( ( ( $g - $b ) / $d ), 6 ); if ($b > $g) { //will have given a negative value for $h $h += 360; } break; case $g: $h = 60 * ( ( $b - $r ) / $d + 2 ); break; case $b: $h = 60 * ( ( $r - $g ) / $d + 4 ); break; } //end switch } //end else // make any lightness adjustment required if ($ladj > 0) { $l += (1 - $l) * $ladj/100; } elseif ($ladj < 0) { $l += $l * $ladj/100; } //put the values in an array and scale the saturation and lightness to be percentages $hsl = array( round( $h), round( $s*100), round( $l*100) ); //we could return that, but lets build a CSS compatible string and return that instead $hslstr = 'hsl('.$hsl[0].','.$hsl[1].'%,'.$hsl[2].'%)'; return $hslstr; } ``` In real life I would break out the hex string to RGB array conversion and the percentage adjustment into separate functions, but have included them here for completeness. You could also use the percent adjustment to shift the hue or saturation once you've got the colour in HSL format.
``` function hexToHsl($hex) { $hex = array($hex[0].$hex[1], $hex[2].$hex[3], $hex[4].$hex[5]); $rgb = array_map(function($part) { return hexdec($part) / 255; }, $hex); $max = max($rgb); $min = min($rgb); $l = ($max + $min) / 2; if ($max == $min) { $h = $s = 0; } else { $diff = $max - $min; $s = $l > 0.5 ? $diff / (2 - $max - $min) : $diff / ($max + $min); switch($max) { case $rgb[0]: $h = ($rgb[1] - $rgb[2]) / $diff + ($rgb[1] < $rgb[2] ? 6 : 0); break; case $rgb[1]: $h = ($rgb[2] - $rgb[0]) / $diff + 2; break; case $rgb[2]: $h = ($rgb[0] - $rgb[1]) / $diff + 4; break; } $h /= 6; } return array($h, $s, $l); } ```
38,914,843
If possible, I'd like to reload a jQuery `prototype`/`function` after a delay without refresh all the page. ``` my.prototype.reloadMe = function () { setTimeout(function(){ my.reloadMe(); },1000); alert('ok'); }; ``` I tried with a `setTimeout` in the function but it didn't work: it refreshs only one time. Thanks for your suggestions or explanations.
2016/08/12
[ "https://Stackoverflow.com/questions/38914843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6607318/" ]
In your code you define a **prototype** function, and then you try to call it as an object function. You should get an error like "`my.reloadMe()` is not a function". ``` my.prototype.reloadMe = function () { setTimeout(function(){ my.reloadMe(); // "my" object does not contain "reloadMe" function },1000); alert('ok'); }; ``` If you want to access this function, you can either call this prototype function explicitly: ``` setTimeout(function(){ my.prototype.reloadMe(); }, 1000); ``` or instantiate your object and call this function: ``` setTimeout(function(){ new my().reloadMe(); }, 1000); ``` which both do not sound correct. It looks like the best solution is to name your anonymous function: ``` my.prototype.reloadMe = function reload() { setTimeout(reload, 1000); alert('ok'); };); ``` **Note 1:** in your code you use `setTimeOut`, while it is `setTimeout`. JS is case-sensitive. Perhaps, it can be a source of the error. **Note 2:** any of this code will make it run in an infinite loop. So, actually, you will get an alert every second. I hope that it is exactly what you are trying to achieve :)
```js //Create your object: function myobject(){ } //add prototype to that object myobject.prototype.reloadMe = function(){ // instead of recursion you can use interval setInterval(function () { alert('ok'); }, 1000); } // instantiate that object var my = new myobject(); //call your function my.reloadMe(); ```
49,076
I am trying to derive the pdf of the sum of independent random variables. At first i would like to do this for a simple case: sum of gaussian random variables. I was surprised to see that i don't get a gaussian density function when i sum an even number of gaussian random variables. I actually get: [![enter image description here](https://i.stack.imgur.com/AZuU1.png)](https://i.stack.imgur.com/AZuU1.png) which looks like two halfs of a gaussian distribution. On the other hand, when i sum an odd number of gaussian distributions i get the right distribution: [![enter image description here](https://i.stack.imgur.com/RD9B6.png)](https://i.stack.imgur.com/RD9B6.png) below the code i used to produce the results above: ``` import numpy as np from scipy.stats import norm from scipy.fftpack import fft,ifft import matplotlib.pyplot as plt %matplotlib inline a=10**(-15) end=norm(0,1).ppf(a) sample=np.linspace(end,-end,1000) pdf=norm(0,1).pdf(sample) plt.subplot(211) plt.plot(np.real(ifft(fft(pdf)**2))) plt.subplot(212) plt.plot(np.real(ifft(fft(pdf)**3))) ``` Could someone help me understand why i get odd results for even sums of gaussians distribution? Thanks in advance
2018/05/08
[ "https://dsp.stackexchange.com/questions/49076", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/35618/" ]
The FFT algorithm expects the origin of the signal to be on the leftmost sample of the signal. You are convolving two shifted Gaussian together, yielding a Gaussian that is even more shifted. Because of the FFT imposes periodicity, when the curve is shifted past the right edge it comes back in on the left edge. Whit an odd number the shift is exactly the full width of the signal, so you don’t notice it. A solution would be to use a zero-mean Gaussian distribution, which you can obtain from yours by `ifftshift`. After performing the convolution, you can shift it back to where it was using `fftshift`. ``` np.fft.fftshift(ifft(fft(np.fft.ifftshift(pdf))**2)) ```
Perhaps you can use a kde function to estimate the kernel? ``` import numpy as np import matplotlib.pyplot as plt from scipy import stats N = 10**4 x12 = np.array([ [np.random.normal(),np.random.normal()] for i in range(N)]) X = np.sort(x12[:,0] + x12[:,1]) density = stats.kde.gaussian_kde(X) plt.plot(X,density(X)) ``` It might be slow, nevertheless, to run for large $N$.
35,667,548
**I am unable to call** ``` -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation ``` **On following IBAction** ``` - (IBAction)button:(UIButton *)sender { } ``` help me
2016/02/27
[ "https://Stackoverflow.com/questions/35667548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5718089/" ]
Use sendgrid-java. It is pretty straight forward to send emails using this library. ``` SendGrid sendgrid = new SendGrid('YOUR_SENDGRID_API_KEY'); SendGrid.Email email = new SendGrid.Email(); email.addTo("example@example.com"); email.setFrom("other@example.com"); email.setSubject("Hello World"); email.setText("My first email with SendGrid Java!"); try { SendGrid.Response response = sendgrid.send(email); System.out.println(response.getMessage()); } catch (SendGridException e) { System.err.println(e); } ```
As @Anil said, you can tried to send emails using the SendGrid SDK for Java, please see the library on GitHub <https://github.com/sendgrid/sendgrid-java>, or directly add its [maven dependency](http://mvnrepository.com/artifact/com.sendgrid/sendgrid-java/) below into your maven project. ``` <dependency> <groupId>com.sendgrid</groupId> <artifactId>sendgrid-java</artifactId> <version>2.2.2</version> </dependency> ``` The other way is using the SendGrid REST API via HTTP using the Class `HTTPConnection` in Java, please see the docs for [WebAPI v2](https://sendgrid.com/docs/API_Reference/Web_API/index.html) or [WebAPI v3](https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html).
141,349
What would be a cleaner way to write the following? ``` // Check if add user was attempted if ($params['submit']) { // Verify all fields are filled in if (Utilities::checkAllFieldsNotEmpty($params)) { // Make sure username is not taken if (Admin::checkUsername($params['username'])) { // Check if directory is created if (Admin::createUsersDirectory($params['username'])) { if (Admin::createNewUser($params['name'], $params['username'], $params['password'], $params['admin'])) { Utilities::setMessage("Excellent!", "User was created successfully.", "admin_modal"); } } else { Utilities::setMessage("Whoa!", "Directory creation failed.", "admin_modal"); } } else { Utilities::setMessage("Whoa!", "Username in use.", "admin_modal"); } } else { Utilities::setMessage("Whoa!", "Please fill in all fields", "admin_modal"); } // Return admin view with message return $this->view->render($response, 'admin/admin.twig', [ 'name' => $user['name'], 'message' => $_SESSION['message'], 'form' => [ 'name' => $params['name'], 'username' => $params['username'], 'admin' => $params['admin'] ] ]); } ```
2016/09/14
[ "https://codereview.stackexchange.com/questions/141349", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/74542/" ]
Don't nest your conditions like this. Validate the input up front and fail out if need be. For example that might look like this: ``` if(empty($params['submit'])) { // no parameters set // log error, throw exception, etc. as approrpiate } if(Utilities::checkAllFieldsNotEmpty($params) === false) { // fail out // not sure if you really need this condition if you validate each field // individually } // etc. ``` Then I would suggest that your Admin class should abstract away the details of user creation away from this script. Ideally this script could just have something like: ``` try { $user = Admin::createNewUser(...); } catch (Exception $e) { // do something to handle exception } ``` And `createNewUser()` would go through all the logic of for validating user name, setting up directories, etc. This code should know nothing about what is required to create a "user" outside of whatever information needs to be passed (i.e. user name).
Since at most one of the messages will be selected, you should invert the conditions to make it linear rather than nested. This has the benefit of putting each error message right next to its corresponding test. ``` if (!Utilities::checkAllFieldsNotEmpty($params)) { Utilities::setMessage("Whoa!", "Please fill in all fields", "admin_modal"); } elseif (!Admin::checkUsername($params['username'])) { Utilities::setMessage("Whoa!", "Username in use.", "admin_modal"); } elseif (!Admin::createUsersDirectory($params['username'])) { Utilities::setMessage("Whoa!", "Directory creation failed.", "admin_modal"); } elseif (Admin::createNewUser($params['name'], $params['username'], $params['password'], $params['admin'])) { Utilities::setMessage("Excellent!", "User was created successfully.", "admin_modal"); } ``` There are still a couple of problems, though. First, I would say that the methods named `check…` do not clearly convey what they do. Based on those names, I would expect that they throw an exception if they fail the test. If they are actually predicates, it would be better to name them `Utilities::areAllFieldsNotEmpty(…)` and `Admin::isUsernameAvailable(…)`. A hint that something is wrong is that the `Admin::createNewUser(…)` call is not negated like the others. The problem is that you've forgotten to display an error message for that potential failure: ``` … } elseif (!Admin::createNewUser($params['name'], $params['username'], $params['password'], $params['admin'])) { Utilities::setMessage("Whoa!", "User creation failed!", "admin_modal"); } else { Utilities::setMessage("Excellent!", "User was created successfully.", "admin_modal"); } ```
53,242,134
In my project I have a Window called AccountWindow.xaml which has a ContentControl to display the two UserControls. **AccountWindow** ``` <Window> <Window.Resources> <!-- Login User Control Template --> <DataTemplate x:Name="LoginUserControl" DataType="{x:Type ViewModels:LoginViewModel}"> <AccountViews:LoginUserControl DataContext="{Binding}"/> </DataTemplate> <!-- Registration User Control Template --> <DataTemplate x:Name="RegistrationUserControl" DataType="{x:Type ViewModels:RegistrationViewModel}"> <AccountViews:RegistrationUserControl DataContext="{Binding}" /> </DataTemplate> </Window.Resources> <Grid> <!-- ContentControl that displays the two User Controls --> <ContentControl Content="{Binding}" /> </Grid> </Window> ``` I then have two user controls called LoginUserControl and RegistrationUserControl **Login User Control** ``` <Grid Background="Pink"> <Button Content="Switch To Register View" Command="{Binding SwitchToReg}" Margin="100" /> </Grid> ``` **Register User Control** ``` <Grid Background="Orange"> <Button Content="Press Me" Command="{Binding PressMe}" Margin="100" /> </Grid> ``` Both the Login User Control and the Registration User Control have their own ViewModels with a RelayCommand inside that is bound to the buttons as shown in the code. **Login View Model** ``` public class LoginViewModel { public RelayCommand SwitchToReg { get { return new RelayCommand(param => { Console.WriteLine("Switch To Reg"); // Somehow change the content control in the AccountWindow to show the RegistrationDataTemplate??? }); } } } ``` **The Problem** I want to be able to change the content of the ContentControl in the AccountWindow when the user presses on one of the buttons in the UserControls. For example, when the user presses the button in the Login User Control called "Switch To Register View" it executes a the Command SwitchToReg and changes the content control to RegistrationUserControl & its ViewModel. How could this be possible?
2018/11/10
[ "https://Stackoverflow.com/questions/53242134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10273347/" ]
To achieve that you would need to pass a reference for the AccountWindow into the UserControl when you are constructing it and then your Command can update the ContentControl using the reference you have provided. This is introducing coupling which is better to avoid so instead I would suggest thinking about the design of the AccountWindow. I would use grid rows to separate the ContentControl area from the button which will change the UserControl. [![Example window](https://i.stack.imgur.com/5xfoT.png)](https://i.stack.imgur.com/5xfoT.png) In the window above, the blue area is where I would host the ContentControl and the red area is part of the AccountWindow. This way, the behaviour for switching the ContentControl is entirely handled by the AccountWindow.
You can create a property and attache it to the control. Or you can create another user control and make it visible o not controled by the property that you created.
6,814,127
I've installed postgres with the kyngchaos installer a couple of months ago. I've now updated to OSX Lion, but the database server fails to start. A comment on kyngchaos's blog (<http://www.kyngchaos.com/blog/2011/20110723_lion>) made me look at the 'postgres' user: it doesn't exist anymore! At least, I can't "sudo su postgres" anymore. So I figure that's the reason my server doesn't run. How can I best restore that user?
2011/07/25
[ "https://Stackoverflow.com/questions/6814127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27401/" ]
(Answering myself) In the end, the only thing I needed to do was to re-create the "postgres" user. Beforehand, I listed the contents of `/usr/local/pgsql/` and saw that for instance the `data/` directory was owned by user `101` and group `postgres`. So I wanted to tie that postgres user to the 101 userid: ``` sudo dscl . -create /Users/postgres sudo dscl . -create /Users/postgres UniqueID 101 ``` (And afterwards I restarted my mac as I didn't know how to start that postgres server by hand... ;-)
I was having a similar problem, and looking through system.log in Console, there were various messages about permissions on the postgresql data directory. I played around with chown and other things, but ended up simply reinstalling - everything is working fine now.
205,299
I tried the following code in LINQPad and got the results given below: ``` List<string> listFromSplit = new List<string>("a, b".Split(",".ToCharArray())).Dump(); listFromSplit.ForEach(delegate(string s) { s.Trim(); }); listFromSplit.Dump(); ``` > > "a" and " b" > > > so the letter b didn't get the white-space removed as I was expecting...? Anyone have any ideas [NOTE: the .Dump() method is an extension menthod in LINQPad that prints out the contents of any object in a nice intelligently formatted way]
2008/10/15
[ "https://Stackoverflow.com/questions/205299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5351/" ]
Further to the answer posted by [Adrian Kuhn](https://stackoverflow.com/questions/205299/why-does-my-attempt-to-trim-strings-in-a-liststring-not-appear-to-work/205509#205509) you could do the following: ``` var result = listFromSplit.Select(s => s.Trim()); ```
You are not assigning the trimmed result to anything. This is a classic error, I've only just got out of the habit of making this mistake with string.Replace :)
5,742,119
How do you handle multiple file fields in Django. For example if I had only one form field i would pass the request.FILES['file'] to a handling function. But what is the way to go when there are more files?
2011/04/21
[ "https://Stackoverflow.com/questions/5742119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/701362/" ]
I'm late to the party, but I've been trying to figure this out for a while and finally have a solution. Have a look at the code used here: <https://code.djangoproject.com/ticket/12446> You can access multipart values with getlist. If my HTML form was: ``` <form enctype="multipart/form-data" action="" method="post"> <input type="file" name="myfiles" multiple> <input type="submit" name="upload" value="Upload"> </form> ``` My django code to process it would look like: ``` for afile in request.FILES.getlist('myfiles'): # do something with afile ``` Writing a form field/widget to handle this properly is my next step. I'm still rather new to using Django, so I'm learning as I go.
`request.FILES.get('filename', None)` responds to the existence of a form-named field like this: ``` <input type="file" name="filename"></input> ``` If you had two such fields: ``` <input type="file" name="file1"></input> <input type="file" name="file2"></input> ``` Then `request.FILES.get('file1', None)` and `request.FILES.get('file2', None)` should give you those files respectively. The reason for this is multipart mime. The three parts (form data, file1, file2) should be uploaded and Django's UploadFileHandler splits this apart into `request.POST` and `request.FILES` respectively.

Dataset Card for "stack-exchange-sample10000"

More Information needed

Downloads last month
2
Edit dataset card