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.
697,256
I was thinking back to my introduction to programming recently and remembered writing a C++ program that deliberately read and wrote to memory addresses at random. I did this to see what would happen. To my surprise, on my Windows 98 PC, my program would create some really weird side effects. Occasionally it would toggle OS settings, or create graphical glitches. More often than not it would do nothing or just crash the entire system. I later learned this was because Windows 98 didn't restrict what a user process had access to. I could read and write to RAM used by other processes and even the OS. It is my understanding that this changed with Windows NT (though I think it took a while to get right). Now Windows prevents you from poking around in RAM that doesn't belong to your process. I vaguely remember running my program on a Linux system later on and not getting nearly as many entertaining results. If I understand correctly this is, at least in part, due to the separation of User and Kernel space. So, my question is: Was there a time when Linux did not separate User and Kernel space? In other words, was there a time when my rogue program could have caused similar havoc to a Linux system?
2022/03/29
[ "https://unix.stackexchange.com/questions/697256", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/239497/" ]
> > Was there a time when Linux did not separate User and Kernel space? > > > That depends on how you define the terms "Linux", "user space", and "kernel space". Remember how Linus Torvalds originally created Linux. Linus saved some money to buy himself an (at the time state-of-the-art) PC with an Intel 80386 CPU. He wanted to understand how the 80386 works, and he thought the best way to do that would be to write some low-level hardware code in 80386 assembly. At the same time, he was also dissatisfied with the performance of the terminal emulator running under Minix he was using to log into the university. So, he decided to write a terminal emulator in 80386 assembly which you could boot directly. For this, he needed to write a bootloader, a keyboard driver, a (character) display driver, a serial driver, and a driver for whatever protocol he used to connect to the university. Soon, he found that he also wanted to download files from the university, so he had to implement some file transfer protocol (probably ZMODEM, but maybe he chose XMODEM for simplicity) and also a hard disk driver, partition table parser, and a filesystem driver for the Minix filesystem. Because he also wanted to continue working while the terminal emulator was performing some long-running operation (such as a file download), he implemented multithreading. This is the point where he realized that he had already implemented some significant portions of an Operating System, and so he thought it would be another fun project to turn the terminal emulator into one. At some point after that, he accidentally mistyped a command and overwrote his Minix partition with a backup. Now he had a choice to make: reinstall Minix or finish his Operating System and use that instead. When he came to a point where his Operating System was capable of running simple programs, he decided to upload it to the university's FTP server, and named it Freax (he thought that naming something after himself was pretentious and arrogant). The sysadmin of the FTP server didn't like the name, though, and decided to rename the file to Linux, which he thought sounded better. Another while later, Linus made the very first public mention of Linux in his famous message where he stated that Linux was so tied to the 80386 that it would never be portable to anything else and where he predicted that Linux would never be big and professional. Now, the question is: at which point in this journey did "Linux" become "Linux" and at which point in this journey did Linux become a "kernel" so that talking about separation of user and kernel space even makes sense? As I said at the beginning: it really depends on how you define those terms. > > In other words, was there a time when my rogue program could have caused similar havoc to a Linux system? > > > There was certainly a time in its evolution where the piece of software which later became an OS and which was later called "Linux" had no protection, had complex enough services that you might get away with calling it a "kernel" and had independent enough subsystems that you might get away with calling those subsystems "programs". For example, in a "real" Unix system, the terminal emulator and the file transfer would typically be two separate programs and the thing that coordinates the two and which houses the code for accessing the serial port, the hard disk, the screen, the keyboard, and the filesystem would be the kernel. But was this piece of software "Linux"? I will leave that to you to decide.
Yes, Linux has always need an MMU to work for memory protection. Many people have ported it to small embedded systems without MMU but there won't be complete memory protection anymore, so a process can read/write pretty much everything * [Is the MMU inside of Unix/Linux kernel? or just in a hardware device with its own memory?](https://unix.stackexchange.com/q/473274/44425) * [Is the MMU (Memory Management Unit) chip necessary for a processor to have virtual memory support?](https://unix.stackexchange.com/q/395603/44425) * [Memory Management](https://www.kernel.org/doc/html/latest/admin-guide/mm/index.html)
47,856,649
I have two custom controls: `CustomTextBox` and `CustomNumericUpDown`. I want them to have a shared behavior, which consists of a few methods and a few properties. Solutions I came up with: 1. **Both should extend an abstract class containing the shared behavior.** The problem is that one extends `TextBox` the other extends `NumericUpDown`. I cannot think of a way for both of them to inherit my abstract class except by multiple inheritance, which is not allowed in C#. 2. **Implement a shared interface.** This is obviously stupid since interfaces cannot have an implementation. 3. **Using extension methods**. More specifically, make both of them share an interface, and create extension methods for this interface. The problem is that [you cannot (currently) have extension properties in C#](https://blogs.msdn.microsoft.com/ericlippert/2009/10/05/why-no-extension-properties/), and I really do not want to implement getters and setters using actual methods due to [the principle of least astonishment](https://en.wikipedia.org/wiki/Principle_of_least_astonishment). Is there an elegant approach to this problem that doesn't involve repeating code? --- **Edit**: --- For example, I want both `CustomTextBox` and `CustomNumericUpDown` to have a `ValidateInput()` method and a `ValidationRules` property. i.e., I want to add a method and a property to both of them.
2017/12/17
[ "https://Stackoverflow.com/questions/47856649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1925272/" ]
Far from elegant, but if you don't need to rely on the specific implementation details of the derived controls, you could use a combination of an interface (to enforce the implementation of the properties and methods you want), and [delegation](https://en.wikipedia.org/wiki/Delegation_pattern) (to encapsulate/centralize the shared behavior). The implementation of the interface in the derived controls is completely boilerplate and always delegates elsewhere. ``` public class ValidationService { public void RegisterRules(Control control, string[] rules) { // store rules } public string[] GetRules(Control control) { // retrieve rules } public void Validate(Control control) { // validate } } public interface IValidatable { ValidationService ValidationService { get; set; } string[] Rules { get; set; } void ValidateControl(); } public class MyTextBox : TextBox, IValidatable { public ValidationService ValidationService { get; set; } public string[] Rules { get => ValidationService.GetRules(this); set => ValidationService.RegisterRules(this, value); } public void ValidateControl() { ValidationService.Validate(this); } } public class MyNumericUpDown : NumericUpDown, IValidatable { public ValidationService ValidationService { get; set; } public string[] Rules { get => ValidationService.GetRules(this); set => ValidationService.RegisterRules(this, value); } public void ValidateControl() { ValidationService.Validate(this); } } ``` This approach gets messy, however, if your validation behavior relies on specific details of the derived controls.
create a base class containing the common functionality. extend that class for each of the controls you need and place the control inside that class. ``` public class MyUserControl : UserControl { public MyUserControl() : base() { } // add common behaviour here (validation, etc) } public class MyTextBox : MyUserControl { public MyTextBox() : base() { Add(new TextBox()); } ... } ```
254,727
I know this is easy with a 301 redirect in the apache config, but I'm looking for a 3rd party service that can do this cheaply or free. I'll be using this to redirect non-www traffic to a www record I've CNAME'ed to an Amazon Elastic Load Balancer hostname.
2011/04/01
[ "https://serverfault.com/questions/254727", "https://serverfault.com", "https://serverfault.com/users/76820/" ]
Amazon's Route53 DNS service supports pseudo-A records for an ELB instance (they call them "ALIAS" records).
Well... Why don't just add a record like ``` $ORIGIN domain.com. @ IN A 1.2.3.4 www IN A 1.2.3.4 ``` Into your DNS zone file?
59,144,698
I'm Trying to make a draft post visible to admins only .(when the admin visits the post page it should display the post even if its not published ) I tried to create a middle-ware : ``` public function handle($request, Closure $next) { $post = Post::findBySlugOrFail($request->slug); if ($post->status == "draft") { abort(404); } elseif (auth()->check() && auth()->user()->hasAnyRole(['Administrator'])) { return $next($request); } return $next($request); } ``` I have `status` column in my `posts` table. It always shows `404` not found. Am i doing it wrong ? Any idea how can this be done ?
2019/12/02
[ "https://Stackoverflow.com/questions/59144698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12311699/" ]
Either add `return false;` at the end of your inline Javascript event listener: ``` <button type="submit" onclick="this.disabled=true; this.value='Sending, please wait...'; this.form.submit(); return false;" class="btn btn-primary" align="right">Submit</button> ``` or simply omit `this.form.submit();` (because that is what a submit button already does by itself when clicked): ``` <button type="submit" onclick="this.disabled=true; this.value='Sending, please wait...';" class="btn btn-primary" align="right">Submit</button> ```
I would suggest you to disable the button by adding a disabled attribute to it once the user has submitted the form. You can submit a form using javascript using `form.submit();`. This way you can remove type="submit" and allows you to have more freedom in controlling the behaviour of onClick event. For example: ```js function myFunction() { document.getElementById("myBtn").disabled = true; } ``` ```html <button id="myBtn"onclick="myFunction()">Clickable once only.</button> ```
49,225,505
I need to make text wrap around image with bootstrap 4 wihout floats, is it possible? Here my code: ``` <article class="row single-post mt-5 no-gutters"> <div class="image-wrapper col-md-6"> <?php the_post_thumbnail(); ?> </div> <div class="single-post-content-wrapper p-3"> <?php the_content(); ?> </div> </article> ``` Here what I have now: [![enter image description here](https://i.stack.imgur.com/nwtsm.png)](https://i.stack.imgur.com/nwtsm.png) Here what I need to have: [![enter image description here](https://i.stack.imgur.com/ZnLBS.png)](https://i.stack.imgur.com/ZnLBS.png)
2018/03/11
[ "https://Stackoverflow.com/questions/49225505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4598861/" ]
> > I need to make text wrap around image with bootstrap 4 wihout floats, is it possible? > > > No, in this case, you must use the `float-left` class for the image. But you don't have to use any wrapper for the image. You can get rid of that wrapper div entirely and add your classes to the image. Another thing you absolutely must do: Put all of your content into Bootstrap columns because only Bootstrap columns may be the direct children of Bootstrap rows. Here's a working code snippet (note: I left the image wrapper div in there but I recommend you get rid of it because that's totally unnecessary code. Add your classes directly to the image): ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <div class="container"> <article class="row single-post mt-5 no-gutters"> <div class="col-md-6"> <div class="image-wrapper float-left pr-3"> <img src="https://placeimg.com/150/150/animals" alt=""> </div> <div class="single-post-content-wrapper p-3"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil ad, ex eaque fuga minus reprehenderit asperiores earum incidunt. Possimus maiores dolores voluptatum enim soluta omnis debitis quam ab nemo necessitatibus. <br><br> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil ad, ex eaque fuga minus reprehenderit asperiores earum incidunt. Possimus maiores dolores voluptatum enim soluta omnis debitis quam ab nemo necessitatibus. </div> </div> </article> </div> ```
``` <div class="row"> <div class="col-lg-2 col-12"> <div class="icon mb-4 text-center"><i class="fa fa-github"></i></div> </div> <div class="col-10"> <h4 class="h4">Title</h4> <p class="text-muted">Some text here</p> </div> ``` I have used this in bootstrap 4.
278,886
When I first learned about bowl feeders I thought that there was some sort of rotation that would cause it to go up, but apparently it is caused by vibrating the bowl. I do not understand how vibrations can cause a part to move upwards. From what I understand, vibrations will have a similar effect to reducing friction, which means that it would cause the parts to fall down the slope more easily. How does it work? Is the vibration applied in a certain direction/rotation/etc. which causes this upward movement? Or is it just normal vibration? There is [an article describing vibratory bowl feeders here](http://www.rnaautomation.com/products/feeding-and-handling/vibratory-feeders/), and [a YouTube video showing one in operation here](https://www.youtube.com/watch?v=QsJzSFVAnhk).
2016/09/08
[ "https://physics.stackexchange.com/questions/278886", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/81170/" ]
I found this answer at, <http://www.changeover.com/vibratorybowlfeeders.html> "Properly tuned, a feeder will vibrate properly but, by itself, vibration will do little more than make the parts bounce around. In order to make the parts move, the vibration must be focused in the desired direction. This is done by mounting the springs on an angle rather than vertically. As the feeder bowl rotates back and forth on its springs the angle causes it to move vertically as well. As it moves forward and up, friction pushes the part forward. As it moves back and down, the part falls vertically. This sawtooth motion can move parts gently at astonishing speeds."
The bowl feeder as well as its linear version based on the hysteresis of the involved spring-magnet device-system. Changing the frequency of the vibrations of the magnetic device you can make that the parts in the feeder will vibrate in standstill or will move backwards. A big difference in the load will do the same. Instead of electromagnets they use piezoelectric devices too, or for really big feeders simply an electro motor with a unbalanced weight on its axis.
78,392
[Jacobian](http://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant), [Lorentz](http://en.wikipedia.org/wiki/Lorentz_transformation) and [Fourier Transformation](http://en.wikipedia.org/wiki/Fourier_transform). I am confused with the physical interpretation/meaning of all these transformations. 1. As far as I understood, Jacobian transforms from one coordinate space to another (there are examples for Jacobian from cartesian to spherical so and so...). But Lorentz transform also do similar transformation from one coordinate space to another right? So, Jacobian is also a kind of Lorentz transform! Or else what is the physical difference? 2. Finally, I got confused with the Fourier transform as well! It also transform from one space to another!. How can we explain the physical difference and physical usefulness of all these transforms? How we decide what transformation can be done in some physical situation? Can anyone please explain with physical example and comparing these three transformations?
2013/09/24
[ "https://physics.stackexchange.com/questions/78392", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/20190/" ]
It's sloppy language that is confusing you here. 1. A Jacobian is not a transformation. The Jacobian *of a* transformation measures by how much the transformation expands or shrinks volume(/area/length/hypervolume/whatever) elements. Example: let $x' = 2x$. Then $dx = dx'/2$. The Jacobian is the $1/2$, meaning nothing more than "a unit of the $x'$ scale has a length of 1/2 a unit on the $x$ scale." The formula involving partial derivatives and a determinant is the generalization of this to arbitrary dimensionality & coordinate transformations, but the meaning is exactly the same. 2. Lorentz transformations are the transformations that preserve intervals in Minkowski spacetime. In terms of cartesian coordinate systems ($x,y,z,t$) they are the linear transformations that preserve $-\mathrm{d}t^2 + \mathrm{d}x^2 + \mathrm{d}y^2 + \mathrm{d}z^2$ and their Jacobian is $1$, i.e. they don't expand or shrink spacetime volume elements $\mathrm{d}t\mathrm{d}x\mathrm{d}y\mathrm{d}z$. In crazy weird coordinates Lorentz transformations would surely look awful, and you would have to do gymnastics to keep track of their Jacobian, but that just means that if you care about Lorentz invariance you shouldn't be using crazy weird coordinate systems. :) 3. Fourier transforms are a change of basis on *function space*. You have a function on configuration space $f(x)$, say, and you would like to describe it by its wavenumber spectrum $\tilde{f}(k)$ instead. Fourier transform gives you the connection between the two bases. The function hasn't changed, and the function space hasn't changed either, but you are using a different set of basis functions to "map out" the space. Functions which look local in configuration space, like $\delta(x-x\_0)$ map to extended waves in wavenumber space $\exp(i x\_0 k)$ and vice versa, so which basis is more convenient depends on the application. But try to keep clear that you are not mapping positions to wavenumbers or vice versa. You are mapping the *description of the abstract function $f$ in terms of local functions of coordinates $x$* into the *description of the same abstract function $f$ in terms of local functions of wavenumbers $k$*, no different from going from an abstract vector $\vec{v}$ written in components in the $\hat{x},\hat{y},\hat{z}$ basis to the same vector written in components in the $\hat{x}',\hat{y}',\hat{z}'$ basis.
A **Fourier transform** is a linear transformation between two particular bases, the point functions and the periodic functions. The vector space we are talking about here is the space of functions. A **Jacobian matrix** is a linear approximation for a general transformation. For example, you mention transforming from a Cartesian basis to a spherical basis. This isn't a linear transformation, but we can approximate it as one if we restrict our attention to small regions of space. A Jacobian is the determinant of the Jacobian matrix. A **Lorentz transformation** is a linear transformation of space-time that has several additional restrictions (eg preserves the space-time interval, preserves parity) that are physical in nature.
36,947,847
I have always found the `range` function missing from JavaScript as it is available in python and others? Is there any concise way to generate range of numbers in ES2015 ? EDIT: MY question is different from the mentioned duplicate as it is specific to ES2015 and not ECMASCRIPT-5. Also I need the range to be starting from 0 and not specific starting number (though it would be good if that is there)
2016/04/29
[ "https://Stackoverflow.com/questions/36947847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3878940/" ]
You can use the spread operator on the keys of a freshly created array. `[...Array(n).keys()]` or `Array.from(Array(n).keys())` The `Array.from()` syntax is necessary if working with TypeScript
A lot of these solutions build on instantiating real Array objects, which can get the job done for a lot of cases but can't support cases like `range(Infinity)`. You could use a simple generator to avoid these problems and support infinite sequences: ``` function* range( start, end, step = 1 ){ if( end === undefined ) [end, start] = [start, 0]; for( let n = start; n < end; n += step ) yield n; } ``` Examples: ``` Array.from(range(10)); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] Array.from(range(10, 20)); // [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ] i = range(10, Infinity); i.next(); // { value: 10, done: false } i.next(); // { value: 11, done: false } i.next(); // { value: 12, done: false } i.next(); // { value: 13, done: false } i.next(); // { value: 14, done: false } ```
6,059,526
Question: --------- Is it posible to detect when a file, for wich a have an open FileStream, was renamed. Case: ----- I am trying to monitor the logs for our application, I read from the logfiles since I do not want to interfere with the logging itself. This works great until the file gets rolled. My application keeps reading from a renamed file without even noticing. I **tried** using a FileSystemWatcher to detect the roll, but sometimes a get a lot of events, sometimes I don't, so that's not really a good solution (also the logfiles could reside on a network share wich could be an extra hold-back for using a FSW). If I could find out which file(name) I have an open handle to, I could compare that to the `_fileName` but I don't know how or if this can be done. Are there any other options I could explore? Code: ----- this is a simplified version of my filemonitoring class: ``` public class MonitorFile { private String _fileName = String.Empty; private bool _stopMonitoring = false; public MonitorFile(string fileName) { _fileName = fileName; } // Simplified method public void StartMonitoring() { using (var reader = new StreamReader( new FileStream( _monitorFileName, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite))) { while (!_stopMonitoring) { Thread.Sleep(500); while ((line = reader.ReadLine()) != null) { //...Do stuff with the lines } } } } } ```
2011/05/19
[ "https://Stackoverflow.com/questions/6059526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366970/" ]
There is an MSDN example showing [how you can obtain a file name from a file handle](http://msdn.microsoft.com/en-us/library/aa366789%28v=vs.85%29.aspx) (which you have access to via the `Handle` property of the `FileStream`) using Win32 APIs, but I doubt this approach will work for files on a remote network share. You may well be out of luck in the general case.
You could extract the directory name from the monitor file path. Then after your readLine loop: Get the file list in the directory, sorted by last updated date take the first item in the list compare it to the file name you are reading from and if they are different update your reader This works on the assumption that only files in the directory will be log files and you are always wanting to be reading from the most recently updated file
44,954,872
Does git allow (i.e., is there a valid use case) a `.git/` folder inside subfolders? Or is the `.git/` folder supposed to be only in one place and that is in the project's root location?
2017/07/06
[ "https://Stackoverflow.com/questions/44954872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2856202/" ]
In general, the `.git` folder should only be at the project's root location (by design). However, the repository may be set up to use [git submodules](https://git-scm.com/docs/git-submodule), and this could result in subdirectories having their own `.git` folder.
Having a unique .git directory at the root of the project is a convenience. The .git directory can be anywhere in your project (or even outside) and it can be modified by setting GIT\_DIR environment variable. But if you consider having it inside a subdirectory of your project, it is quite simple to delete it unwillingly which is much harder to do if it's at the root of the project.
45,010,081
I am following [Code for sending images using firebase](https://github.com/sancarbar/firebase-android.) I have configured the firebase storage url,database url ,database rule(true),sha1 placed google-services.json in app folder but when i debug the code the it(user) shows null value `FirebaseUser user = firebaseAuth.getCurrentUser();` .My code is given below: ``` import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import butterknife.Bind; import butterknife.ButterKnife; public class LoginActivity extends AppCompatActivity implements FirebaseAuth.AuthStateListener { @Bind( R.id.login_button ) Button loginButton; FirebaseAuth firebaseAuth = FirebaseAuth.getInstance(); @Override protected void onCreate( @Nullable Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_login ); ButterKnife.bind( this ); } @Override public void onStart() { super.onStart(); firebaseAuth.addAuthStateListener( this ); verifyCurrentUserAndStartMainActivityIfLoggedIn(); } @Override public void onStop() { super.onStop(); firebaseAuth.removeAuthStateListener( this ); } public void onLoginClicked( View view ) { loginButton.setEnabled( false ); firebaseAuth.signInAnonymously(); } @Override public void onAuthStateChanged( @NonNull FirebaseAuth firebaseAuth ) { verifyCurrentUserAndStartMainActivityIfLoggedIn(); } private void verifyCurrentUserAndStartMainActivityIfLoggedIn() { FirebaseUser user = firebaseAuth.getCurrentUser(); if ( user != null ) //HERE I AM GETTING "user=null" ?? { startActivity( new Intent( this, MainActivity.class ) ); Toast.makeText(this,"Login success",Toast.LENGTH_LONG).show(); finish(); } else { loginButton.setEnabled( true ); } } } ``` After successfully login when (user !=null) the next activity displays now the sample url of next activity is ``` // StorageReference storageRef = storage.getReferenceFromUrl( "gs://funchat-ef3ed.appspot.com" ); ``` and i have created new storage in firebase get the url is: ``` StorageReference storageRef = storage.getReferenceFromUrl( "gs://fir-imagesending-1a8c1.appspot.com"); ``` When I use above url application crashes. The code is given below: ``` public class MainActivity extends AppCompatActivity { static final int REQUEST_IMAGE_CAPTURE = 1; FirebaseDatabase database = FirebaseDatabase.getInstance(); FirebaseAuth firebaseAuth = FirebaseAuth.getInstance(); DatabaseReference databaseReference = database.getReference( "messages" ); FirebaseStorage storage = FirebaseStorage.getInstance(); // StorageReference storageRef = storage.getReferenceFromUrl( "gs://funchat-ef3ed.appspot.com" ); StorageReference storageRef = storage.getReferenceFromUrl( "gs://fir-imagesending-1a8c1.appspot.com"); ``` I am unable to find where I am missing?
2017/07/10
[ "https://Stackoverflow.com/questions/45010081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8248471/" ]
Your code seems to be far from oficial [firebase documentation](https://firebase.google.com/docs/auth/android/anonymous-auth) 1. ensure you have anonymous login enabled in firebase console 2. sign in anonymously with callback `mAuth.signInAnonymously().addOnCompleteListener` 3. in `onComplete()` observe whether `Task.isSuccessful()` is true and if not what `task.getException()` return. 4. and always follow official documentation not just somebody you have found on github If you really want to know why your `FirebaseUser` is `null`, then read [firebase docs](https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuth) If you post the exception I can help you.
You have to allow anonymous logins if you havn't and then `signInAnonymously()...` or you can make user login with google signin provided by firebase (for this first allow user signin with google in firebase console) and then just store all the instances as in singleton class. **will be much easy to do with much security**.
53,760,622
The following example is simplified. In my project I have a big `List(of String)` where I have to do some manipulations on the strings. For this I created a `Sub` where I do the manipulation and that should rewrite the Elements of the `List(of String)`. ``` Module Module1 Sub Main() Dim myList As List(Of String) = New List(Of String) myList.Add("1Tom") myList.Add("2Lisa") 'Now I want apply a function to the List. As an example I created one that removes the first Letteer RemoveFirstChar(myList) For Each str As String In myList Console.Write(str) Next Console.Read() End Sub Sub RemoveFirstChar(ByRef myList As List(Of String)) For Each str As String In myList str = str.Substring(2) Next End Sub End Module ``` The string manipulation itself within the Sub works but it is not written into the initial List-Object. I actually thought that using `ByRef` would do this. Is it possible to do it this way and I just have a mistake or do I have to create a new `List(of String)` using a function and override the inital object. Like: ``` myList = foo(myList) ``` If both would work, what is more efficient? Since I have to do this on a List(of Strings) wiht few hundret thousand elements.
2018/12/13
[ "https://Stackoverflow.com/questions/53760622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2377949/" ]
Your have missed `[]` in the name value, it should be `name="shape[]"` ```js $('#form_filter input[name="shape[]"][value=Round]').prop('checked', true); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form id="form_filter" action="{{ Request::fullUrl() }}" method="post"> <input type="checkbox" name="shape[]" value="Aviator"> <input type="checkbox" name="shape[]" value="Round"> <input type="checkbox" name="shape[]" value="Oval"> </form> ```
You should just use quotes inside the selector, ie: ``` $('#form_filter input[name="shape[]"][value="Round"]').length === 1 // true ``` Or: ``` $('#form_filter input[name="shape[]"][value="Round"]').prop('checked', true); // checks your specific checkbox ``` [jQuery docs on equals selector](https://api.jquery.com/attribute-equals-selector/) also state the following: > > attribute: An attribute name. > > > value: An attribute value. Can be either a valid identifier or a > *quoted string*. > > > --- Test on the [JSFiddle](http://jsfiddle.net/1hrbfmqc/).
3,047,706
In my textbook is stated: Let G be a finite-dimensional vector space of real functions in $R^D$. What is meant by "*vector space of real functions*"? I know what a vector space is, by I don't get how can real functions form vector space (The only vector spaces that I might see regarding a function are the vector space of the domain and codomain) Please, if you are aware, provide me a tangible and intuitive example with the explanation, as I find examples extremely useful for understanding.
2018/12/20
[ "https://math.stackexchange.com/questions/3047706", "https://math.stackexchange.com", "https://math.stackexchange.com/users/557201/" ]
$\mathbb R^D$ is the set of all functions $f:D \to \mathbb R.$ If we define an addition $f+g$ and a scalar multiplication $ \alpha f$ in this set by $(f+g)(x)=f(x)+g(x)$ and $( \alpha f)(x)= \alpha f(x)$, then $\mathbb R^D$ is a real vector space ( of functions).
I'll offer a point of view that gives some concrete examples. As people have mentioned, the only thing necessary to have a "vector space" is the ability to add objects together, and multiply them by scalars (subject to some special rules). We have this for functions that share a common domain and codomain. If we consider **all** functions with codomain $\mathbb{R}$, and fixed codomain $D$, we get an infinite-dimensional vector space (unless $D$ is a finite set). This is what is usually called $\mathbb{R}^{D}$. Now, if we want a **finite** dimensional vector space, what we are looking for is a subspace of $\mathbb{R}^{D}$ that can be spanned by a finite set of functions. Here span is the normal linear algebra concept, where we are allowed to take linear combinations of the functions, e.g. the span of functions $f(x)$ and $g(x)$ would look like $\{ af(x) + bg(x) \ : \ a,b \in \mathbb{R}\}$. Some examples: 1. If we take the set of constant functions $f(x) = c$ for $c \in \mathbb{R}$, this is a 1-dimensional vector space of functions, because any such function is just $c$ times the function $f(x) = 1$. 2. If we take the set of polynomials of degree less than $n$, we get a vector space of dimensions $n+1$, for example the polynomials with degree less than 4 gives a 5-dimensional vector space with basis $\{1,x,x^{2}, x^{3}, x^{4}\}$. 3. If we take linear combinations of $\sin{x}$ and $\cos{x}$, we get a vector space of dimension 2 containing functions of the form $\{a\sin{x}+b\cos{x} \ : \ a,b \in \mathbb{R}\}$ (it can be shown that $\sin{x}$ and $\cos{x}$ are not scalar multiples of each other, so are linearly independent).
1,002,395
I want to add aliases to my network links to use them as short descriptions. I am configuring my interfaces using systemd-networkd, having systemd version 241 on a debian buster server. I've created the file `-rw-r--r-- 1 root root 68 Feb 9 12:53 /etc/systemd/network/ens19.link` with the content: ``` [MATCH] MACAddress=7a:08:e8:12:fc:c7 [LINK] Alias=myalias ``` I've tried to reboot the system, but the alias does not appear: ``` 3: ens19: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000 link/ether 7a:08:e8:12:fc:c7 brd ff:ff:ff:ff:ff:ff ``` Doing `ip l set ens19 alias myalias` gives the intended result: ``` 3: ens19: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000 link/ether 7a:08:e8:12:fc:c7 brd ff:ff:ff:ff:ff:ff alias myalias ``` How can I achieve that using systemd-networkd?
2020/02/09
[ "https://serverfault.com/questions/1002395", "https://serverfault.com", "https://serverfault.com/users/527627/" ]
I should have read [the manual](https://www.freedesktop.org/software/systemd/man/systemd.link.html) more carefully. > > The first (in lexical order) of the link files that matches a given device is applied. Note that a default file 99-default.link is shipped by the system. Any user-supplied .link should hence have a lexically earlier name to be considered at all. > > > Renaming `/etc/systemd/network/ens19.link` to `/etc/systemd/network/00-ens19.link` helped. `[MATCH]` should be `[Match]` and `[LINK]` should be `[Link]`. To apply a changed .link file to the link I can reboot or run ``` udevadm test-builtin net_setup_link /sys/class/net/ens19 ``` (Because .link files are processed by udev and not systemd-networkd, restarting systemd-networkd is insufficient.)
As per [systemd.network](https://www.freedesktop.org/software/systemd/man/systemd.network.html) link aliases are not (yet?) supported.
24,615,660
Could someone please help me handle this issue in jQuery I have a requirement where I have two dropdowns: 1. The no of floors of the flat (**numberOfFloors**) 2. The flat where the user stays (**whichFloorYouStay**) I need to remove all the invalid options from the second dropdown. How do I achieve this? For example: If a user select the **numberOfFloors** option as 3, then I should remove options 4 and 5 from **whichFloorYouStay** dropdown and just load 1,2,3 as **whichFloorYouStay** options. Similarly, if a user select the **numberOfFloors** option as 1, then I should remove options 2,3,4,5 from **whichFloorYouStay** dropdown and just load 1 as **whichFloorYouStay** option. Please find my JSBin link: <http://jsbin.com/sibufive/1/edit?html,js,output>
2014/07/07
[ "https://Stackoverflow.com/questions/24615660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3673638/" ]
I am not sure whether you can do it using css.Anyway you can do this using javascript. The code will be as follows : ``` String.prototype.chunk = function(n) { var space = []; for(var i=0, len=this.length; i < len; i += n) { space.push(this.substr(i, n)) } return space }; "0102030405".chunk(2).join(' '); ``` Check [Fiddle](http://jsfiddle.net/mijoemathew/Fysr4/)
It cannot be done in CSS, because there is no selector that would refer to, say, the 3rd character in the content of an element or the the first two characters. CSS operates on elements and pseudo-elements, and no currently defined pseudo-element is suitable for this. If possible, the content should be modified server-side or, if that’s not possible, with client-side JavaScript so that either the character pairs appear as elements or there are space characters between them, e.g. `<span class="number">01 02 03 04 05</span>`. In the latter case, you can use `word-spacing` (probably with a negative value) to tune the amount of spacing.
19,089,163
I am using the RSA python package to encrypt a message and try to pass it to a PHP site to decrypt. See below: ``` message = rsa.encrypt('abc', pubkey) print message print type(message) ``` What I get is some encrypted text ``` q??$$??kK?Y??p?[e?[??f???x??s!?s?>?z?*y?p?????????分? ? ???({u????NH?B???N?%?@5|?~?????\U?.??r?Y?q <type 'str'> ``` What's the best way to pass it to other languages to decrypt?
2013/09/30
[ "https://Stackoverflow.com/questions/19089163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342553/" ]
The "-D" prefix in the argument means that it's a *system property*. A system property is defined like this in(<http://docs.oracle.com/javase/jndi/tutorial/beyond/env/source.html#SYS>): > > A system property is a key/value pair that the Java runtime defines to > describe the user, system environment, and Java system. The runtime > defines and uses a set of default system properties. Other properties > can be made available to a Java program via the -D command line option > to the Java interpreter. > > >
mvn eclipse:eclipse -Dwtpversion=2.0 makes it a maven project that can be run from eclipse
20,505,869
For example, there is a list: `s = [1,2,3,4]` from which we want to get new list `s1 = [1.5, 2.5, 3.5]` (length was reduced). How to compute this with the most efficient way in Python (e.g. map, generator comprehensions)? *Update:* OK, this example was very artificial. Accidently, I'm trying to find the fastest way to compute new list from old. And it will be interesting for me to see optimal ways (minor memory usage, for example)
2013/12/10
[ "https://Stackoverflow.com/questions/20505869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2938167/" ]
``` alist = [(s[i]+s[i+1])/2 for i in range(len(s)-1)] ``` well, i dont know how efficient it is.
I am guessing that the fastest way, if you have a large list, is the following: ``` import numpy as np kernel = np.array([0.5, 0.5]) # convolution kernel my_list = range(100000) # lots of data arr = np.array(my_list) # make it an array result = np.convolve(arr, kernel, 'valid') # convolve ``` This uses convolution in the numeric python package, which should be really fast. I would love to see if someone can find a faster solution :) **Edit** Did some benchmarking, and for lists of size 1000+ the numpy version is faster than Twisted Meadows version.
29,784,077
I'm trying to write a custom iterator in spacebars (I'm using meteor 1.1.3). The iterator is to be a sequential for loop (basically to replace my usage of #each when needed since I believe #each is not guaranteed to be sequential in its iteration). I have tried the following: In lib - ``` UI.registerHelper 'sequentialFor', () -> ret = "" for i in [0...@.length] id = @[i] ret = ret + Template.noop ret ``` noop.html - ``` <template name="noop"> {{> UI.contentBlock this}} <template> ``` main.html - ``` {{#sequentialFor ids}} <div id="wow-{{this}}">stuff</div> {{/sequentialFor}} ``` ids in the above is an array of strings passed from one of main's template helpers. Right now it complains the the return from my UI helper is [object Object] [object Object]. For sanity's sake I know that if I replace my UI helper with: ``` UI.registerHelper 'sequentialFor', () -> //ret = "" //for i in [0...@.length] // id = @[i] // ret = ret + template id = @[0] Template.noop ``` I get that the div in my main.html shows up with the appropriate id as a part of its id attribute as desired. However, I can't seem to make the for loop work. I can't simply return the div in main.html directly from the helper because I have a lot of divs that I need to wrap with my new iterator, each of which has very different attributes. I guess the simple question is, how do I define my own block iterator (akin to #each) in spacebars? The more difficult question may be, what is wrong with my approach above? I have considered a wide array of resources but have only the found the following to be very helpful: [How to pass an object from to a block helper back to the block in meteor blaze?](https://stackoverflow.com/questions/23854851/how-to-pass-an-object-from-to-a-block-helper-back-to-the-block-in-meteor-blaze) <https://github.com/meteor/meteor/wiki/Using-Blaze> <https://github.com/meteor/meteor/blob/devel/packages/spacebars/README.md> [Iterating over basic “for” loop using Handlebars.js](https://stackoverflow.com/questions/11924452/handlebar-js-iterating-over-for-basic-loop) **NOTE** I'm using coffeescript
2015/04/21
[ "https://Stackoverflow.com/questions/29784077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3431836/" ]
I managed to get a custom iterator using a recursive technique similar to what you might use in Haskell or Lisp: ```html <body> {{#countdown n=5}} <p>item {{this}}</p> {{/countdown}} </body> <template name="countdown"> {{#if positive}} {{> Template.contentBlock n}} {{#countdown n=nMinusOne}} {{> Template.contentBlock this}} {{/countdown}} {{/if}} </template> ``` ```js Template.countdown.helpers({ positive: function () {return this.n > 0;}, nMinusOne: function () {return this.n - 1;} }); ``` See [meteorpad](http://meteorpad.com/pad/7qEFvrZcPEMrDcMsb/Custom%20iterator). The performance is probably far worse than the usual `{{#each}}`.
It appears to me that you want to create a `<div>` for each of an array of IDs (correct me if I'm wrong). This is how I would go about it, no custom iterator necessary: ``` Template.registerHelper('ids', function(arrayWithIds) { if (!arrayWithIds) return []; // do some sorting or whatever with arrayWithIds, for example: var arrayOfIds = _.map(arrayWithIds, function(obj) { return obj._id; }); return arrayOfIds; }); ``` Then in main.html: ``` {{#each ids someDataSetWithIds}} // `someDataSetWithIds` is the helper's parameter // `this` in each case is an ID <div id="wow-{{this}}"></div> {{/each}} ``` If your helper returns an object, you would use `this._id` in the template, instead. Did I misunderstand what you're trying to achieve?
4,360,008
I have the following problem. A web service is sending a JSON POST request to my app and I want to parse it. I thought I just can access the params with ``` @var = params[:name_of_the_JSON_fields] ``` but it doesn't work. I see in my Heroku logs, that the request is done and that the parameters are there, but I just can't store them. Does anyone have an idea?
2010/12/05
[ "https://Stackoverflow.com/questions/4360008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522484/" ]
In most cases with the symptom desribed, the true root of the problem is the source of the incoming request: if it is sending JSON to your app, it should be sending a Content-Type header of `application/json`. If you're able to modify the app sending the request, adjust that header, and Rails will parse the body as JSON, and everything will work as expected, with the parsed JSON fields appearing in your `params` hash. When that is not possible (for instance when you don't control the source of the request - as in the case of receiving an Amazon SNS notification), Rails will not automatically parse the body as JSON for you, so the best you can to is read and parse it yourself, as in: ```rb json_params = JSON.parse(request.raw_post) ```
If you are receiving JSON in the params hash you can convert it yourself: ``` @var = JSON.parse(params[:name_of_the_JSON_fields]) ```
67,655,803
I would like to know which functions I can use with RDCOMClient objects. For example, to create an email we can use ``` OutApp <- COMCreate("Outlook.Application") # create an email outMail = OutApp$CreateItem(0) ``` Along with `outMail[["subject"]]`, `outMail[["HTMLbody"]]` or `outMail[["Attachments"]]$Add(filepath)` But how can I get a comprehensive list? The [RDCOMClient doc](http://www.omegahat.net/RDCOMClient/Docs/introduction.html) is out-of date and the functions listed such as `getFuncs()` and `getElements()` are not available in the package anymore. Using `names()` to try and find out what was under the hood gave me no result, and ``` install.packages("remotes") remotes::install_github("omegahat/SWinTypeLibs") ``` gives an error as well. Any idea on how to check Outlook for objects?
2021/05/23
[ "https://Stackoverflow.com/questions/67655803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5224236/" ]
If you have Outlook, Excel or Word installed then you can do the following ... 1. Press F11 to get to a Visual Basic Application (VBA) Integrated Development Environment (IDE). 2. On the menu bar go to Tools->References to prompt the References dialog box. 3. On the References dialog box, in the Available References checkbox list, page down until you find Microsoft Outlook Library (or similar), once found then check the checkbox and then press OK to confirm selection and dismiss dialog. This adds a reference to the Outlook type library to the current project. 4. With the Outlook type library referenced (see step (3)) one can now press F2 to show the Object Browser dialog box. 5. In the Object Browser dialog box, select the top left dropdown list which will probably say `<All Libraries>` . Change the dropdown so it says Outlook, this will scope the object browser to just the Outlook type library. 6. You can now browse all the objects in the Outlook type library. Select a class in the Classes pane on the left hand side and the class's methods will appear in the right hand side. Enjoy!
This can somewhat easily be done for Outlook, because every outlook object has a `class` property. If you have a given object of `COMIDispatch` class in R, and it is a reference to an Outlook object, you can use the function `class()` to retrieve its class and then check the [OlObjectClass enumeration](https://learn.microsoft.com/en-us/office/vba/api/outlook.olobjectclass) for what properties and methods that class has. A short step by step example: ``` > # initialise the app > Outlook_App <- RDCOMClient::COMCreate("Outlook.Application") ``` In order to find out what we can do with that object, we need to look up the reference. For that, we need its class. ``` > Outlook_App$class() [1] 0 ``` So we look up 0 in the [OlObjectClass enumeration](https://learn.microsoft.com/en-us/office/vba/api/outlook.olobjectclass) and find out it's an Application object. Its properties and methods are listed in the referenced link in the [OlObjectClass enumeration](https://learn.microsoft.com/en-us/office/vba/api/outlook.olobjectclass): [Application](https://learn.microsoft.com/en-us/office/vba/api/outlook.application). Here, we have access to the methods and properties. For the events, we would need the now defunct packages RDCOMEvents and/or RDCOMServer. But we can try the method `getNameSpace("MAPI")` to access some other functionality. We know that we have to use the "MAPI" parameter from the method description linked above. ``` > Outlook_Namespace <- Outlook_App$getNameSpace("MAPI") ``` Now, the Namepace object has another class, for which we can look up the object definition and so on and so forth. **Unfortunately this does not work for Excel objects, since they do not have a class property, if anyone knows a solution please contact me.**
88,648
Assuming someone has a PhD, MD, CISSP, CPA, CFA, MS, etc. etc. What's the proper way to order them after their name and is the comma needed after the last name? (i.e. Jane Smith, PhD, MD, etc. or John Smith MD, PhD, etc.)
2017/04/27
[ "https://academia.stackexchange.com/questions/88648", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/67448/" ]
Questions over titling are almost always a matter of local convention and personal preference. You can read more than you wanted to know over at Wikipedia: <https://en.wikipedia.org/wiki/Post-nominal_letters> A few rules of thumb: * If you're naming someone in a friendly context then your biggest concern is usually *etiquette* rather than technical correctness. If someone insists on being called "Jane Doe, PhD, MD" rather than "Jane Doe, MD, PhD" then it would be incredibly rude to object to them. Most people would not care, but if in doubt you should ask. * If you're establishing the credibility of someone, such as in a piece of journalism, then you list only relevant degrees starting with the highest degree. Even if multiple degrees are relevant it's likely that one degree will be most relevant. * If you follow the cite note for US degrees in the Wikipedia link above, you'll eventually get to [this page](http://www.formsofaddress.info/post_nominals.html#378), in which a protocol expert says that this is the appropriate order, with ties within each category being broken alphabetically: ``` 1) Religious orders 2) Theological degrees 3) Academic degrees 4) Honorary degrees, honors, decorations 5) Professional licenses, certifications & affiliations ``` * Don't list degrees that have been superseded by another degree. That is, don't say "John Doe, PhD, MS, BS" because the MS and BS degrees have been eclipsed by the PhD.
My understanding is that two degrees may be listed if they are in different disciplines, even though in one discipline a degree may be lower in status. e.g. PhD, MPH where the PhD is in psychology and the MPH is in public health. How else would one establish credentials in both fields.
17,600,605
I've got a Maven project which uses Java-configured Spring (`@Configuration` etc.). Properties which are referenced by `@Value` are stored in different places, e.g. Tomcat's context.xml. For testing I've created a .properties file to provide some values for the components and services. In my JUnit test (which uses a spring test context) this .properties file is added via `@PropertySource`. The **problem** is that the values will not be loaded from the file, instead the value identifier is set as value, e.g. `${someFlag:false}` (so I get ClassCastExceptions for any other than String). Also the default value will not be set, so I think, the values won't be processed at all. I'm sure Spring finds this file because when I change the value of `@PropertySource` I get some FileNotFoundException. Nevertheless I've tried different variants to point to this file an all have worked (tested by renaming which produced FileNotFoundException): * classpath:/test.properties (my preferred notation) * /test.properties * file:src/test/resources/test.properties I'm also sure that Spring itself works, because when I remove the `@Value`, the class under test is injected via `@Autowired` in my test as expected. Down below you'll find the problem scenario stripped down as much as possible. For versions and dependencies please see the pom.xml at the bottom. MyService.java -------------- ``` package my.package.service; // Imports @Service public class MyService { @Value("${someFlag:false}") private Boolean someFlag; public boolean hasFlag() { return BooleanUtils.isTrue(someFlag); } } ``` MyConfiguration.java -------------------- ``` @Configuration @ComponentScan(basePackages = {"my.package.service"}) public class MyConfiguration { } ``` MyServiceComponentTest.java --------------------------- ``` @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {MyTestConfiguration.class}) public class MyServiceComponentTest { @Autowired private MyService service; @Test public void hasFlagReturnsTrue() { assertThat(service.hasFlag(), is(true)); } } ``` MyTestConfiguration.java ------------------------ ``` @Configuration @Import({MyConfiguration.class}) @PropertySource("classpath:/test.properties") public class MyTestConfiguration { } ``` src/test/resources/test.properties ---------------------------------- ``` someFlag=true ``` pom.xml ------- ``` <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>3.2.3.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- Test dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> ```
2013/07/11
[ "https://Stackoverflow.com/questions/17600605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1711751/" ]
The issue here is you need a `PropertySourcesPlaceholderConfigurer` also which is actually responsible for resolving the `${..}` fields, just add another bean which creates this bean: ``` @Bean public static PropertySourcesPlaceholderConfigurer propertiesResolver() { return new PropertySourcesPlaceholderConfigurer(); } ```
In addition to Biju Kunjummen answer: If you use @ConfigurationProperties to inject properties into bean setters, then ConfigurationPropertiesBindingPostProcessor need to be created (instead of PropertySourcesPlaceholderConfigurer): ``` @Configuration static class PropertyConfig { @Bean public static ConfigurationPropertiesBindingPostProcessor propertiesProcessor() { return new ConfigurationPropertiesBindingPostProcessor(); } } ```
31,114,578
To be more specific I need: ``` // seconds from Jan 1 2010 val currentAerospikeTime = (new Date().getTime - new Date(110, 0, 1).getTime)/1000; ``` But it uses the deprecated `Date` constructor, so I get a warning. But in Scala there is no way to turn off the warning for a single line (and I don't want to turn it off completely). So how can I rewrite it, to make it terser and let it compile without the warning? Maybe I'm missing something but I can't find a short way to do it, neither with the Java 8 API nor with the Joda library (didn't reserch it thoroughly, but I don't want to add the library just for this line either).
2015/06/29
[ "https://Stackoverflow.com/questions/31114578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91495/" ]
In Java 8 and JodaTime there is a concept of Duration. The number of seconds since 1-1-2010 can be determined by (java 8 example) ``` LocalDateTime jan2010 = LocalDate.of(2010,1,1).atStartOfDay(); // can also pass a ZoneId here Long secondsSince2010 = Duration.of(jan2010, LocalDateTime.now()).getSeconds(); ``` For JodaTime the solution is similar, only the construction of objects and methods are slightly different.
Instead of using the constructor in the class Date, what about trying Calendar? ``` Calendar.set(year + 1900, month, date); ``` It's what is recommended in the javadoc of the deprecated constructor you looked for.
3,390
I'm curious whether there is a way to store a hash of a multi-set of integers that has the following properties, ideally: 1. It uses O(1) space 2. It can be updated to reflect an insertion or deletion in O(1) time 3. Two identical collections (i.e., collections that have the same elements with the same multiplicities) should always hash to the same value, and two distinct collections should hash to different values with high probability (i.e., the function is independent or pairwise independent) One initial attempt at this would be to store the product modulo a random prime of the hashes of the individual elements. This satisfies 1 and 2 but it's not clear whether it, or a close variation, would satisfy 3. I originally posted this on [StackOverflow](https://stackoverflow.com/questions/4175951/what-is-a-good-hash-function-for-a-collection-i-e-multi-set-of-integers). \*Properties 1 and 2 could be relaxed a little to, say, O(log n), or a small sublinear polynomial. The point is to see whether we can identify multi-sets and reliably test equality without storing the elements themselves.
2010/11/29
[ "https://cstheory.stackexchange.com/questions/3390", "https://cstheory.stackexchange.com", "https://cstheory.stackexchange.com/users/2422/" ]
If you think of sets as living in universe $[u]$, it is quite easy to solve your problem with $O(\lg u)$ update time. All you need is a fast hash function for a vector of $u$ numbers, with fast "local updates". Wikipedia/Universal hashing suggests $h(\vec{x}) = \big(\sum\_{i=1}^{u} x\_i a^i \big) \bmod{p}$, where $p$ is a large enough prime and $a$ is uniformly drawn from $[p]$. When you add or remove element $i$, you have to add/subtract $a^i$ from the hash code, which takes $O(\lg i)$ time using divide and conquer for the exponentiation. Since a polynomial of degree $u$ can only have $u$ roots, the probability of collision for two distinct sets is $O(u/p)$. This can be made very small by taking $p$ to be large enough (for instance, $p=u^2$ and you work in "double precision"). If the sets are much smaller than $[u]$, you can of course begin by hashing the universe down to a smaller universe. Does anybody know a solution with $O(1/p)$ collision probability when hashing to range $[p]$? This ought to be possible.
Carter and Wegman cover this in [New hash functions and their use in authentication and set equality](http://www.sciencedirect.com/science/article/pii/0022000081900337); it's very similar to what you describe. Essentially a commutative hash function can be updated one element at a time for insertions and deletions, and high probability matches, in O(1).
4,806
The Book of Revelation self-identifies as a letter to seven churches: > > John to the seven churches that are in Asia [***-v.4***](http://www.biblegateway.com/passage/?search=Revelation%201:4&version=NASB) > > > John explains his experience to them as follows: > > I, John, your brother and fellow partaker in the tribulation and kingdom and perseverance which are in Jesus, was on the island called Patmos because of the word of God and the testimony of Jesus. I was in the Spirit on the Lord’s day, and I heard behind me a loud voice like the sound of a trumpet, saying, “Write in a book what you see, and send it to the seven churches: to Ephesus and to Smyrna and to Pergamum and to Thyatira and to Sardis and to Philadelphia and to Laodicea.” [***-v.9-11***](http://www.biblegateway.com/passage/?search=Revelation%201:9-11&version=NASB) > > > One common teaching is that these seven churches are symbolic, and should be interpreted as seven successive "church ages." For example, the [Wikipedia article](http://en.wikipedia.org/wiki/Seven_churches_of_Asia#Seven_Dispensations) on the subject says the following: > > The messages to the seven churches, while being for actual churches, can also be applied to seven distinct ages of the Church. > > > (The first result from a quick [Google search](https://www.google.com/search?q=seven%20churches%20dispensations%20OR%20ages#safe=active&sclient=psy-ab&q=seven%20churches%20dispensations%20OR%20ages&oq=seven%20churches%20dispensations%20OR%20ages&gs_l=serp.3..35i39.2180.3131.2.3252.8.8.0.0.0.0.184.821.5j3.8.0.cappswebhl.1.0.0...1.1.12.psy-ab.ssn9bZ_DnA8&pbx=1&bav=on.2,or.r_qf.&bvm=bv.46226182,d.cGE&fp=1f7c6e771dc5a6b1&biw=1320&bih=672) yields [a site](http://en.believethesign.com/index.php/Seven_Church_Ages) that actually identifies dates and "spokesmen" for each of these church ages!) My question here is not so much about the character of each church, or even about whether they do or do not correspond to the character of the Church in various eras since the time of Christ. What I am wondering is whether there is any indication in the text that these letters were ***meant*** to describe successive church ages? In other words, was that the authorial intent? I am specifically looking for exegetical support, if it exists.
2013/05/07
[ "https://hermeneutics.stackexchange.com/questions/4806", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/529/" ]
I translate from Fr. Castellani's book, in which he takes the seven-churches-as-seven-ages-of-the-Church approach: > > Our interpretation is based on: > > > 1. the fact that the epistles to the seven 'angels' are under the general title of 'Prophecies' or 'Revelation'; > 2. the fact that seven simple 'pastoral letters' would be ridiculous after the solemn vision of Christ the King; > 3. the authority of St Augustine, who says that in the Apokalypsis '*totum tempus Ecclesiae complectitur*'; > 4. the fact that many Holy Fathers believe these messages to be directed to all Churches: '*per septem accipiamus universas*', as > Anselm of Laon (12th century), which is much more reasonable to > understand in the sense of 'all in time' and not 'all in space during > the 1st century', many of them now extinct. Otherwise the messages > would be of little use to us now. > > > Besides this, we are in the company of the noted *Glossa* of the ancient Fathers, of Albert Magnus, the Mediaevals, Abbot Joachim, Nicholas of Lyra, Bruno d'Asti, Holzhauser, Billot, Eyzaguirre, among others. > > > (Castellani, **El Apokalypsis de San Juan**, Vórtice 2005, Buenos Aires. `ISBN 987-9222-22-9`)
Just a really quick answer here Jaz as I am short on time, but while researching came across this and noticed a lack. You can readily see this is a prophetic not a literal message when you read the letter to Smyrna. 10 days of persecution (Rev 2:10). This, from an historicist interpretation and using the biblical day for a year symbology, is the Diocletian persecution from A.D. 303 to A.D. 313. Naturally this persecution occurred in all the churches, not only Smyrna. A quick read of the text and a little thought makes it pretty clear :-) Edit 1 ------ It has been a long time, but I promised to return to this answer and fill in the detail I lacked at the time. Here is the longer version: The book opens and immediately says in verse one that it is prophetic of the future, that it is the word of God and the testimony of Jesus Christ. (Revelation in 19:10 self clarifies also that "the testimony of Jesus is the spirit of prophecy"). It further says (also verse 1) it is signified - made known by a sign, it indicates. This admonition is there for the specific reason to warn us that this book uses types and symbols, and gives us a heads up. Just as a lecturer would warn you to watch carefully for some effect before he conducts an experiment. We must read *all* that follows with this warning, or 'heads up', in mind. Further, in reading the book of Revelation we find that approximately 75% of the book uses Old Testament references. To understand it, you need to be thoroughly versed in scripture. (NB specifically that to the audience of the day, the Old Testament *was* the scripture. There was no New Testament at that time. They rightly heard and studied the letters and writings of the apostles, but at that time did not put them on equal footing with the Bible, the Old Testament - This point seems to escape many in their studies. When Paul taught the Bereans and they searched the scriptures diligently, it means they studied the Old Testament, to see if what he preached was according to this word.) It also pays to note that the book of Revelation follows Christ through the Sanctuary service in the sequence of "The Candlestick, the Table of Shewbread, The Altar of Incense, the veil and finally the Ark of the Covenant." The ancient tabernacle was given as a demonstration of the steps that the plan of salvation would follow. It began at the Altar. The plan of salvation begins with the sacrifice of Jesus on the cross. Without that sacrifice, there is no meaning to anything else. Without that sacrifice, there is no plan. It is *the* plan. Next, also in the "outer court" (this signifies the world) is the Laver, which typifies baptism. First we accept the sacrifice of Jesus in our stead, and then as a public display of our decision we are "baptised into His death", "buried with Him" and are raised "so that we too might walk in newness of life." These two things took place and take place in the world, in the outer court. When a prophecy is given to a prophet, it is always grounded in the 'now' as from the perspective of the prophet. To Daniel and Kind Nebuchadnezzar, the vision of the image began with the 'now' of Babylon. By the time of Daniel's vision in chapter 8, the Medo Persian empire was ascending and Babylon was about to fall. His vision thus began with the Ram which signified them, followed by the Grecian Goat and the notable horn being Alexander the Great, etc. In the vision of chapter 7, still the first year of Belshazzar, Babylon was not yet at the point of destruction, so it includes Babylon as the first beast, the first kingdom. (Gabriel explains to Daniel and to us the meaning of these symbols) So Daniel in chapter 7 sees Lion, Bear, Leopard, Terrible Beast. Now when we read the description of Rev 13's beast, we find a terrible beast was like a leopard, feet like a bear, mouth of a lion. It is in reverse order to the vision of Daniel. Daniel was looking forward, John was looking back in history. The vision was given from the perspective of 'now' for John. The 'now' for John also included the story of Jesus. Chapter 1 identifies Him as "I am He who lives, and was dead, and behold, I am alive forevermore. Amen. And I have the keys of Hades and of Death." John knew, as do we, that the only One who fits this description is Jesus Christ. It is the recent past, and the next sentence continues this with "Write the things which you have seen, the things which are, and the things which will take place after this." Once again, we are at the end of the chapter, again reminded that this book is prophetic and that it uses signs (the seven stars, the seven candlesticks - are signs, they signify some thing). With two warnings that this is a book of prophecy now under our belt, we read of the seven churches which are the seven candlesticks. They are also typified by the menorah of the ancient Jewish tabernacle. What was the duty of the priest at the candlestick? It was to trim the wicks and to supply them with oil (which the Bible elsewhere tells us, typifies the Holy Spirit) so that they would not go out. As Paul tells us, Jesus is our eternal High Priest, and in the type symbolised by the earthly tabernacle, his first duty is the candlesticks, which we now learn signify the seven churches. Knowing that this is a book of prophecy, and given two warnings that this talks of the 'now' and then of the future, when we read the first church we should expect what? I can see no other than it beginning in the 'now' or possibly in the immediate future, as the vision of Daniel 7 begins in the 'now' of the Babylonian Empire or as Daniel 8, the immediate future when Babylon has fallen. When we read this churches description, that it tested apostles, it most certainly fits. The book of Acts describes a church full of love for one another, a church which shared gladly with brothers and sisters who were in need. The warning however is that they already have, maybe are busy falling, or soon will fall from their first love. Jesus commends them on all their actions except this and enjoins them to return to their first love, which He most clearly approves. The next church is persecuted, but when we hit 2:10, we read about '10 days of tribulation'. From Benson's Commentary (early 1800's by Rev Joseph Benson 1749-1821) mentions that Bishop Newton (That is Thomas Newton 1704-1782) held that this was the Diocletian Persecution, probably written in his book "Dissertation on the Prophecies". I have not read that one myself to confirm though. The Jamieson-Fausset-Brown Bible Commentary also refers to 10 years on the year-day principle, which is learnt in Numbers 14:34, Ezekiel 4:5-8, and most clearly Daniel 9:24-27. More on that some other time. The same in Gill's Exposition of the Entire Bible (1746-63) by John Gill (1697-1771), where the discussion on Revelation 2:10 states the following: > > the Dioclesian persecution lasted ten years almost throughout: and some think that this last persecution, which held ten years, is here particularly meant, and not without some good reason; since it is usual in prophetic writings, and in this book of the Revelation, to put days for years; so that these ten days may be the ten years the last persecution held, and at which time the period of this church state ended, and that of Pergamos took place. > > > I have, while doing some Bible, Bible History, Reformation History, Early Church History and the current state of the Protestant faith study, to my great surprise discovered that almost all of the Protestant faiths have lost sight of the day-year principle that the early reformers uncovered! To me this is astounding. The day-year principle, or the Historicist interpretation was believed by Martin Luther, Philip Melanchthon, Jan Hus, William Tyndale, John Wycliffe, John Knox, John Calvin, John Wesley, C.H Spurgeon, Bishop Thomas Newton (mentioned before), Sir Isaac Newton, Ulrich Zwingli and others. How on earth can Protestants forget these hard won truths, some won by men who fought the ruthless and tyrannical Holy Roman Empire to the death? I was truly stunned when I learnt that of all the Protestant faiths, there are only three that still hold this. One of them are the Jehovah's Witnesses. A most unusual faith in many respects - the most interesting being in claiming honour for Jehovah and denying the deity of Christ, not realising that Jesus is Jehovah :-) Truly, the second angel's message of Revelation 14:8 is rapidly approaching. Babylon the Great is falling. Perhaps that explains why my first answer above which just assumed that Protestants knew these things, was not understood at all. That those who adhere to Catholic teachings might not understand or perhaps vehemently disagree, I could expect. But virtually everyone? That blindsided me :-) Reference the [Diocletianic Persection](https://en.wikipedia.org/wiki/Diocletianic_Persecution) on Wikipedia, from AD 303 to AD 313 for the 10 days (years) of persection mentioned. As expected, if Smyrna reflects the next church in history, AD 303-313 most certainly fits. Historically we see the next church being a compromising church (Pergamos) as the pure faith is slowly but surely adulterated as church and state mix. This probably runs to about 538 AD. This compromise results in the next church. The corrupt church, Thyatira. The main church has become entirely corrupt, but there are still those who hold fast to the pure faith, like the Waldensians, Hussites, etc. This probably endures till around AD 1565. It covers what we call the 'Dark Ages'. Corrupt practices abound. Tradition replaces the Bible, human priesthood, sacred relics, a focus on works, the teaching of purgatory, the immortal soul, the Pope is the emperor of the world, the king of heaven, and God upon earth, auricular confession, and many many others. But this church is also the one that lights the flame of the Protestant Reformation. Jesus speaks to them words of hope though, he promises to fight with them against the corruption. He puts on them no other burden but to hold fast what they have. History tells us that they most certainly did, and they were great men of God. The dead church, Sardis. The Protestant faith degenerates in the post-Reformation period. Lifeless formalism, spiritual complacency, creedal and dry philosophical arguments replace a focus on the saving grace of the gospel and commitment to Christ. But there were a notable few who remained pure and Christ centred. Call this the church till approximately 1730's or 40's. The faithful church, Philadelphia. Great spiritual revivals took place in Great Britain and America. Known as the [First](https://en.wikipedia.org/wiki/First_Great_Awakening) and [Second Awakenings](https://en.wikipedia.org/wiki/Second_Great_Awakening) took place during the next phase of history. Jesus says they have little strength (coming out from the dead church) but those who persevere and overcome are promised the New Jerusalem. This probably runs into the late 1800's or early 1900's. The final church, the lukewarm one. Laodiceans. Sadly, it is us. We have, we think, become rich, wealthy and in need of nothing. Our true state says Jesus, is the exact opposite. But, we are the last church, and it is in our day that this world will end. Turn to Jesus, be zealous and repent. He knocks, let Him in! If we have a knowledge of church history, if we compare these churches to history, they are remarkably accurate. A final note, due to us having lost sight of something common in the time of John when he wrote Revelation. If you look on the map, and see the physical location of the 7 churches, they go in a rough half circle, clockwise from west to east. If you lived in the time of John, and were in the Northern Hemisphere, a sundial would trace a very similar pattern. It may well be yet another hint to apply the messages to the churches to times in history, from the dawn of the new church, Spiritual Israel, to the sunset of this tired old world which we are destroying at a rapid and alarming pace. However, I still believe, that if you are simply asking for an exegetical reason for why the seven churches correspond to seven church ages, there is ample reason to do so, the simplest and easiest being to notice the 10 days of persecution and tie that to the 10 years of the Diocletianic Persecution. Along with the introduction telling you it refers to the things that shortly must take place, the evidence points strongly to read seven successive ages. An exegetical reason to justify seven church ages, I truly believe, is just a quick read and some thought. Understanding and interpreting it all! A fraction of which I have now done. That is another matter entirely! *That* takes long and hard study! If it is seven ages, it is telling us that Jesus is walking through history and time with his church, it is the object of His most close affection, his chosen instrument to spread His message to all. He trims the wick and ensures that the oil is there to keep it alive, even during the most trying circumstances. He is the builder and the keeper of our faith. The church is built on Him, the one and only Rock and Cornerstone. I trust this elaborates - not too verbosely - why I hold that the Bible teaches seven ages through which the church goes, and does so in a suitable manner.
38,161,926
I have an array like this `[HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"]`. I got this from console. I trying to find out value like below ``` var sku = skus_colorcode.indexOf('9620'); console.log(sku); ``` But it is returning -1. Why I am getting this result ??
2016/07/02
[ "https://Stackoverflow.com/questions/38161926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5043301/" ]
Try this ``` function arraySearch(arr,val) { for (var key in arr) { this_val = array[key]; if(this_val == val){ return key; break; } } } ```
This should be ``` var obj = {HT2787UK: "9618", HT2787Z1UK: "9619", HT2787Z3UK: "9621", HT2787Z2UK: "9620"} for (var key of obj) { if (obj[key] == "9620"){ return key; } } return false ```
21,017,542
I am trying to add this simple search form while applying form inline class so that controls appear next to each other, but I get the controls displayed above each other and the search bottom in white and looking strange, so can someone please tell me what I am missing here? ``` <div class="container"> <div class="row"> <div class="col-md-8"> <form class="form-inline" action="#" method="post"> Search<input type="text" id="search" name="search" class="input-small" placeholder="Search..."> <select id="searchon" name="searchon"> <option value="0">First Name</option> <option value="1">Last Name</option> </select> <button type="submit" class="btn">Search</button> </form> </div> </div> </div> ```
2014/01/09
[ "https://Stackoverflow.com/questions/21017542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574486/" ]
I had a similar issue with a code snippet from bootstrap. I found that the 2 classes 'control-group' and 'controls' broke the inline. removing the 2 classes fixed it for me. ``` <div class="control-group"> <label class="control-label" for="Name">Name</label> <div class="controls"> <input type="text" id="Name" placeholder="Name"> </div> </div> ``` to: ``` <label class="control-label" for="Name">Name</label> <input type="text" id="Name" placeholder="Name"> ```
Yes! removing the second class from the div worked for me. ``` <form class="form-inline name=" search"> <fieldset> <div class="form-group"> <input name="rego" id="search_box" style="text-transform:uppercase" maxlength="6" type="text" class="form-control input-md" placeholder="PLATE NO"> <input class="btn btn-lg btn-primary" type="submit" value=" Programe Tag " /> </div> </fieldset> ``` to ``` <form class="form-inline name=" search"> <fieldset> <input name="rego" id="search_box" style="text-transform:uppercase" maxlength="6" type="text" class="form-control input-md" placeholder="PLATE NO"> <input class="btn btn-lg btn-primary" type="submit" value=" Programe Tag " /> </fieldset> ```
54,353,640
I'm trying to implement Stripe Checkout into my website. In local the api work normal but in host I get the error : > > Class 'Stripe\Stripe' not found > > > **Note:** In my host I don't have SSH. And I added files manually with FTP. ``` \Stripe\Stripe::setApiKey("sk_test_XXXXXX"); $token = $request->stripeToken; $customer = \Stripe\Customer::create([ 'email' => $client->email, 'source' => $token, ]); ```
2019/01/24
[ "https://Stackoverflow.com/questions/54353640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8386280/" ]
As mentioned you have installed Stripe library manually and uploaded on server. To use this library include init file. ``` require_once('/path/to/stripe-php/init.php'); ``` ON next step set Api key, Make sure to use test api key for testing. ``` \Stripe\Stripe::setApiKey( "sk_test_XXXXXX"); ``` Make sure to download latest stripe library from [Githut repo](https://github.com/stripe/stripe-php/releases)
Please use stripe library with the below code to resolve the error ``` $stripe_obj = new Stripe(); $stripe = $stripe_obj->setApiKey(env('STRIPE_SECRET')); ```
160,003
Is there a straightforward way to migrate all **email-related "stuff"** (mailboxes, settings, contacts, calendar, etc.) from a PC running Vista & Outlook 2007 to a Mac running Mac OS X Snow Leopard and Entourage 2008? Not sure if it's relevant, but the email accounts are all POP; if the mail was IMAP, at least part of the project would be easier. I've found a bunch of 12-step procedures using Thunderbird as a "middleman" and some other involved plans, but they seem unnecessarily complex. I keep feeling that there must be some ridiculously easy procedure or tool, but I haven't found it.
2010/07/04
[ "https://superuser.com/questions/160003", "https://superuser.com", "https://superuser.com/users/1056/" ]
I didn't intend to answer my own question, but just in case anyone else is unfortunate enough to be in a similar situation... I ended up using the [O2M program](http://www.littlemachines.com/) ($10) from Little Machines. Even though the website looks like it's from 1997, the program did exactly what it was supposed to. Over 30,000 emails, 600 contacts, and God knows what else was transferred w/o any problems. Even though I was hoping for a free & easy solution (those 2 often co-exist), in this case, it was the best $10 I (actually, someone else) spent.
I just used [02M](http://www.littlemachines.com/) to perform this same task. VERY slow... but got the job done. Now trying to figure out notes =. > > O2M may be the fastest way to move your Windows® Outlook® email, contacts, and calendar appointments from your PC to your Macintosh® computer! (1) Just fire up O2M on your Windows PC, pick the Outlook folders you want to export, choose the filtering options you want to use, and click Start — O2M does the rest, automatically exporting your Outlook data into portable files you can import directly into your Apple® Mail, Address Book, iCal, Microsoft Entourage, or other Macintosh-compatible programs. Back up all of your PC's email and email attachments to your Apple! Copy your Outlook contacts from work to home and vice-versa! Migrate all of your calendar appointments from your old PC to your new Mac! The possibilities are endless! > > >
17,245,805
I'm trying to display data from four tables. Three of these tables constitute a one-to-many relationship. I need to group certain data according to a shared suit\_id and I need to be able to freely sort on fields from different tables. I also need to be able to sort on more than one field from different tables. * The data represents legal cases (suits) from court records. * For each suit there are possibly many parties. * There will only be one charge for any given party and that party\_type will be "Defendant". **DB structure:** ![Highlighted are the fields that I need to sort on. The internal relation of suit\_id to parent\_suit\_id may not be needed. I added it for testing.](https://i.stack.imgur.com/u1FJn.png) The following is my current query which returns the correct data. The data is properly grouped by suit\_id but the sorting is off and my query doesn't allow me to control the sorting. ``` SELECT s.suit_id, s.case_number, p.party_id, p.name, c.charge_id, c.charge_code FROM suit_party sp LEFT JOIN suit s ON sp.suit_id = s.suit_id LEFT JOIN ( SELECT pp.* FROM party pp WHERE pp.party_type != 'Bond Entity' ORDER BY pp.last_name DESC ) p ON sp.party_id = p.party_id LEFT JOIN charge c ON p.party_id = c.party_id WHERE p.party_id IS NOT NULL GROUP BY sp.party_id, sp.suit_id ``` **Sample output** ``` +---------+-------------+----------+------------------+-----------+-------------+ | suit_id | case_number | party_id | name | charge_id | charge_code | +---------+-------------+----------+------------------+-----------+-------------+ | 1 | 66519GE | 1 | Trouble, Tony T. | 1 | 262061253 | | 1 | 66519GE | 2 | Law, Officer | NULL | NULL | | 2 | 2013A262076 | 3 | Bad, Bobby B. | 2 | 0528 | | 2 | 2013A262076 | 5 | Police, Peter | NULL | NULL | | 3 | A357654KK | 6 | Krook, Kimberly | 3 | 2143 | | 3 | A357654KK | 7 | Crime, Capn | NULL | NULL | | 4 | B357654KK | 8 | Krook, Kimberly | 4 | 0660 | | 4 | B357654KK | 9 | Law, Officer | NULL | NULL | +---------+-------------+----------+------------------+-----------+-------------+ ``` I'd like to be able to sort by name and charge\_code while keeping the suit\_id's properly grouped. <http://www.sqlfiddle.com/#!2/e6daf9>
2013/06/21
[ "https://Stackoverflow.com/questions/17245805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1406432/" ]
The F12 Developer Tools are a great source for troubleshooting issues with Internet Explorer. Understand that while Browser Emulation is pretty good, it's not perfect. There could be differences between Native IE7, and Emulated IE7. One invaluable tool that I have grown to rely on is Fiddler Web Proxy Debugger. It's not related to Internet Explorer, but it makes debugging in IE much easier than ever before. With it you can modify the markup of any page (even those that don't belong to you), modify the JavaScript and CSS, and even [setup Auto Responder](http://www.youtube.com/watch?v=BV-DZ3zuyG8)'s to swap out files on arbitrary requests. Check it out at <http://fiddler2.com>
Use IE. Go to the Tool Gear and go to F12 Developer Tools or Hit F12. Now go to Browser Mode. If you are using a Mac you may need Parallels. You should use IE itself.
3,227,050
i've been working for some time with an opensource library ("[fast artificial neural network](http://leenissen.dk/fann/)"). I'm using it's source in my static library. When i compile it however, i get hundreds of linker warnings which are probably caused by the fact that the library includes it's \*.c files in other \*.c files (as i'm only including some headers i need and i did not touch the code of the lib itself). My question: Is there a good reason why the developers of the library used this approach, which is strongly discouraged? (Or at least i've been told all my life that this is bad and from my own experience i believe it IS bad). Or is it just bad design and there is no gain in this approach? I'm aware of [this related question](https://stackoverflow.com/questions/232693/including-one-c-source-file-in-another) but it does not answer my question. I'm looking for reasons that might justify this. A bonus question: Is there a way how to fix this without touching the library code too much? I have a lot of work of my own and don't want to create more ;)
2010/07/12
[ "https://Stackoverflow.com/questions/3227050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/350605/" ]
As far as I see (`grep '#include .*\.c'`), they only do this in doublefann.c, fixedfann.c, and floatfann.c, and each time include the reason: ``` /* Easy way to allow for build of multiple binaries */ ``` This exact use of the preprocessor for simple copy-pasting is indeed the only valid use of including implementation (\*.c) files, and relatively rare. (If you want to include some code for another reason, just give it a different name, like \*.h or \*.inc.) An alternative is to specify configuration in macros given to the compiler (e.g. -DFANN\_DOUBLE, -DFANN\_FIXED, or -DFANN\_FLOAT), but they didn't use this method. (Each approach has drawbacks, so I'm not saying they're necessarily wrong, I'd have to look at that project in depth to determine that.) They provide makefiles and MSVS projects which should already *not* link doublefann.o (from doublefann.c) with either fann.o (from fann.c) or fixedfann.o (from fixedfann.c) and so on, and either their files are screwed up or something similar has gone wrong. Did you try to create a project from scratch (or use your existing project) and add all the files to it? If you did, what is happening is each implementation file is being compiled independently and the resulting object files contain conflicting definitions. This is the standard way to deal with implementation files and many tools assume it. The only possible solution is to fix the project settings to not link these together. (Okay, you could drastically change their source too, but that's not really a solution.) While you're at it, if you continue without using their project settings, you can likely skip compiling fann.c, et. al. and possibly just removing those from the project is enough – then they won't be compiled and linked. You'll want to choose exactly *one* of double-/fixed-/floatfann to use, otherwise you'll get the same link errors. (I haven't looked at their instructions, but would not be surprised to see this summary explained a bit more in-depth there.)
I'm doing this at the moment at home because I'm a relative newcomer to C++ on Linux and don't want to get bogged down in difficulties with the linker. But I wouldn't recommend it for proper work. (I also once had to include a header.dat into a C++ program, because Rational Rose didn't allow headers to be part of the issued software and we needed that particular source file on the running system (for arcane reasons).)
67,557,239
Let's say I have data `test` (dput given) where a list-col say `items`: ``` test <- structure(list(items = list('a', c('b', 'c'), c('d', 'e'), 'f', c('g', 'h')), ID = c(1,1,1,2,2)), row.names = c(NA, 5L), class = "data.frame") library(tidyverse) test %>% group_by(ID) %>% mutate(dummy = accumulate(items, ~paste(.x, .y))) ``` I am getting an output with list-col like this ``` items ID dummy 1 a 1 a 2 b, c 1 a b, a c 3 d, e 1 a b d, a c e 4 f 2 f 5 g, h 2 f g, f h ``` I would like there to be four items in row3, having each possible combination, i.e. `c("a b d", "a b e", "a c d", "a c e")`. It however doesn't matter if these are separate items in the list or not. In other words, the output of dummy may be of type multi-level list, where row3 will contain four items in the list. I tried using `expand.grid`, but I am doing something wrong somewhere! So my desired output will look like ``` items ID dummy 1 a 1 a 2 b, c 1 a b, a c 3 d, e 1 a b d, a c d, a b e, a c e 4 f 2 f 5 g, h 2 f g, f h ```
2021/05/16
[ "https://Stackoverflow.com/questions/67557239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2884859/" ]
If you want every possible combination use `sapply` over `.x` ``` library(dplyr) library(purrr) test %>% group_by(ID) %>% mutate(dummy = accumulate(items, ~c(sapply(.x, paste, .y)))) %>% pull(dummy) #[[1]] #[1] "a" #[[2]] #[1] "a b" "a c" #[[3]] #[1] "a b d" "a b e" "a c d" "a c e" #[[4]] #[1] "f" #[[5]] #[1] "f g" "f h" ```
Another approach with `expand.grid()`, ``` test %>% group_by(ID) %>% mutate(dummy = accumulate(items, ~do.call("paste",expand.grid(.x, .y)))) %>% data.frame() ``` gives, ``` items ID dummy 1 a 1 a 2 b, c 1 a b, a c 3 d, e 1 a b d, a c d, a b e, a c e 4 f 2 f 5 g, h 2 f g, f h ```
22,707,965
I want first record in 15 minutes interval. I have a MySQL table which has datetime rows with ~1min interval, I want to retrieve the first record and after that again the first record within the next 15 min. I am confused whether to use join or MySQL variable or nested query. Even if you dont know right guide me what should I use variables or join or nested ? To be specific we have a table with one column date\_timestamp as ``` +---------------------+ | date_timestamp | +---------------------+ | 2014-01-07 11:49:42 | | 2014-01-07 11:50:12 | | 2014-01-07 11:50:31 | | 2014-01-07 11:50:42 | | 2014-01-07 11:51:22 | | 2014-01-07 11:51:42 | | 2014-01-07 11:52:52 | | 2014-01-07 11:53:12 | | 2014-01-07 11:53:32 | | 2014-01-07 11:54:22 | | 2014-01-07 11:55:42 | | 2014-01-07 11:58:02 | | 2014-01-07 11:59:22 | | 2014-01-07 12:00:02 | | 2014-01-07 12:00:42 | | 2014-01-07 12:01:32 | | 2014-01-07 12:01:52 | | 2014-01-07 12:02:22 | | 2014-01-07 12:03:42 | | 2014-01-07 12:04:42 | | 2014-01-07 12:05:02 | +---------------------+ i want the output to be if i select 5 minute interval +---------------------+ | date_timestamp | +---------------------+ | 2014-01-07 11:49:42 | | 2014-01-07 11:54:22 | | 2014-01-07 11:59:22 | | 2014-01-07 12:04:42 | +---------------------+ ```
2014/03/28
[ "https://Stackoverflow.com/questions/22707965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348419/" ]
**UPDATE (adjusted to meet your sample data and to ignore seconds):** ``` select date_timestamp from ( select date_timestamp , if(date_format(date_timestamp, '%Y-%m-%d %H:%i:00') = @a, 1, 0) as equals , if(date_format(date_timestamp, '%Y-%m-%d %H:%i:00') = @a, @a:=@a + interval 5 minute, @a) as mya from my_table, (select @a := (select date_format(min(date_timestamp), '%Y-%m-%d %H:%i:00') from my_table)) var_init order by date_timestamp ) sq where equals = 1; ``` * see it working live in an `[sqlfiddle](http://sqlfiddle.com/#!2/fd4cf/3/0)` **Original answer:** I would use user defined variables. Test data: ``` create table interv(id int auto_increment primary key, myd datetime); insert into interv(myd) values (now()), (now() + interval 7 minute), (now() + interval 9 minute), (now() + interval 15 minute), (now() + interval 16 minute), (now() + interval 30 minute), (now() + interval 35 minute); ``` Query: ``` select id, myd from ( select id , myd , if(myd = @a, 1, 0) as equals , if(myd = @a, @a:=@a + interval 15 minute, @a) as mya from interv, (select @a := (select min(myd) from interv)) var_init order by myd ) sq where equals = 1; ``` Result: ``` | ID | MYD | |----|------------------------------| | 1 | March, 28 2014 09:03:23+0000 | | 4 | March, 28 2014 09:18:23+0000 | | 6 | March, 28 2014 09:33:23+0000 | ``` * see it working live in an `[sqlfiddle](http://sqlfiddle.com/#!2/454a0/1/0)`
Not clear with the question, Still if you are using mYSQL go get the last inseted row ``` SELECT * FROM tablename ORDER BY id DESC LIMIT 1 ``` or ``` $sql = "SELECT * FROM table WHERE id = LAST_INSERT_ID()"; ```
259,140
Please help me figure out the meaning of the phrase "slid down tubes" in the following sentence from the description of the game "Minion Rush": For six and a half harrowing minutes, we ran up ramps and slid down tubes, steered around boxes and into hapless bystanders, until we hit a surfboard that refused to budge. ([Apple's App Store](https://apps.apple.com/bg/story/minion-rush/id1385190513)) I got a reference to the word "tubes" here: > > While you run, you encounter a series of obstacles, from a range of > metal rockets to glass transportation tubes for the minions. ([Venture Beat](https://venturebeat.com/community/2013/07/22/despicable-mes-minion-rush-is-addictive-fun-but-runs-into-nothing-new-territory/)) > > > I am still not sure about the meaning of the phrase "slid down tubes".
2020/09/02
[ "https://ell.stackexchange.com/questions/259140", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/21367/" ]
Inflection ---------- In English, verbs have multiple forms, so - for example - there's **have**, **has**, **had**, **having**, all of which belong to the verb **to have**. Infinitive ---------- Verbs are conventionally cited or named by their infinitive forms. The infinitive form may include a preceding "to", or it may be a bare infinitive (without "to"). The form in the dictionary usually excludes the preceding "to". The form used to cite the verb when discussing it often includes the "to". To be ----- The verb **to be** is irregular, and has the present tense forms **am** (as in *I am*), **are** (as in *you are*, *we are*, *they are*), and **is** (*he/she/it is*), along with the past tense forms **was** (as in *I was*, *he/she/it was*) and **were** (as in *you were*, *we were*, *they were*). The past participle is **been**, present participle **being**. Etymologically, the different forms of this verb come from multiple roots. If you look up [be](https://www.oxfordlearnersdictionaries.com/definition/english/be_1?q=be) in the Oxford Advanced Learner's Dictionary, it has a list of "verb forms" that you can expand. You can also read about the verb "to be" [here](https://learnenglish.britishcouncil.org/english-grammar-reference/the-verb-be). Examples of *be* as an infinitive --------------------------------- Here are some examples of *be* in its infinitive form: * *I want **to be** a star.* * *We could **be** friends.* * *It might **be** too late.* * *I don't want **to be** abandoned.* * *It's nice **to be** here.* **Imperative.** As pointed out by Lambie, **be** is also used as the imperative form, e.g. *Be quiet* or *Please be kind*.
No one really answered the question of why it is called "to-be" but rather they answer it on very technical terms when he said that he is not a native speaker. I am also wondering if Native speakers do know the origin "to be"... I am also wondering why it is called "to be"... so here's my personal theory "be", according to the dictionary means "exist" with "to" on it means "to exist". ergo, it is called "to be" verbs because it is meant to exist or could be existing, or about to exist. "to be" is somewhat a word that links sentences and or phrases that is: 1. About to happen. (She "is" going to jump.) 2. Already happened. (They "are" cursed by the witch.") 3. It is currently happening. (I "am" eating.) imagine without the "be" verbs... I hope this makes sense why it is called "to be"
107,598
I am looking for a phrase or an idiom that means that i have selected the one object from a group or settled on some solution out of many others. Let me provide some examples: 1. I went to the travel agency and they offered me a list of tours. I thought long and hard over the 2 hours and finally selected the most interesting tour among others proposed. 2. I asked for a word on ELU and other users kindly provided me with a bunch of words with requested meaning. I thought for a moment and finally selected the only word I really liked. 3. I developed some C++ library and ran into a problem. I tried many solutions and finally decided which one will work for the situation. In Russian we usually use the idiom "ostanovitsya na" that means "to stop on something". What is the similar phrase (or idiom) in American and British English? ### Update I finally **end up with** "end up"! It is as close to Russian "ostanovitsya na" as it can ever be. Another 2 very similar phrases are "to decide on" and "to settle on". I would like to deeply thank all those who have contributed to the discussion of this question!
2013/03/16
[ "https://english.stackexchange.com/questions/107598", "https://english.stackexchange.com", "https://english.stackexchange.com/users/6628/" ]
A word mentioned in the question is suitable: *[settle](http://en.wiktionary.org/wiki/settle#Verb)* (sense 7, “To determine, as something which is exposed to doubt or question; to free from uncertainty or wavering; to make sure, firm, or constant; to establish”). You can say, “I settled upon the fourth alternative”. In my mind, *settled upon* may indicate slightly more thought about the alternatives than would use of *[picked](http://en.wiktionary.org/wiki/picked#Verb)* or *[chose](http://en.wiktionary.org/wiki/chose#Verb)*. Also consider aforementioned *[selected](http://en.wiktionary.org/wiki/selected#Verb)* and *[decided](http://en.wiktionary.org/wiki/decided)* on or upon. [Links and definitions: en.wiktionary.org.] As far as idiom goes, I don't know of one comparable to “ostanovitsya na / to stop on something”. One might say, “I took X home to mama” / “My take-home was X” / “I hooked up with X” to express choosing X with more thought or less. Those are all more figurative than idiomatic but are informal and readily understood. *Edit:* ezpresso's comment reminded me I left a link out. *[End up](http://www.thefreedictionary.com/end+up)* has a sense “to arrive, esp by a circuitous or lengthy route or process”. Eg: “I ended up with the fifth alternative” or “I ended up using the sixth alternative” or “In the end I took the seventeenth alternative”.
You could simply use "*finalize*". It is quite commonly used and is similar in form to what you are trying to say in the examples. The usage is that you *finalized something* or *finalized a decision*. It should be general enough for your needs.
39,054,764
I need for some debugging to see the original order of one JavaScript object's properties but (at least in chrome devtools) `console.log()` shows me an alphabetically ordered object. Ex: ``` var obj = { z: 1, t: 2, y: 3, a: 4, n: 5, k: 6 } ``` `console.log(obj)` shows this: ``` Object {z: 1, t: 2, y: 3, a: 4, n: 5…} a:4 k:6 n:5 t:2 y:3 z:1 //expected (needed ) original order z: 1 t: 2 y: 3 a: 4 n: 5 k: 6 ```
2016/08/20
[ "https://Stackoverflow.com/questions/39054764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2951051/" ]
`console.log` does indeed sort the properties, in some cases you can use `JSON.stringify` which preserves the order, e.g. ``` console.log(JSON.stringify(obj, null /*replacer function */, 4 /* space */)) ``` NB: contrary to the popular belief, js objects maintain the enumeration order, as per the [OwnPropertyKeys specification](http://www.ecma-international.org/ecma-262/6.0/#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys) (integers first, then other properties in insertion order)
Just to clarify `Console.log` does sort but it also doesn't.... This is a list of breakpoints, the correct order (as it was created) is `default`, `mobileM`, `mobileL`, `tablet`, `desktopM` and that's what's show in the first line. [![enter image description here](https://i.stack.imgur.com/JJ8Fa.png)](https://i.stack.imgur.com/JJ8Fa.png) But when you expand it they're in alphabetical order. Same if you hover over something and view the popup. The point being one minute it does sort them and the next it doesn't. Really ought to be an option, but doesn't seem to be - and this mixed behavior can really trip you up if you're normally not concerned about property order.
36,892
I am trying to make thick forest in blender using emitter or hair emitter. The problem is that with huge ammount of trees they intersect with each other and I do not want that to happen. I did use various setting, groups and tricks without success. Does anyone have idea how to make it work? Here you can find [blend file](http://www.pasteall.org/blend/37829)
2015/09/02
[ "https://blender.stackexchange.com/questions/36892", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/16849/" ]
I would suggest to disable **Emit in Random order**. [![enter image description here](https://i.stack.imgur.com/eOwM2.jpg)](https://i.stack.imgur.com/eOwM2.jpg) Particles in this case are emitted from faces. Every faces has it's own id. With the **Random** opton enabled you are asking Blender to pick a Random face id to generate the next particle. In this case, where your simulation does'n run trought time, means that is very likely to have a particle create in the same place of another. Let's say you have 100 faces. First random id is 1, so a tree is generated in Face1. Than pick another id, randomly..it may occour to pick the same id..1, so the generated tree will be overlapped to the previous one. It may seems that you have a low probability to pick the only 1% that is already came out, but you have to consider that for each particle cration iteration, the number of "free" ids lower, so when you are at half of the particle cration, you'll have 50% probability of overlap. If this effect is not very strong is because you have also **Random distribution** option enabled. [![enter image description here](https://i.stack.imgur.com/3AoY3.jpg)](https://i.stack.imgur.com/3AoY3.jpg) With that, you are asking to position randomly the created tree on the face. So , despite they are created on the same face, the might have different location. On th other side, it may occour that two tree of born in adiacent faces, let's say along the common border, will be very near, causing overlap. Particles generation is not aware of where other particles have previously been generated (it would be very high computing demanding for large numbers), so for now it is not possible to have a **random distribution** without any overlaps. --- One possible **workaround** can bw to subdivide your mesh till the faces are almost the size of the trees XY bounding plane. Now you should have about 2000 faces in the "forest area". If we put without a tree in the center of each faces we would be able to create about 2000 trees without any overlap. [![enter image description here](https://i.stack.imgur.com/Adpi9.jpg)](https://i.stack.imgur.com/Adpi9.jpg) This obiuvsly resamble more to a plantation than a forest, but by lowering the amount of trees and the use of voronoi density map: [![enter image description here](https://i.stack.imgur.com/mRIpG.jpg)](https://i.stack.imgur.com/mRIpG.jpg) you should be able to dampen the "grid" effect a bit. [![](https://blend-exchange.giantcowfilms.com/embedImage.png?bid=462)](https://blend-exchange.giantcowfilms.com/b/462/)
Poisson disk sampling --------------------- Since the coming of Geometry Nodes we have some tools that can be useful in distriubuting points onto a surface. From the page manual about [Point distribute node](https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/point/point_distribute.html) > > The Point Distribute node places points on the surface of the input geometry object. Point, corner and polygon attributes of the input geometry are transferred to the generated points. That includes vertex weights and UV maps. Additionally, the generated points will have a normal, id and rotation attribute. > > > > > Poisson Disk: Distribute points randomly on the surface **while taking a minimum distance into account**. > > > You need to set a minimum distance to ensure some room between the particles. [![enter image description here](https://i.stack.imgur.com/x1TYV.png)](https://i.stack.imgur.com/x1TYV.png) [![enter image description here](https://i.stack.imgur.com/FFrjB.gif)](https://i.stack.imgur.com/FFrjB.gif)
30,710,022
How do I get the length of every image with `100px` or more of `width`: ``` if( $('img').width( >= 100 ).length > 0 ){ [MORE CODE] } ```
2015/06/08
[ "https://Stackoverflow.com/questions/30710022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2714670/" ]
Use jQuery [filter()](http://api.jquery.com/filter/) like ``` $('img').filter(function(){ return $(this).width() >= 100; }); ```
Try ``` $('img').each(function() { if($(this).width() >= 100) { // more code } }); ```
111,047
I'd like to double my ceiling joists to make my attic space easier to work in (for electrical/plumbing) and for lightweight storage. **Status Quo:** 2x4's (actual size) spaced 16" on-center running the width of the building uninterrupted, with the ends resting on top of the wall top plate. Each joist is strong enough to support my weight (~175lbs ) concentrated in a ~1' segment of the joist, and there isn't much deflection either. **Goal:** Reinforce the joists and lay down a wood subfloor (OSB, ply, etc.) so I'm not tiptoeing on joists whenever I'm up there. **Plan:** "Sister" or double the ceiling joists with 2x6's or 2x8's with the ends resting on the wall top plates then lay the subfloor on the new joists. **Question:** I understand that there are requirements for doubling joists, including how frequently they need to be fastened, but does this plan make sense overall?
2017/03/27
[ "https://diy.stackexchange.com/questions/111047", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/64100/" ]
If you have no sag in the ceiling just screw 3/4 inch plywood on on top of the ceiling joist. This will add strength to them and keep your headroom. Be sure to run the length of the plywood across the joist.
Add plywood to the bottom of the 2X4 , with deck screws . Plywood on top is a floor and adds to the strength making something like an "H" beam. You lose very little height this way.
21,599,818
I am having some trouble with a website I am creating, I am using Adobe Dreamweaver to just write code in, not using its visual builder. I have code like this in the file: ``` <button type="button" onclick="addToCart("box")">Add to cart</button> ``` But when I view this in Firefox and Internet explorer, when I inspect the page using Firefox the code turns to this: ``` <button pens")"="" onclick="addToCart(" type="button"> ``` The strange thing is when I view the page source in Firefox it shows up correct. I did try to also declare the encoding with the meta tag as UTF-8, but no luck (Yes I saved it as this before hand in just notepad). What can I do? EDIT: Im ashamed of myself for not seeing this myself, but in my opinion Dreamweaver isn't very good as an IDE.
2014/02/06
[ "https://Stackoverflow.com/questions/21599818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2428239/" ]
The easiest fix is to use single quotes in your javascript: ``` <button type="button" onclick="addToCart('box')">Add to cart</button> ```
This has nothing to do with encoding. Like Munter says, use single quotes. Viewing the source just shows the code you typed; If you inspect the element you see what the browser thinks you mean, because the code you wrote is invalid.
18,696,150
I have an `List` of `String`s and I would like to `trim()` each element of the list. Currently, I'm using an `ArrayList`, doing a simple loop through the elements, and adding the trimmed element to a return list, like so: ``` int listLen = listToTrim.size(); List<String> trimmedList = new ArrayList<String>( listLen ); for ( int i = 0; i < listLen; i++ ) { trimmedList.add( listToTrim.get( i ).trim() ); } return trimmedList; ``` For large lists, would there be a more efficient way of doing this?
2013/09/09
[ "https://Stackoverflow.com/questions/18696150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2531232/" ]
Nope, you're good. That's about as efficient as it'll get. There's no magic that avoids iterating. One point to keep in mind, 'though: If `listToTrim` is not a random-access-list (i.e. it does *not* implement [`RandomAccess`](http://docs.oracle.com/javase/7/docs/api/java/util/RandomAccess.html)), then using an `Iterator` (or an enhanced for-loop, which uses an `Iterator` internally) instead of a traditional for-loop is usually much more efficient. The most notable `List` that doesn't implement `RandomAccess` is the `LinkedList`. Calling `l.get(300)` on a `LinkedList` with 600 elements will have to iterate through ~300 elements to get the correct one! Modifying your code to use an enhanced for-loop would look like this: ``` public List<String> trimStrings(Listy<String> listToTrim) { List<String> trimmedList = new ArrayList<String>(listToTrim.size()); for (String str : listToTrim) { trimmedList.add(str.trim()); } return trimmedList; } ``` If you don't need the original list any more, then re-using the original list can save memory and improve performance: ``` public void trimStringsInPlace(List<String> listToTrim) { ListIterator<String> it = listToTrim.listIterator(); while (it.hasNext()) { it.set(it.next().trim()); } } ```
Joachim already answered the question. But one suggestion- **listToTrim** - when you add items to listToTrim, trim first before you add. That way, you don't have to iterate and modify or create another list just to do so. It doesn't sound logical. **Edit** based from comment: ``` String fruits = "Apple, Banana , Mango, Passion Fruit, Grapes "; List<String> fruitList = Arrays.asList((fruits.trim()).split("\\s*,\\s*")); // Trim first and then regex matches spaces before and after comma for(String fruit : fruitList){ System.out.println("Fruit: " + fruit + "\tLength: " + fruit.length()); } ``` **Output:** ``` Fruit: Apple Length: 5 Fruit: Banana Length: 6 Fruit: Mango Length: 5 Fruit: Passion Fruit Length: 13 Fruit: Grapes Length: 6 ```
4,879,624
What is the reason virtualenv does not associate `.py(w)` files with virtualenv's version of Python executables? This seems like an ideal task for virtualenv on Windows taking into consideration that there's no mechanism like [shebang](http://en.wikipedia.org/wiki/Shebang_%28Unix%29) on Windows.
2011/02/02
[ "https://Stackoverflow.com/questions/4879624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95735/" ]
File type associations are handled in the Windows registry. The virtualenv activate script would have to modify the registry keys and the deactivate script would need to restore the previous value (or risk breaking the associations). What happens if you activate a virtualenv, open a second instance of cmd.exe, and activate a different virtualenv? Unless you deactivate them in the right order, the stored values for the registry keys would be lost. I'm not a virtualenv developer, I'd say that the potential problems far outweigh the slight benefit.
[virtualenvwrapper-win](http://pypi.python.org/pypi/virtualenvwrapper-win) does associate Python files with currently active virtualenv: > > Note that the batch script `pyassoc` requires an elevated command prompt or that UAC is disabled. This script associates .py > files with `python.bat`, a simple batch file that calls the right > `python.exe` based on whether you have an active virtualenv. This > allows you to call python scripts from the command line and have the > right python interpreter invoked. Take a look at the source -- it's > incredibly simple but the best way I've found to handle conditional > association of a file extension. > > > [`python.bat`](https://github.com/davidmarble/virtualenvwrapper-win/blob/master/scripts/python.bat) looks like this ``` @echo off if defined PYTHONHOME ( goto MAIN ) FOR /F "tokens=*" %%i in ('whereis.bat python.exe') do set PYTHONHOME=%%~dpi SET PYTHONHOME=%PYTHONHOME:~0,-1% :MAIN SETLOCAL EnableDelayedExpansion if defined VIRTUAL_ENV ( set PY="%VIRTUAL_ENV%\Scripts\python.exe" ) else ( set PY="%PYTHONHOME%\python.exe" ) ENDLOCAL & %PY% %* :END ``` **UPDATE** Now it's possible – see [How to associate Python scripts with active virtualenv?](https://stackoverflow.com/questions/17867214/how-to-associate-python-scripts-with-active-virtualenv)
30,594
All of the flagship starships of humanity/the Federation get the name Enterprise: Enterprise NX-01, USS Enterprise NCC-1701, USS Enterprise NCC-1701 D, [etc.](https://scifi.stackexchange.com/questions/15/how-many-different-enterprises-were-there) Flagships of the United Federation of Planets could be named under a naming convention following from the first Warp 5 starship of humanity, the Enterprise NX-01 (humans were the dominant race in the Federation after all). But, how did Enterprise NX-01 get its name? And how did this naming convention arise? What's the in-universe history behind this naming?
2013/01/16
[ "https://scifi.stackexchange.com/questions/30594", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/931/" ]
Captain Decker showing Ilia the ships named "Enterprise" in [Star Trek: The Motion Picture](http://en.memory-alpha.org/wiki/Star_Trek:_The_Motion_Picture): ![Enterprises](https://i.stack.imgur.com/wBMhX.jpg) And from [Enterprise history](http://en.memory-alpha.org/wiki/Enterprise_history) on Memory Alpha: * **First image:** The [Enterprise was a noted sailing frigate](http://en.memory-alpha.org/wiki/Enterprise_(frigate)), either of the Royal Navy or of the US Navy. She was active in the late 18th century. (ENT: "United") * **Second image:** The [USS Enterprise (CV-6)](http://en.memory-alpha.org/wiki/USS_Enterprise_(CV-6)) was an aircraft carrier that served in World War II. (ENT: "Storm Front") Its successor was the USS Enterprise (CVN-65), which was the first nuclear-powered aircraft carrier. * **Third image:** The first space shuttle was the [Enterprise OV-101](http://en.memory-alpha.org/wiki/Enterprise_(OV-101)). (Star Trek: The Motion Picture) + *Note: Also featured in the opening of [Star Trek: Enterprise](http://en.memory-alpha.org/wiki/Star_Trek:_Enterprise)* * **Fourth image:** An early Warp starship was the [USS Enterprise (XCV 330)](http://en.memory-alpha.org/wiki/USS_Enterprise_(XCV_330)). (Star Trek: The Motion Picture) + *Notable for **not** having the traditional nacelles+saucer design of usual Starfleet ships.* * **Fifth image:** The original NCC-1701 from The Original Series. (At least according to Memory Alpha. I don't recognize it from the above screenshot.. Odd shadows.) Not in the above, but featured in the opening sequence of *Star Trek: Enterprise*: * The [HMS Enterprize](http://en.memory-alpha.org/wiki/HMS_Enterprize) was a noted sailing ship of the British Royal Navy. A galleon, she was active sometime between the 16th century and the early 18th century. Additionally, I'm fairly certain Captain Archer had a similar scene as the above, where he explains the history of the name "Enterprise" to [Commander Shran](http://en.memory-alpha.org/wiki/Thy%27lek_Shran). I don't recall which episode, though..
The Enterprise (NCC-1701) was a Constitution-class heavy cruiser. By naval tradition, the class shares its name with the first ship of that class. For example, the first Nimitz-class carrier was the USS Nimitz, the first Kitty Hawk-class carrier was the USS Kitty Hawk, etc. So, the Enterprise was actually the SECOND ship of its class. The first ship of its class was... the NCC-1700 Constitution, of course. The NCC-1701-A was actually the NCC-1798 Ti-Ho, a refitted Constitution-class starship which was a testbed for transwarp technology alongside the USS Excelsior. After Kirk was exonerated, it was given a new name and number. The NCC-1701-B, NCC-1701-C, NCC-1701-D, and NCC-1701-E were Excelsior-class, Ambassador-class, Galaxy-class, and Sovereign-class. So, in every case (except for the NX-01), the Enterprise was NOT the first ship of its class. Thought I'd better point that out, for anyone who thought that the Enterprise had some sort of special importance from being the "first of its class" or any such nonsense.