qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
135,152
So it has been well documented that GUI applications (like gedit or textedit) should [NOT](https://askubuntu.com/questions/270006/why-user-should-never-use-normal-sudo-to-start-graphical-application) be run with sudo. Ubuntu et al get gksu and gksudo (and the like) so question: what do WE (Mac users) get? Given that the Darwin kernel is built on some \*BSD code, I assume the same issues apply, but how do we go around this?
2014/06/16
[ "https://apple.stackexchange.com/questions/135152", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/81404/" ]
To edit `/etc/hosts` with Sublime Text: `sudo /Applications/Sublime\ Text.app/Contents/MacOS/Sublime\ Text /etc/hosts` If you have to do this on the regular basis, you can add this snippet to your ~/.bash\_profile ``` # sudoapp: Runs .app with root privileges # Usage: sudoapp /Applications/Name.app /etc/hosts # -------------------------------------------------------------------- sudoapp () { sudo "$1/Contents/MacOS/$(defaults read "$1/Contents/Info.plist" CFBundleExecutable)" $2 } ``` Apps running with root privileges will use `/private/var/root` as home folder, thus all config and temporary files owned by root that will be created in the process will stay where they should be - in the `root` home directory. This is the same as logging in as root and running the app, but without the hassle of user switching. This method works on 10.6 — 10.11 *Update: Apple's own TextEdit refuses to start if run as root in 10.11 and newer, so I changed my example to use Sublime Text instead*
There are good reasons NOT to edit files as root. Why not just copy them to a temporary file, edit this and copy back. You could use `visudo` although this requires some knowledge of `vi`, but is OK for making simple changes to `/etc/fstab` or similar. You could try setting the EDITOR environment variable and running `visudo` although I have never tried this with a graphic editor.
135,152
So it has been well documented that GUI applications (like gedit or textedit) should [NOT](https://askubuntu.com/questions/270006/why-user-should-never-use-normal-sudo-to-start-graphical-application) be run with sudo. Ubuntu et al get gksu and gksudo (and the like) so question: what do WE (Mac users) get? Given that the Darwin kernel is built on some \*BSD code, I assume the same issues apply, but how do we go around this?
2014/06/16
[ "https://apple.stackexchange.com/questions/135152", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/81404/" ]
While is it possible to launch a graphical application as the root user, it is not recommended. It may work, most of the time, but avoid relying on this behaviour. Avoid root ========== Running an application as root is not recommended because it dramatically increases the risk of causing problems with your Mac. The use of root should be limited to the smallest possible piece of code with strict controls in-place. Applications are increasingly moving towards a fragmented design to avoid exposing too much power to code that does not require it. * A mistake in code running with root permissions is a security risk. * A mistake in code without root permissions is much less capable of causing serious problems. There are edge cases but these are increasingly rare. The introduction of sandboxing and XPC are part of Apple's efforts to reduce the need to provide excessive authority to processes running on OS X. Command Line Tools ------------------ If you need to work with files as root user, use command line tools such as `vim`, `emacs`, or `nano`. These tools do not rely on the WindowServer and can happily be launched as root within another user session: ``` sudo nano <path to edit> ``` Graphical Tools --------------- If you prefer graphical editors, use an editor that works with the design of Mac OS X. [BBEdit](http://www.barebones.com/products/bbedit/) is an excellent editor that will correctly handle editing [root owned files](http://www.barebones.com/support/bbedit/auth-saves.html). When you edit a root owned file with BBEdit, a second process is used to bridge the permissions gap between you and the owner of the file. This process passes through Apple's sanctioned paths and thus ensures a predictable experience - hopefully across multiple major versions of Mac OS X. ### Why? WindowServer Limits and Design Scope There are subtle technical problems with launching a graphical application within another user session. The underlying technical problems stem from one user wanting to launch a graphical process within another user's session. Mac OS X's WindowServer was never designed with this as a goal. User sessions are extremely difficult to break out of even as root user – all for desirable security reasons. Apple has dramatically improved the WindowServer design in the last few major versions of Mac OS X. It is now possible to have multiple users logged into different graphical sessions on one Mac through Screen Sharing. This seemingly simple improvement relied on a huge amount of behind the scenes effort from Apple's engineers. However, Apple is unlikely to provide an easy way to cross launch applications as different users from within a single graphical user session. How would this benefit their customers? If you want to explore this topic further, look for questions involving `launchctl` and running applications in other active user sessions.
There are good reasons NOT to edit files as root. Why not just copy them to a temporary file, edit this and copy back. You could use `visudo` although this requires some knowledge of `vi`, but is OK for making simple changes to `/etc/fstab` or similar. You could try setting the EDITOR environment variable and running `visudo` although I have never tried this with a graphic editor.
135,152
So it has been well documented that GUI applications (like gedit or textedit) should [NOT](https://askubuntu.com/questions/270006/why-user-should-never-use-normal-sudo-to-start-graphical-application) be run with sudo. Ubuntu et al get gksu and gksudo (and the like) so question: what do WE (Mac users) get? Given that the Darwin kernel is built on some \*BSD code, I assume the same issues apply, but how do we go around this?
2014/06/16
[ "https://apple.stackexchange.com/questions/135152", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/81404/" ]
There are good reasons NOT to edit files as root. Why not just copy them to a temporary file, edit this and copy back. You could use `visudo` although this requires some knowledge of `vi`, but is OK for making simple changes to `/etc/fstab` or similar. You could try setting the EDITOR environment variable and running `visudo` although I have never tried this with a graphic editor.
Sergei's answer didn't work for me on OS X 10.8.5 `$ sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit /etc/hosts` I got a permissions error message ![ERROR](https://i.stack.imgur.com/XmBsA.png) Since `sudo`ing the binary first, then double-clicking the file in Finder worked, I came up with the following less simple command `$ sudo -b /Applications/TextEdit.app/Contents/MacOS/TextEdit && sleep .5 && open -a /Applications/TextEdit.app /etc/hosts` You can make a function of it like Sergei's, if need be.
135,152
So it has been well documented that GUI applications (like gedit or textedit) should [NOT](https://askubuntu.com/questions/270006/why-user-should-never-use-normal-sudo-to-start-graphical-application) be run with sudo. Ubuntu et al get gksu and gksudo (and the like) so question: what do WE (Mac users) get? Given that the Darwin kernel is built on some \*BSD code, I assume the same issues apply, but how do we go around this?
2014/06/16
[ "https://apple.stackexchange.com/questions/135152", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/81404/" ]
To edit `/etc/hosts` with Sublime Text: `sudo /Applications/Sublime\ Text.app/Contents/MacOS/Sublime\ Text /etc/hosts` If you have to do this on the regular basis, you can add this snippet to your ~/.bash\_profile ``` # sudoapp: Runs .app with root privileges # Usage: sudoapp /Applications/Name.app /etc/hosts # -------------------------------------------------------------------- sudoapp () { sudo "$1/Contents/MacOS/$(defaults read "$1/Contents/Info.plist" CFBundleExecutable)" $2 } ``` Apps running with root privileges will use `/private/var/root` as home folder, thus all config and temporary files owned by root that will be created in the process will stay where they should be - in the `root` home directory. This is the same as logging in as root and running the app, but without the hassle of user switching. This method works on 10.6 — 10.11 *Update: Apple's own TextEdit refuses to start if run as root in 10.11 and newer, so I changed my example to use Sublime Text instead*
While is it possible to launch a graphical application as the root user, it is not recommended. It may work, most of the time, but avoid relying on this behaviour. Avoid root ========== Running an application as root is not recommended because it dramatically increases the risk of causing problems with your Mac. The use of root should be limited to the smallest possible piece of code with strict controls in-place. Applications are increasingly moving towards a fragmented design to avoid exposing too much power to code that does not require it. * A mistake in code running with root permissions is a security risk. * A mistake in code without root permissions is much less capable of causing serious problems. There are edge cases but these are increasingly rare. The introduction of sandboxing and XPC are part of Apple's efforts to reduce the need to provide excessive authority to processes running on OS X. Command Line Tools ------------------ If you need to work with files as root user, use command line tools such as `vim`, `emacs`, or `nano`. These tools do not rely on the WindowServer and can happily be launched as root within another user session: ``` sudo nano <path to edit> ``` Graphical Tools --------------- If you prefer graphical editors, use an editor that works with the design of Mac OS X. [BBEdit](http://www.barebones.com/products/bbedit/) is an excellent editor that will correctly handle editing [root owned files](http://www.barebones.com/support/bbedit/auth-saves.html). When you edit a root owned file with BBEdit, a second process is used to bridge the permissions gap between you and the owner of the file. This process passes through Apple's sanctioned paths and thus ensures a predictable experience - hopefully across multiple major versions of Mac OS X. ### Why? WindowServer Limits and Design Scope There are subtle technical problems with launching a graphical application within another user session. The underlying technical problems stem from one user wanting to launch a graphical process within another user's session. Mac OS X's WindowServer was never designed with this as a goal. User sessions are extremely difficult to break out of even as root user – all for desirable security reasons. Apple has dramatically improved the WindowServer design in the last few major versions of Mac OS X. It is now possible to have multiple users logged into different graphical sessions on one Mac through Screen Sharing. This seemingly simple improvement relied on a huge amount of behind the scenes effort from Apple's engineers. However, Apple is unlikely to provide an easy way to cross launch applications as different users from within a single graphical user session. How would this benefit their customers? If you want to explore this topic further, look for questions involving `launchctl` and running applications in other active user sessions.
135,152
So it has been well documented that GUI applications (like gedit or textedit) should [NOT](https://askubuntu.com/questions/270006/why-user-should-never-use-normal-sudo-to-start-graphical-application) be run with sudo. Ubuntu et al get gksu and gksudo (and the like) so question: what do WE (Mac users) get? Given that the Darwin kernel is built on some \*BSD code, I assume the same issues apply, but how do we go around this?
2014/06/16
[ "https://apple.stackexchange.com/questions/135152", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/81404/" ]
To edit `/etc/hosts` with Sublime Text: `sudo /Applications/Sublime\ Text.app/Contents/MacOS/Sublime\ Text /etc/hosts` If you have to do this on the regular basis, you can add this snippet to your ~/.bash\_profile ``` # sudoapp: Runs .app with root privileges # Usage: sudoapp /Applications/Name.app /etc/hosts # -------------------------------------------------------------------- sudoapp () { sudo "$1/Contents/MacOS/$(defaults read "$1/Contents/Info.plist" CFBundleExecutable)" $2 } ``` Apps running with root privileges will use `/private/var/root` as home folder, thus all config and temporary files owned by root that will be created in the process will stay where they should be - in the `root` home directory. This is the same as logging in as root and running the app, but without the hassle of user switching. This method works on 10.6 — 10.11 *Update: Apple's own TextEdit refuses to start if run as root in 10.11 and newer, so I changed my example to use Sublime Text instead*
Sergei's answer didn't work for me on OS X 10.8.5 `$ sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit /etc/hosts` I got a permissions error message ![ERROR](https://i.stack.imgur.com/XmBsA.png) Since `sudo`ing the binary first, then double-clicking the file in Finder worked, I came up with the following less simple command `$ sudo -b /Applications/TextEdit.app/Contents/MacOS/TextEdit && sleep .5 && open -a /Applications/TextEdit.app /etc/hosts` You can make a function of it like Sergei's, if need be.
135,152
So it has been well documented that GUI applications (like gedit or textedit) should [NOT](https://askubuntu.com/questions/270006/why-user-should-never-use-normal-sudo-to-start-graphical-application) be run with sudo. Ubuntu et al get gksu and gksudo (and the like) so question: what do WE (Mac users) get? Given that the Darwin kernel is built on some \*BSD code, I assume the same issues apply, but how do we go around this?
2014/06/16
[ "https://apple.stackexchange.com/questions/135152", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/81404/" ]
While is it possible to launch a graphical application as the root user, it is not recommended. It may work, most of the time, but avoid relying on this behaviour. Avoid root ========== Running an application as root is not recommended because it dramatically increases the risk of causing problems with your Mac. The use of root should be limited to the smallest possible piece of code with strict controls in-place. Applications are increasingly moving towards a fragmented design to avoid exposing too much power to code that does not require it. * A mistake in code running with root permissions is a security risk. * A mistake in code without root permissions is much less capable of causing serious problems. There are edge cases but these are increasingly rare. The introduction of sandboxing and XPC are part of Apple's efforts to reduce the need to provide excessive authority to processes running on OS X. Command Line Tools ------------------ If you need to work with files as root user, use command line tools such as `vim`, `emacs`, or `nano`. These tools do not rely on the WindowServer and can happily be launched as root within another user session: ``` sudo nano <path to edit> ``` Graphical Tools --------------- If you prefer graphical editors, use an editor that works with the design of Mac OS X. [BBEdit](http://www.barebones.com/products/bbedit/) is an excellent editor that will correctly handle editing [root owned files](http://www.barebones.com/support/bbedit/auth-saves.html). When you edit a root owned file with BBEdit, a second process is used to bridge the permissions gap between you and the owner of the file. This process passes through Apple's sanctioned paths and thus ensures a predictable experience - hopefully across multiple major versions of Mac OS X. ### Why? WindowServer Limits and Design Scope There are subtle technical problems with launching a graphical application within another user session. The underlying technical problems stem from one user wanting to launch a graphical process within another user's session. Mac OS X's WindowServer was never designed with this as a goal. User sessions are extremely difficult to break out of even as root user – all for desirable security reasons. Apple has dramatically improved the WindowServer design in the last few major versions of Mac OS X. It is now possible to have multiple users logged into different graphical sessions on one Mac through Screen Sharing. This seemingly simple improvement relied on a huge amount of behind the scenes effort from Apple's engineers. However, Apple is unlikely to provide an easy way to cross launch applications as different users from within a single graphical user session. How would this benefit their customers? If you want to explore this topic further, look for questions involving `launchctl` and running applications in other active user sessions.
Sergei's answer didn't work for me on OS X 10.8.5 `$ sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit /etc/hosts` I got a permissions error message ![ERROR](https://i.stack.imgur.com/XmBsA.png) Since `sudo`ing the binary first, then double-clicking the file in Finder worked, I came up with the following less simple command `$ sudo -b /Applications/TextEdit.app/Contents/MacOS/TextEdit && sleep .5 && open -a /Applications/TextEdit.app /etc/hosts` You can make a function of it like Sergei's, if need be.
26,470,305
I'm writing some test functions for a form I made. There are a couple of QMessageBox that are invoked(one through QMessageBox.question method and one through the QMessageBox.information method. While my custom widget is not shown on screen, these two actually show up on screen. I tried dismissing them by looping through widgets I get in QApplication.topLevelWidgets() and dismissing the right one, however, it seems my code only continues executing after I manually dismiss the MessageBox. So my question is two-fold: 1) How do I keep the QMessageBox (or any widget really) from showing on screen during testing. 2) How can I programmatically accept/reject/dismiss this widget.
2014/10/20
[ "https://Stackoverflow.com/questions/26470305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/868270/" ]
You can set up a timer to automatically accept the dialog. If the timeout is long, the dialog will still display for a while: ``` w = QtGui.QDialog(None) t = QtCore.QTimer(None) t.timeout.connect(w.accept) t.start(1) w.exec_() ``` For your specific case, if you don't want to touch the code being testes, you can have the timer run a function to accept all current modal widgets, as you were suggesting: ``` def accept_all(): for wid in app.topLevelWidgets(): if wid.__class__ == QtGui.QDialog: #or QMessageBox, etc: wid.accept() t = QtCore.QTimer(None) t.timeout.connect(accept_all) t.start(10) ```
I decided to use the mock module instead. It seemed better since the other solution would actually draw on screen, which is not optimal for testing. If you have the same problem and would like to mock a question QMessageBox you can something like this: ``` @patch.object(path.QMessageBox, "question", return_value=QtGui.QMessageBox.Yes) ``` Would simulate a MessageBox in which the Yes button was clicked.
26,470,305
I'm writing some test functions for a form I made. There are a couple of QMessageBox that are invoked(one through QMessageBox.question method and one through the QMessageBox.information method. While my custom widget is not shown on screen, these two actually show up on screen. I tried dismissing them by looping through widgets I get in QApplication.topLevelWidgets() and dismissing the right one, however, it seems my code only continues executing after I manually dismiss the MessageBox. So my question is two-fold: 1) How do I keep the QMessageBox (or any widget really) from showing on screen during testing. 2) How can I programmatically accept/reject/dismiss this widget.
2014/10/20
[ "https://Stackoverflow.com/questions/26470305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/868270/" ]
You can set up a timer to automatically accept the dialog. If the timeout is long, the dialog will still display for a while: ``` w = QtGui.QDialog(None) t = QtCore.QTimer(None) t.timeout.connect(w.accept) t.start(1) w.exec_() ``` For your specific case, if you don't want to touch the code being testes, you can have the timer run a function to accept all current modal widgets, as you were suggesting: ``` def accept_all(): for wid in app.topLevelWidgets(): if wid.__class__ == QtGui.QDialog: #or QMessageBox, etc: wid.accept() t = QtCore.QTimer(None) t.timeout.connect(accept_all) t.start(10) ```
I think it makes sense with Qt testing (including PySide/PyQt) to mock your GUI interaction and do dedicated GUI testing separately as necessary. For mocking GUI interaction, I'd use the [mock](https://pypi.python.org/pypi/mock) library, as I myself do regularly. The drawback of this is that you have to depend on mock definitions, which may drift out of sync with respect to your production application. On the other hand, your tests will be speedier than involving the actual GUI. For testing the GUI itself, I'd write a separate layer of tests using a GUI testing tool such as [Froglogic Squish](http://www.froglogic.com/squish/gui-testing/). It'll typically lead to more involved/slower tests, but you'll test your application directly, and not merely simulate the GUI layer. My approach in this regard is invest in such a tool if the budget allows, and run these tests as necessary keeping in mind they'll be relatively slow.
9,775,150
I have a TreeView control for which each node in it I want to share a ContextMenuStrip which has two ToolStripMenuItems ie: ``` this.BuildTree = new MyApp.MainForm.TreeView(); this.ItemMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.DeleteMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ShowLogMenuItem = new System.Windows.Forms.ToolStripMenuItem(); ... this.ItemMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.DeleteMenuItem, this.ShowLogMenuItem}); ``` So I show and hide these to items according to certain criteria on a right click in a MouseUp event. When both are hidden I hide the ContextMenuStrip itself. Problem is when I hide the ContextMenuStrip it seems the next time I want to show one of the menu items I have to click twice on the node. The strange thing is on the first click to reshow one or both of the the items I have the following code: ``` ItemMenuStrip.Visible = true; ShowLogMenuItem.Visible = true; ``` The two lines above don't seem to do anything ie both remain false in the debugger view after stepping over each line. I don't think I've got any events on these values being set at least I don't have any events attached. What am I doing wrong?
2012/03/19
[ "https://Stackoverflow.com/questions/9775150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/176168/" ]
I suggest you to set: `this.BuildTree.ContextMenuStrip = this.ItemMenuStrip;` to make the menu automatically open on tree right-click. Then subscribe [`ItemMenuStrip.Opening`](http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripdropdown.opening.aspx) event to change the visibility of items and the contextmenu itself: ``` void ItemMenuStrip_Opening(object sender, CancelEventArgs e) { if (something) { e.Cancel = true; // don't show the menu } else { // show/hide the items... } } ``` If you need to know the current position of the clicked point (e.g. to check if a tree node is clicked), you can use [`Control.MousePosition`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mouseposition.aspx) property. Note that `MousePosition` is a point in screen coordinates, so you need to call `treeView1.PointToClient(position)` to get the tree coordinates e.g. : ``` private void ItemMenuStrip_Opening(object sender, CancelEventArgs e) { var pointClicked = this.BuildTree.PointToClient(Control.MousePosition); var nodeClicked = this.BuildTree.GetNodeAt(pointClicked); if (nodeClicked == null) { // no tree-node is clicked --> don't show the context menu e.Cancel = true; } else { // nodeClicked variable is the clicked node; // show/hide the context menu items accordingly } } ```
So figured out what was going wrong I was setting Visible on this.ItemMenuStrip rather than the this.BuildTree.ContextMenuStrip. This seems rather strange to me as I would have thought BuildTree.ContextMenuStrip was just a direct reference to the ItemMenuStrip but apparently not.
25,592,867
I wanted to show a ProgressDialog when data need to be uploaded to the server. I have checked this question [Best way to show a loading/progress indicator?](https://stackoverflow.com/questions/12841803/best-way-to-show-a-loading-spinner) the best answer was ``` ProgressDialog progress = new ProgressDialog(this); progress.setTitle("Loading"); progress.setMessage("Wait while loading..."); progress.show(); // To dismiss the dialog progress.dismiss(); ``` when i tried to implement this in my code, nothing showed at all !! what is that i am doing wrong here?! this is my code ``` private void UpdateData() { ProgressDialog progress = new ProgressDialog(this); progress.setTitle("Loading"); progress.setMessage("Wait while loading..."); progress.show(); try { UpdateWSTask updateWSTask = new UpdateWSTask(); String Resp = updateWSTask.execute().get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } progress.dismiss(); ``` }
2014/08/31
[ "https://Stackoverflow.com/questions/25592867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1492229/" ]
The proper way of showing a `ProgressDialog` with a `AsyncTask` would be by displaying the dialog on the `onPreExecute()` method of the `AsyncTask` and hide it at `onPostExecute()` method of it: ``` private class SampleTask extends AsyncTask<Void, Integer, String> { ProgressDialog progress = new ProgressDialog(YourActivity.this); protected Long doInBackground(Void... urls) { // execute the background task } protected void onPreExecute(){ // show the dialog progress.setTitle("Loading"); progress.setMessage("Wait while loading..."); progress.setIndeterminate(true); progress.show(); } protected void onPostExecute(String result) { progress.hide(); } } ``` Both: onPreExecute() and onPostExecute() run on the main thread, while doInBackground() as the name suggests is executed on the background thread. **Edit:** Within your activity, where you want to call the AsyncTask you just need to execute it: ``` UpdateWSTask updateWSTask = new UpdateWSTask(); updateWSTask.execute(); ```
A better idea would be to do this with AsyncTask class. You can take care of UI work in preExecute and postExecute methods and do your main work in doInBackground method. Nice and clean! It seems that you already doing this. Move the dialog code to the asynctask class. You just need a reference to the context and you can provide it with a constructor for your custom asynctask class
55,391,243
I have created a module in which i am overwriting core functionality of product listing widget. I can achieve this using preference but i want to understand plugin method.. Below is my code for frontend/di.xml ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\CatalogWidget\Block\Product\ProductsList"> <plugin name="widget_product_listing_add_attribute" type="Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin" sortOrder="1"/> </type> </config> ``` and below is my code for plugin block. ``` namespace Test\CatalogWidget\Plugin\Block\Product; class ProductsListAddAttributePlugin { public function beforeCreateCollection(\Magento\CatalogWidget\Block\Product\ProductsList $subject, \Magento\Catalog\Model\ResourceModel\Product\Collection $result) { /** * @var \Magento\CatalogWidget\Block\Product\ProductsList $subject * @var \Magento\Catalog\Model\ResourceModel\Product\Collection $result */ die('ProductsListAddAttributePlugin before....'); } } ``` after installing module and running di:compile.. when i reload the page i am getting below error. > > Fatal error: Uncaught ArgumentCountError: Too few arguments to > function > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin::beforeCreateCollection(), > 1 passed in > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php > on line 121 and exactly 2 expected in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php:6 > Stack trace: #0 > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(121): > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin->beforeCreateCollection(Object(Magento\CatalogWidget\Block\Product\ProductsList\Interceptor)) > > > 1 C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(153): > ============================================================================================ > > > Magento\CatalogWidget\Block\Product\ProductsList\Interceptor->Magento\Framework\Interception{closure}() > > > 2 C:\xampp\htdocs\projects\hello\generated\code\Magento\CatalogWidget\Block\Product\ProductsList\Interceptor.php(26): > ===================================================================================================================== > > > Mag in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php > on line 6 > > >
2019/03/28
[ "https://Stackoverflow.com/questions/55391243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4008990/" ]
You need to add semi-colon after insert method. ``` namespace App\Http\Controllers; use DB; class course_controller extends Controller { public function show_details() { $prospects = DB::table('prospect')->get(); foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); // add semicolon here } // don't need semi-colon here } } ```
You misplaced a semicolon, check here: ``` foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]) }; <-- this one ``` Change it to: ``` foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); } ``` and this is not a great idea to trigger a insert query on every iteration, instead create an array and save it in one query.
55,391,243
I have created a module in which i am overwriting core functionality of product listing widget. I can achieve this using preference but i want to understand plugin method.. Below is my code for frontend/di.xml ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\CatalogWidget\Block\Product\ProductsList"> <plugin name="widget_product_listing_add_attribute" type="Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin" sortOrder="1"/> </type> </config> ``` and below is my code for plugin block. ``` namespace Test\CatalogWidget\Plugin\Block\Product; class ProductsListAddAttributePlugin { public function beforeCreateCollection(\Magento\CatalogWidget\Block\Product\ProductsList $subject, \Magento\Catalog\Model\ResourceModel\Product\Collection $result) { /** * @var \Magento\CatalogWidget\Block\Product\ProductsList $subject * @var \Magento\Catalog\Model\ResourceModel\Product\Collection $result */ die('ProductsListAddAttributePlugin before....'); } } ``` after installing module and running di:compile.. when i reload the page i am getting below error. > > Fatal error: Uncaught ArgumentCountError: Too few arguments to > function > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin::beforeCreateCollection(), > 1 passed in > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php > on line 121 and exactly 2 expected in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php:6 > Stack trace: #0 > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(121): > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin->beforeCreateCollection(Object(Magento\CatalogWidget\Block\Product\ProductsList\Interceptor)) > > > 1 C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(153): > ============================================================================================ > > > Magento\CatalogWidget\Block\Product\ProductsList\Interceptor->Magento\Framework\Interception{closure}() > > > 2 C:\xampp\htdocs\projects\hello\generated\code\Magento\CatalogWidget\Block\Product\ProductsList\Interceptor.php(26): > ===================================================================================================================== > > > Mag in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php > on line 6 > > >
2019/03/28
[ "https://Stackoverflow.com/questions/55391243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4008990/" ]
You need to add semi-colon after insert method. ``` namespace App\Http\Controllers; use DB; class course_controller extends Controller { public function show_details() { $prospects = DB::table('prospect')->get(); foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); // add semicolon here } // don't need semi-colon here } } ```
``` public function show_details() { $prospects = DB::table('prospect')->get(); foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); //Add semicolon here } } ```
55,391,243
I have created a module in which i am overwriting core functionality of product listing widget. I can achieve this using preference but i want to understand plugin method.. Below is my code for frontend/di.xml ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\CatalogWidget\Block\Product\ProductsList"> <plugin name="widget_product_listing_add_attribute" type="Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin" sortOrder="1"/> </type> </config> ``` and below is my code for plugin block. ``` namespace Test\CatalogWidget\Plugin\Block\Product; class ProductsListAddAttributePlugin { public function beforeCreateCollection(\Magento\CatalogWidget\Block\Product\ProductsList $subject, \Magento\Catalog\Model\ResourceModel\Product\Collection $result) { /** * @var \Magento\CatalogWidget\Block\Product\ProductsList $subject * @var \Magento\Catalog\Model\ResourceModel\Product\Collection $result */ die('ProductsListAddAttributePlugin before....'); } } ``` after installing module and running di:compile.. when i reload the page i am getting below error. > > Fatal error: Uncaught ArgumentCountError: Too few arguments to > function > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin::beforeCreateCollection(), > 1 passed in > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php > on line 121 and exactly 2 expected in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php:6 > Stack trace: #0 > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(121): > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin->beforeCreateCollection(Object(Magento\CatalogWidget\Block\Product\ProductsList\Interceptor)) > > > 1 C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(153): > ============================================================================================ > > > Magento\CatalogWidget\Block\Product\ProductsList\Interceptor->Magento\Framework\Interception{closure}() > > > 2 C:\xampp\htdocs\projects\hello\generated\code\Magento\CatalogWidget\Block\Product\ProductsList\Interceptor.php(26): > ===================================================================================================================== > > > Mag in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php > on line 6 > > >
2019/03/28
[ "https://Stackoverflow.com/questions/55391243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4008990/" ]
You need to add semi-colon after insert method. ``` namespace App\Http\Controllers; use DB; class course_controller extends Controller { public function show_details() { $prospects = DB::table('prospect')->get(); foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); // add semicolon here } // don't need semi-colon here } } ```
``` foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(array('prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested)); } ```
55,391,243
I have created a module in which i am overwriting core functionality of product listing widget. I can achieve this using preference but i want to understand plugin method.. Below is my code for frontend/di.xml ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\CatalogWidget\Block\Product\ProductsList"> <plugin name="widget_product_listing_add_attribute" type="Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin" sortOrder="1"/> </type> </config> ``` and below is my code for plugin block. ``` namespace Test\CatalogWidget\Plugin\Block\Product; class ProductsListAddAttributePlugin { public function beforeCreateCollection(\Magento\CatalogWidget\Block\Product\ProductsList $subject, \Magento\Catalog\Model\ResourceModel\Product\Collection $result) { /** * @var \Magento\CatalogWidget\Block\Product\ProductsList $subject * @var \Magento\Catalog\Model\ResourceModel\Product\Collection $result */ die('ProductsListAddAttributePlugin before....'); } } ``` after installing module and running di:compile.. when i reload the page i am getting below error. > > Fatal error: Uncaught ArgumentCountError: Too few arguments to > function > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin::beforeCreateCollection(), > 1 passed in > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php > on line 121 and exactly 2 expected in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php:6 > Stack trace: #0 > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(121): > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin->beforeCreateCollection(Object(Magento\CatalogWidget\Block\Product\ProductsList\Interceptor)) > > > 1 C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(153): > ============================================================================================ > > > Magento\CatalogWidget\Block\Product\ProductsList\Interceptor->Magento\Framework\Interception{closure}() > > > 2 C:\xampp\htdocs\projects\hello\generated\code\Magento\CatalogWidget\Block\Product\ProductsList\Interceptor.php(26): > ===================================================================================================================== > > > Mag in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php > on line 6 > > >
2019/03/28
[ "https://Stackoverflow.com/questions/55391243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4008990/" ]
You need to add semi-colon after insert method. ``` namespace App\Http\Controllers; use DB; class course_controller extends Controller { public function show_details() { $prospects = DB::table('prospect')->get(); foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); // add semicolon here } // don't need semi-colon here } } ```
The semicolon(`;`) is missing in your `insert` Query: ``` foreach ($prospects as $prospect){ DB::table('course_prospect')->insert([ 'prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested ]); //You missed the semicolon here } //remove semicolon from here ``` The syntax for [insert method](https://laravel.com/docs/5.8/queries#inserts) for inserting records into the database The Syntax for foreach: ``` foreach($prospects as $prospect){ } ```
55,391,243
I have created a module in which i am overwriting core functionality of product listing widget. I can achieve this using preference but i want to understand plugin method.. Below is my code for frontend/di.xml ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\CatalogWidget\Block\Product\ProductsList"> <plugin name="widget_product_listing_add_attribute" type="Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin" sortOrder="1"/> </type> </config> ``` and below is my code for plugin block. ``` namespace Test\CatalogWidget\Plugin\Block\Product; class ProductsListAddAttributePlugin { public function beforeCreateCollection(\Magento\CatalogWidget\Block\Product\ProductsList $subject, \Magento\Catalog\Model\ResourceModel\Product\Collection $result) { /** * @var \Magento\CatalogWidget\Block\Product\ProductsList $subject * @var \Magento\Catalog\Model\ResourceModel\Product\Collection $result */ die('ProductsListAddAttributePlugin before....'); } } ``` after installing module and running di:compile.. when i reload the page i am getting below error. > > Fatal error: Uncaught ArgumentCountError: Too few arguments to > function > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin::beforeCreateCollection(), > 1 passed in > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php > on line 121 and exactly 2 expected in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php:6 > Stack trace: #0 > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(121): > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin->beforeCreateCollection(Object(Magento\CatalogWidget\Block\Product\ProductsList\Interceptor)) > > > 1 C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(153): > ============================================================================================ > > > Magento\CatalogWidget\Block\Product\ProductsList\Interceptor->Magento\Framework\Interception{closure}() > > > 2 C:\xampp\htdocs\projects\hello\generated\code\Magento\CatalogWidget\Block\Product\ProductsList\Interceptor.php(26): > ===================================================================================================================== > > > Mag in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php > on line 6 > > >
2019/03/28
[ "https://Stackoverflow.com/questions/55391243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4008990/" ]
You need to add semi-colon after insert method. ``` namespace App\Http\Controllers; use DB; class course_controller extends Controller { public function show_details() { $prospects = DB::table('prospect')->get(); foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); // add semicolon here } // don't need semi-colon here } } ```
You've misplaced the `;` and that caused the issue And also I'm recommending you to use the associated model instead of `DB` just like below ``` use App/Prospect; use App/CourseProspect; class course_controller extends Controller { public function show_details() { $prospects = Prospect::all(); foreach ($prospects as $prospect) { CourseProspect::create([['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]]); }; } } ```
55,391,243
I have created a module in which i am overwriting core functionality of product listing widget. I can achieve this using preference but i want to understand plugin method.. Below is my code for frontend/di.xml ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\CatalogWidget\Block\Product\ProductsList"> <plugin name="widget_product_listing_add_attribute" type="Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin" sortOrder="1"/> </type> </config> ``` and below is my code for plugin block. ``` namespace Test\CatalogWidget\Plugin\Block\Product; class ProductsListAddAttributePlugin { public function beforeCreateCollection(\Magento\CatalogWidget\Block\Product\ProductsList $subject, \Magento\Catalog\Model\ResourceModel\Product\Collection $result) { /** * @var \Magento\CatalogWidget\Block\Product\ProductsList $subject * @var \Magento\Catalog\Model\ResourceModel\Product\Collection $result */ die('ProductsListAddAttributePlugin before....'); } } ``` after installing module and running di:compile.. when i reload the page i am getting below error. > > Fatal error: Uncaught ArgumentCountError: Too few arguments to > function > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin::beforeCreateCollection(), > 1 passed in > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php > on line 121 and exactly 2 expected in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php:6 > Stack trace: #0 > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(121): > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin->beforeCreateCollection(Object(Magento\CatalogWidget\Block\Product\ProductsList\Interceptor)) > > > 1 C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(153): > ============================================================================================ > > > Magento\CatalogWidget\Block\Product\ProductsList\Interceptor->Magento\Framework\Interception{closure}() > > > 2 C:\xampp\htdocs\projects\hello\generated\code\Magento\CatalogWidget\Block\Product\ProductsList\Interceptor.php(26): > ===================================================================================================================== > > > Mag in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php > on line 6 > > >
2019/03/28
[ "https://Stackoverflow.com/questions/55391243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4008990/" ]
``` public function show_details() { $prospects = DB::table('prospect')->get(); foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); //Add semicolon here } } ```
You misplaced a semicolon, check here: ``` foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]) }; <-- this one ``` Change it to: ``` foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); } ``` and this is not a great idea to trigger a insert query on every iteration, instead create an array and save it in one query.
55,391,243
I have created a module in which i am overwriting core functionality of product listing widget. I can achieve this using preference but i want to understand plugin method.. Below is my code for frontend/di.xml ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\CatalogWidget\Block\Product\ProductsList"> <plugin name="widget_product_listing_add_attribute" type="Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin" sortOrder="1"/> </type> </config> ``` and below is my code for plugin block. ``` namespace Test\CatalogWidget\Plugin\Block\Product; class ProductsListAddAttributePlugin { public function beforeCreateCollection(\Magento\CatalogWidget\Block\Product\ProductsList $subject, \Magento\Catalog\Model\ResourceModel\Product\Collection $result) { /** * @var \Magento\CatalogWidget\Block\Product\ProductsList $subject * @var \Magento\Catalog\Model\ResourceModel\Product\Collection $result */ die('ProductsListAddAttributePlugin before....'); } } ``` after installing module and running di:compile.. when i reload the page i am getting below error. > > Fatal error: Uncaught ArgumentCountError: Too few arguments to > function > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin::beforeCreateCollection(), > 1 passed in > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php > on line 121 and exactly 2 expected in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php:6 > Stack trace: #0 > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(121): > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin->beforeCreateCollection(Object(Magento\CatalogWidget\Block\Product\ProductsList\Interceptor)) > > > 1 C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(153): > ============================================================================================ > > > Magento\CatalogWidget\Block\Product\ProductsList\Interceptor->Magento\Framework\Interception{closure}() > > > 2 C:\xampp\htdocs\projects\hello\generated\code\Magento\CatalogWidget\Block\Product\ProductsList\Interceptor.php(26): > ===================================================================================================================== > > > Mag in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php > on line 6 > > >
2019/03/28
[ "https://Stackoverflow.com/questions/55391243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4008990/" ]
``` public function show_details() { $prospects = DB::table('prospect')->get(); foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); //Add semicolon here } } ```
``` foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(array('prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested)); } ```
55,391,243
I have created a module in which i am overwriting core functionality of product listing widget. I can achieve this using preference but i want to understand plugin method.. Below is my code for frontend/di.xml ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\CatalogWidget\Block\Product\ProductsList"> <plugin name="widget_product_listing_add_attribute" type="Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin" sortOrder="1"/> </type> </config> ``` and below is my code for plugin block. ``` namespace Test\CatalogWidget\Plugin\Block\Product; class ProductsListAddAttributePlugin { public function beforeCreateCollection(\Magento\CatalogWidget\Block\Product\ProductsList $subject, \Magento\Catalog\Model\ResourceModel\Product\Collection $result) { /** * @var \Magento\CatalogWidget\Block\Product\ProductsList $subject * @var \Magento\Catalog\Model\ResourceModel\Product\Collection $result */ die('ProductsListAddAttributePlugin before....'); } } ``` after installing module and running di:compile.. when i reload the page i am getting below error. > > Fatal error: Uncaught ArgumentCountError: Too few arguments to > function > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin::beforeCreateCollection(), > 1 passed in > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php > on line 121 and exactly 2 expected in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php:6 > Stack trace: #0 > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(121): > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin->beforeCreateCollection(Object(Magento\CatalogWidget\Block\Product\ProductsList\Interceptor)) > > > 1 C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(153): > ============================================================================================ > > > Magento\CatalogWidget\Block\Product\ProductsList\Interceptor->Magento\Framework\Interception{closure}() > > > 2 C:\xampp\htdocs\projects\hello\generated\code\Magento\CatalogWidget\Block\Product\ProductsList\Interceptor.php(26): > ===================================================================================================================== > > > Mag in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php > on line 6 > > >
2019/03/28
[ "https://Stackoverflow.com/questions/55391243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4008990/" ]
``` public function show_details() { $prospects = DB::table('prospect')->get(); foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); //Add semicolon here } } ```
The semicolon(`;`) is missing in your `insert` Query: ``` foreach ($prospects as $prospect){ DB::table('course_prospect')->insert([ 'prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested ]); //You missed the semicolon here } //remove semicolon from here ``` The syntax for [insert method](https://laravel.com/docs/5.8/queries#inserts) for inserting records into the database The Syntax for foreach: ``` foreach($prospects as $prospect){ } ```
55,391,243
I have created a module in which i am overwriting core functionality of product listing widget. I can achieve this using preference but i want to understand plugin method.. Below is my code for frontend/di.xml ``` <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\CatalogWidget\Block\Product\ProductsList"> <plugin name="widget_product_listing_add_attribute" type="Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin" sortOrder="1"/> </type> </config> ``` and below is my code for plugin block. ``` namespace Test\CatalogWidget\Plugin\Block\Product; class ProductsListAddAttributePlugin { public function beforeCreateCollection(\Magento\CatalogWidget\Block\Product\ProductsList $subject, \Magento\Catalog\Model\ResourceModel\Product\Collection $result) { /** * @var \Magento\CatalogWidget\Block\Product\ProductsList $subject * @var \Magento\Catalog\Model\ResourceModel\Product\Collection $result */ die('ProductsListAddAttributePlugin before....'); } } ``` after installing module and running di:compile.. when i reload the page i am getting below error. > > Fatal error: Uncaught ArgumentCountError: Too few arguments to > function > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin::beforeCreateCollection(), > 1 passed in > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php > on line 121 and exactly 2 expected in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php:6 > Stack trace: #0 > C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(121): > Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin->beforeCreateCollection(Object(Magento\CatalogWidget\Block\Product\ProductsList\Interceptor)) > > > 1 C:\xampp\htdocs\projects\hello\vendor\magento\framework\Interception\Interceptor.php(153): > ============================================================================================ > > > Magento\CatalogWidget\Block\Product\ProductsList\Interceptor->Magento\Framework\Interception{closure}() > > > 2 C:\xampp\htdocs\projects\hello\generated\code\Magento\CatalogWidget\Block\Product\ProductsList\Interceptor.php(26): > ===================================================================================================================== > > > Mag in > C:\xampp\htdocs\projects\hello\app\code\Test\CatalogWidget\Plugin\Block\Product\ProductsListAddAttributePlugin.php > on line 6 > > >
2019/03/28
[ "https://Stackoverflow.com/questions/55391243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4008990/" ]
``` public function show_details() { $prospects = DB::table('prospect')->get(); foreach ($prospects as $prospect) { DB::table('course_prospect')->insert(['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]); //Add semicolon here } } ```
You've misplaced the `;` and that caused the issue And also I'm recommending you to use the associated model instead of `DB` just like below ``` use App/Prospect; use App/CourseProspect; class course_controller extends Controller { public function show_details() { $prospects = Prospect::all(); foreach ($prospects as $prospect) { CourseProspect::create([['prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested]]); }; } } ```
54,162,010
Would the following two `np.dot` give the same result for a square array `x`? ``` import numpy as np x = np.arange(4 * 4).reshape(4, 4) np.dot(x, x.T, out=x) # method 1 x[:] = np.dot(x, x.T) # method 2 ``` Thanks. Why I ask: `x += x.T` is not the same as `x += x.T.copy()` I don't know how does the internal of np.dot work. Does np.dot similarly treat the out argument as a view? is it ok if out is one of the matrices to be multiplied? The numpy that I am using is from anaconda, which is using mkl as a backend.
2019/01/12
[ "https://Stackoverflow.com/questions/54162010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8704463/" ]
Yes, they are the same, but performance wise I see interesting results for integer arrays: ``` import perfplot def f1(x): x = x.copy() np.dot(x, x.T, out=x) return x def f2(x): x = x.copy() x[:] = np.dot(x, x.T) return x perfplot.show( setup=lambda n: np.arange(n * n).reshape(n, n), kernels=[f1, f2], labels=['out=...', 're-assignment'], n_range=[2**k for k in range(0, 9)], xlabel='N', equality_check=np.allclose ) ``` [![enter image description here](https://i.stack.imgur.com/MTuHQ.png)](https://i.stack.imgur.com/MTuHQ.png) I've used [`perfplot`](https://github.com/nschloe/perfplot) to generate plot timings. --- For float arrays, there is absolutely no difference. ``` perfplot.show( setup=lambda n: np.arange(n * n).reshape(n, n).astype(float), kernels=[f1, f2], labels=['out=...', 're-assignment'], n_range=[2**k for k in range(0, 9)], xlabel='N', equality_check=np.allclose ) ``` [![enter image description here](https://i.stack.imgur.com/ioBbE.png)](https://i.stack.imgur.com/ioBbE.png)
Yes, both methods produce identical arrays. ``` import numpy as np def method_1(): x = np.arange(4 * 4).reshape(4, 4) np.dot(x, x.T, out=x) return x def method_2(): x = np.arange(4 * 4).reshape(4, 4) x[:] = np.dot(x, x.T) return x array_1 = method_1() array_2 = method_2() print(np.array_equal(array_1, array_2)) ``` gives the output: > > True > > >
54,162,010
Would the following two `np.dot` give the same result for a square array `x`? ``` import numpy as np x = np.arange(4 * 4).reshape(4, 4) np.dot(x, x.T, out=x) # method 1 x[:] = np.dot(x, x.T) # method 2 ``` Thanks. Why I ask: `x += x.T` is not the same as `x += x.T.copy()` I don't know how does the internal of np.dot work. Does np.dot similarly treat the out argument as a view? is it ok if out is one of the matrices to be multiplied? The numpy that I am using is from anaconda, which is using mkl as a backend.
2019/01/12
[ "https://Stackoverflow.com/questions/54162010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8704463/" ]
Yes, they are the same, but performance wise I see interesting results for integer arrays: ``` import perfplot def f1(x): x = x.copy() np.dot(x, x.T, out=x) return x def f2(x): x = x.copy() x[:] = np.dot(x, x.T) return x perfplot.show( setup=lambda n: np.arange(n * n).reshape(n, n), kernels=[f1, f2], labels=['out=...', 're-assignment'], n_range=[2**k for k in range(0, 9)], xlabel='N', equality_check=np.allclose ) ``` [![enter image description here](https://i.stack.imgur.com/MTuHQ.png)](https://i.stack.imgur.com/MTuHQ.png) I've used [`perfplot`](https://github.com/nschloe/perfplot) to generate plot timings. --- For float arrays, there is absolutely no difference. ``` perfplot.show( setup=lambda n: np.arange(n * n).reshape(n, n).astype(float), kernels=[f1, f2], labels=['out=...', 're-assignment'], n_range=[2**k for k in range(0, 9)], xlabel='N', equality_check=np.allclose ) ``` [![enter image description here](https://i.stack.imgur.com/ioBbE.png)](https://i.stack.imgur.com/ioBbE.png)
I have an older version of numpy installed (1.11.0) where method #1 produces some weird output. I understand this is not the expected behavior, and was fixed in later versions; but just in case this happens to someone else: ``` Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 >>> import numpy as np >>> x = np.arange(4 * 4).reshape(4, 4) >>> np.dot(x, x.T, out=x) array([[ 14, 94, 1011, 15589], [ 115715, 13389961335, 120510577872, 1861218976248], [ 182547, 21820147595568, 1728119013671256390, 5747205779608970957], [ 249379, 29808359122268, 7151350849816304816, -3559891853923251270]]) >>> np.version.version '1.11.0' ``` As far as I can test, at least since numpy 1.14.1 the method #1 gives the expected output; as the method #2 does with both versions.
188,383
Just want to check. What is the limit of function $\frac{z}{\bar{z}-z}$ at $z=0$? I got $\lim\_{\substack{z \to 0 \\ z \in \mathbb{R}}} \frac{z}{\overline{z}-z} =-\infty$ and $\lim\_{\substack{z \to 0 \\ z \in i\mathbb{R}}} \frac{z}{\overline{z}-z} =-\frac{1}{2}$, so $f$ is not defined at $z=0$? Byt the way does this have any singularities? And finally is this analytic in unit circle?
2012/08/29
[ "https://math.stackexchange.com/questions/188383", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
To solve the equation $$z\bar{z}+z+\bar{z}+iz-\overline{iz}=9+4i,$$ we can proceed much as you did. Let $z=a+ib$. Then $z\bar{z}=(a+ib)(a-ib)=a^2+b^2$. We have $iz=-b+ia$, so its conjugate is $-b-ia$. Our expression is therefore equal to $$a^2+b^2+(a+ib)+(a-ib)+(-b+ia)-(-b-ia),$$ which simplifies to $a^2+b^2+2a+2ia$. This is $9+4i$ precisely if the imaginary parts match **and** the real parts match. We end up with the equations $2a=4$ and $a^2+b^2+2a=9$. Now $a$ and then $b$ are easy to find.
Alternative approach: the real part of both hands must be equal: $$z\bar z + z+\bar z = 9.$$ The imaginary part of both hands must be equal: $$i(z+\bar z)=4i.$$ So $z$ and $\bar z$ are two numbers; their sum is $4$ and their product is $9-4=5$. So they satisfy $$ z^2 - 4z + 5 = 0.$$ This you can solve.
4,195,609
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the `AsyncTask`. In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an `AsyncTask` if Yes is clicked. My question is how to pass an `ArrayList<String>` to the `AsyncTask` (and work with it there), and how to get back a new `ArrayList<String>` like a result from the `AsyncTask`? The code of the method looks like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); ArrayList<String> result = new ArrayList<String>(); new calc_stanica().execute(passing,result); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); ``` So, as you see, I would like to send the string array list "passing" to the `AsyncTask`, and to get the "result" string array list back from it. And the calc\_stanica `AssycTask` class looks like this: ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { //Some calculations... return something; //??? } protected void onPostExecute(Void unused) { dialog.dismiss(); } ``` So my question is how to get the elements of the "passing" array list in the `AsyncTask doInBackground` method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
2010/11/16
[ "https://Stackoverflow.com/questions/4195609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509666/" ]
Change your method to look like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); new calc_stanica().execute(passing); //no need to pass in result list ``` And change your async task implementation ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { ArrayList<String> result = new ArrayList<String>(); ArrayList<String> passed = passing[0]; //get passed arraylist //Some calculations... return result; //return result } protected void onPostExecute(ArrayList<String> result) { dialog.dismiss(); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); } ``` UPD: If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place: ``` new calc_stanica() { protected void onPostExecute(ArrayList<String> result) { // here you have access to the context in which execute was called in first place. // You'll have to mark all the local variables final though.. } }.execute(passing); ```
Why would you pass an ArrayList?? It should be possible to just call execute with the params directly: ``` String curloc = current.toString(); String itemdesc = item.mDescription; new calc_stanica().execute(itemdesc, curloc) ``` That how varrargs work, right? Making an ArrayList to pass the variable is double work.
4,195,609
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the `AsyncTask`. In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an `AsyncTask` if Yes is clicked. My question is how to pass an `ArrayList<String>` to the `AsyncTask` (and work with it there), and how to get back a new `ArrayList<String>` like a result from the `AsyncTask`? The code of the method looks like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); ArrayList<String> result = new ArrayList<String>(); new calc_stanica().execute(passing,result); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); ``` So, as you see, I would like to send the string array list "passing" to the `AsyncTask`, and to get the "result" string array list back from it. And the calc\_stanica `AssycTask` class looks like this: ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { //Some calculations... return something; //??? } protected void onPostExecute(Void unused) { dialog.dismiss(); } ``` So my question is how to get the elements of the "passing" array list in the `AsyncTask doInBackground` method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
2010/11/16
[ "https://Stackoverflow.com/questions/4195609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509666/" ]
Change your method to look like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); new calc_stanica().execute(passing); //no need to pass in result list ``` And change your async task implementation ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { ArrayList<String> result = new ArrayList<String>(); ArrayList<String> passed = passing[0]; //get passed arraylist //Some calculations... return result; //return result } protected void onPostExecute(ArrayList<String> result) { dialog.dismiss(); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); } ``` UPD: If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place: ``` new calc_stanica() { protected void onPostExecute(ArrayList<String> result) { // here you have access to the context in which execute was called in first place. // You'll have to mark all the local variables final though.. } }.execute(passing); ```
I sort of agree with leander on this one. call: ``` new calc_stanica().execute(stringList.toArray(new String[stringList.size()])); ``` task: ``` public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> { @Override protected ArrayList<String> doInBackground(String... args) { ... } @Override protected void onPostExecute(ArrayList<String> result) { ... //do something with the result list here } } ``` Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure); ``` public class calc_stanica extends AsyncTask<String, Void, Boolean> { private List<String> resultList; @Override protected boolean doInBackground(String... args) { ... } @Override protected void onPostExecute(boolean success) { ... //if successfull, do something with the result list here } } ```
4,195,609
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the `AsyncTask`. In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an `AsyncTask` if Yes is clicked. My question is how to pass an `ArrayList<String>` to the `AsyncTask` (and work with it there), and how to get back a new `ArrayList<String>` like a result from the `AsyncTask`? The code of the method looks like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); ArrayList<String> result = new ArrayList<String>(); new calc_stanica().execute(passing,result); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); ``` So, as you see, I would like to send the string array list "passing" to the `AsyncTask`, and to get the "result" string array list back from it. And the calc\_stanica `AssycTask` class looks like this: ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { //Some calculations... return something; //??? } protected void onPostExecute(Void unused) { dialog.dismiss(); } ``` So my question is how to get the elements of the "passing" array list in the `AsyncTask doInBackground` method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
2010/11/16
[ "https://Stackoverflow.com/questions/4195609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509666/" ]
Change your method to look like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); new calc_stanica().execute(passing); //no need to pass in result list ``` And change your async task implementation ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { ArrayList<String> result = new ArrayList<String>(); ArrayList<String> passed = passing[0]; //get passed arraylist //Some calculations... return result; //return result } protected void onPostExecute(ArrayList<String> result) { dialog.dismiss(); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); } ``` UPD: If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place: ``` new calc_stanica() { protected void onPostExecute(ArrayList<String> result) { // here you have access to the context in which execute was called in first place. // You'll have to mark all the local variables final though.. } }.execute(passing); ```
I dont do it like this. I find it easier to overload the constructor of the asychtask class .. public class calc\_stanica extends AsyncTask> ``` String String mWhateveryouwantToPass; public calc_stanica( String whateveryouwantToPass) { this.String mWhateveryouwantToPass = String whateveryouwantToPass; } /*Now you can use whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/ ... ... ```
4,195,609
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the `AsyncTask`. In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an `AsyncTask` if Yes is clicked. My question is how to pass an `ArrayList<String>` to the `AsyncTask` (and work with it there), and how to get back a new `ArrayList<String>` like a result from the `AsyncTask`? The code of the method looks like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); ArrayList<String> result = new ArrayList<String>(); new calc_stanica().execute(passing,result); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); ``` So, as you see, I would like to send the string array list "passing" to the `AsyncTask`, and to get the "result" string array list back from it. And the calc\_stanica `AssycTask` class looks like this: ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { //Some calculations... return something; //??? } protected void onPostExecute(Void unused) { dialog.dismiss(); } ``` So my question is how to get the elements of the "passing" array list in the `AsyncTask doInBackground` method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
2010/11/16
[ "https://Stackoverflow.com/questions/4195609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509666/" ]
Change your method to look like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); new calc_stanica().execute(passing); //no need to pass in result list ``` And change your async task implementation ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { ArrayList<String> result = new ArrayList<String>(); ArrayList<String> passed = passing[0]; //get passed arraylist //Some calculations... return result; //return result } protected void onPostExecute(ArrayList<String> result) { dialog.dismiss(); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); } ``` UPD: If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place: ``` new calc_stanica() { protected void onPostExecute(ArrayList<String> result) { // here you have access to the context in which execute was called in first place. // You'll have to mark all the local variables final though.. } }.execute(passing); ```
You can receive returning results like that: `AsyncTask` class ```java @Override protected Boolean doInBackground(Void... params) { if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) { try { throw new SQLException("Database credentials missing"); } catch (SQLException e) { e.printStackTrace(); } } try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass); } catch (SQLException e) { e.printStackTrace(); } return true; } ``` receiving class: ```java _store.execute(); boolean result =_store.get(); ``` Hoping it will help.
4,195,609
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the `AsyncTask`. In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an `AsyncTask` if Yes is clicked. My question is how to pass an `ArrayList<String>` to the `AsyncTask` (and work with it there), and how to get back a new `ArrayList<String>` like a result from the `AsyncTask`? The code of the method looks like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); ArrayList<String> result = new ArrayList<String>(); new calc_stanica().execute(passing,result); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); ``` So, as you see, I would like to send the string array list "passing" to the `AsyncTask`, and to get the "result" string array list back from it. And the calc\_stanica `AssycTask` class looks like this: ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { //Some calculations... return something; //??? } protected void onPostExecute(Void unused) { dialog.dismiss(); } ``` So my question is how to get the elements of the "passing" array list in the `AsyncTask doInBackground` method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
2010/11/16
[ "https://Stackoverflow.com/questions/4195609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509666/" ]
Why would you pass an ArrayList?? It should be possible to just call execute with the params directly: ``` String curloc = current.toString(); String itemdesc = item.mDescription; new calc_stanica().execute(itemdesc, curloc) ``` That how varrargs work, right? Making an ArrayList to pass the variable is double work.
I sort of agree with leander on this one. call: ``` new calc_stanica().execute(stringList.toArray(new String[stringList.size()])); ``` task: ``` public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> { @Override protected ArrayList<String> doInBackground(String... args) { ... } @Override protected void onPostExecute(ArrayList<String> result) { ... //do something with the result list here } } ``` Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure); ``` public class calc_stanica extends AsyncTask<String, Void, Boolean> { private List<String> resultList; @Override protected boolean doInBackground(String... args) { ... } @Override protected void onPostExecute(boolean success) { ... //if successfull, do something with the result list here } } ```
4,195,609
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the `AsyncTask`. In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an `AsyncTask` if Yes is clicked. My question is how to pass an `ArrayList<String>` to the `AsyncTask` (and work with it there), and how to get back a new `ArrayList<String>` like a result from the `AsyncTask`? The code of the method looks like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); ArrayList<String> result = new ArrayList<String>(); new calc_stanica().execute(passing,result); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); ``` So, as you see, I would like to send the string array list "passing" to the `AsyncTask`, and to get the "result" string array list back from it. And the calc\_stanica `AssycTask` class looks like this: ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { //Some calculations... return something; //??? } protected void onPostExecute(Void unused) { dialog.dismiss(); } ``` So my question is how to get the elements of the "passing" array list in the `AsyncTask doInBackground` method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
2010/11/16
[ "https://Stackoverflow.com/questions/4195609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509666/" ]
Why would you pass an ArrayList?? It should be possible to just call execute with the params directly: ``` String curloc = current.toString(); String itemdesc = item.mDescription; new calc_stanica().execute(itemdesc, curloc) ``` That how varrargs work, right? Making an ArrayList to pass the variable is double work.
I dont do it like this. I find it easier to overload the constructor of the asychtask class .. public class calc\_stanica extends AsyncTask> ``` String String mWhateveryouwantToPass; public calc_stanica( String whateveryouwantToPass) { this.String mWhateveryouwantToPass = String whateveryouwantToPass; } /*Now you can use whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/ ... ... ```
4,195,609
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the `AsyncTask`. In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an `AsyncTask` if Yes is clicked. My question is how to pass an `ArrayList<String>` to the `AsyncTask` (and work with it there), and how to get back a new `ArrayList<String>` like a result from the `AsyncTask`? The code of the method looks like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); ArrayList<String> result = new ArrayList<String>(); new calc_stanica().execute(passing,result); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); ``` So, as you see, I would like to send the string array list "passing" to the `AsyncTask`, and to get the "result" string array list back from it. And the calc\_stanica `AssycTask` class looks like this: ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { //Some calculations... return something; //??? } protected void onPostExecute(Void unused) { dialog.dismiss(); } ``` So my question is how to get the elements of the "passing" array list in the `AsyncTask doInBackground` method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
2010/11/16
[ "https://Stackoverflow.com/questions/4195609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509666/" ]
Why would you pass an ArrayList?? It should be possible to just call execute with the params directly: ``` String curloc = current.toString(); String itemdesc = item.mDescription; new calc_stanica().execute(itemdesc, curloc) ``` That how varrargs work, right? Making an ArrayList to pass the variable is double work.
You can receive returning results like that: `AsyncTask` class ```java @Override protected Boolean doInBackground(Void... params) { if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) { try { throw new SQLException("Database credentials missing"); } catch (SQLException e) { e.printStackTrace(); } } try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass); } catch (SQLException e) { e.printStackTrace(); } return true; } ``` receiving class: ```java _store.execute(); boolean result =_store.get(); ``` Hoping it will help.
4,195,609
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the `AsyncTask`. In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an `AsyncTask` if Yes is clicked. My question is how to pass an `ArrayList<String>` to the `AsyncTask` (and work with it there), and how to get back a new `ArrayList<String>` like a result from the `AsyncTask`? The code of the method looks like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); ArrayList<String> result = new ArrayList<String>(); new calc_stanica().execute(passing,result); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); ``` So, as you see, I would like to send the string array list "passing" to the `AsyncTask`, and to get the "result" string array list back from it. And the calc\_stanica `AssycTask` class looks like this: ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { //Some calculations... return something; //??? } protected void onPostExecute(Void unused) { dialog.dismiss(); } ``` So my question is how to get the elements of the "passing" array list in the `AsyncTask doInBackground` method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
2010/11/16
[ "https://Stackoverflow.com/questions/4195609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509666/" ]
I sort of agree with leander on this one. call: ``` new calc_stanica().execute(stringList.toArray(new String[stringList.size()])); ``` task: ``` public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> { @Override protected ArrayList<String> doInBackground(String... args) { ... } @Override protected void onPostExecute(ArrayList<String> result) { ... //do something with the result list here } } ``` Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure); ``` public class calc_stanica extends AsyncTask<String, Void, Boolean> { private List<String> resultList; @Override protected boolean doInBackground(String... args) { ... } @Override protected void onPostExecute(boolean success) { ... //if successfull, do something with the result list here } } ```
I dont do it like this. I find it easier to overload the constructor of the asychtask class .. public class calc\_stanica extends AsyncTask> ``` String String mWhateveryouwantToPass; public calc_stanica( String whateveryouwantToPass) { this.String mWhateveryouwantToPass = String whateveryouwantToPass; } /*Now you can use whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/ ... ... ```
4,195,609
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the `AsyncTask`. In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an `AsyncTask` if Yes is clicked. My question is how to pass an `ArrayList<String>` to the `AsyncTask` (and work with it there), and how to get back a new `ArrayList<String>` like a result from the `AsyncTask`? The code of the method looks like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); ArrayList<String> result = new ArrayList<String>(); new calc_stanica().execute(passing,result); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); ``` So, as you see, I would like to send the string array list "passing" to the `AsyncTask`, and to get the "result" string array list back from it. And the calc\_stanica `AssycTask` class looks like this: ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { //Some calculations... return something; //??? } protected void onPostExecute(Void unused) { dialog.dismiss(); } ``` So my question is how to get the elements of the "passing" array list in the `AsyncTask doInBackground` method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
2010/11/16
[ "https://Stackoverflow.com/questions/4195609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509666/" ]
I sort of agree with leander on this one. call: ``` new calc_stanica().execute(stringList.toArray(new String[stringList.size()])); ``` task: ``` public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> { @Override protected ArrayList<String> doInBackground(String... args) { ... } @Override protected void onPostExecute(ArrayList<String> result) { ... //do something with the result list here } } ``` Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure); ``` public class calc_stanica extends AsyncTask<String, Void, Boolean> { private List<String> resultList; @Override protected boolean doInBackground(String... args) { ... } @Override protected void onPostExecute(boolean success) { ... //if successfull, do something with the result list here } } ```
You can receive returning results like that: `AsyncTask` class ```java @Override protected Boolean doInBackground(Void... params) { if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) { try { throw new SQLException("Database credentials missing"); } catch (SQLException e) { e.printStackTrace(); } } try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass); } catch (SQLException e) { e.printStackTrace(); } return true; } ``` receiving class: ```java _store.execute(); boolean result =_store.get(); ``` Hoping it will help.
4,195,609
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the `AsyncTask`. In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an `AsyncTask` if Yes is clicked. My question is how to pass an `ArrayList<String>` to the `AsyncTask` (and work with it there), and how to get back a new `ArrayList<String>` like a result from the `AsyncTask`? The code of the method looks like this: ``` String curloc = current.toString(); String itemdesc = item.mDescription; ArrayList<String> passing = new ArrayList<String>(); passing.add(itemdesc); passing.add(curloc); ArrayList<String> result = new ArrayList<String>(); new calc_stanica().execute(passing,result); String minim = result.get(0); int min = Integer.parseInt(minim); String glons = result.get(1); String glats = result.get(2); double glon = Double.parseDouble(glons); double glat = Double.parseDouble(glats); GeoPoint g = new GeoPoint(glon, glat); String korisni_linii = result.get(3); ``` So, as you see, I would like to send the string array list "passing" to the `AsyncTask`, and to get the "result" string array list back from it. And the calc\_stanica `AssycTask` class looks like this: ``` public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = new ProgressDialog(baraj_mapa.this); dialog.setTitle("Calculating..."); dialog.setMessage("Please wait..."); dialog.setIndeterminate(true); dialog.show(); } protected ArrayList<String> doInBackground(ArrayList<String>... passing) { //Some calculations... return something; //??? } protected void onPostExecute(Void unused) { dialog.dismiss(); } ``` So my question is how to get the elements of the "passing" array list in the `AsyncTask doInBackground` method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
2010/11/16
[ "https://Stackoverflow.com/questions/4195609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509666/" ]
I dont do it like this. I find it easier to overload the constructor of the asychtask class .. public class calc\_stanica extends AsyncTask> ``` String String mWhateveryouwantToPass; public calc_stanica( String whateveryouwantToPass) { this.String mWhateveryouwantToPass = String whateveryouwantToPass; } /*Now you can use whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/ ... ... ```
You can receive returning results like that: `AsyncTask` class ```java @Override protected Boolean doInBackground(Void... params) { if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) { try { throw new SQLException("Database credentials missing"); } catch (SQLException e) { e.printStackTrace(); } } try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass); } catch (SQLException e) { e.printStackTrace(); } return true; } ``` receiving class: ```java _store.execute(); boolean result =_store.get(); ``` Hoping it will help.
17,408,693
I have just (for the first time) compiled and installed kamailio, following [this](http://www.kamailio.org/wiki/) guide. For configuration, I am following the documentation [here](http://www.kamailio.org/wiki/) I am trying to test a new SIP user. I have created it with: ``` » kamctl add test testpasswd ``` The user is there: ``` » kamctl db show subscriber |----+----------+--------------------+------------+---------------+----------------------------------+----------------------------------+------| | id | username | domain | password | email_address | ha1 | ha1b | rpid | |----+----------+--------------------+------------+---------------+----------------------------------+----------------------------------+------| | 5 | test | tethys.wavilon.net | testpasswd | | 5cf40781f33c6f43a26244046564b67e | eb898de815bc16092e4c2e8c04bfe188 | NULL | |----+----------+--------------------+------------+---------------+----------------------------------+----------------------------------+------| ``` I try to connect with my sip client, and the registration times out (`Request Timeout (408)`). I have tried to verify what is going on by doing: ``` » kamailio -l <my-ip> -E -ddddd -D 1 ``` And I see lots of messages, one of them interesting: ``` 0(15818) DEBUG: auth [api.c:86]: pre_auth(): auth:pre_auth: Credentials with realm '<my-ip>' not found ``` But I do not know how to solve this problem. How can I verify what credentials associated to realm `<my-ip>` are configured? What is a "realm"? I do not find any beginners guide for `kamailio`. Is there a simple how-to on how to setup a simple `kamailio` configuration?
2013/07/01
[ "https://Stackoverflow.com/questions/17408693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647991/" ]
The log message you pasted in the question is for debug purposes (hence DEBUG level) and it could be printed for first SIP requests that come with no credentioals (e.g., first REGISTER) -- in such case it is all ok. Those requests are challenged for authentication with 401 replies, then they are resent by phone with credentials in Autorization header. If for those requests with credentials you don't get the same realm as used in challenge function parameters (e.g., www\_challenge(), auth\_challenge()...), then the SIP phone might be misconfigured. Typically the realm is the same as SIP domain in order to ensure it is unique, but that is not a must. With default kamailio configuration, the realm is the From header URI domain. However, you say you get 408 timeout for registration, then the issues might be something else. When the credentials matching the realm are not found, then 401reply is sent back, not 408. The reason for timeout could be that the REGISTER didn't get to kamailio or kamailio tries to send it somewhere else. You should look at the SIP traffic on the kamailio server to see what happens. You can use ngrep for that purpose, like: ``` ngrep -d any -qt -W byline . port 5060 ``` Watch to see if the REGISTER comes to kamailio server and if it is attempted to be sent to another IP.
Kamailio is a proxy. It is not simple, so if you want something simple, try [Asterisk](http://www.asterisk.org/) instead. Kamailio configuration **requires** knowledge of SIP. For this problem: you set the realm somewhere (in config file or in database) but are not using it for registration. Possible solutions would be to: 1. Remove the realm or set it to the correct domain name (and use it!). In the default config, that means disabling domains. 2. Use `tethys.wavilon.net` as you described in the subscriber table. For more info, go to the Kamailio site and read [this document](http://kamailio.org/docs/modules/4.1.x/modules/auth_db.html).
17,408,693
I have just (for the first time) compiled and installed kamailio, following [this](http://www.kamailio.org/wiki/) guide. For configuration, I am following the documentation [here](http://www.kamailio.org/wiki/) I am trying to test a new SIP user. I have created it with: ``` » kamctl add test testpasswd ``` The user is there: ``` » kamctl db show subscriber |----+----------+--------------------+------------+---------------+----------------------------------+----------------------------------+------| | id | username | domain | password | email_address | ha1 | ha1b | rpid | |----+----------+--------------------+------------+---------------+----------------------------------+----------------------------------+------| | 5 | test | tethys.wavilon.net | testpasswd | | 5cf40781f33c6f43a26244046564b67e | eb898de815bc16092e4c2e8c04bfe188 | NULL | |----+----------+--------------------+------------+---------------+----------------------------------+----------------------------------+------| ``` I try to connect with my sip client, and the registration times out (`Request Timeout (408)`). I have tried to verify what is going on by doing: ``` » kamailio -l <my-ip> -E -ddddd -D 1 ``` And I see lots of messages, one of them interesting: ``` 0(15818) DEBUG: auth [api.c:86]: pre_auth(): auth:pre_auth: Credentials with realm '<my-ip>' not found ``` But I do not know how to solve this problem. How can I verify what credentials associated to realm `<my-ip>` are configured? What is a "realm"? I do not find any beginners guide for `kamailio`. Is there a simple how-to on how to setup a simple `kamailio` configuration?
2013/07/01
[ "https://Stackoverflow.com/questions/17408693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647991/" ]
I got the same issue. I that add the alias record in kamailio.cfg and it works well. ``` alias="tethys.wavilon.net" ```
Kamailio is a proxy. It is not simple, so if you want something simple, try [Asterisk](http://www.asterisk.org/) instead. Kamailio configuration **requires** knowledge of SIP. For this problem: you set the realm somewhere (in config file or in database) but are not using it for registration. Possible solutions would be to: 1. Remove the realm or set it to the correct domain name (and use it!). In the default config, that means disabling domains. 2. Use `tethys.wavilon.net` as you described in the subscriber table. For more info, go to the Kamailio site and read [this document](http://kamailio.org/docs/modules/4.1.x/modules/auth_db.html).
17,408,693
I have just (for the first time) compiled and installed kamailio, following [this](http://www.kamailio.org/wiki/) guide. For configuration, I am following the documentation [here](http://www.kamailio.org/wiki/) I am trying to test a new SIP user. I have created it with: ``` » kamctl add test testpasswd ``` The user is there: ``` » kamctl db show subscriber |----+----------+--------------------+------------+---------------+----------------------------------+----------------------------------+------| | id | username | domain | password | email_address | ha1 | ha1b | rpid | |----+----------+--------------------+------------+---------------+----------------------------------+----------------------------------+------| | 5 | test | tethys.wavilon.net | testpasswd | | 5cf40781f33c6f43a26244046564b67e | eb898de815bc16092e4c2e8c04bfe188 | NULL | |----+----------+--------------------+------------+---------------+----------------------------------+----------------------------------+------| ``` I try to connect with my sip client, and the registration times out (`Request Timeout (408)`). I have tried to verify what is going on by doing: ``` » kamailio -l <my-ip> -E -ddddd -D 1 ``` And I see lots of messages, one of them interesting: ``` 0(15818) DEBUG: auth [api.c:86]: pre_auth(): auth:pre_auth: Credentials with realm '<my-ip>' not found ``` But I do not know how to solve this problem. How can I verify what credentials associated to realm `<my-ip>` are configured? What is a "realm"? I do not find any beginners guide for `kamailio`. Is there a simple how-to on how to setup a simple `kamailio` configuration?
2013/07/01
[ "https://Stackoverflow.com/questions/17408693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647991/" ]
The log message you pasted in the question is for debug purposes (hence DEBUG level) and it could be printed for first SIP requests that come with no credentioals (e.g., first REGISTER) -- in such case it is all ok. Those requests are challenged for authentication with 401 replies, then they are resent by phone with credentials in Autorization header. If for those requests with credentials you don't get the same realm as used in challenge function parameters (e.g., www\_challenge(), auth\_challenge()...), then the SIP phone might be misconfigured. Typically the realm is the same as SIP domain in order to ensure it is unique, but that is not a must. With default kamailio configuration, the realm is the From header URI domain. However, you say you get 408 timeout for registration, then the issues might be something else. When the credentials matching the realm are not found, then 401reply is sent back, not 408. The reason for timeout could be that the REGISTER didn't get to kamailio or kamailio tries to send it somewhere else. You should look at the SIP traffic on the kamailio server to see what happens. You can use ngrep for that purpose, like: ``` ngrep -d any -qt -W byline . port 5060 ``` Watch to see if the REGISTER comes to kamailio server and if it is attempted to be sent to another IP.
I got the same issue. I that add the alias record in kamailio.cfg and it works well. ``` alias="tethys.wavilon.net" ```
19,142,530
I'm facing a problem right now. We and our team are developing a new app with REST. The problem we are facing is we need sometimes get some kind of data and don't know how to create the URI. for example. If i need a list of products then api/products/ (GET) will do the trick. A single product, api/products/1 (GET) what if i just need a list of products out of stock, or a products with just 1 item left? what URI would I user?. I don't think REST can do it. Thanks you. BTW: I'm using VS 2012 Web API.
2013/10/02
[ "https://Stackoverflow.com/questions/19142530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738416/" ]
You can use "query parameters" for "filtering" in REST, it is a common approach. Keep in mind that REST is a "architectural style", i.e., a set of principles that leave some room for interpretation. In your case I would say you could create something like this: * query all products in stock: `GET /api/products?instock=true` * query products with only 1 left: `GET /api/products?countinstock=1` Where "instock" and "countinstock" are "query parameters", which you use in your REST API implementation as filters to query you DB. This approach is commonly accepted in RESTful designs, namely you still have the "resource" (products) on which you perform a GET action/verb, the only extra part is the "query parameters" used to filter and constraint the "action" upon the "resources. See some further discussions in this topic (and supporting the user of "query parameters") here: * [RESTful URL design for search](https://stackoverflow.com/questions/207477/restful-url-design-for-search) * [Using Query String in REST Web Services](https://stackoverflow.com/questions/16086513/using-query-string-in-rest-web-services)
Why not just modify your controller to take multiple parameters like id and inStock? For instance your URI could be something like `api/products?id=1&inStock=0`
22,132,573
I'm currently developing on a Bluetooth LE embedded project. For discovering my BLE peripherals, I currently use some apps for Android 4.3 (e.g. Nordic [nRF Toolbox](http://www.nordicsemi.com/eng/Products/nRFready-Demo-APPS/nRF-Toolbox-for-Android-4.3) and [nRF Master Control Panel](http://www.nordicsemi.com/eng/Products/nRFready-Demo-APPS/nRF-Master-Control-Panel-for-Android-4.3)) and iOS ([LightBlue](https://itunes.apple.com/us/app/lightblue-bluetooth-low-energy/id557428110)). On my desktop PC (running kubuntu 12.04), I currently use hcitool and gatttool from commandline e.g. for viewing and changing the characteristics values of my BLE peripherals. Did anybody know, if there was a gui tool available for linux, with similar features like the Nordic nRF Android Apps or like LightBlue for iOS? I want to use the linux GUI tool for: * explore my advertising BLE peripherals * connect them * discover their provided services & characteristics * view & change the characteristics values
2014/03/02
[ "https://Stackoverflow.com/questions/22132573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2880699/" ]
Linux currently does not have any GUI based BLE tools. The LightBlue referred to in [user1990's answer](https://stackoverflow.com/a/25177672/2880699) is actually an old outdated program that does not implement BLE. Anything short of command-line BlueZ using gatttool, or hcitool to do what you want, you will not find. [This site](http://joost.damad.be/2013/08/experiments-with-bluetooth-low-energy.html) has a good tutorial for device, characteristic, and service discovery.
LightBlue is avaiable on linux and mac os X. [LightBlue](http://lightblue.sourceforge.net/)
22,132,573
I'm currently developing on a Bluetooth LE embedded project. For discovering my BLE peripherals, I currently use some apps for Android 4.3 (e.g. Nordic [nRF Toolbox](http://www.nordicsemi.com/eng/Products/nRFready-Demo-APPS/nRF-Toolbox-for-Android-4.3) and [nRF Master Control Panel](http://www.nordicsemi.com/eng/Products/nRFready-Demo-APPS/nRF-Master-Control-Panel-for-Android-4.3)) and iOS ([LightBlue](https://itunes.apple.com/us/app/lightblue-bluetooth-low-energy/id557428110)). On my desktop PC (running kubuntu 12.04), I currently use hcitool and gatttool from commandline e.g. for viewing and changing the characteristics values of my BLE peripherals. Did anybody know, if there was a gui tool available for linux, with similar features like the Nordic nRF Android Apps or like LightBlue for iOS? I want to use the linux GUI tool for: * explore my advertising BLE peripherals * connect them * discover their provided services & characteristics * view & change the characteristics values
2014/03/02
[ "https://Stackoverflow.com/questions/22132573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2880699/" ]
Linux currently does not have any GUI based BLE tools. The LightBlue referred to in [user1990's answer](https://stackoverflow.com/a/25177672/2880699) is actually an old outdated program that does not implement BLE. Anything short of command-line BlueZ using gatttool, or hcitool to do what you want, you will not find. [This site](http://joost.damad.be/2013/08/experiments-with-bluetooth-low-energy.html) has a good tutorial for device, characteristic, and service discovery.
I realize this is an old thread, but maybe it can be helpful to someone anyway. The company I work for has just released a prerelease version of a [new Bluetooth Smart tool](https://devzone.nordicsemi.com/blogs/765/new-bluetooth-smart-tool-from-nordic). It's available for Linux, OSX and Windows. Note that it requires a development kit from Nordic Semiconductor to operate.
13,219,734
I have radiobuttons with data\_bind = "checked" binding. I need to call custom function to customize ui when one of the radiobuttons checked. Html Daily Weekly Monthly ``` <div data-bind="visible: FrequencyType() == 1"> Message 1 </div> <div data-bind="visible: FrequencyType() == 2"> Message 2 </div> <div data-bind="visible: FrequencyType() == 3"> //Before show html here I want to call js function </div> ``` js ``` function AppViewModel() { this.FrequencyType = ko.observable("0"); } $(document).ready(function () { viewModel = new AppViewModel(); // Activates knockout.js ko.applyBindings(viewModel); }); ``` [jsfiddler](http://jsfiddle.net/TuBzb/2/) How can I do it with knockout?
2012/11/04
[ "https://Stackoverflow.com/questions/13219734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525278/" ]
You need to add a couple of [ProxyHTMLURLMap](http://httpd.apache.org/docs/2.4/mod/mod_proxy_html.html) directives to the above, to inspect and rewrite any hard coded URL's in the returned HTML e.g. ``` ProxyRequests Off ProxyPass /external/ http://www.external.com/onlyforme ProxyHTMLURLMap http://www.external.com/onlyforme /external <Location /external/> ProxyPassReverse http://www.external.com/onlyforme SetOutputFilter proxy-html ProxyHTMLURLMap / /external/ ProxyHTMLURLMap /site_media /external/site_media/ </Location> ``` See also: <http://wiki.uniformserver.com/index.php/Reverse_Proxy_Server:_mod_proxy_html>
[arober11](https://stackoverflow.com/users/1443513/arober11)'s answer greatly helped solving my similar issue. I tried to narrow it down to the shortest set of rules possible, and there is my own configuration to have an [Etherpad](http://etherpad.org) running at <https://my-domain-name.wtf/pad> : ``` <Location /pad> ProxyPass http://localhost:9001 retry=0 # retry=0 => avoid 503's when restarting etherpad-lite ProxyPassReverse http://localhost:9001 SetOutputFilter proxy-html ProxyHTMLURLMap http://localhost:9001 </Location> RewriteRule ^/pad$ /pad/ [R] ```
45,781,862
I would like to do an operation on a 2-D matrix which somehow looks like the outer product of a vector. I already have written some codes for this task, but it is pretty slow, so I would like to know if there is anything I can do to accelerate it. I would like to show the code I wrote first, followed by an example to illustrate the task I wanted to do. --- **My code, version row-by-row** ``` function B = outer2D(A) B = zeros(size(A,1),size(A,2),size(A,2)); %Pre-allocate the output array for J = 1 : size(A,1) B(J,:,:) = transpose(A(J,:))*A(J,:); %Perform outer product on each row of A and assign to the J-th layer of B end end ``` Using the matrix A = randn(30000,20) as the input for testing, it spends 0.317 sec. --- **My code, version page-by-page** ``` function B = outer2D(A) B = zeros(size(A,1),size(A,2),size(A,2)); %Pre-allocate the output array for J = 1 : size(A,2) B(:,:,J) = repmat(A(:,J),1,size(A,2)).*A; %Evaluate B page-by-page end end ``` Using the matrix A = randn(30000,20) as the input for testing, it spends 0.146 sec. --- **Example 1** ``` A = [3 0; 1 1; 1 0; -1 1; 0 -2]; %A is the input matrix. B = outer2D(A); disp(B) ``` Then I would expect ``` (:,:,1) = 9 0 1 1 1 0 1 -1 0 0 (:,:,2) = 0 0 1 1 0 0 -1 1 0 4 ``` The first row of B, [9 0; 0 0], is the outer product of [3 0], i.e. [3; 0]\*[3 0] = [9 0; 0 0]. The second row of B, [1 1; 1 1], is the outer product of [1 1], i.e. [1; 1]\*[1 1] = [1 1; 1 1]. The third row of B, [1 0; 0 0], is the outer product of [1 0], i.e. [1; 0]\*[1 0] = [1 0; 0 0]. And the same for the remaining rows. --- **Example 2** ``` A = 0 -1 -2 0 1 0 -3 0 2 0 0 0 1 0 0 B = outer2D(A) disp(B) ``` Then, similar to the example 1, the expected output is ``` (:,:,1) = 0 0 0 0 0 0 9 0 -6 0 0 0 1 0 0 (:,:,2) = 0 1 2 0 1 0 0 0 0 0 0 0 0 0 0 (:,:,3) = 0 2 4 0 0 0 -6 0 4 0 0 0 0 0 0 ``` --- Because the real input in my project is like in the size of 30000 × 2000 and this task is to be performed for many times. So the acceleration of this task is quite essential for me. I am thinking of eliminating the for-loop in the function. May I have some opinions on this problem?
2017/08/20
[ "https://Stackoverflow.com/questions/45781862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8389552/" ]
With auto expansion: ``` function B = outer2D(A) B=permute(permute(A,[3 1 2]).*A',[2 3 1]); end ``` Without auto expansion: ``` function B = outer2Dold(A) B=permute(bsxfun(@times,permute(A,[3 1 2]),A'),[2 3 1]); end ```
Outer products are not possible in the matlab language.
3,842,833
Often in programming, it is a very common requirement that some piece of functionality will require a lot of conditional logic, but not quite enough to warrant a rules engine. For example, testing a number is divisible by x but also a multiple of something, a factor of something else, a square root of something, etc. As you can imagine, something along these lines will easily involve a lot of ifs/elses. While it is possible to reduce the clutter with more modern programming techniques, how do you quickly and, in a calculated fashon, deduce the required ifs/elses? For example, in a program to deduce the necessary quote for a car insurance prospective customer (rules engines aside btw), there would be conditional logic for age, location, driving points, what age those points are collected at, etc. Is there any mental technique to quickly deduce the redundant conditional branches? Is it just plain experience and no special mental technique? This is important because pair programming there is a lot of noise and thus difficult to actually think something through or even get enough time to implement the idea. Thanks
2010/10/01
[ "https://Stackoverflow.com/questions/3842833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32484/" ]
I would suggest that trying to do this sort of thing in your head is asking for trouble, and trying to do it with a partner is going to make it much worse. Sometimes you have to sit and think and even make some notes on paper. If you don't like propositional logic, try [decision tables](http://en.wikipedia.org/wiki/Decision_table).
I would say you should use propositional logic. Suggest that: q = age is greater than 18 p = location is within 10 miles r = driving points are less than 3 s = age is less than 18 when points are collected you could say... `(^ is AND) if (q ^ p ^ r ^ s) { //you are eligible or something! } else { //get outta here }`
3,842,833
Often in programming, it is a very common requirement that some piece of functionality will require a lot of conditional logic, but not quite enough to warrant a rules engine. For example, testing a number is divisible by x but also a multiple of something, a factor of something else, a square root of something, etc. As you can imagine, something along these lines will easily involve a lot of ifs/elses. While it is possible to reduce the clutter with more modern programming techniques, how do you quickly and, in a calculated fashon, deduce the required ifs/elses? For example, in a program to deduce the necessary quote for a car insurance prospective customer (rules engines aside btw), there would be conditional logic for age, location, driving points, what age those points are collected at, etc. Is there any mental technique to quickly deduce the redundant conditional branches? Is it just plain experience and no special mental technique? This is important because pair programming there is a lot of noise and thus difficult to actually think something through or even get enough time to implement the idea. Thanks
2010/10/01
[ "https://Stackoverflow.com/questions/3842833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32484/" ]
I would add simple, readable, short methods, such as: ``` IsMinor(..) IsRecordClean(..) ``` And then use them in conjunction to create new methods with meaningful names, such as: ``` IsMeetingPreReqs(..) //which checks several "simple" conditions IsValidForInsurance(..) ``` (Sorry for the examples, I'm struggling with my English here, but you get the point..) IMO that will make your code much clearer, and thus reduce the chances of being confused by distractions. Not mental per se, but kinda..
I would say you should use propositional logic. Suggest that: q = age is greater than 18 p = location is within 10 miles r = driving points are less than 3 s = age is less than 18 when points are collected you could say... `(^ is AND) if (q ^ p ^ r ^ s) { //you are eligible or something! } else { //get outta here }`
3,842,833
Often in programming, it is a very common requirement that some piece of functionality will require a lot of conditional logic, but not quite enough to warrant a rules engine. For example, testing a number is divisible by x but also a multiple of something, a factor of something else, a square root of something, etc. As you can imagine, something along these lines will easily involve a lot of ifs/elses. While it is possible to reduce the clutter with more modern programming techniques, how do you quickly and, in a calculated fashon, deduce the required ifs/elses? For example, in a program to deduce the necessary quote for a car insurance prospective customer (rules engines aside btw), there would be conditional logic for age, location, driving points, what age those points are collected at, etc. Is there any mental technique to quickly deduce the redundant conditional branches? Is it just plain experience and no special mental technique? This is important because pair programming there is a lot of noise and thus difficult to actually think something through or even get enough time to implement the idea. Thanks
2010/10/01
[ "https://Stackoverflow.com/questions/3842833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32484/" ]
I would suggest that trying to do this sort of thing in your head is asking for trouble, and trying to do it with a partner is going to make it much worse. Sometimes you have to sit and think and even make some notes on paper. If you don't like propositional logic, try [decision tables](http://en.wikipedia.org/wiki/Decision_table).
I would add simple, readable, short methods, such as: ``` IsMinor(..) IsRecordClean(..) ``` And then use them in conjunction to create new methods with meaningful names, such as: ``` IsMeetingPreReqs(..) //which checks several "simple" conditions IsValidForInsurance(..) ``` (Sorry for the examples, I'm struggling with my English here, but you get the point..) IMO that will make your code much clearer, and thus reduce the chances of being confused by distractions. Not mental per se, but kinda..
3,609,362
I know that Windows Sidebar Gadget API provides functionality beyond normal Javascript capabilities. Does it manipulate files? How? I didn't find how to do it in the [API Reference](http://msdn.microsoft.com/en-us/library/aa965853(VS.85).aspx)
2010/08/31
[ "https://Stackoverflow.com/questions/3609362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
I don't think you can disable one element? If you disable it then why have it at all? You can only disable the whole `<select>` input. Suggest you write validation to not accept the first element. Edit after OP's comment about being able to do this Here is another answer ``` // Get the countries element (do this after adding your options), then set the // attribute disable for option '1' $form->getElement("countries")->setAttrib("disable", array(1)); ``` This is suggested [here](http://snipplr.com/view/37588/zend-framework--form-element-select-options-disable/)
Credit goes to jakenoble. Just reformatted the code to use the formSelect-viewhelper instead of a form-element. ``` <?php $countries = array(1 => 'Select Option', 2 => 'us', 3 =>'uk'); echo $this->formSelect('country', 2, array('disable' => array(1)), $countries) ``` This will result in: ``` <select name="country" id="country"> <option value="1" label="Select Option" disabled="disabled">Select Option</option> <option value="2" label="us" selected="selected">us</option> <option value="3" label="uk">uk</option> </select> ```
3,609,362
I know that Windows Sidebar Gadget API provides functionality beyond normal Javascript capabilities. Does it manipulate files? How? I didn't find how to do it in the [API Reference](http://msdn.microsoft.com/en-us/library/aa965853(VS.85).aspx)
2010/08/31
[ "https://Stackoverflow.com/questions/3609362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
I don't think you can disable one element? If you disable it then why have it at all? You can only disable the whole `<select>` input. Suggest you write validation to not accept the first element. Edit after OP's comment about being able to do this Here is another answer ``` // Get the countries element (do this after adding your options), then set the // attribute disable for option '1' $form->getElement("countries")->setAttrib("disable", array(1)); ``` This is suggested [here](http://snipplr.com/view/37588/zend-framework--form-element-select-options-disable/)
There IS a way of doing it through Zend\_Form (at least on my current ve 1.11): ``` $this->addElement ( "select","selectName", array("multiOptions"=>array("one","two","three"), "disable"=>array(0,1)) ); ``` That one will disable first two options.
3,609,362
I know that Windows Sidebar Gadget API provides functionality beyond normal Javascript capabilities. Does it manipulate files? How? I didn't find how to do it in the [API Reference](http://msdn.microsoft.com/en-us/library/aa965853(VS.85).aspx)
2010/08/31
[ "https://Stackoverflow.com/questions/3609362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48465/" ]
There IS a way of doing it through Zend\_Form (at least on my current ve 1.11): ``` $this->addElement ( "select","selectName", array("multiOptions"=>array("one","two","three"), "disable"=>array(0,1)) ); ``` That one will disable first two options.
Credit goes to jakenoble. Just reformatted the code to use the formSelect-viewhelper instead of a form-element. ``` <?php $countries = array(1 => 'Select Option', 2 => 'us', 3 =>'uk'); echo $this->formSelect('country', 2, array('disable' => array(1)), $countries) ``` This will result in: ``` <select name="country" id="country"> <option value="1" label="Select Option" disabled="disabled">Select Option</option> <option value="2" label="us" selected="selected">us</option> <option value="3" label="uk">uk</option> </select> ```
26,308
When I type `mail` command, I get a "No mail for USER" answer, but there's indeed mail (it's in `/home/USER/Maildir/new`) I guess it has something to do with the mailbox being in Maildir format, instead of mbox, but I don't know how to tell mailutils (specifically the mail command) which format to use.
2011/02/14
[ "https://askubuntu.com/questions/26308", "https://askubuntu.com", "https://askubuntu.com/users/8851/" ]
Afaik "mail" utility checks mails at the location given with the MAIL environment variable. Try this command: `MAIL=/home/USER/Maildir/ mail` (for sure, replace USER with something meaningful & valid). If that works, it seems that you should set MAIL variable you can do it in your bash profile / rc file for example. You can check the content of your current MAIL variable with: `echo $MAIL`
To fetch mail from users home directory, use mail with -f option ``` mail -f /home/USER/Maildir/ ```
41,227,543
I have installed Xcode in my machine in order to use it for desktop development (OS X/Cocoa/Command line tools). Whenever I create a new project, there are templates in the wizard for iOS, watchOS and tvOS development, but at this moment I have no interest in these SDKs. Since Xcode.app is taking a lot of space in my disk even after a fresh install, is it possible to remove these SDKs and reclaim some space?
2016/12/19
[ "https://Stackoverflow.com/questions/41227543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2033517/" ]
I found out how to do this. I don't know at this moment if this can have any side-effect on other components for Xcode that could fail. In that case it may be possible to reinstall it from the Mac AppStore again. Xcode packages the SDKs for these different products as Platforms. There is a Platform for macOS, a Platform for iOS, and so on. All these Platforms are stored in this folder: ``` /Applications/Xcode.app/Contents/Developer/Platforms ``` It seems it's possible to actually remove platforms by deleting the correspondent folders inside, such as: ``` /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform ``` Whenever one or more of these folders are deleted, the New Project wizard won't even show them anymore as categories. [![New Project wizard](https://i.stack.imgur.com/o5pcB.png)](https://i.stack.imgur.com/o5pcB.png)
Above in incorrect. You will have to reinstall Xcode if you delete any of these folders. /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform I deleted above Xcode wanted me to reinstall. Try to delete all folders besides "developer" inside platform folders. Example, delete all beside this: /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform/developer. Other folders in that area you can delete
44,429,163
I am creating an web page in which have a `Dropdownlist`. I have to retrieve data for the drop\_down\_list from the database. Is there any way to get data from the database to the html view my html code: `<select name="drop down"><option value="1">@test.list[i]</option></select>` I got the database value to the list variable but I don't know how to pass the data to the html view. Please help me in this issue.Thanks
2017/06/08
[ "https://Stackoverflow.com/questions/44429163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7689376/" ]
You need to create Select List of Items : **Your Action with List of Items in View Bag :** ``` public ActionResult ActionName() { List<SelectListItem> Items = new List<SelectListItem>(); CustReportName.Add(new SelectListItem() { Text = "List1", Value = "1", Selected = false }); CustReportName.Add(new SelectListItem() { Text = "List2", Value = "2", Selected = true }); ViewBag.ListItems = Items; return View("ViewName"); } ``` **For Multiple values from database table:** ``` public ActionResult ActionName() { IEnumerable<SelectListItem> ItemsList = from item in YourTableObject select new SelectListItem { Value = Convert.ToString(item.Id), Text = item.ItemName }; ViewBag.ListItems = new SelectList(ItemsList, "Value", "Text"); return View("ViewName"); } ``` **Your DropdownList On view :** ``` @Html.DropDownListFor(model => model.ItemId, new SelectList(ViewBag.ItemList, "Value", "Text", 0), "-Select Item-", new { @class = "form-control", @id = "ItemId" }) ``` **Cheers !!**
It is just a simple two step process: Step1 :Action method code ``` public ActionResult Index() { ViewBag.users = db.users.ToList(); } ``` Step2: cshtml code ``` @Html.DropDownListFor(model => model.someId, new SelectList(ViewBag.users, "userId", "userName"), "Select users") ``` Note: with this, you can bind n number of data from the database to dropdownlist Hope it was useful Thanks Karthik
22,991,518
I would like to see a most concise way to do what is outlined in this SO question: [Sum values from multiple rows into one row](https://stackoverflow.com/questions/13940397/sum-values-from-multiple-rows-into-one-row?rq=1) that is, combine multiple rows while summing a column. But how to then delete the duplicates. In other words I have data like this: ``` Person Value -------------- 1 10 1 20 2 15 ``` And I want to sum the values for any duplicates (on the Person col) into a single row and get rid of the other duplicates on the Person value. So my output would be: ``` Person Value ------------- 1 30 2 15 ``` And I would like to do this without using a temp table. I think that I'll need to use `OVER PARTITION BY` but just not sure. Just trying to challenge myself in not doing it the temp table way. Working with SQL Server 2008 R2 Simply put, give me a concise stmt getting from my input to my output in the same table. So if my table name is `People` if I do a `select * from People` on it before the operation that I am asking in this question I get the first set above and then when I do a `select * from People` after the operation, I get the second set of data above.
2014/04/10
[ "https://Stackoverflow.com/questions/22991518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2788458/" ]
Not sure why not using Temp table but here's one way to avoid it (tho imho this is an overkill): ``` UPDATE MyTable SET VALUE = (SELECT SUM(Value) FROM MyTable MT WHERE MT.Person = MyTable.Person); WITH DUP_TABLE AS (SELECT ROW_NUMBER() OVER (PARTITION BY Person ORDER BY Person) As ROW_NO FROM MyTable) DELETE FROM DUP_TABLE WHERE ROW_NO > 1; ``` First query updates *every* duplicate person to the summary value. Second query removes duplicate persons. **Demo: <http://sqlfiddle.com/#!3/db7aa/11>**
All you're asking for is a simple `SUM()` aggregate function and a `GROUP BY` ``` SELECT Person, SUM(Value) FROM myTable GROUP BY Person ``` The `SUM()` by itself would sum up the values in a column, but when you add a secondary column and `GROUP BY` it, SQL will show distinct values from the secondary column and perform the aggregate function by those distinct categories.
25,081,679
I have a search button where it search the report for the input date. But when I clicked the button The table shows empty even If I input correctly the start and end date. PHP code ``` <?php include('konek.php'); $start = isset($_GET['d1']) ? $_GET['d1'] : ''; $end = isset($_GET['d2']) ? $_GET['d2'] : ''; if (isset($_GET['submit']) && $_GET['submit']=='Search') { $result = mysql_query("SELECT t1.qty, t2.lastname, t2.firstname, t2.date, t3.name, t2.reservation_id, t2.payable FROM prodinventory AS t1 INNER JOIN reservation AS t2 ON t1.confirmation=t2.confirmation INNER JOIN products AS t3 ON t1.room=t3.id WHERE t2.date BETWEEN '$start' AND '$end' GROUP BY t2.confirmation"); while ($row = mysql_fetch_array($result)){ echo'<tr class="record">'; echo'<td>'; echo $row['reservation_id']; echo'</td>'; echo'<td>'; echo $row['date']; echo'</td>'; echo'<td>'; echo $row['firstname'].' '.$row['lastname']; echo'</td>'; echo'<td>'; echo $row['name'].' '.$row['qty']; echo'</td>'; echo'<td>'; echo $row['payable']; echo'</td>'; echo'</tr>'; echo'</tbody>'; echo'</table>'; $result1 = mysql_query("SELECT SUM(payable) FROM reservation WHERE date BETWEEN '$d1' AND '$d2'"); while ($rows1 = mysql_fetch_array($result1)) { ?> <div class="pull-right"> <div class="span"> <div class="alert alert-info"><i class="icon-credit-card icon-large"> </i>&nbsp;Sub Total: PHP&nbsp;<?php echo number_format(floatval($rows1['SUM(payable)'])); ? ></div> </div> </div> </center> <?php }}} ?> ``` Here's my HTML form ``` <form action="salesreport.php" method="GET"> <input name="submit" id="submit" type="submit" class="btnsearch" value="Search" /> From : <input type="text" name="d1" id="d1" class="tcal" value="" /> To: <input type="text" name="d2" id="d2" class="tcal" value="" /> ```
2014/08/01
[ "https://Stackoverflow.com/questions/25081679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3896397/" ]
First of all, I'd revisit the idea of storing any dates or times as strings.. it leads to exactly this kind of problem. MySQL actually treats dates as strings anyway, with added date functionality.. and stores them in the more sensible format of %Y-%m-%d, which produces the correct ordering. If you absolutely cannot change the database.. either contact someone who can or run your query as: ``` SELECT * FROM schedule WHERE username='".$_SESSION['username']."' ORDER BY STR_TO_DATE(date, '%d/%m/%Y') ASC, start_time ASC ``` `DATE_FORMAT` casts a date to the string format specified. In your case it was implicitly converting your string into a date (as it was passed into the function) and then formatting it back to it's original format.. hence the ordering you are seeing.
The function `date_format()` formats a date and outputs a string. You want `str_to_date()`: ``` ORDER BY STR_TO_DATE(date, '%d/%m/%Y') ```
8,670,295
I have a table with an integer column ranging from 1 to 32 (this column identify the type of record stored). The types 5 and 12 represents 70% of the total number of rows, and this number is greater than 1M rows, so it seems to makes sense to partition the table. Question is: how can I create a set of 3 partitions, one containing the type 5 records, the second containing the type 12 records, and the third one with the remaining records?
2011/12/29
[ "https://Stackoverflow.com/questions/8670295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1121513/" ]
<http://dev.mysql.com/doc/refman/5.1/en/partitioning-list.html> ``` create table some_table ( id INT NOT NULL, some_id INT NOT NULL ) PARTITION BY LIST(some_id) ( PARTITION fives VALUES IN (5), PARTITION twelves VALUES IN (12), PARTITION rest VALUES IN (1,2,3,4,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32) ); ```
Use [Partition by list](http://dev.mysql.com/doc/refman/5.1/en/partitioning-list.html)
8,670,295
I have a table with an integer column ranging from 1 to 32 (this column identify the type of record stored). The types 5 and 12 represents 70% of the total number of rows, and this number is greater than 1M rows, so it seems to makes sense to partition the table. Question is: how can I create a set of 3 partitions, one containing the type 5 records, the second containing the type 12 records, and the third one with the remaining records?
2011/12/29
[ "https://Stackoverflow.com/questions/8670295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1121513/" ]
<http://dev.mysql.com/doc/refman/5.1/en/partitioning-list.html> ``` create table some_table ( id INT NOT NULL, some_id INT NOT NULL ) PARTITION BY LIST(some_id) ( PARTITION fives VALUES IN (5), PARTITION twelves VALUES IN (12), PARTITION rest VALUES IN (1,2,3,4,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32) ); ```
Provided that `type` is an index, then MySQL has already logically partitioned the table for you. Unless you really need physical partitioning, it seems to me you are only making trouble for yourself.
2,665,543
Solve $$1001y''' + 3.2y'' + \pi y' - \sqrt{4}y = 0$$ Initial Conditions: $$y(0) = 0, y'(0) = 0, y''(0) = 0$$ I plugged it into the characteristic equation, but I don't know where to go from there... $$1001r^3 + 3.2r^2 + \pi r - 2 = 0$$ Some help would be appreciated, thanks.
2018/02/25
[ "https://math.stackexchange.com/questions/2665543", "https://math.stackexchange.com", "https://math.stackexchange.com/users/416804/" ]
I think the point of this problem is that, by the uniqueness theorem, there is only one solution, and from the initial conditions, it is clear that $y(t)=0$ is that solution. I don't think you were supposed to mess with the characteristic equation at all.
Case 1: Assuming the last square root applies only to 4 (thus the question becomes trivial). WolframAlpha provides the solution: $$ y(x) = c\_3 e^{0.426569 x} + c\_1 e^{-1.81328 x} sin(1.18346 x) + c\_2 e^{-1.81328 x} cos(1.18346 x) $$ Which comes from the characteristic equation you gave. You would have to find the root either numerically or with Cardano's Method after a change in variables. <https://en.wikipedia.org/wiki/Cubic_function> The coefficients $c\_1,c\_2$ and $c\_3$ can be found with the initial conditions, but no surprise they're zero. Case 1: The last square root applies to $y$ as well, so your question becomes a little more convoluted. You can still make a change of variables $u^2=y$, and the equation becomes: $$ 1×(d^3 u(t)^2)/(dt^3) + 3.2×(d^2 u(t)^2)/(dt^2) + π×(du(t)^2)/(dt) - 2 u(t) = 0 $$ $$ (6.4 u(t) + 6 u'(t)) u^(3)(t) = 2 u(t) - 2 π u(t) u'(t) - 6.4 u'(t)^2 - 2 u(t) u^(3)(t) $$ While I fail to find a straightforward solution for this, you can check that again, no surprise the initial conditions being zero means that $y'''(0)$ is also zero, and thus $y(t)=0$ is a valid solution to your initial value problem.
19,638,090
Why is this not working for me? I keep getting the error: ``` java.sql.SQLException: Can not issue data manipulation statements with executeQuery(). ``` My code: ``` private void speler_deleteActionPerformed(java.awt.event.ActionEvent evt) { int row = tbl_spelers.getSelectedRow(); int SpelerID = (int) tbl_spelers.getValueAt(row, 0); Speler speler = new Speler(); try { DBClass databaseClass = new DBClass(); Connection connectie = databaseClass.getConnection(); // NOG ONVEILIG - WACHTEN OP DB SELECT IN DBCLASS!!! String deleteQry = "DELETE FROM `Speler` WHERE SpelerID = " + SpelerID + ";"; ResultSet rs = databaseClass.GetFromDB(deleteQry); } catch (SQLException ex) { Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex); } } ```
2013/10/28
[ "https://Stackoverflow.com/questions/19638090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2854129/" ]
You have to use [`excuteUpdate()`](http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29) for **delete**. Docs of [`excuteUpdate()`](http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29) > > Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement. > > > Where as [`executeQuery()`](http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeQuery%28java.lang.String%29) > > Executes the given SQL statement, which returns a single ResultSet object. > > >
executeQuery() method of jdbc is to select records, you can use executeUpdate() for update operations. Please refer to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html) for the purpose/ intent of each method: > > > ``` > boolean execute() > > ``` > > Executes the SQL statement in this PreparedStatement object, which may > be any kind of SQL statement. > > > > ``` > ResultSet executeQuery() > > ``` > > Executes the SQL query in this PreparedStatement object and returns > the ResultSet object generated by the query. > > > > ``` > int executeUpdate() > > ``` > > Executes the SQL statement in this PreparedStatement object, which > must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement > that returns nothing, such as a DDL statement. > > >
19,638,090
Why is this not working for me? I keep getting the error: ``` java.sql.SQLException: Can not issue data manipulation statements with executeQuery(). ``` My code: ``` private void speler_deleteActionPerformed(java.awt.event.ActionEvent evt) { int row = tbl_spelers.getSelectedRow(); int SpelerID = (int) tbl_spelers.getValueAt(row, 0); Speler speler = new Speler(); try { DBClass databaseClass = new DBClass(); Connection connectie = databaseClass.getConnection(); // NOG ONVEILIG - WACHTEN OP DB SELECT IN DBCLASS!!! String deleteQry = "DELETE FROM `Speler` WHERE SpelerID = " + SpelerID + ";"; ResultSet rs = databaseClass.GetFromDB(deleteQry); } catch (SQLException ex) { Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex); } } ```
2013/10/28
[ "https://Stackoverflow.com/questions/19638090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2854129/" ]
You have to use [`excuteUpdate()`](http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29) for **delete**. Docs of [`excuteUpdate()`](http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29) > > Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement. > > > Where as [`executeQuery()`](http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeQuery%28java.lang.String%29) > > Executes the given SQL statement, which returns a single ResultSet object. > > >
Firstly, you need to use `excuteUpdate()` for the delete, and next ``` String deleteQry = "DELETE FROM `Speler` WHERE SpelerID = " + SpelerID + ";"; ``` remove the `semi-colon` and the "`" which encloses the table name "Speler", from the query.
19,638,090
Why is this not working for me? I keep getting the error: ``` java.sql.SQLException: Can not issue data manipulation statements with executeQuery(). ``` My code: ``` private void speler_deleteActionPerformed(java.awt.event.ActionEvent evt) { int row = tbl_spelers.getSelectedRow(); int SpelerID = (int) tbl_spelers.getValueAt(row, 0); Speler speler = new Speler(); try { DBClass databaseClass = new DBClass(); Connection connectie = databaseClass.getConnection(); // NOG ONVEILIG - WACHTEN OP DB SELECT IN DBCLASS!!! String deleteQry = "DELETE FROM `Speler` WHERE SpelerID = " + SpelerID + ";"; ResultSet rs = databaseClass.GetFromDB(deleteQry); } catch (SQLException ex) { Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex); } } ```
2013/10/28
[ "https://Stackoverflow.com/questions/19638090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2854129/" ]
You have to use [`excuteUpdate()`](http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29) for **delete**. Docs of [`excuteUpdate()`](http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29) > > Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement. > > > Where as [`executeQuery()`](http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeQuery%28java.lang.String%29) > > Executes the given SQL statement, which returns a single ResultSet object. > > >
You need to execute you query using **`executeUpdate()`** Also, you just need to make a slight adjustment to your String `deleteQry` as follows: ``` String deleteQry = "DELETE FROM Speler WHERE SpelerID = " + SpelerID; ``` Hope this helps...
3,285,344
> > How does one calculate the following integral? > > > $$ > \int\_0^1\frac{x\ln (1+x)}{1+x^2}dx > $$ > > > **CONTEXT**: Our teacher asks us to calculate the integral using *only* [changes of variables](https://en.wikipedia.org/wiki/Change_of_variables), [integrations by parts](https://en.wikipedia.org/wiki/Integration_by_parts) and the following known result: $$ \int\_0^1 \frac{\ln x}{x-1}\,dx=\frac{\pi^2}{6}, $$ without using complex analysis, series, [differentiation under the integral sign](https://en.wikipedia.org/wiki/Leibniz_integral_rule), double integrals or special functions. Some methods not respecting the teacher's requirement are found in answers to [this question](https://math.stackexchange.com/questions/2182816/prove-that-int-01-fracx-ln-1x1x2dx-frac-pi296-frac-ln2-28).
2019/07/06
[ "https://math.stackexchange.com/questions/3285344", "https://math.stackexchange.com", "https://math.stackexchange.com/users/417942/" ]
For start we'll prove a result that it's going to be used later. $$\boxed{\int\_0^1 \frac{\ln(1+x)}{x}dx=\frac12 \int\_0^1 \frac{\ln x}{x-1}dx}=\frac12\cdot \frac{\pi^2}{6}$$ *proof:* $$\int\_0^1 \frac{\ln x}{x+1}dx+\int\_0^1 \frac{\ln x}{x-1}dx=\int\_0^1 \frac{2x\ln x}{x^2-1}dx\overset{x^2\to x}=\frac12 \int\_0^1 \frac{\ln x}{x-1}dx $$ $$\Rightarrow \int\_0^1 \frac{\ln x}{x+1}dx=-\frac12 \int\_0^1 \frac{\ln x}{x-1}dx$$ $$\int\_0^1 \frac{\ln(1+x)}{x}dx=\underbrace{\ln x \ln(1+x)\bigg|\_0^1}\_{=0}-\int\_0^1 \frac{\ln x}{1+x}dx=\frac12 \int\_0^1 \frac{\ln x}{x-1}dx$$ Now back to the question. Consider the following integrals:$$I=\int\_0^1\frac{x\ln (1+x)}{1+x^2}dx,\quad J=\int\_0^1\frac{x\ln (1-x)}{1+x^2}dx$$ --- $$I+J=\int\_0^1 \frac{x\ln(1-x^2)}{1+x^2}dx\overset{x^2=t}=\frac12\int\_0^1 \frac{\ln(1-t)}{1+t}dt$$ Now we will integral by parts, however we can't chose $\ln(1+t)'=\frac{1}{1+t}$ since we run into divergence issues. We will take $(\ln (1+t)-\ln 2)'=\frac{1}{1+t}$ then: $$I+J=\frac12\bigg[\underbrace{\ln(1-t)(\ln(1+t)-\ln 2)\bigg]\_0^1}\_{=0}+\frac12 \int\_0^1 \frac{\ln\left(\frac{1+t}{2}\right)}{1-t}dt$$ Now substitute $t=\frac{1-y}{1+y}$ in order to get: $$I+J=-\frac12 \int\_0^1 \frac{\ln(1+y)}{y(1+y)}dy=\frac12 \int\_0^1 \frac{\ln(1+y)}{1+y}dy-\frac12\int\_0^1 \frac{\ln(1+y)}{y}dy$$ $$=\frac14 \ln^2(1+y)\bigg|\_0^1 -\frac14 \cdot \frac{\pi^2}{6}=\boxed{\frac{\ln^2 2}{4}-\frac{\pi^2}{24}}$$ --- Similarly, for $I-J$ set $\frac{1-x}{1+x}= t$ to get: $$I-J=-\int\_0^1 \frac{x\ln\left(\frac{1-x}{1+x}\right)}{1+x^2}dx=\underbrace{\int\_0^1 \frac{t\ln t}{1+t^2}dt}\_{t^2\rightarrow t}-\int\_0^1 \frac{\ln t}{1+t}dt$$ $$=\frac14 \int\_0^1 \frac{\ln t}{1+t}dt-\int\_0^1 \frac{\ln t}{1+t}dt=-\frac34 \left(\underbrace{\ln(1+t)\ln t \bigg|\_0^1}\_{=0} -\int\_0^1 \frac{\ln(1+t)}{t}dt\right)$$ $$=\frac34 \int\_0^1 \frac{\ln(1+t)}{t}dt=\frac38 \int\_0^1 \frac{\ln t}{t-1}dt=\boxed{\frac{\pi^2}{16}}$$ --- Finally we can extract the integral as: $$I=\frac12 \left((I+J)+(I-J)\right)=\frac12\left(\frac{\ln^2 2}{4}-\frac{\pi^2}{24}+\frac{\pi^2}{16}\right)=\boxed{\frac{\ln^2 2}{8}+\frac{\pi^2}{96}}$$ Supplementary result is following: $$\boxed{\int\_0^1\frac{x\ln (1-x)}{1+x^2}dx=\frac{\ln^2 2}{8}-\frac{5\pi^2}{96}}$$
Alternative solution: \begin{align} J&=\int\_0^1 \frac{x\ln(1+x)}{1+x^2}\,dx\\ A&=\int\_0^1 \frac{\ln(1+x^2)}{1+x}\,dx\\ &=\Big[\ln(1+x^2)\ln(1+x)\Big]\_0^1-2\int\_0^1 \frac{x\ln(1+x)}{1+x^2}\,dx\\ &=\ln^2 2-2J\\ J&=\frac{1}{2}\ln^2 2-\frac{1}{2}A\\ B&=\int\_0^1 \frac{\ln\left(\frac{1-x^2}{1+x^2}\right)}{1+x}\,dx\\ C&=\int\_0^1 \frac{\ln\left(1-x\right)}{1+x}\,dx\\ \end{align} Perform the change of variable $y=\dfrac{1-x^2}{1+x^2}$, \begin{align} B&=\frac{1}{2}\int\_0^1 \frac{\left(\sqrt{1+x}-\sqrt{1-x}\right)\ln x}{x\sqrt{1-x}(1+x)}\,dx\\ &=\frac{1}{2}\int\_0^1 \left(\frac{1}{\sqrt{1-x^2}}-\frac{1}{1+x}\right)\frac{\ln x}{x}\,dx\\ &=\frac{1}{2}\Big[\left(\ln(1+x)-\ln(1+\sqrt{1-x^2})+\ln 2\right)\ln x\Big]\_0^1-\\ &\frac{1}{2}\int\_0^1\frac{\ln(1+x)-\ln(1+\sqrt{1-x^2})+\ln 2}{x}\,dx\\ &=-\frac{1}{2}\int\_0^1 \frac{\ln(1+x)}{x}\,dx+\frac{1}{2}\int\_0^1\left(\frac{\ln(1+\sqrt{1-x^2})}{x}-\frac{\ln 2}{x}\right)\,dx \end{align} In the second integral, perform the change of variable $y=\dfrac{1-\sqrt{1-x^2}}{1+\sqrt{1-x^2}}$, \begin{align} B&=-\frac{1}{2}\int\_0^1 \frac{\ln(1+x)}{x}\,dx-\frac{1}{4}\int\_0^1 \frac{(1-x)\ln(1+x)}{x(1+x)}\,dx\\ &=-\frac{1}{2}\int\_0^1 \frac{\ln(1+x)}{x}\,dx-\frac{1}{4}\int\_0^1\left(\frac{\ln(1+x)}{x}-\frac{2\ln(1+x)}{1+x}\right)\,dx\\ &=-\frac{3}{4}\int\_0^1 \frac{\ln(1+x)}{x}\,dx+\frac{1}{4}\Big[\ln^2(1+x)\Big]\_0^1\\ &=\left(-\frac{3}{4}\Big[\ln x\ln(1+x)\Big]\_0^1+\frac{3}{4}\int\_0^1 \frac{\ln x}{1+x}\,dx\right)+\frac{1}{4}\ln^2 2\\ &=\frac{3}{4}\int\_0^1 \frac{\ln x}{1+x}\,dx+\frac{1}{4}\ln^2 2\\ \end{align} Perform the change of variable $y=\dfrac{1-x}{1+x}$, \begin{align} C&=\int\_0^1 \frac{\ln\left(\frac{2x}{1+x}\right)}{1+x}\,dx\\ &=\int\_0^1 \frac{\ln 2}{1+x}\,dx+\int\_0^1 \frac{\ln x}{1+x}\,dx-\int\_0^1 \frac{\ln(1+x)}{1+x}\,dx\\ &=\ln^2 2+\int\_0^1 \frac{\ln x}{1+x}\,dx-\frac{1}{2}\ln^2 2\\ &=\int\_0^1 \frac{\ln x}{1+x}\,dx+\frac{1}{2}\ln^2 2\\ B&=\int\_0^1 \frac{\ln\left(\frac{(1-x)(1+x)}{1+x^2}\right)}{1+x}\,dx\\ &=C+\int\_0^1 \frac{\ln(1+x)}{1+x}\,dx-A\\ &=C+\frac{1}{2}\ln^2 2-A \end{align} Therefore, \begin{align}A&=C+\frac{1}{2}\ln^2 2-B\\ &=\left(\int\_0^1 \frac{\ln x}{1+x}\,dx+\frac{1}{2}\ln^2 2\right)+\frac{1}{2}\ln^2 2-\left(\frac{3}{4}\int\_0^1 \frac{\ln x}{1+x}\,dx+\frac{1}{4}\ln^2 2\right)\\ &=\frac{1}{4}\int\_0^1 \frac{\ln x}{1+x}\,dx+\frac{3}{4}\ln^2 2\\ &=\frac{1}{4}\left(\int\_0^1 \frac{\ln x}{1-x}\,dx-\frac{2x\ln x}{1-x^2}\,dx\right)+\frac{3}{4}\ln^2 2 \end{align} In the second integral perform the change of variable $y=x^2$, \begin{align}A&=\frac{1}{4}\left(\int\_0^1 \frac{\ln x}{1-x}\,dx-\frac{1}{2}\int\_0^1\frac{\ln x}{1-x}\,dx\right)+\frac{3}{4}\ln^2 2\\ &=\frac{1}{8}\int\_0^1\frac{\ln x}{1-x}\,dx+\frac{3}{4}\ln^2 2\\ J&=\frac{1}{2}\ln^2 2-\frac{1}{2}\left(\frac{1}{8}\int\_0^1\frac{\ln x}{1-x}\,dx+\frac{3}{4}\ln^2 2\right)\\ &=\frac{1}{8}\ln^2 2-\frac{1}{16}\int\_0^1\frac{\ln x}{1-x}\,dx\\ &=\boxed{\frac{1}{8}\ln^2 2+\frac{1}{96}\pi^2}\\ \end{align}
68,882,552
Hope you are doing well. Database created in consumer account from share is read only, so consumer won't have any storage charges right. I have one doubt here, let say consumer created a materialized views from that database and then does the consumer incur storage charges because materialized views stores result set. Regards, Sudhakar
2021/08/22
[ "https://Stackoverflow.com/questions/68882552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7171412/" ]
[Creating a Materialized View on Shared Data](https://docs.snowflake.com/en/user-guide/views-materialized.html#creating-a-materialized-view-on-shared-data) > > Note > > > **Remember that maintaining materialized views will consume credits. When you create a materialized view on someone else’s shared table, the changes to that shared table will result in charges to you as your materialized view is maintained** > > >
Materialized views will incur additional costs based on storage and compute resources. The updates to base table can consume significant resources, resulting in credit usage. This is also applicable on the shared database created from a share in a consumer account, as a Materialized view created has to be maintained. <https://docs.snowflake.com/en/user-guide/views-materialized.html#creating-a-materialized-view-on-shared-data> <https://docs.snowflake.com/en/user-guide/views-materialized.html#maintenance-costs-for-materialized-views> <https://docs.snowflake.com/en/user-guide/views-materialized.html#viewing-costs>
8,605,052
I am developing an MVC3 application and have been wondering about the following. Should the Entity Framework object (`DbContext` object) be disposed before passing data to the view? The obvious issue with this is you will not be able to drill down into the foreign key relations. Is there a performance hit by doing this?
2011/12/22
[ "https://Stackoverflow.com/questions/8605052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/601245/" ]
Yes you absolutely should dispose of the context The performance hit should be minimal . Any object that can be disposed of should be disposed of ALWAYS. Dependency injection can free you from having to worry about calling it if done properly as the DI framework will dispose of it for you if instructed.
If, by "entityframe work object" you mean the DbContext object, then No, don't worry about it. ...also, this should be a Controller level object, not a View level one.
8,605,052
I am developing an MVC3 application and have been wondering about the following. Should the Entity Framework object (`DbContext` object) be disposed before passing data to the view? The obvious issue with this is you will not be able to drill down into the foreign key relations. Is there a performance hit by doing this?
2011/12/22
[ "https://Stackoverflow.com/questions/8605052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/601245/" ]
Don't pass EF entities into your view, use the view model pattern. And don't rely too much on lazy loading, it will perform poorly. Use the Include method to eagerly load the objects you need. And yes, you need dispose (or preferably using), otherwise your system will leak connections and probably starve the pool under non-trivial loads.
If, by "entityframe work object" you mean the DbContext object, then No, don't worry about it. ...also, this should be a Controller level object, not a View level one.
8,605,052
I am developing an MVC3 application and have been wondering about the following. Should the Entity Framework object (`DbContext` object) be disposed before passing data to the view? The obvious issue with this is you will not be able to drill down into the foreign key relations. Is there a performance hit by doing this?
2011/12/22
[ "https://Stackoverflow.com/questions/8605052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/601245/" ]
Agree with the answer of Adam Tuliper. With the addition, that if you need to access the related objects you could use the .Include(o => o.EntityName) method to make sure the data is included in the data retrieval. This blog is writing about loading related objects: <http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx>
If, by "entityframe work object" you mean the DbContext object, then No, don't worry about it. ...also, this should be a Controller level object, not a View level one.
8,605,052
I am developing an MVC3 application and have been wondering about the following. Should the Entity Framework object (`DbContext` object) be disposed before passing data to the view? The obvious issue with this is you will not be able to drill down into the foreign key relations. Is there a performance hit by doing this?
2011/12/22
[ "https://Stackoverflow.com/questions/8605052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/601245/" ]
Yes you absolutely should dispose of the context The performance hit should be minimal . Any object that can be disposed of should be disposed of ALWAYS. Dependency injection can free you from having to worry about calling it if done properly as the DI framework will dispose of it for you if instructed.
Don't pass EF entities into your view, use the view model pattern. And don't rely too much on lazy loading, it will perform poorly. Use the Include method to eagerly load the objects you need. And yes, you need dispose (or preferably using), otherwise your system will leak connections and probably starve the pool under non-trivial loads.
8,605,052
I am developing an MVC3 application and have been wondering about the following. Should the Entity Framework object (`DbContext` object) be disposed before passing data to the view? The obvious issue with this is you will not be able to drill down into the foreign key relations. Is there a performance hit by doing this?
2011/12/22
[ "https://Stackoverflow.com/questions/8605052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/601245/" ]
Yes you absolutely should dispose of the context The performance hit should be minimal . Any object that can be disposed of should be disposed of ALWAYS. Dependency injection can free you from having to worry about calling it if done properly as the DI framework will dispose of it for you if instructed.
Agree with the answer of Adam Tuliper. With the addition, that if you need to access the related objects you could use the .Include(o => o.EntityName) method to make sure the data is included in the data retrieval. This blog is writing about loading related objects: <http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx>
56,150,853
Given a matrix `mat` and an array `arr`, for each row of the matrix if elements of Column 1 are equal to the corresponding element of the array, then print the corresponding value of Column 2 of the matrix. ``` mat = np.array([['abc','A'],['def','B'],['ghi','C'],['jkl','D']]) arr = np.array(['abc','dfe','ghi','kjl']) ```
2019/05/15
[ "https://Stackoverflow.com/questions/56150853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11503893/" ]
This can be solved via [numpy.where](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html). Extract the first row of the matrix using `mat[:,0]`, and compare it to `arr` using `np.where(mat[:,0] == arr)` to extract the indexes. and use those indexes to get the elements you want from `mat` ``` In [1]: import numpy as np ...: ...: mat = np.array([['abc','A'],['def','B'],['ghi','C'],['jkl','D']]) ...: ...: arr = np.array(['abc','dfe','ghi','kjl']) In [2]: print(mat[np.where(mat[:,0] == arr)]) [['abc' 'A'] ['ghi' 'C']] ```
Output should be `['A', 'C']`` So above code can be modified as ``` print(mat[np.where(mat[:,0]=arr)][:,1] # output ['A' 'C'] ```
302,239
In the following sample document, ``` \documentclass[tikz]{standalone} \usetikzlibrary{chains} \begin{document} \begin{tikzpicture} %circle \draw[black, thick] (0,0) circle (5); %binding sites \begin{scope}[start chain=bindingchain] \foreach \a/\c in {150/green, 270/red, 390/blue} \draw[gray] (0,0) -- (\a:5) coordinate[\c, midway, thick, draw, circle, minimum width=25, on chain]; \end{scope} \end{tikzpicture} \end{document} ``` I want the blue, red and green circle to be centred in the middle of the line. However, the blue and and red one are off: [![output as produced by pdflatex](https://i.stack.imgur.com/ehrUU.png)](https://i.stack.imgur.com/ehrUU.png) Could someone explain why this is happening, and how to fix it? Edit: While Stefan Pinnow's answer solves my original question, as it avoids the dependence on the `chains` library, I'd still be interested in why `chains` interacts with `midway` in this way.
2016/04/03
[ "https://tex.stackexchange.com/questions/302239", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/102257/" ]
A `coordinate` is a *point*. It doesn't make sense to use this for things which have dimensions. These should be *nodes*. I'm slightly surprised that the code compiles at all. Correcting this doesn't actually change the output: ``` \draw[gray] (0,0) -- (\a:5) node [\c, midway, thick, draw, circle, minimum width=25, on chain] {}; ``` but it makes more sense. A `chain` has a direction. By default, a chain is `going right`. That means that each node on the chain is set to the right of the previous one. Here's what seems to happen: 1. TikZ moves to the point specified as midway between the origin and `(\a:5)`. 2. It then adds the effect of `on chain` by moving right by the standard `node distance`, but it retains the default `center` anchor. Here's a picture showing the blue circle along with two black circles. The first is drawn at (1) and the second at (2) from the movements specified above: [![equivalence](https://i.stack.imgur.com/FXcX6.png)](https://i.stack.imgur.com/FXcX6.png) Normally, the effect of `going right` would be to use `west` as the anchor, but the default `center` seems to hold here. If you want to add nodes to a chain but do not want the chain to determine the placement of the nodes, then do not use `on chain`. Instead create the nodes first and then use `\chainin ();`. For example, adding the `scopes` library for convenience: ``` \begin{tikzpicture} \draw[black, thick] (0,0) circle (5); {[start chain=bindingchain] \foreach \a/\c in {150/green, 270/red, 390/blue} { \draw[gray] (0,0) -- (\a:5) node (\c) [\c, midway, thick, draw, circle, minimum width=25] {}; \chainin (\c); } } \end{tikzpicture} ``` [![chained nodes](https://i.stack.imgur.com/yHkYk.png)](https://i.stack.imgur.com/yHkYk.png) If you want to make use of the `join` option, you can add it when you `\chainin` the nodes. For example: ``` \begin{tikzpicture} \draw[black, thick] (0,0) circle (5); {[start chain=bindingchain] \foreach \a/\c in {150/green, 270/red, 390/blue} { \draw[gray] (0,0) -- (\a:5) node (\c) [\c, midway, thick, draw, circle, minimum width=25] {}; \chainin (\c) [join]; } } \end{tikzpicture} ``` [![join the chain](https://i.stack.imgur.com/6HtaY.png)](https://i.stack.imgur.com/6HtaY.png) Other options for chains can be added in similar fashion. Complete code: ``` \documentclass[tikz,multi,border=10pt]{standalone} \usetikzlibrary{chains,scopes} \begin{document} \begin{tikzpicture} \draw[black, thick] (0,0) circle (5); {[start chain=bindingchain] \foreach \a/\c in {150/green, 270/red, 390/blue} { \draw[gray] (0,0) -- (\a:5) node (\c) [\c, midway, thick, draw, circle, minimum width=25] {}; \chainin (\c); } } \end{tikzpicture} \begin{tikzpicture} \draw[black, thick] (0,0) circle (5); {[start chain=bindingchain] \foreach \a/\c in {150/green, 270/red, 390/blue} { \draw[gray] (0,0) -- (\a:5) node (\c) [\c, midway, thick, draw, circle, minimum width=25] {}; \chainin (\c) [join]; } } \end{tikzpicture} \begin{tikzpicture} \draw[black, thick] (0,0) circle (5); {[start chain=first] \node [on chain, thick, double, draw, circle, minimum width=25] at (270:2.5) {}; \node [on chain, thick, double, draw, circle, minimum width=25, anchor=center] {}; \node (s) [thick, double, draw, circle, minimum width=25] at (390:2.5) {}; \chainin (s); \node [on chain, thick, double, draw, circle, minimum width=25, anchor=center] {}; } \begin{scope}[start chain=bindingchain] \foreach \a/\c in {150/green, 270/red, 390/blue} \draw[gray] (0,0) -- (\a:5) node [\c, midway, thick, draw, circle, minimum width=25, on chain] {}; \end{scope} \end{tikzpicture} \end{document} ```
This can all be done without the `chains` library ... ``` \documentclass[border=2mm]{standalone} \usepackage{tikz} \begin{document} \begin{tikzpicture} %circle \draw[black, thick] (0,0) circle (5); \foreach \a/\c/\name in {150/green/a, 270/red/b, 390/blue/c} \draw[gray] (0,0) -- (\a:5) node [\c, midway, thick, draw, circle, minimum size=25] (\name) {} ; \draw (a) -- (b) -- (c); \end{tikzpicture} \end{document} ``` [![image showing the result of above code](https://i.stack.imgur.com/3zX9m.png)](https://i.stack.imgur.com/3zX9m.png)
2,890
From what I remember, no character in Pokemon is shown going to any sort of religious house of worship, and there doesn't seem to be much if any mention of religion/religious beliefs until Sinnoh, where there is lore following Arceus's creation of the world. Are there any organized religions in the world, worshiping either Arceus or some other deity/pantheon?
2013/03/14
[ "https://anime.stackexchange.com/questions/2890", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/93/" ]
Neither in the Anime, nor in the Games or the Manga is ever mentioned something about religions. Religious aspects can be seen sometimes (like your example of Arceus, but also the wise men in the Sprout Tower or the Slowpoke-temple in the anime), but they aren't a real topic. Either in the anime or in one of the games, it's mentioned that most of the people at least in Lavender Town are religious. But besides of that, nothing was mentioned in the anime/manga/games.
Well, I don't know if this would work, but there was that big crystal flower tractor beam hidden underground under Geosenge Town in X and Y, and the long living AZ used it to kill off dozens of Pokémon to bring back his floette, correct? I think that Lysandre, for the sake of his 'beautiful' world, sought to unleash that crystal flower tractor beam and eradicate all Pokémon as his duty, so I guess he believed religiously in a world without Pokémon. (That's also a little rich from Lysandre, cause he would be seen using Pokémon, jk) Otherwise, I dunno. It in some aspects depends on how you view the games itself, and how it relates to real life beliefs, places, and all sorts. It was basically Lysandre's religion that, 'let's say there is a god, and he came to me and told me to try making a Pokemon free world, and I agreed, cause I liked the idea, and I want to achieve that.' Sorta like that. He sorta is following that 'God' that wanted him to do it. (Even though the god wasn't mentioned at all, that's still what I think) I don't know, but hope this helped! - Matt Hope I don't get down rated.
2,890
From what I remember, no character in Pokemon is shown going to any sort of religious house of worship, and there doesn't seem to be much if any mention of religion/religious beliefs until Sinnoh, where there is lore following Arceus's creation of the world. Are there any organized religions in the world, worshiping either Arceus or some other deity/pantheon?
2013/03/14
[ "https://anime.stackexchange.com/questions/2890", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/93/" ]
It's not a religion from the present Pokemon World, but in the manga series *[The Electric Tale of Pikachu (Dengeki Pikachu)](http://bulbapedia.bulbagarden.net/wiki/The_Electric_Tale_of_Pikachu)*, in the fourth chapter ([Haunting my Dreams](http://bulbapedia.bulbagarden.net/wiki/ET04)), Brock says to Ash that in "ancient times" the people who lived near the Pokemon Tower in Lavender Town worshipped Pokemon as gods: [![enter image description here](https://i.stack.imgur.com/dRh8F.png)](https://i.stack.imgur.com/dRh8F.png)
Neither in the Anime, nor in the Games or the Manga is ever mentioned something about religions. Religious aspects can be seen sometimes (like your example of Arceus, but also the wise men in the Sprout Tower or the Slowpoke-temple in the anime), but they aren't a real topic. Either in the anime or in one of the games, it's mentioned that most of the people at least in Lavender Town are religious. But besides of that, nothing was mentioned in the anime/manga/games.
2,890
From what I remember, no character in Pokemon is shown going to any sort of religious house of worship, and there doesn't seem to be much if any mention of religion/religious beliefs until Sinnoh, where there is lore following Arceus's creation of the world. Are there any organized religions in the world, worshiping either Arceus or some other deity/pantheon?
2013/03/14
[ "https://anime.stackexchange.com/questions/2890", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/93/" ]
It's not a religion from the present Pokemon World, but in the manga series *[The Electric Tale of Pikachu (Dengeki Pikachu)](http://bulbapedia.bulbagarden.net/wiki/The_Electric_Tale_of_Pikachu)*, in the fourth chapter ([Haunting my Dreams](http://bulbapedia.bulbagarden.net/wiki/ET04)), Brock says to Ash that in "ancient times" the people who lived near the Pokemon Tower in Lavender Town worshipped Pokemon as gods: [![enter image description here](https://i.stack.imgur.com/dRh8F.png)](https://i.stack.imgur.com/dRh8F.png)
Well, I don't know if this would work, but there was that big crystal flower tractor beam hidden underground under Geosenge Town in X and Y, and the long living AZ used it to kill off dozens of Pokémon to bring back his floette, correct? I think that Lysandre, for the sake of his 'beautiful' world, sought to unleash that crystal flower tractor beam and eradicate all Pokémon as his duty, so I guess he believed religiously in a world without Pokémon. (That's also a little rich from Lysandre, cause he would be seen using Pokémon, jk) Otherwise, I dunno. It in some aspects depends on how you view the games itself, and how it relates to real life beliefs, places, and all sorts. It was basically Lysandre's religion that, 'let's say there is a god, and he came to me and told me to try making a Pokemon free world, and I agreed, cause I liked the idea, and I want to achieve that.' Sorta like that. He sorta is following that 'God' that wanted him to do it. (Even though the god wasn't mentioned at all, that's still what I think) I don't know, but hope this helped! - Matt Hope I don't get down rated.
170,801
What is the usual community response to questions that are posted on other sites as well? For example if the same question is posted on [StackOverflow](https://stackoverflow.com/) and on [CodeProject](http://www.codeproject.com/) what would the community do? Answer the question or direct users to the other site? I assume they would just answer it. But what if it became a common fad? If a tool was made to post questions simultaneously across these type of sites? It seems to me this would be an approach used by people who want to combine the corporate intelligence of people, regardless of which communities they are most closely tied to
2013/03/07
[ "https://meta.stackexchange.com/questions/170801", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/182146/" ]
It would in most likelihood not even be noticed. Most people are not super active on more than one site. People would just answer it and move on.
Posting a question on both StackOverflow and Code Project is perfectly legitimate. And it's perfectly acceptable (and even encouraged) for people to answer the question a second time on StackOverflow. And as for this problem happening in mass quantities, and writing a tool for migration... We'll cross that bridge when we come to it. I'm not quite sure what problem you're trying to solve.
170,801
What is the usual community response to questions that are posted on other sites as well? For example if the same question is posted on [StackOverflow](https://stackoverflow.com/) and on [CodeProject](http://www.codeproject.com/) what would the community do? Answer the question or direct users to the other site? I assume they would just answer it. But what if it became a common fad? If a tool was made to post questions simultaneously across these type of sites? It seems to me this would be an approach used by people who want to combine the corporate intelligence of people, regardless of which communities they are most closely tied to
2013/03/07
[ "https://meta.stackexchange.com/questions/170801", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/182146/" ]
We don't mind cross-posting across to other sites. We **do** mind however, about cross posting inside the Stack Exchange network (i.e. don't post the same question on both Stack Overflow and, say, Programmers). If the OP is attentive enough to respond to both questions he started on the two different sites, so be it.
Posting a question on both StackOverflow and Code Project is perfectly legitimate. And it's perfectly acceptable (and even encouraged) for people to answer the question a second time on StackOverflow. And as for this problem happening in mass quantities, and writing a tool for migration... We'll cross that bridge when we come to it. I'm not quite sure what problem you're trying to solve.
7,930,931
I'm working on an Asp.Net MVC 3 application using Fluent NHibernate. I'm just attempting to add an IoC container using StructureMap. I have implemented a custom controller factory which uses StructureMap to create the controller and inject dependencies. Each controller constructor takes one or more services, which in turn take a DAO as constructor argument. Each DAO constructor takes an ISessionFactory. For my StructureMap NHibernate registry I have the following: ``` internal class NHibernateRegistry : Registry { public NHibernateRegistry() { var connectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString; For<ISessionFactory>() .Singleton() .Use(x => new AppSessionFactory().GetSessionFactory(connectionString)); For<ISession>() .HybridHttpOrThreadLocalScoped() .Use(x => x.GetInstance<ISessionFactory>().OpenSession()); } } public class AppSessionFactory { public ISessionFactory GetSessionFactory(string connectionString) { return GetConfig(connectionString) .BuildSessionFactory(); } public static FluentConfiguration GetConfig(string connectionString) { return Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(x => x.Is(connectionString))) .Mappings( x => x.FluentMappings.AddFromAssemblyOf<AppEntity>()); } } ``` This all works fine for a single database and single session factory. However the application uses multiple databases. What is the best way to handle this?
2011/10/28
[ "https://Stackoverflow.com/questions/7930931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95423/" ]
Registering multiple session factories is easy - the problem is selecting the right one when you need it. For example, let's say we have some sort of laboratory that has multiple databases. Each lab has a Location and multiple Samples for that location. We could have a SampleRepository that models that. Each Location has a unique key to identify it (e.g. "LabX", "LabY", "BlackMesa"). We can use that unique key as the name of the database connection string in the app.config file. In this example, we would have three connection strings in the app.config file. Here's a sample connectionStrings section: ``` <connectionStrings> <add name="LabX" connectionString="Data Source=labx;User ID=someuser;Password=somepassword"/> <add name="LabY" connectionString="Data Source=laby;User ID=someuser;Password=somepassword"/> <add name="BlackMesa" connectionString="Data Source=blackmesa;User ID=freemang;Password=crowbar"/> </connectionStrings> ``` Thus, we need to have a unique session factory for each connection string. Let's create a NamedSessionFactory that wraps ISessionFactory: ``` public interface INamedSessionFactory { public string Name { get; } // The name from the config file (e.g. "BlackMesa") public ISessionFactory SessionFactory { get; } } public class NamedSessionFactory : INamedSessionFactory { public string Name { get; private set; } public ISessionFactory SessionFactory { get; private set; } public NamedSessionFactory(string name, ISessionFactory sessionFactory) { Name = name; SessionFactory = sessionFactory; } } ``` Now we need to modify your AppSessionFactory a bit. First off, what you've created is a session factory factory - that's not quite what we're looking for. We want to give our factory a location and get a session out of it, not a session factory. Fluent NHibernate is what gives us session factories. ``` public interface IAppSessionFactory { ISession GetSessionForLocation(string locationKey); } ``` The trick here is accept a list of INamedSessionFactory objects in the constructor. StructureMap should give us all of the INamedSessionFactory objects that we've registered. We'll get to registration in a second. ``` public class AppSessionFactory : IAppSessionFactory { private readonly IList<INamedSessionFactory> _factories; public AppSessionFactory(IEnumerable<INamedSessionFactory factories) { _factories = new List<INamedSessionFactory>(factories); } ``` This is where the magic happens. Given a location key, we run through our list of factories looking for one with the same name as locationKey, then ask it to open a session and return it to the caller. ``` public ISession GetSessionForLocation(string locationKey) { var sessionFactory = _factories.Where(x => x.Name == locationKey).Single(); return sessionFactory.OpenSession(); } } ``` Now let's wire this all together. ``` internal class NHibernateRegistry : Registry { public NHibernateRegistry() { ``` We're going to loop through all of the connection strings in our app.config file (there would be three of them in this example) and register an INamedSessionFactory object for each one. ``` foreach (ConnectionStringSettings location in ConfigurationManager.ConnectionStrings) { For<INamedSessionFactory>() .Singleton() .Use(x => new NamedSessionFactory( location.Name, GetSessionFactory(location.ConnectionString)); } ``` We also need to register IAppSessionFactory. ``` For<IAppSessionFactory>() .Singleton() .Use<AppSessionFactory>(); } ``` You'll notice that we've moved this logic out of the factory class... These are helper methods for creating session factories from Fluent NHibernate. ``` private static ISessionFactory GetSessionFactory(string connectionString) { return GetConfig(connectionString) .BuildSessionFactory(); } public static FluentConfiguration GetConfig(string connectionString) { return Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(x => x.Is(connectionString))) .Mappings( x => x.FluentMappings.AddFromAssemblyOf<AppEntity>()); } } ``` That should do it! Let's create a repository for getting at our samples... ``` public class SampleRepository { private readonly IAppSessionFactory _factory; public SampleRepository(IAppSessionFactory factory) { _factory = factory; } public IEnumerable<Sample> GetSamplesForLocation(Location location) { using (ISession session = _factory.GetSessionForLocation(location.Key) { foreach (Sample sample in session.Query<Sample>()) yield return sample; } } } ``` Now you can get a single instance of SampleRepository and use the GetSamplesForLocation method to pull samples from any of the three databases we have registered in app.config. Might want to avoid BlackMesa though. I understand there were problems there.
Are you sure this thing works? **string ISessionFactory** ``` public string ISessionFactory SessionFactory { get; private set; } ``` should this be ``` public interface INamedSessionFactory { ISessionFactory SessionFactory { get; set; } string Name { get; } } public class NamedSessionFactory : INamedSessionFactory { public ISessionFactory SessionFactory { get; set; } public string Name { get; private set; } public NamedSessionFactory(string Name, ISessionFactory SessionFactory) { this.Name = Name; this.SessionFactory = SessionFactory; } } ```
22,118,221
I have a string and I need to scan for every occurrence of "foo" and read all the text following it until a second `"`. ~~Since Rust does not have a `contains` function for strings~~, I need to iterate by characters scanning for it. How would I do this? **Edit**: Rust's `&str` has a [`contains()`](https://doc.rust-lang.org/std/primitive.str.html#method.contains) and [`find()`](https://doc.rust-lang.org/std/primitive.str.html#method.find) method.
2014/03/01
[ "https://Stackoverflow.com/questions/22118221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2171584/" ]
> > I need to iterate by characters scanning for it. > > > The [`.chars()` method](http://doc.rust-lang.org/std/primitive.str.html#method.chars) returns an iterator over characters in a string. e.g. ``` for c in my_str.chars() { // do something with `c` } for (i, c) in my_str.chars().enumerate() { // do something with character `c` and index `i` } ``` If you are interested in the byte offsets of each char, you can use [`char_indices`](https://doc.rust-lang.org/std/primitive.str.html#method.char_indices). Look into `.peekable()`, and use `peek()` for looking ahead. It's wrapped like this because it supports UTF-8 codepoints instead of being a simple vector of characters. You could also create a vector of `char`s and work on it from there, but that's more time and space intensive: ``` let my_chars: Vec<_> = mystr.chars().collect(); ```
The concept of a "character" is very ambiguous and can mean many different things depending on the type of data you are working with. The most obvious answer is the [`chars`](https://doc.rust-lang.org/std/primitive.str.html#method.chars) method. However, this does not work as advertised. What looks like a single "character" to you may actually be made up of multiple Unicode *code points*, which can lead to unexpected results: ```rust "a̐".chars() // => ['a', '\u{310}'] ``` For a lot of string processing, you want to work with *graphemes*. A grapheme consists of one or more unicode code points represented as a string slice. These map better to the human perception of "characters". To create an iterator of graphemes, you can use the [`unicode-segmentation`](https://github.com/unicode-rs/unicode-segmentation) crate: ```rust use unicode_segmentation::UnicodeSegmentation; for grapheme in my_str.graphemes(true) { // ... } ``` If you are working with raw ASCII then none of the above applies to you, and you can simply use the `bytes` iterator: ```rust for byte in my_str.bytes() { // ... } ``` Although, if you are working with ASCII then arguably you shouldn't be using `String`/`&str` at all and instead use `Vec<u8>`/`&[u8]` directly.
22,118,221
I have a string and I need to scan for every occurrence of "foo" and read all the text following it until a second `"`. ~~Since Rust does not have a `contains` function for strings~~, I need to iterate by characters scanning for it. How would I do this? **Edit**: Rust's `&str` has a [`contains()`](https://doc.rust-lang.org/std/primitive.str.html#method.contains) and [`find()`](https://doc.rust-lang.org/std/primitive.str.html#method.find) method.
2014/03/01
[ "https://Stackoverflow.com/questions/22118221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2171584/" ]
> > I need to iterate by characters scanning for it. > > > The [`.chars()` method](http://doc.rust-lang.org/std/primitive.str.html#method.chars) returns an iterator over characters in a string. e.g. ``` for c in my_str.chars() { // do something with `c` } for (i, c) in my_str.chars().enumerate() { // do something with character `c` and index `i` } ``` If you are interested in the byte offsets of each char, you can use [`char_indices`](https://doc.rust-lang.org/std/primitive.str.html#method.char_indices). Look into `.peekable()`, and use `peek()` for looking ahead. It's wrapped like this because it supports UTF-8 codepoints instead of being a simple vector of characters. You could also create a vector of `char`s and work on it from there, but that's more time and space intensive: ``` let my_chars: Vec<_> = mystr.chars().collect(); ```
``` fn main() { let s = "Rust is a programming language"; for i in s.chars() { print!("{}", i); }} ``` > > Output: Rust is a programming language > > > I use the chars() method to iterate over each element of the string.
22,118,221
I have a string and I need to scan for every occurrence of "foo" and read all the text following it until a second `"`. ~~Since Rust does not have a `contains` function for strings~~, I need to iterate by characters scanning for it. How would I do this? **Edit**: Rust's `&str` has a [`contains()`](https://doc.rust-lang.org/std/primitive.str.html#method.contains) and [`find()`](https://doc.rust-lang.org/std/primitive.str.html#method.find) method.
2014/03/01
[ "https://Stackoverflow.com/questions/22118221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2171584/" ]
The concept of a "character" is very ambiguous and can mean many different things depending on the type of data you are working with. The most obvious answer is the [`chars`](https://doc.rust-lang.org/std/primitive.str.html#method.chars) method. However, this does not work as advertised. What looks like a single "character" to you may actually be made up of multiple Unicode *code points*, which can lead to unexpected results: ```rust "a̐".chars() // => ['a', '\u{310}'] ``` For a lot of string processing, you want to work with *graphemes*. A grapheme consists of one or more unicode code points represented as a string slice. These map better to the human perception of "characters". To create an iterator of graphemes, you can use the [`unicode-segmentation`](https://github.com/unicode-rs/unicode-segmentation) crate: ```rust use unicode_segmentation::UnicodeSegmentation; for grapheme in my_str.graphemes(true) { // ... } ``` If you are working with raw ASCII then none of the above applies to you, and you can simply use the `bytes` iterator: ```rust for byte in my_str.bytes() { // ... } ``` Although, if you are working with ASCII then arguably you shouldn't be using `String`/`&str` at all and instead use `Vec<u8>`/`&[u8]` directly.
``` fn main() { let s = "Rust is a programming language"; for i in s.chars() { print!("{}", i); }} ``` > > Output: Rust is a programming language > > > I use the chars() method to iterate over each element of the string.
26,065,679
I have the following code that is facing a NullPointerException error in Netbeans. The code is actually written for use with a GUI using java frames. But I edited to only use it from the cmd. I have ran through the codes but couldn't find out why the error is popping up. Can anyone highlight whats the problem here? The error message indicated the line of error is at the assignment of threeDPixMod and oneDPix ``` package image_processor; import java.awt.*; import java.awt.image.*; import java.io.*; import javax.imageio.ImageIO; class ImgMod02a { BufferedImage rawImg; BufferedImage buffImage; int imgCols;//Number of horizontal pixels int imgRows;//Number of rows of pixels static String theProcessingClass = "C:/Users/Faiz/Documents/NetBeansProjects/image_processor/src/image_processor/ImgMod35a.java"; static String theImgFile = "C:/Users/Faiz/Desktop/DCT/ibrahim2.jpg"; int[][][] threeDPix; int[][][] threeDPixMod; int[] oneDPix; //Reference to the image processing object. ImgIntfc02 imageProcessingObject; //-------------------------------------------// public static void main(String[] args) throws IOException { //Display name of processing program and // image file. System.out.println("Processing program: " + theProcessingClass); System.out.println("Image file: " + theImgFile); //Instantiate an object of this class ImgMod02a obj = new ImgMod02a(); }//end main //-------------------------------------------// public ImgMod02a() throws IOException { rawImg = ImageIO.read(new File(theImgFile)); imgCols = rawImg.getWidth(); imgRows = rawImg.getHeight(); threeDPixMod = imageProcessingObject.processImg(threeDPix,imgRows,imgCols); oneDPix = convertToOneDim(threeDPixMod,imgCols,imgRows); oneDPix = new int[imgCols * imgRows]; //Create an empty BufferedImage object buffImage = new BufferedImage(imgCols,imgRows,BufferedImage.TYPE_INT_ARGB); // Draw Image into BufferedImage Graphics g = buffImage.getGraphics(); g.drawImage(rawImg, 0, 0, null); //Convert the BufferedImage to numeric pixel // representation. DataBufferInt dataBufferInt = (DataBufferInt)buffImage.getRaster().getDataBuffer(); oneDPix = dataBufferInt.getData(); threeDPix = convertToThreeDim(oneDPix,imgCols,imgRows); try { imageProcessingObject = (ImgIntfc02)Class.forName("image_processor.ImgMod35a").newInstance(); }catch(Exception e) { System.out.println(e); }//end catch }//end constructor //===========================================// int[][][] convertToThreeDim(int[] oneDPix,int imgCols,int imgRows) { //Create the new 3D array to be populated // with color data. int[][][] data = new int[imgRows][imgCols][4]; for(int row = 0;row < imgRows;row++){ //Extract a row of pixel data into a // temporary array of ints int[] aRow = new int[imgCols]; for(int col = 0; col < imgCols;col++) { int element = row * imgCols + col; aRow[col] = oneDPix[element]; }//end for loop on col for(int col = 0;col < imgCols;col++) { //Alpha data data[row][col][0] = (aRow[col] >> 24) & 0xFF; //Red data data[row][col][1] = (aRow[col] >> 16) & 0xFF; //Green data data[row][col][2] = (aRow[col] >> 8) & 0xFF; //Blue data data[row][col][3] = (aRow[col]) & 0xFF; }//end for loop on col }//end for loop on row return data; }//end convertToThreeDim //-------------------------------------------// final int[] convertToOneDim(int[][][] data,int imgCols,int imgRows) { int[] oneDPix = new int[imgCols * imgRows * 4]; for(int row = 0,cnt = 0;row < imgRows;row++) { for(int col = 0;col < imgCols;col++){ oneDPix[cnt] = ((data[row][col][0] << 24)& 0xFF000000)| ((data[row][col][1] << 16) & 0x00FF0000)| ((data[row][col][2] << 8) & 0x0000FF00)| ((data[row][col][3]) & 0x000000FF); cnt++; }//end for loop on col }//end for loop on row return oneDPix; }//end convertToOneDim }//end ImgMod02a.java class ``` The processImg is a method from an interface ``` interface ImgIntfc02 { int[][][] processImg(int[][][] threeDPix, int imgRows, int imgCols); } ``` This is the line that is causing the error ``` threeDPixMod = imageProcessingObject.processImg(threeDPix,imgRows,imgCols); ``` But when I try commenting out the line, other lines appear to have the NullPointerException error as well. The error message: > > Exception in thread "main" java.lang.NullPointerException > > at > image\_processor.ImgMod02a.(ImgMod02a.java:48) > > at > image\_processor.ImgMod02a.main(ImgMod02a.java:37) > > >
2014/09/26
[ "https://Stackoverflow.com/questions/26065679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1867016/" ]
Without using `for` at all, you need a lambda: ``` >>> a = [[1.2,5.8,6,3], [1,48,5], [2.,3], [4,7,5.,2,5,3,6,554,6.,6,9], [6,.3,8,45.2,.001]] >>> reduce(lambda x, y: x*len(y), a, 1) 1320 ``` Or without lambda: ``` >>> reduce(operator.mul, map(len, a), 1) ``` Or using numpy: ``` >>> import numpy as np >>> np.prod(map(len, a)) ```
This uses `reduce` and `operator.mul`: ``` >>> import operator >>> a = [[1.2,5.8,6,3], [1,48,5], [2.,3], [4,7,5.,2,5,3,6,554,6.,6,9], [6,.3,8,45.2,.001]] >>> reduce(operator.mul, (len(l) for l in a), 1) 1320 ```
10,329
Would it be possible for a an amateur who is interested in getting some "hands-on" experience in desining and training deep neural networks, to use an ordinary laptop for that purpose (no GPU), or is it hopeless to get good results in reasonable time without a powerful computer/cluster/GPU? To be more specific, the laptop's CPU is an Intel Core i7 5500U fith generation, with 8GB RAM. Now, since I haven't specified what problems I would like to work on, I'll frame my questions in a different way: which deep architectures would you recommend that I try to implement with my hardware, such that the following goal is achieved: Acquiring intuition and knowledge about how and when to use techniques that were introduced in the past 10 years and were essential to the uprising of deep nets (such as understanding of initialisations, drop-out, rmsprop, just to name a few). I read about these techniques, but of course without trying them out myself I wouldn't know exactly how and when to implement these in an effective way. On the other hand, I'm afraid that if I try using a PC which isn't strong enough, then my own learning rate will be so slow that it would be meaningless to say that I've acquired any better understanding. And if I try using these techniques on shallow nets, maybe I wouldn't be building the right intuition. I imagine the process of (my) learning as follows: I implement a neural net, let it practice for up to several hours, see what I've got, and repeat the process. If I do this once or twice a day, I would be happy if after, say, 6 months I will have gained practical knowledge which is comparable to what a professional in the field should know.
2016/02/20
[ "https://datascience.stackexchange.com/questions/10329", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/16424/" ]
**Yes, a laptop will work just fine for getting acquainted with some deep learning projects:** You can pick a smallish deep learning problem and gain some tractable insight using a laptop so give it a try. The [Theano](http://deeplearning.net/software/theano/) project has a [set of tutorials](http://deeplearning.net/tutorial/lenet.html) on digit recognition that I've played with and moded on a laptop. [Tensorflow](https://www.tensorflow.org/) also has a [set of tutorials](https://www.tensorflow.org/versions/r0.8/tutorials/index.html). I let some of the longer runs go overnight, but nothing was intractable. You might also consider availing yourself of [AWS](https://aws.amazon.com/) or one of the other cloud services. For 20-30 dollars you can perform some of the bigger calculations in the cloud on some sort of [elastic computing node](https://aws.amazon.com/ec2/). The secondary advantage is that you can also list AWS or other cloud services as skill on your resume also :-) Hope this helps!
> > [...] is it hopeless to get good results in reasonable time without a powerful computer/cluster/GPU? > > > It's not hopeless and you can, without doubt, gain lots of relevant experience with deep learning using the computer spec you mentioned. It will come down to your neural network architecture (number of layers and neurons), size of the dataset (number of inputs), nature of the data (inherent patterns), and implementation. And although you may need to limit yourself with those regards it won't prevent you from acquiring intuition and knowledge you're referring to. You'll easily experience problems of overfitting, influence of regularization, effects of pre-training, impact of different neuron types and architectures to name a few. I'll give you a more concrete example. I've implemented a couple of deep learning algorithms (all CPU-based) in Julia and run them on a MacBook Air (similar to your spec). The code was not terribly optimised as neurons and layers were represented by actual data structures rather than a single giant matrix. So further performance improvements were possible. For a fully-connected network of 56x300x300x300x1 (56 inputs and approx 200k connections) and 250 training examples I was able to get 5k back propagation passes within a day. Often that was enough to overfit the data or perfectly fit the training set (but this will depend on your dataset and other aforementioned factors). If the data has strong patterns and less than 10k examples you often won't need that many iterations. It's not uncommon that few hundreds of pre-training and refinement iterations lead to good results. So yes, your laptop is good enough and you could run meaningful experiments that take several hours. > > [...] which deep architectures would you recommend that I try to implement with my hardware, such that the following goal is achieved: Acquiring intuition and knowledge about how and when to use techniques that were introduced in the past 10 years and were essential to the uprising of deep nets. > > > I'd suggest to pick smaller datasets with strong patterns. And I'd recommend to look into pre-training techniques such as auto-encoders because they often require fewer iterations to reach better results. Start with back propagation and build from there, try different architectures, neuron types, use regularization, auto-encoders, dropout, ... Also make sure to pick a performant language or library for your experiments.
67,399,543
I am trying to select an HTML element with an id that is a number, ie. `<div id=27047243>` When I try to use the select method like this `soup.select("#27047243")` I get an error that says *Malformed id selector* I figured I need to escape the number somehow, I tried like this `soup.select(r"#\3{number}"` but even though I did not get the error anymore, I could not get the element I know I could use the find method `soup.find(id="27047243")` and that works, but the problem is I need to go deeper into nested elements so I want to know if there is a way how to do this using 'select' so I can use CSS selectors
2021/05/05
[ "https://Stackoverflow.com/questions/67399543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14062581/" ]
This can be seen quite often in [Streamlit discussions](https://discuss.streamlit.io/t/the-button-inside-a-button-seems-to-reset-the-whole-app-why/1051) because it looks like a bug at the first glance, but it's not. A simple and silly answer would be "That's the way streamlit is designed". So every time you press the button, streamlit will re-run the whole web page and it doesn't remember the previous state(information in the previous button). Although I never found any official answer on how to exactly solve this, I did manage to do some workarounds. 1. Using checkboxes rather than buttons 2. Using [Session State](https://discuss.streamlit.io/t/is-there-any-working-example-for-session-state-for-streamlit-version-0-63-1/4551) 3. Creating small functions and calling them during your `if` conditions.
When you click `About Python`: * the value of `left_one` becomes `True` * the value of all other buttons (including `generate_syntax`) becomes `False` When you click `Generate Syntax`: * the value of `generate_syntax` becomes `True` * the value of `left_one` becomes `False` The issue is that you never meet both conditions of `generate_syntax` being `True` AND `left one` being `True`. So you never print `"Hello All"` Streamlit only thinks of one statechange at a time when it comes to buttons. The way to get around this is by using an object to store state. @pathe\_rao has already suggesting using `SessionState` object from [this gist](https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92): ```py import streamlit as st ### Copy and Paste Session state code here session_state = SessionState.get(left =False, right = False, center = False) left, center, right = st.beta_columns(3) left_one = left.button("About Python",key = "1") center_one = center.button("Learn Python", key = "2") right_one = right.button("Practice Python", key = "3") if left_one or session_state.left: session_state.left = True session_state.right = False session_state.center = False generate_syntax = st.button("Generate Syntax", key = "4") if generate_syntax: st.write("Hello All..") if center_one or session_state.center: session_state.left = False session_state.right = False session_state.center = True if right_one or session_state.right: session_state.left = False session_state.right = True session_state.center = False ```
52,401,118
I have created a scheduler with following events and resources ``` var sampleEvents = [{ 'id': '1', 'resourceid': '27', 'start': '2018-09-19T07:00:00', 'stop': '2018-09-19T16:00:00', 'title': 'Message 1', }]; var sampleResources = [{ facility_type: "Message Type", id: '27', title: "Message 1" }]; $('#calendar').fullCalendar({ schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives', now: currenDate //Today's Date, editable: false, header: { left: 'today prev,next', center: 'title', right: 'month,timelineDay,agendaWeek' }, defaultView: 'month', resourceGroupField: 'facility_type', resourceColumns: [ { labelText: 'Facility', field: 'title', width: 150, }, ], resources: sampleEvents, events: sampleResources, dayClick: function(date, jsEvent, view) { if(view.name == 'month' || view.name == 'basicWeek') { $('#calendar').fullCalendar('changeView', 'timelineDay'); $('#calendar').fullCalendar('gotoDate', date); } }, }); }, function (error) { }); ``` The events are showing in month view, but they are not shown in day view. Can someone tell me where the problem is?
2018/09/19
[ "https://Stackoverflow.com/questions/52401118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In JavaScript, variable and property names are case-sensitive. Therefore ``` 'resourceid': '27'` ``` should be ``` 'resourceId': '27' ``` as [per the example in the documentation](https://fullcalendar.io/docs/resources-and-events). The event isn't showing the timeline view because as far as fullCalendar is concerned you didn't tell it which resource to associate it with.
``` resources: sampleEvents, events: sampleResources, ``` You filled them wrong. Switch them. It will work. ``` resources: sampleResources, events: sampleEvents, ```
52,401,118
I have created a scheduler with following events and resources ``` var sampleEvents = [{ 'id': '1', 'resourceid': '27', 'start': '2018-09-19T07:00:00', 'stop': '2018-09-19T16:00:00', 'title': 'Message 1', }]; var sampleResources = [{ facility_type: "Message Type", id: '27', title: "Message 1" }]; $('#calendar').fullCalendar({ schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives', now: currenDate //Today's Date, editable: false, header: { left: 'today prev,next', center: 'title', right: 'month,timelineDay,agendaWeek' }, defaultView: 'month', resourceGroupField: 'facility_type', resourceColumns: [ { labelText: 'Facility', field: 'title', width: 150, }, ], resources: sampleEvents, events: sampleResources, dayClick: function(date, jsEvent, view) { if(view.name == 'month' || view.name == 'basicWeek') { $('#calendar').fullCalendar('changeView', 'timelineDay'); $('#calendar').fullCalendar('gotoDate', date); } }, }); }, function (error) { }); ``` The events are showing in month view, but they are not shown in day view. Can someone tell me where the problem is?
2018/09/19
[ "https://Stackoverflow.com/questions/52401118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In JavaScript, variable and property names are case-sensitive. Therefore ``` 'resourceid': '27'` ``` should be ``` 'resourceId': '27' ``` as [per the example in the documentation](https://fullcalendar.io/docs/resources-and-events). The event isn't showing the timeline view because as far as fullCalendar is concerned you didn't tell it which resource to associate it with.
Assigned objects are improper. If you pass the correct objects. It will work fine ``` resources: sampleResources, events: sampleEvents ``` You can refer below working jsfiddle link ``` http://jsfiddle.net/jso51pm6/3769/ ```
52,401,118
I have created a scheduler with following events and resources ``` var sampleEvents = [{ 'id': '1', 'resourceid': '27', 'start': '2018-09-19T07:00:00', 'stop': '2018-09-19T16:00:00', 'title': 'Message 1', }]; var sampleResources = [{ facility_type: "Message Type", id: '27', title: "Message 1" }]; $('#calendar').fullCalendar({ schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives', now: currenDate //Today's Date, editable: false, header: { left: 'today prev,next', center: 'title', right: 'month,timelineDay,agendaWeek' }, defaultView: 'month', resourceGroupField: 'facility_type', resourceColumns: [ { labelText: 'Facility', field: 'title', width: 150, }, ], resources: sampleEvents, events: sampleResources, dayClick: function(date, jsEvent, view) { if(view.name == 'month' || view.name == 'basicWeek') { $('#calendar').fullCalendar('changeView', 'timelineDay'); $('#calendar').fullCalendar('gotoDate', date); } }, }); }, function (error) { }); ``` The events are showing in month view, but they are not shown in day view. Can someone tell me where the problem is?
2018/09/19
[ "https://Stackoverflow.com/questions/52401118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Assigned objects are improper. If you pass the correct objects. It will work fine ``` resources: sampleResources, events: sampleEvents ``` You can refer below working jsfiddle link ``` http://jsfiddle.net/jso51pm6/3769/ ```
``` resources: sampleEvents, events: sampleResources, ``` You filled them wrong. Switch them. It will work. ``` resources: sampleResources, events: sampleEvents, ```
571,507
I'm not really knowledgeable on physics but was curious about this and couldn't find any good answers related to it.
2020/08/06
[ "https://physics.stackexchange.com/questions/571507", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/271661/" ]
Energy is conserved in the whole universe \*. Nevertheless, if you delimit a system and you focus only on that system, forces can vary the energy of the system. Total energy is conserved in the universe, but in your particular system migh not. If you wide your system to include more objects, then you'll find energy conserved. [\*] Energy will be conserved as long as time is translationally symmetric (i.e. all instants are equivalent), according to Noether's theorems.
To be clear, if you "lift a book at constant velocity" you are still having to provide a force against gravity and so are still "doing work". Perhaps what you mean is an object moving at constant velocity in a vacuum. If no external forces act on this object its energy doesn't change. If you're asking if the conservation of energy holds in the two following situations *in a vacuum*: 1. You apply a force $F$ to an initially stationary object and move it from $A$ to $B$. 2. You allow an object to travel at a constant velocity between $A$ and $B$ without applying any force to it. then the answer is yes. Energy *is* conserved in both of these cases. 1. In the first case you (the person pushing the object) are applying a force to the object and giving up some of your energy which turns into kinetic energy for the object. The total energy you lose to the object equals the total kinetic energy gained by the object. So no net energy is being lost, only transferred. 2. In this situation energy is neither being lost nor gained by both you and the object.
571,507
I'm not really knowledgeable on physics but was curious about this and couldn't find any good answers related to it.
2020/08/06
[ "https://physics.stackexchange.com/questions/571507", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/271661/" ]
Energy is conserved in the whole universe \*. Nevertheless, if you delimit a system and you focus only on that system, forces can vary the energy of the system. Total energy is conserved in the universe, but in your particular system migh not. If you wide your system to include more objects, then you'll find energy conserved. [\*] Energy will be conserved as long as time is translationally symmetric (i.e. all instants are equivalent), according to Noether's theorems.
When you lift a book you are expending energy, you can accelerate it all the time you are lifting it, or you can lift it steadily at a constant speed. In both cases you are increasing the book's gravitational potential energy, also some of your energy may go to air friction and sound waves. So none of the energy you spend is lost.
571,507
I'm not really knowledgeable on physics but was curious about this and couldn't find any good answers related to it.
2020/08/06
[ "https://physics.stackexchange.com/questions/571507", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/271661/" ]
Energy is conserved in the whole universe \*. Nevertheless, if you delimit a system and you focus only on that system, forces can vary the energy of the system. Total energy is conserved in the universe, but in your particular system migh not. If you wide your system to include more objects, then you'll find energy conserved. [\*] Energy will be conserved as long as time is translationally symmetric (i.e. all instants are equivalent), according to Noether's theorems.
Yes, the conservation of energy holds when there are net forces too, and the difference between the two cases that you proposed is the behaviour of kinetic energy: * if the net force is zero the speed is constant, as well as the kinetic energy; also consider that in reality -even when you try to lift a book at constant speed- the net force applied to the book (you + gravity) must still be non-zero when you start and you finish: it is initially positive (meaning that $F\_{you}>F\_g$) to get it moving from rest and negative to make it stop, in such a way that the total work stays equal to zero. * in the accelerated case the final kinetic energy is greater than the initial kinetic energy, and their difference is exactly the "net" work of the forces, as described by the work-energy principle: $$ L = \Delta K $$
63,754
My players often want to see if they know something about a monster or not, specially stuff like weaknesses and resistances. I have this idea that there should be somewhere in the MM or DMG explaining the proper way to do proceed, but I can't find it. How do I know which is the best ability (skill) check for knowing about what a DMG monster can do and what it is weak against, and how do I calculate what DC is appropriate for such a check? Please answer with RAW if possible. I already know I can adjudicate, which is what I always do, but I want to know if there is something in the rules that I have missed.
2015/06/19
[ "https://rpg.stackexchange.com/questions/63754", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/15810/" ]
**There are no, concrete RAW monster knowledge checks in 5e** The PHB, MM, and DMG do not mention anything like a monster knowledge check as existed in previous editions. Tied with that is the fact that monster types are not directly tied to skills. As such I can only offer guidelines based on my own experiences with 4e and 5e and what I have done as a GM. **Go with what makes sense for the creature/creature type.** Beasts for example might allow either the nature or survival skill to be applied to a knowledge check, arcana for any constructs or monsters from other planes, religion for demons, devils, and angels etc. **Apply the standard DC check ratio as laid out in all of the books and pdfs.** * 10 Easy * 15 Medium * 20 Hard * 25 Very Hard Passing the easy check lets the players know/guess the monster and its type. Medium Allows the players to know the types of attacks it will make (melee vs ranged and can it cast spells). Hard also lets the know resistances or immunities. Finally with a Very Hard DC met the players can look at the actual creature statblock. You can even restrict the Very Hard DC to only be given out to a player who is trained in the skill you are asking for. **That said, are monster knowledge checks required?** Its entirely possible for you as the DM to simply state whether or not a PC would know about a monster based on their backgrounds and experiences. You would need to discuss this option with players, but 5e's rules-lite narrative leanings would lend itself well to this so long as your players were on board with it.
If you run a group focused on role-playing and stories, don't tell the players specific stats like armor class or DMG unless you see the need to. If your group is more combat-heavy, then stats would be more appropriate. No rule in the book really provides concrete guidelines to structuring knowledge checks. I am aware that this question is asking about 5th edition. However, the 4th edition Monster Manual does include suggested checks for monster lore. Most of these lore checks include combat tactics, personality traits, flaws, but never direct stats. Perhaps they would give you an idea of how to structure your checks. Example: (4th edition Monster Manual pg 138) Goblin Lore: A character knows the following information with a successful **Nature** check. **DC 15** - Goblins are cowardly and tend to retreat or surrender when outmatched. They are fond of taking slaves and often become slaves themselves. **DC 20** - Goblins sleep, eat, and spend leisure time in shared living areas. Only a leader has private chambers. A goblin lair is stinking and soiled, though easily defensible and often riddled with simple traps designed to snare or kill intruders.
66,579,069
I'm trying to grab the data feed on my blog with the help of blogger json. I made it with the help of javascript to retrieve the data, but I was confused about displaying the last data in an array of feeds. Whereas what is shown is all the arrays based on the labels in the feeds. My question: how to show only the last data in an array in blogger feeds. ```js function series(e) { for (var t = 0; t < e.feed.entry.length; t++) { var r, l = e.feed.entry[t], n = l.title.$t; if (t == e.feed.entry.length) break; for (var i = 0; i < l.link.length; i++) if ("replies" == l.link[i].rel && "text/html" == l.link[i].type && (l.link[i].title, l.link[i].href), "alternate" == l.link[i].rel) { r = l.link[i].href; break } document.write('<a href="' + r + '" title="' + n + '">' + n + "</a>") } } ``` ```html <script src="https://anitoki.malestea.com/feeds/posts/default/-/Horimiya?orderby=published&amp;alt=json-in-script&amp;callback=series&amp;max-results=999"></script> ```
2021/03/11
[ "https://Stackoverflow.com/questions/66579069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10788263/" ]
This code shows only the last entry in the array using `arr.slice(-1)`, if you meant first element just remove `.slice(-1)` from the code ```js function series(response) { if (response.feed.openSearch$totalResults.$t > 0) { var entry = response.feed.entry.slice(-1)[0], title = entry.title.$t, url = entry.link.filter(function(e) { return e.rel === "alternate"; })[0].href; document.write('<a href="' + url + '" title="' + title + '">' + title + "</a><br/>"); } else { // no posts } } ```
```js function series(e) { var r, l = e.feed.entry[e.feed.entry.length - 1], n = l.title.$t; for (var i = 0; i < l.link.length; i++) { if ("replies" == l.link[i].rel && "text/html" == l.link[i].type && (l.link[i].title, l.link[i].href), "alternate" == l.link[i].rel) { r = l.link[i].href; break } document.write('<a href="' + r + '" title="' + n + '">' + n + "</a>") } } ```
66,570,424
There is a problem with this program. I'm trying to make it so when someone types 'hi' in Discord, two bots respond. The problem is that the bots keep saying hi to the other one. Here is the code: ``` msg = message.content# Makes sure that the author of the message isn't itself if message.author == client.user: return if message.author.id != '818469783891607562': if any(word in msg for word in common_Greetings_List): time.sleep(2) await message.channel.send("Hey!")``` ```
2021/03/10
[ "https://Stackoverflow.com/questions/66570424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14945848/" ]
Just to share with you my understanding on why do we need these 2 layers of data presentation, and convert model to entity and vise versa. Imagine you have several backends, each having it's own data structure, but in your application it is represented by the single data class. For example, you fetch e-currency data from different sources - and on the top of that you have your own source of data. So you have 2+ DTO, and those map to your model which is later used in UI presentation.
Hopefully I was able to figure this out. I am adding the questions and answers together for ease. Questions: So to conclude such a long writeup, here my questions are; 1. [Question] When we create data models extending entity, what should be the one called in UI - data model or domain entity? I can make it work with both but then data model becomes useless especially when we post data using entity and retrieve same thing. Also, this requires the entities to have proper methods to map data for SQLite. If I change to Firebase, the domain logic to format data needs change, which breaks the core principle - closed for edit and most importantly data layer affects domain layer. [Answer]: It should be the entity. A data model's duty is to convert an external data to app's entity model. Also, it handles the additional duty of de-converting entity to outer layer format. 2. [Question]Is data model used only when the data is fetched externally and needed extra work to make it look like an entity data? Or in other words, if I am just posting a transaction and read in within the app, would entity suffice? [Answer]: Data Model is created to parse and convert external data to entity and back. So, classes dealing with this data uses data models. Following is an article written recently on clean architecture implementation. [Flutter clean architecture with Riverpod](https://medium.com/@inspiretechdevs/flutter-clean-architecture-with-riverpod-part-1-d7e5b5ec28ac)
66,570,424
There is a problem with this program. I'm trying to make it so when someone types 'hi' in Discord, two bots respond. The problem is that the bots keep saying hi to the other one. Here is the code: ``` msg = message.content# Makes sure that the author of the message isn't itself if message.author == client.user: return if message.author.id != '818469783891607562': if any(word in msg for word in common_Greetings_List): time.sleep(2) await message.channel.send("Hey!")``` ```
2021/03/10
[ "https://Stackoverflow.com/questions/66570424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14945848/" ]
Model should be used as a data mapping. Its only mission is mapping data from data sources (remote or local) to repository. And models should be used only in "data layer". In domain layer and presentation layer, you should use entities. In future, if you need to modify fields in model, you can modify model file only or extends a new one, and nothing change in domain and presentation layers.
Hopefully I was able to figure this out. I am adding the questions and answers together for ease. Questions: So to conclude such a long writeup, here my questions are; 1. [Question] When we create data models extending entity, what should be the one called in UI - data model or domain entity? I can make it work with both but then data model becomes useless especially when we post data using entity and retrieve same thing. Also, this requires the entities to have proper methods to map data for SQLite. If I change to Firebase, the domain logic to format data needs change, which breaks the core principle - closed for edit and most importantly data layer affects domain layer. [Answer]: It should be the entity. A data model's duty is to convert an external data to app's entity model. Also, it handles the additional duty of de-converting entity to outer layer format. 2. [Question]Is data model used only when the data is fetched externally and needed extra work to make it look like an entity data? Or in other words, if I am just posting a transaction and read in within the app, would entity suffice? [Answer]: Data Model is created to parse and convert external data to entity and back. So, classes dealing with this data uses data models. Following is an article written recently on clean architecture implementation. [Flutter clean architecture with Riverpod](https://medium.com/@inspiretechdevs/flutter-clean-architecture-with-riverpod-part-1-d7e5b5ec28ac)
55,752
I'm accessing TLS 1.3 test server "<https://tls13.pinterjann.is>" via a java http client using TLS 1.3. Everything seems to work fine as the html response indicates: [![HTML Response](https://i.stack.imgur.com/AJmFO.png)](https://i.stack.imgur.com/AJmFO.png) What I don't understand: Why does Wireshark show in the overview Protocol TLSv1.3 but in the details Version TLS 1.2? Is Wireshark just displaying the wrong Version or am I actually using TLS 1.2? Thanks in advance for your support. [![Wireshark ClientHello](https://i.stack.imgur.com/XgQgd.png)](https://i.stack.imgur.com/XgQgd.png) [![Wireshark HelloRetry](https://i.stack.imgur.com/qVS89.png)](https://i.stack.imgur.com/qVS89.png) [![Wireshark ClientHello 2](https://i.stack.imgur.com/h0JIb.png)](https://i.stack.imgur.com/h0JIb.png) [![Wireshark ServerHello](https://i.stack.imgur.com/sQgsU.png)](https://i.stack.imgur.com/sQgsU.png)
2018/12/31
[ "https://networkengineering.stackexchange.com/questions/55752", "https://networkengineering.stackexchange.com", "https://networkengineering.stackexchange.com/users/53911/" ]
Sorry, for the confusion, I was missing the exact TLS 1.3 semantics: For instance, in the Client Hello, the field "version" must contain the fixed value 0x0303 (TLS 1.2), while the prefered version is contained in the extension "supported versions". From RFC 8446 (TLS 1.3 spec): ``` struct { ProtocolVersion legacy_version = 0x0303; /* TLS v1.2 */ Random random; opaque legacy_session_id<0..32>; CipherSuite cipher_suites<2..2^16-2>; opaque legacy_compression_methods<1..2^8-1>; Extension extensions<8..2^16-1>; } ClientHello; ``` > > legacy\_version: In previous versions of TLS, this field was used for > version negotiation and represented the highest version number > supported by the client. Experience has shown that many servers > do not properly implement version negotiation, leading to "version > intolerance" in which the server rejects an otherwise acceptable > ClientHello with a version number higher than it supports. In > TLS 1.3, the client indicates its version preferences in the > "supported\_versions" extension (Section 4.2.1) and the > legacy\_version field MUST be set to 0x0303, which is the version > number for TLS 1.2. TLS 1.3 ClientHellos are identified as having > a legacy\_version of 0x0303 and a supported\_versions extension > present with 0x0304 as the highest version indicated therein. > (See Appendix D for details about backward compatibility.) > > > This agrees with what Wireshark displays: [![Wireshark supported versions](https://i.stack.imgur.com/OujTt.png)](https://i.stack.imgur.com/OujTt.png)
> > Why does Wireshark show in the overview Protocol TLSv1.3 but in the details Version TLS 1.2? > > > Wireshark reports TLS 1.3 in the protocol column due to Server Hello containing a [Supported Versions extension](https://www.rfc-editor.org/rfc/rfc8446#section-4.2.1) with TLS 1.3. Recall that TLS sessions begin with a handshake to negotiate parameters such as the protocol version and ciphers. The client sends a Client Hello handshake message in a TLS record containing: * TLS Record - Version: minimum supported TLS version (in TLS 1.2 and before). In TLS 1.3, this field is not really used and MUST be 0x0303 ("TLS 1.2") or 0x301 ("TLS 1.0") for compatibility purposes. Reference: [RFC 8446 (page 79)](https://www.rfc-editor.org/rfc/rfc8446#page-79) * Client Hello - Version: maximum supported TLS version (in TLS 1.2 and before). In TLS 1.3, this field is not used but MUST be set to 0x0303 ("TLS 1.2"). Reference: [RFC 8446 (4.1.2. Client Hello)](https://www.rfc-editor.org/rfc/rfc8446#section-4.1.2) * Client Hello - Supported Versions Extension: list of supported versions. This is the only value used by TLS 1.3 implementations (which may agree TLS 1.3, 1.2 or other versions). Reference: [RFC 8446 (4.2.1. Supported Versions)](https://www.rfc-editor.org/rfc/rfc8446#section-4.2.1) The server sends a Server Hello handshake message with: * Server Hello - Version: negotiated version (for TLS 1.2 and before). If TLS 1.3 is negotiated, it MUST be set to 0x0303 ("TLS 1.2"). * Server Hello - Supported Versions: a single negotiated version (for TLS 1.3). Cannot be used to negotiate earlier versions. So in TLS 1.2, the client sends a range of supported versions while a TLS 1.3 client sends a list of supported versions. The server will then pick a single version, but for compatibility purposes it will use a new field for selecting TLS 1.3 or newer. (Even if a client advertises support for some version (e.g. via a TLS record version containing "TLS 1.0"), it could still fail the handshake though if the server agrees to this low version.) Another thing to be aware of: Wireshark tries to interpret a packet immediately as it is received. At the time the Client Hello is received, it will not know the final version and therefore assume the TLS Record Version. When the Server Hello is received, it can adjust the version accordingly: ``` $ tshark -r test/captures/tls13-rfc8446.pcap 1 0.000000 10.9.0.1 → 10.9.0.2 TLSv1 304 Client Hello 2 0.002634 10.9.0.2 → 10.9.0.1 TLSv1.3 658 Server Hello, Change Cipher Spec, Application Data 3 0.005266 10.9.0.1 → 10.9.0.2 TLSv1.3 130 Change Cipher Spec, Application Data 4 0.005772 10.9.0.2 → 10.9.0.1 TLSv1.3 468 Application Data ... ``` In a two-pass dissection (which also includes the Wireshark GUI), the agreed version will be known when it prints the results of the second pass: ``` $ tshark -r test/captures/tls13-rfc8446.pcap -2 1 0.000000 10.9.0.1 → 10.9.0.2 TLSv1.3 304 Client Hello 2 0.002634 10.9.0.2 → 10.9.0.1 TLSv1.3 658 Server Hello, Change Cipher Spec, Application Data 3 0.005266 10.9.0.1 → 10.9.0.2 TLSv1.3 130 Change Cipher Spec, Application Data 4 0.005772 10.9.0.2 → 10.9.0.1 TLSv1.3 468 Application Data ... ``` Test capture used above: <https://github.com/wireshark/wireshark/blob/master/test/captures/tls13-rfc8446.pcap>
8,413,797
This is an extremely strange situation, but I just cannot point out what I'm doing wrong. I'm executing a big bunch of SQL scripts (table creation scripts, mostly). They are executed through Java, using `sqlcmd`. Here's the `sqlcmd` command I use. ``` sqlcmd -m 11 -S SERVER -d DB -U USER -P PASS -r0 -i "SCRIPT.sql" 2> "ERRORS.log" 1> NULL ``` *Note:* I use the `-r0` and redirects to make sure only errors go into the log file. I chuck out all STDOUTs. Now I execute this command in Java, using `getRuntime.exec()`, like this. ``` Runtime.getRuntime().gc(); strCmd = "cmd /c sqlcmd -m 11 -S SERVER -d DB -U USER -P PASS -r0 -i \"SCRIPT.sql\" 2> \"ERRORS.log\" 1> NULL" Process proc = Runtime.getRuntime().exec(strCmd); proc.waitFor(); ``` *Note:* I use `cmd /c`, so that the command runs in its own shell and exits gracefully. Also, this helps in immediately reading the error log to look for errors. **The Problem!** This command works perfectly when run by hand on the command prompt (i.e. the tables are getting created as intended). However, when executed through Java as shown, the scripts are run, and and there are no errors, no exceptions, nothing in the logs. ***But***, when checking in SSMS, the tables aren't there! Where do I even begin debugging this issue? **UPDATE: I'M A MORON** The return value from the `getRuntime().exec` method is 1. It should be 0, which denotes normal execution. Any pointers on how to fix this? **UPDATE 2** I've looked at the process' ErrorStream, and this is what it has. > > Sqlcmd: Error: Error occurred while opening or operating on file 2> > (Reason: The filename, directory name, or volume label syntax is > incorrect). > > > Looks like the path I'm passing is wrong. The error log goes into my profile directory, which is `C:\Documents and Settings\my_username`. Do the spaces in the path matter? I'm anyways double-quoting them!
2011/12/07
[ "https://Stackoverflow.com/questions/8413797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398713/" ]
Have a look at the exec method with an string array as parameter: ``` java.lang.Runtime.exec(String[] cmdArray) ``` The JavaDoc for this method says: > > Executes the specified command and arguments in a separate process. > > > So, the first item in the array is the command and all of your arguments are appended to the array, e. g., ``` Runtime.getRuntime().exec(new String[] {"cmd", "/c", "sqlcmd ... "}); ``` After looking at your comment and the implementation of `exec(String)` it seems to be, that the exec method recognizes the pipe operator `>` as an argument to `cmd`, because `exec(String)` splits the command string to an array using whitespaces as seperators.
I don't have privs to post comments - which is what this is - but what if you try putting in a bogus user id for the DB? Does that cause a different execution path? Will that give you a Java error? Or an Auth error in your DB? Also, def tweak the user, not the password and learn from my experience that if you tweak the password that's a great way to get an account locked out! The other thing - and this may be a shot in the dark - but what are the JRE and driver you're using? I believe there's a known issue with JRE 1.6.0.29 and the sqljdbc4 JAR. I have more details on this, but I'll have to post the link once I get to work. Edit: I know it's been established that the JRE/sqljdbc combo isn't your issue, but if folks search and find this, here is the link I spoke of above: [Driver.getConnection hangs using SQLServer driver and Java 1.6.0\_29](https://stackoverflow.com/questions/7841411/driver-getconnection-hangs-using-sqlserver-driver-and-java-1-6-0-29)
8,413,797
This is an extremely strange situation, but I just cannot point out what I'm doing wrong. I'm executing a big bunch of SQL scripts (table creation scripts, mostly). They are executed through Java, using `sqlcmd`. Here's the `sqlcmd` command I use. ``` sqlcmd -m 11 -S SERVER -d DB -U USER -P PASS -r0 -i "SCRIPT.sql" 2> "ERRORS.log" 1> NULL ``` *Note:* I use the `-r0` and redirects to make sure only errors go into the log file. I chuck out all STDOUTs. Now I execute this command in Java, using `getRuntime.exec()`, like this. ``` Runtime.getRuntime().gc(); strCmd = "cmd /c sqlcmd -m 11 -S SERVER -d DB -U USER -P PASS -r0 -i \"SCRIPT.sql\" 2> \"ERRORS.log\" 1> NULL" Process proc = Runtime.getRuntime().exec(strCmd); proc.waitFor(); ``` *Note:* I use `cmd /c`, so that the command runs in its own shell and exits gracefully. Also, this helps in immediately reading the error log to look for errors. **The Problem!** This command works perfectly when run by hand on the command prompt (i.e. the tables are getting created as intended). However, when executed through Java as shown, the scripts are run, and and there are no errors, no exceptions, nothing in the logs. ***But***, when checking in SSMS, the tables aren't there! Where do I even begin debugging this issue? **UPDATE: I'M A MORON** The return value from the `getRuntime().exec` method is 1. It should be 0, which denotes normal execution. Any pointers on how to fix this? **UPDATE 2** I've looked at the process' ErrorStream, and this is what it has. > > Sqlcmd: Error: Error occurred while opening or operating on file 2> > (Reason: The filename, directory name, or volume label syntax is > incorrect). > > > Looks like the path I'm passing is wrong. The error log goes into my profile directory, which is `C:\Documents and Settings\my_username`. Do the spaces in the path matter? I'm anyways double-quoting them!
2011/12/07
[ "https://Stackoverflow.com/questions/8413797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398713/" ]
I don't have privs to post comments - which is what this is - but what if you try putting in a bogus user id for the DB? Does that cause a different execution path? Will that give you a Java error? Or an Auth error in your DB? Also, def tweak the user, not the password and learn from my experience that if you tweak the password that's a great way to get an account locked out! The other thing - and this may be a shot in the dark - but what are the JRE and driver you're using? I believe there's a known issue with JRE 1.6.0.29 and the sqljdbc4 JAR. I have more details on this, but I'll have to post the link once I get to work. Edit: I know it's been established that the JRE/sqljdbc combo isn't your issue, but if folks search and find this, here is the link I spoke of above: [Driver.getConnection hangs using SQLServer driver and Java 1.6.0\_29](https://stackoverflow.com/questions/7841411/driver-getconnection-hangs-using-sqlserver-driver-and-java-1-6-0-29)
First enable log/view commands output (since exec() returns 1), which would point out possible cause of the issue. Use proc.getInputStream() and print the contents to a file or console.
8,413,797
This is an extremely strange situation, but I just cannot point out what I'm doing wrong. I'm executing a big bunch of SQL scripts (table creation scripts, mostly). They are executed through Java, using `sqlcmd`. Here's the `sqlcmd` command I use. ``` sqlcmd -m 11 -S SERVER -d DB -U USER -P PASS -r0 -i "SCRIPT.sql" 2> "ERRORS.log" 1> NULL ``` *Note:* I use the `-r0` and redirects to make sure only errors go into the log file. I chuck out all STDOUTs. Now I execute this command in Java, using `getRuntime.exec()`, like this. ``` Runtime.getRuntime().gc(); strCmd = "cmd /c sqlcmd -m 11 -S SERVER -d DB -U USER -P PASS -r0 -i \"SCRIPT.sql\" 2> \"ERRORS.log\" 1> NULL" Process proc = Runtime.getRuntime().exec(strCmd); proc.waitFor(); ``` *Note:* I use `cmd /c`, so that the command runs in its own shell and exits gracefully. Also, this helps in immediately reading the error log to look for errors. **The Problem!** This command works perfectly when run by hand on the command prompt (i.e. the tables are getting created as intended). However, when executed through Java as shown, the scripts are run, and and there are no errors, no exceptions, nothing in the logs. ***But***, when checking in SSMS, the tables aren't there! Where do I even begin debugging this issue? **UPDATE: I'M A MORON** The return value from the `getRuntime().exec` method is 1. It should be 0, which denotes normal execution. Any pointers on how to fix this? **UPDATE 2** I've looked at the process' ErrorStream, and this is what it has. > > Sqlcmd: Error: Error occurred while opening or operating on file 2> > (Reason: The filename, directory name, or volume label syntax is > incorrect). > > > Looks like the path I'm passing is wrong. The error log goes into my profile directory, which is `C:\Documents and Settings\my_username`. Do the spaces in the path matter? I'm anyways double-quoting them!
2011/12/07
[ "https://Stackoverflow.com/questions/8413797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/398713/" ]
Have a look at the exec method with an string array as parameter: ``` java.lang.Runtime.exec(String[] cmdArray) ``` The JavaDoc for this method says: > > Executes the specified command and arguments in a separate process. > > > So, the first item in the array is the command and all of your arguments are appended to the array, e. g., ``` Runtime.getRuntime().exec(new String[] {"cmd", "/c", "sqlcmd ... "}); ``` After looking at your comment and the implementation of `exec(String)` it seems to be, that the exec method recognizes the pipe operator `>` as an argument to `cmd`, because `exec(String)` splits the command string to an array using whitespaces as seperators.
First enable log/view commands output (since exec() returns 1), which would point out possible cause of the issue. Use proc.getInputStream() and print the contents to a file or console.
3,061,956
Let $x = 0.3$. The first number of the sequence is $x$. The second number is the first number + $(0.3\cdot 0.3)$. The third number is the second number + $(0.3\cdot 0.3\cdot 0.3)$. This is a recursive formula: $a\_1 = 0.3$ $a\_{n+1} = a\_n + 0.3^{n-1}$ Is it possible to write this equation without recursion? I want to write a programming function in JavaScript that encodes this without using recursion if possible.
2019/01/04
[ "https://math.stackexchange.com/questions/3061956", "https://math.stackexchange.com", "https://math.stackexchange.com/users/524791/" ]
Your sequence seems to be $a\_n = x + x^2 + x^3 + ..... + x^n$ $= (1 + x + x^2 + x^3 + ...... + x^n) - 1$ $= \frac {1-x^{n+1}}{1-x}-1$ $=\frac {1-.3^{n+1}}{.7} - 1$ Google [geometric series](https://en.wikipedia.org/wiki/Geometric_series) Or maybe more straightforward: $a\_n = x + x^2 + ...... + x^n =$ $x(1 + ..... + x^{n-1}) =$ $x \frac {1-x^n}{1-x} = \frac {x - x^{n+1}}{1-x}=$ $\frac {.3-.3^{n+1}}{.7}$ Which can be what $\frac {1 - .3^{n+1}}{.7} -1 = \frac {1 - .3^{n+1}}{.7} -\frac {.7}{.7} = \frac {.3-.3^{n+1}}{.7}$ is also equal to. You can also express it as $\frac {3 - 10\*(.3)^{n+1}}{7}$
You can write: $a\_{n+1} = a\_n + 0.3^{n-1}$ $= a\_{n-1} + 0.3^{n-2} + 0.3^{n-1}$ $ = a\_{n-2} + 0.3^{n-3} + 0.3^{n-2} + 0.3^{n-1}$ $ ... $ $ = a\_1 + \sum\_{k=1}^n 0.3^{n-k+1}$ $ = a\_1 + \sum\_{k=1}^n 0.3^k$ $ = a\_1 + \frac{3}{7}(1-0.3^n)$ $ = 0.3 + \frac{3}{7}(1-0.3^n)$ $ = 0.7286 - 0.4286 \times 0.3^n$
3,061,956
Let $x = 0.3$. The first number of the sequence is $x$. The second number is the first number + $(0.3\cdot 0.3)$. The third number is the second number + $(0.3\cdot 0.3\cdot 0.3)$. This is a recursive formula: $a\_1 = 0.3$ $a\_{n+1} = a\_n + 0.3^{n-1}$ Is it possible to write this equation without recursion? I want to write a programming function in JavaScript that encodes this without using recursion if possible.
2019/01/04
[ "https://math.stackexchange.com/questions/3061956", "https://math.stackexchange.com", "https://math.stackexchange.com/users/524791/" ]
Your sequence seems to be $a\_n = x + x^2 + x^3 + ..... + x^n$ $= (1 + x + x^2 + x^3 + ...... + x^n) - 1$ $= \frac {1-x^{n+1}}{1-x}-1$ $=\frac {1-.3^{n+1}}{.7} - 1$ Google [geometric series](https://en.wikipedia.org/wiki/Geometric_series) Or maybe more straightforward: $a\_n = x + x^2 + ...... + x^n =$ $x(1 + ..... + x^{n-1}) =$ $x \frac {1-x^n}{1-x} = \frac {x - x^{n+1}}{1-x}=$ $\frac {.3-.3^{n+1}}{.7}$ Which can be what $\frac {1 - .3^{n+1}}{.7} -1 = \frac {1 - .3^{n+1}}{.7} -\frac {.7}{.7} = \frac {.3-.3^{n+1}}{.7}$ is also equal to. You can also express it as $\frac {3 - 10\*(.3)^{n+1}}{7}$
If we write $$a\_n=1+0.3+(0.3)^2+\cdots + (0.3)^{n-2}$$then we have $$a\_{n+1}=a\_n+(0.3)^{n-1}=1+0.3+(0.3)^2+\cdots + (0.3)^{n-2}+(0.3)^{n-1}$$also $$1+0.3+(0.3)^2+\cdots + (0.3)^{n-2}={1-(0.3)^{n-1}\over 1-0.3}$$therefore $$a\_n={1-(0.3)^{n-1}\over 0.7}$$
90,625
Which is correct: "Constantin" or "Constantine"? I also encountered in texts "Konstantin" and "Kostantine". Or else is another spelling preferred?
2012/11/08
[ "https://english.stackexchange.com/questions/90625", "https://english.stackexchange.com", "https://english.stackexchange.com/users/30600/" ]
The Roman emperor Flavius Valerius Aurelius Constantinus Augustus is generally rendered as *Constantine* in English, and this form is almost certainly the most common. For personal names, however, there is no single "correct" spelling, as personal names are not regulated in most English-speaking countries. *Constantin* is the French and Romanian spelling, for example, so Constantines from those countries will retain that spelling. The same name transliterated (but not anglicized) from the Cyrillic for a Ukrainian or Russian is often *Konstantin* or *Konstantyn*. You can also turn up *Constantyn* and *Constantyne*, and probably other variations as well.
It depends on the dialect. My grandfather’s name is Constantine, When my Great Grandfather came over from Greece it was Constantine as well. If you go by other variants you will see something along: Constans, Constan, Constant, Constanc, Constance, Consten, Constens, Constense, Constence, Constanse, Constane, Constene, Constante, Contans, Contan, Contant, Contance, Conten, Contens, Contense, Contence, Contanse, Contane, and Contene. There are plenty more as well, but basically it all depends on the country and dialect. Also family names, and personal names throw the name of how it should be spelled, etc throw logic out the window.
3,879,905
I am trying to prove this and have looked at similar questions to gauge how to approach this. I have: Suppose that there exists a smallest rational number greater than $\sqrt{3}$. We shall call that number $n$, which, as it is rational, can be expressed as $\frac{p}{q}$ $\frac{\sqrt{3}+n}{\sqrt{3}}$ is a number greater than $\sqrt{3}$ but less than $n$, but this number would no longer be rational now, would it?
2020/10/24
[ "https://math.stackexchange.com/questions/3879905", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
if you have positive integers $x,y$ with $$ \frac{x}{y} > \sqrt 3 $$ we also have $$ x^2 - 3 y^2 > 0 $$ is an integer so that there is some positive $T$ with $$ x^2 - 3 y^2 = T. $$ Well we calculate that $$ u = 2x + 3y \; \; , \hspace{9mm} v = x+2y $$ satisfy $$ u^2 - 3 v^2 = T > 0 $$ also. $$ u^2 > 3 v^2 $$ $$\frac{u^2}{v^2} > 3 $$ $$ \left( \frac{u}{v} \right)^2 > 3 $$ Well $$ x^2 - 3 y^2 > 0 $$ $$ x^2 > 3 y^2 $$ $$ x^2 + 2 x y > 2xy + 3 y^2 $$ $$ x (x+2y) > y(2x+3y) $$ $$ \frac{x}{y} > \frac{2x+3y}{x+2y} $$ so $$ \frac{x}{y} > \frac{2x+3y}{x+2y} > \sqrt 3 $$
Let $S=\{q\in \mathbb Q:q^2>3\}$ and suppose $q\in S.$ Set $p=\frac{3q+3}{q+3}$. Then, $p<q$ and $p\in S$ because $\left(\frac{3q+3}{q+3}\right)^2-3=\frac{6(q^2-3)}{(q+3)^2}>0.$
3,879,905
I am trying to prove this and have looked at similar questions to gauge how to approach this. I have: Suppose that there exists a smallest rational number greater than $\sqrt{3}$. We shall call that number $n$, which, as it is rational, can be expressed as $\frac{p}{q}$ $\frac{\sqrt{3}+n}{\sqrt{3}}$ is a number greater than $\sqrt{3}$ but less than $n$, but this number would no longer be rational now, would it?
2020/10/24
[ "https://math.stackexchange.com/questions/3879905", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
if you have positive integers $x,y$ with $$ \frac{x}{y} > \sqrt 3 $$ we also have $$ x^2 - 3 y^2 > 0 $$ is an integer so that there is some positive $T$ with $$ x^2 - 3 y^2 = T. $$ Well we calculate that $$ u = 2x + 3y \; \; , \hspace{9mm} v = x+2y $$ satisfy $$ u^2 - 3 v^2 = T > 0 $$ also. $$ u^2 > 3 v^2 $$ $$\frac{u^2}{v^2} > 3 $$ $$ \left( \frac{u}{v} \right)^2 > 3 $$ Well $$ x^2 - 3 y^2 > 0 $$ $$ x^2 > 3 y^2 $$ $$ x^2 + 2 x y > 2xy + 3 y^2 $$ $$ x (x+2y) > y(2x+3y) $$ $$ \frac{x}{y} > \frac{2x+3y}{x+2y} $$ so $$ \frac{x}{y} > \frac{2x+3y}{x+2y} > \sqrt 3 $$
Let $q$ be least integer greater than $\sqrt{3}$, then $q^2>3$.If we can get a rational $q-\frac1 n >\sqrt{3}$ then we'll get a contradiction. Observe $\left(q-\frac1 n\right)^2\geq q^2-\frac{2q}{n}$. By Archimedean principle,$\exists N $such that $\frac 1 N < \frac{q^2-3}{2q}$. $$\therefore q^2-3>\frac{2q}{n}\implies q^2-\frac{2q}{n}>3 \implies .\left(q-\frac1 n\right)^2>3 \implies \left(q-\frac1 n\right) \geq \sqrt{3}$$ $\therefore$ we found a rational $q-\frac 1 N$ which is less than $q$ but greater than $\sqrt{3}$.Which is a contradiction.
3,879,905
I am trying to prove this and have looked at similar questions to gauge how to approach this. I have: Suppose that there exists a smallest rational number greater than $\sqrt{3}$. We shall call that number $n$, which, as it is rational, can be expressed as $\frac{p}{q}$ $\frac{\sqrt{3}+n}{\sqrt{3}}$ is a number greater than $\sqrt{3}$ but less than $n$, but this number would no longer be rational now, would it?
2020/10/24
[ "https://math.stackexchange.com/questions/3879905", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
if you have positive integers $x,y$ with $$ \frac{x}{y} > \sqrt 3 $$ we also have $$ x^2 - 3 y^2 > 0 $$ is an integer so that there is some positive $T$ with $$ x^2 - 3 y^2 = T. $$ Well we calculate that $$ u = 2x + 3y \; \; , \hspace{9mm} v = x+2y $$ satisfy $$ u^2 - 3 v^2 = T > 0 $$ also. $$ u^2 > 3 v^2 $$ $$\frac{u^2}{v^2} > 3 $$ $$ \left( \frac{u}{v} \right)^2 > 3 $$ Well $$ x^2 - 3 y^2 > 0 $$ $$ x^2 > 3 y^2 $$ $$ x^2 + 2 x y > 2xy + 3 y^2 $$ $$ x (x+2y) > y(2x+3y) $$ $$ \frac{x}{y} > \frac{2x+3y}{x+2y} $$ so $$ \frac{x}{y} > \frac{2x+3y}{x+2y} > \sqrt 3 $$
Suppose $q \in \mathbb{Q} > \sqrt{3}$; then $q^2 > 3$, or $q^2= 3 + \delta$ with $\delta \in\mathbb{Q} > 0$. Then we want to choose some rational $\varepsilon>0$ such that $$(q-\varepsilon)^2=q^2-2q\varepsilon+\varepsilon^2=3+\delta-2q\varepsilon+\varepsilon^2 > 3+\delta-2q\varepsilon\ge 3,$$ so that $q-\varepsilon\in\mathbb{Q}$ and $q >q-\varepsilon > \sqrt{3}$. The inequality holds provided that $2q\varepsilon \le \delta.$ In particular, we can just choose $\varepsilon=\delta/(2q)$, noting that this is rational whenever $\delta$ and $q$ are. We conclude that, for any rational $q > \sqrt{3}$, the number $q - (q^2-3)/(2q)=\frac{1}{2}q+\frac{3}{2q}$ is a rational smaller than $q$ but still larger than $\sqrt{3}$.
3,879,905
I am trying to prove this and have looked at similar questions to gauge how to approach this. I have: Suppose that there exists a smallest rational number greater than $\sqrt{3}$. We shall call that number $n$, which, as it is rational, can be expressed as $\frac{p}{q}$ $\frac{\sqrt{3}+n}{\sqrt{3}}$ is a number greater than $\sqrt{3}$ but less than $n$, but this number would no longer be rational now, would it?
2020/10/24
[ "https://math.stackexchange.com/questions/3879905", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let $S=\{q\in \mathbb Q:q^2>3\}$ and suppose $q\in S.$ Set $p=\frac{3q+3}{q+3}$. Then, $p<q$ and $p\in S$ because $\left(\frac{3q+3}{q+3}\right)^2-3=\frac{6(q^2-3)}{(q+3)^2}>0.$
Suppose $q \in \mathbb{Q} > \sqrt{3}$; then $q^2 > 3$, or $q^2= 3 + \delta$ with $\delta \in\mathbb{Q} > 0$. Then we want to choose some rational $\varepsilon>0$ such that $$(q-\varepsilon)^2=q^2-2q\varepsilon+\varepsilon^2=3+\delta-2q\varepsilon+\varepsilon^2 > 3+\delta-2q\varepsilon\ge 3,$$ so that $q-\varepsilon\in\mathbb{Q}$ and $q >q-\varepsilon > \sqrt{3}$. The inequality holds provided that $2q\varepsilon \le \delta.$ In particular, we can just choose $\varepsilon=\delta/(2q)$, noting that this is rational whenever $\delta$ and $q$ are. We conclude that, for any rational $q > \sqrt{3}$, the number $q - (q^2-3)/(2q)=\frac{1}{2}q+\frac{3}{2q}$ is a rational smaller than $q$ but still larger than $\sqrt{3}$.
3,879,905
I am trying to prove this and have looked at similar questions to gauge how to approach this. I have: Suppose that there exists a smallest rational number greater than $\sqrt{3}$. We shall call that number $n$, which, as it is rational, can be expressed as $\frac{p}{q}$ $\frac{\sqrt{3}+n}{\sqrt{3}}$ is a number greater than $\sqrt{3}$ but less than $n$, but this number would no longer be rational now, would it?
2020/10/24
[ "https://math.stackexchange.com/questions/3879905", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let $q$ be least integer greater than $\sqrt{3}$, then $q^2>3$.If we can get a rational $q-\frac1 n >\sqrt{3}$ then we'll get a contradiction. Observe $\left(q-\frac1 n\right)^2\geq q^2-\frac{2q}{n}$. By Archimedean principle,$\exists N $such that $\frac 1 N < \frac{q^2-3}{2q}$. $$\therefore q^2-3>\frac{2q}{n}\implies q^2-\frac{2q}{n}>3 \implies .\left(q-\frac1 n\right)^2>3 \implies \left(q-\frac1 n\right) \geq \sqrt{3}$$ $\therefore$ we found a rational $q-\frac 1 N$ which is less than $q$ but greater than $\sqrt{3}$.Which is a contradiction.
Suppose $q \in \mathbb{Q} > \sqrt{3}$; then $q^2 > 3$, or $q^2= 3 + \delta$ with $\delta \in\mathbb{Q} > 0$. Then we want to choose some rational $\varepsilon>0$ such that $$(q-\varepsilon)^2=q^2-2q\varepsilon+\varepsilon^2=3+\delta-2q\varepsilon+\varepsilon^2 > 3+\delta-2q\varepsilon\ge 3,$$ so that $q-\varepsilon\in\mathbb{Q}$ and $q >q-\varepsilon > \sqrt{3}$. The inequality holds provided that $2q\varepsilon \le \delta.$ In particular, we can just choose $\varepsilon=\delta/(2q)$, noting that this is rational whenever $\delta$ and $q$ are. We conclude that, for any rational $q > \sqrt{3}$, the number $q - (q^2-3)/(2q)=\frac{1}{2}q+\frac{3}{2q}$ is a rational smaller than $q$ but still larger than $\sqrt{3}$.