source
sequence
text
stringlengths
99
98.5k
[ "mathematica.stackexchange", "0000213564.txt" ]
Q: How can I identify symbols within an expression which are wrapped in a local HoldForm? Let's assume a=b, that is, a has value b. In a given expression like e.g. a + i + HoldForm[a + k] + l I would like to substitute - while the whole expression is being held globally - every symbol by its value, unless the symbol is wrapped in a local HoldForm. The form HoldForm[a + i + HoldForm[a + k] + l] /. s_Symbol :> RuleCondition[s,ValueQ[s]] returns b + i + (b + k) + l, that is, all symbols of the expression have been substituted by their values, including the second appearance of a. How can I identify symbols which are wrapped in a local HoldForm and exclude them from this substitution procedure? Or do I have to take a completely different approach? Thanks for help! A: ReplaceAll works top-down, so you can add a rule to your replacement to leave HoldForm objects alone. Assuming the outer Hold wrapper isn't HoldForm you could do: held = Hold[a + i + HoldForm[a + k] + l]; rule = {h_HoldForm :> h, HoldPattern[s_Symbol] :> RuleCondition[s]}; held /. rule Hold[b + i + HoldForm[a + k] + l] If the outer Hold wrapper is a HoldForm, then you would need to change the wrapper before applying the above rule, so you could do something like: held = HoldForm[a + i + HoldForm[a + k] + l]; Apply[HoldForm] @ ReplaceAll[rule] @ Apply[Hold] @ held HoldForm[b + i + HoldForm[a + k] + l]
[ "stackoverflow", "0016774328.txt" ]
Q: simpledateformat for month and day in month only I require this format MonthDay, example 0422 I'm creating SimpleDateFormat sdf = new SimpleDateFormat("MMdd"); and giving it the current month and current day curDate = sdf.parse(curMon+""+curDay); but I'm getting this format: Thu Jun 07 00:00:00 CEST 1973 What do I need to do? A: Instead of using parse, use format as follows: SimpleDateFormat s = new SimpleDateFormat("MMdd"); String d = s.format(new Date()); System.out.println(d); This will generate, since today is 27th May: 0527
[ "stackoverflow", "0032144635.txt" ]
Q: Adding and Removing Div inside a Bootstrap modal I'm trying to show an alert on my modal (from bootstrap) about the account entered by the user (e.g Invalid Account). However, (for example, I entered a wrong account) after getting an error response and prepend it and then enter a wrong account again, it won't remove the previous alert i prepend. Here's what's happening: Here's my HTML Code: <div class="modal-body modal-login"> <?php include( 'login.php'); ?> <form name="test" action="" method="post" role="form" id="loginForm"> <input type="text" class="form-control userTB" name="loginText" placeholder="Username/Email" required> <input type="password" class="form-control passTB" name="passText" placeholder="Password" required> <a href="javascript:void(0)" class="btn btn-info btn-md" id="submit_button">Login</a> </form> </div> My jQuery: jQuery(function ($){ $('#submit_button').click(function(){ var post_url = 'login.php'; $.ajax({ type : 'POST', url : post_url, data: $('#loginForm').serialize(), dataType : 'html', async: true, success : function(data){ $('.modal-login').remove('.alert'); $('.modal-login').prepend(data); } }); }) }); Note: That data from jQuery contains <div class="alert alert-danger">Wrong Account!</div>. A: $(el).remove(selector) is somewhat confusing. It basically means "remove el from the document if it matches selector". This makes more sense if your jQuery object has multiple elements and you're filtering which ones to remove. If you change your code to .remove('.modal-login'), you'll see that it removes the whole modal. You should use .find then .remove: $('.modal-login').find(".alert").remove(); $('.modal-login').prepend(data);
[ "stackoverflow", "0001761185.txt" ]
Q: Blackberry - how to animate Custom Field? I have created a custom field class "Seek" to draw a fillrectangle. class Seek extends Field { int fill; protected void layout(int width, int height) { setExtent(320, 5); } protected void paint(Graphics graphics) { graphics.setColor(Color.RED); graphics.fillRect(0, 0, fill, 5); } protected void setValue(int value) { fill = value; } } And I have created another class Test seek to set the fill value using a timer public class TestSeek extends UiApplication { public static void main(String[] args) { TestSeek gbResults = new TestSeek(); gbResults.enterEventDispatcher(); } private TestSeek() { pushScreen(new ProgressScreen()); } } class ProgressScreen extends MainScreen { Timer timer = new Timer(); int i = 80; Seek SeekField = new Seek(); public ProgressScreen() { add(SeekField); timer.schedule(new RemindTask(), 100, 10); } class RemindTask extends TimerTask { public void run() { if (i < 320) { i += 1; SeekField.setValue(i); } else timer.cancel(); } } } But I am unable to animate filling the rectangle. A: Try calling invalidate() in your setValue method.
[ "stackoverflow", "0037006070.txt" ]
Q: Can't un check all cell before check one swift 2 I m using swift 2 and UITableViews and when I press a cell a checkmark appear, but I wan't that only one cell can be checked in my tableview so the other checkmarks will disappear from my tableview. I tried different technics without success. I have a CustomCell with just a label. Here is my code : import UIKit class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{ @IBOutlet weak var tableView: UITableView! var answersList: [String] = ["One","Two","Three","Four","Five"] override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return answersList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MyCustomCell", forIndexPath: indexPath) as! MyCustomCell cell.displayAnswers(answersList[indexPath.row]) // My cell is just a label return cell } // Mark: Table View Delegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Element selected in one of the array list tableView.deselectRowAtIndexPath(indexPath, animated: true) if let cell = tableView.cellForRowAtIndexPath(indexPath) { if cell.accessoryType == .Checkmark { cell.accessoryType = .None } else { cell.accessoryType = .Checkmark } } } } A: Assuming you've only section here's what you can do // checkmarks when tapped func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let section = indexPath.section let numberOfRows = tableView.numberOfRowsInSection(section) for row in 0..<numberOfRows { if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) { cell.accessoryType = row == indexPath.row ? .Checkmark : .None } } }
[ "stackoverflow", "0043654127.txt" ]
Q: d3 events issue with angular 2 typescript I am trying to include zooming and panning functionality in d3. which works in javascript but giving error in typescript. d3.event.translate and d3.event.scale are not working in angular2 typescript this.svg = this.host.append('svg') .attr('width', this.width) .attr('height', this.height) .style({ 'float': 'right' }) .attr("pointer-events", "all") .call(d3.behavior.zoom().on("zoom", redraw)) .append('svg:g'); function redraw() { this.svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")"); } show this error on console. Property 'translate' does not exist on type 'Event | BaseEvent'. Property 'scale' does not exist on type 'Event | BaseEvent'. A: @mkaran's answer works, but rather defeats the purpose of typescript. The proper cast here is: function redraw() { let e = (<d3.ZoomEvent> d3.event); this.svg.attr("transform", "translate(" + e.translate + ")" + " scale(" + e.scale + ")"); } Since the purpose the TypeScript is types, resorting to any is considered bad practice*. You should also attempt to avoid in-line functions, and rather use proper methods of your class. But that's a question for another day... *sometimes it's just easier :) A: You have a problem with your scope of this .call(d3.behavior.zoom().on("zoom", redraw)) .append('svg:g'); function redraw() { this.svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")"); } should be something like: .call(d3.behavior.zoom().on("zoom", redraw.bind(this))) //<-- bind the outer this here .append('svg:g'); function redraw() { this.svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")"); } or with the es6 arrow syntax: .call(d3.behavior.zoom().on("zoom", ()=> redraw() ) ) //<-- arrow syntax .append('svg:g'); function redraw() { this.svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")"); }
[ "sitecore.stackexchange", "0000025549.txt" ]
Q: Postcondition 'this.Interaction should not be null' exception while identifying a Contact Sitecore 9.3 I have an API endpoint and is being used to identify the contact. When it is being called through Sitecore application, it is working absolutely fine but it's failing with below exception while calling with Postman client. at Sitecore.Framework.Conditions.EnsuresValidator`1.ThrowExceptionCore(String condition, String additionalMessage, ConstraintViolationType type) at Sitecore.Framework.Conditions.Throw.ValueShouldNotBeNull[T](ConditionValidator`1 validator, String conditionDescription) at Sitecore.Framework.Conditions.ValidatorExtensions.IsNotNull[T](ConditionValidator`1 validator, String conditionDescription) at Sitecore.Analytics.Tracking.StandardSession.IdentifyAs(String source, String knownIdentifier) Any pointer? A: We faced the same issue and raised Sitecore support ticket for the same and we get to know that if you try to hit from Postman, need to remove user-agent from postman headers like below - https://www.screencast.com/t/K0BiMxHv This was only happening on Sitecore 9.3, in Sitecore 9.0.2 it was working fine for us. Also, I wrote a blog about this you can check here as well.
[ "ru.stackoverflow", "0000696352.txt" ]
Q: WebView в RecyclerView В CardView у RecyclerView присутствует WebView, при тестировании обычным текстом (вместо WebView был TextView) все летало даже на самых слабых моделях аппаратов, стоило заменить TextView на WebView - стало подтормаживать даже на относительно мощных. Можно как-то облегчить вывод (как я понимаю множества WebView) в RecyclerView? A: используйте TextView для отображения Html текста слудующим образом TextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Descrip‌​tion here</p>"));
[ "stackoverflow", "0034484459.txt" ]
Q: How to test if the user is logged in I am fairly familiar with PHP and wanted to make a Login/Registration system, but I came across a problem with my code. I was trying to test if the user is already logged in so I can redirect them as needed, but whenever I force a login and go to the registration page it does not redirect me back as needed. Please can someone help me. Here is my code. Register.php <?php if (isset($_SESSION['user_id'])) { header('index.php'); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register Account</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link rel="stylesheet" href="../css/app.css"> </head> <body> <div class="container"> <center><form action="#" method="POST"> <div class="form-group top"> <input type="text" name="firstname" class="form-control width" placeholder="Enter Firstname"> </div> <div class="form-group"> <input type="text" name="lastname" class="form-control width" placeholder="Enter Lastname"> </div> <div class="form-group"> <input type="email" name="email" class="form-control width" placeholder="Enter Email"> </div> <div class="form-group"> <input type="password" name="password" class="form-control width" placeholder="Enter Password"> </div> <div class="form-group"> <input type="password" name="password_confirmation" class="form-control width" placeholder="Confirm Password"> </div> <input type="submit" name="register-button-validate" class="btn btn-success btn-lg"> </form></center> </div> </body> </html> Index.php <?php session_start(); $_SESSION['user_id'] = 1; ?> A: First of all, register.php also needs this at the top: session_start(); Basically, any page which writes to or reads from the session will need that. Second, this isn't a redirect: header('index.php'); This is: header('Location: index.php'); An incomplete header is probably just being ignored by the browser, since there's no key telling the browser what to do with that value.
[ "stackoverflow", "0004390853.txt" ]
Q: Display item below row in table on click I have a table displaying some information. What I'd like to accomplish is to allow the user to click on a row, and have the note related to the info in that row display below that row. I am trying to set it up so that I can use the nifty CSS transition feature, so just putting the note in a hidden, absolutely positioned row below the info row is out of the question. CSS transition doesn't act on the position style. I've got it set up so that the note will be in a div. When the user clicks a row in the table, an onClick event calls up a Javascript function which makes the div visible. Now all I need is for the div to line up under the selected table row. How could I get the table row's height and position? I figure I could use that to position the div. Or, is there a better way to do this? Here's an example of what I've got: <style> .emarNote{ transition: all .3s linear; -o-transition: all .3s linear; -moz-transition: all .3s linear; -webkit-transition: all .3s linear; } </style> <script type="text/javascript"> function showEmar(id) { if (document.getElementById("emarNote"+id).style.visibility == "hidden") { document.getElementById("emarNote"+id).style.visibility = 'visible'; document.getElementById("emarNote"+id).style.opacity = 1; } else { document.getElementById("emarNote"+id).style.opacity = 0; document.getElementById("emarNote"+id).style.visibility = 'hidden'; } } </script> <table> <tr onClick="showEmar(1)"> <td>Info</td> <td>Info</td> </tr> </table> <div id="emar1" class="emarNote" style="visibility:hidden; opacity:0; position:absolute;"> note about info </div> A: 1st download JQuery. Then do something like below: <style> .emarNote{ background:#CCCCCC; } </style> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('.emarNote').hide(); $('tbody', '#myTable').click(function(event) { tr_ID = $(event.target).parent().attr('id'); $('#' + tr_ID + '-info').fadeToggle('slow'); }); }); </script> <table id="myTable"> <tbody> <tr id="row1"> <td>Info</td> <td>Info</td> </tr> <tr> <td colspan="2" id="row1-info" class="emarNote">MORE INFO would be really cool and such</td> </tr> </tbody> </table> NOTE: Replace "fadeToggle" with "slideToggle" to acheive a slide effect. Also, I really think you should read up a bit on JQuery to fully understand the solution. You will find that it is actually quite easy to understand once you get the basics.
[ "stackoverflow", "0058732930.txt" ]
Q: Subimage matching on b&w images I'm trying to detect a subimage (Slave image) within a larger image(Master/Base Image) that is only black and white pixels, and then outline the match with a red rectangle. The images are almost always squares or rectangles. I have looked at cv2 and PIL with template matching, but it never works correctly, instead outlining the entire image as a match, not the specific matched area. Additionally, the image sizes are different, so I have looked at multi-scale template matching and it still doesn't work for my need. So, the question I have is, because I'm just dealing with b&w and straight lines that run into each-other, like the images attached, is there just not enough differentiated information between the images to make an accurate match? Alternatively, is there a ML approach that could be taken beyond object recognition? Doug A: The problem is that sub-image search algorithms work by sliding the sub-image over the main image and testing how well they compare at every possible location. Since your sub-image is the same size as your main image, there is only a single location where the sub-image can lie on top of the main image - that is when they are exactly aligned. So you need to trim your sub-image first. Here I do it with ImageMagick in the Terminal: magick compare -metric RMSE -subimage-search haystack.png needle.png locations.png and there is no result. But if I trim it first and then retry: magick needle.png -trim +repage trimmed-needle.png magick compare -metric RMSE -subimage-search haystack.png trimmed-needle.png locations.png I get: 949,638 which means a perfect match at those coordinates. TLDR; You need to trim your sub-image to the smallest possible size and it will work.
[ "chemistry.stackexchange", "0000068388.txt" ]
Q: What is the logic behind complex splitting? Like, on a superficial level I know that due to different coupling constant value complex splitting follows a different rule than when splitting involves same hydrogen neighbors. But I don’t understand why and how complex splitting occurs at a intuitive level. Like in complex splitting, is the magnetic moment from the two different neighboring hydrogen adding or subtracting together to affect nmr peak of one of the peak? Is that what’s happening? A: Spin coupled nuclei are affected by the spin states of their coupled partners. That is to say, they can detect whether their spin coupled partner is spin up or spin down (for spin 1/2 nuclei), and the energy level transitions are different, depending on whether that other spin is up or down. If a nucleus is coupled to more than one spin, it is affected by the spin state of each of those nuclei. 'Complex' coupling or splitting is a qualitative term used to describe first order couplings that involve more than two coupled nuclei. They can easily be described using standard splitting diagrams. Consider the example below for the spin system AMX In the absence of any spin coupling, spin A will appear as a singlet - it has only one energy level transtion available. If it is coupled to spin M, the energy levels of spin A will depend on whether spin M is up or down, and so there are two non-equivalent energy level transitons possible for spin, different in energy determined by the magnitude of the coupling constant. Now, if Spin A is coupled to M AND X, then each of the combinations of the AM transitions will also depend on the spin state of X, and so each of the AM transitions will also have two possible transtions - a total of 4 lines, or what we would call a doublet of doublets. A useful reference for interpreting complicated, but first order, splitting patterns is by Hoye: http://pubs.acs.org/doi/abs/10.1021/jo001139v
[ "math.stackexchange", "0000071170.txt" ]
Q: fixed point in the infinite, involving derivates, and composite of a $ C^1$ function Hello this problem it´s looks easy, but I can´t do it. If you can give me some hint to do it )= It´s says this Let $f:\left[ {a,b} \right] \to \left[ {a,b} \right]$ be $C^1$. Let $p$ a fixed point of $f$ such that $ | f´(p) | < 1 $ Prove that there exist $\delta >0$ such that for every $x \in \left( {p - \delta ,p + \delta } \right)\Rightarrow \,\mathop {\lim }\limits_{n \to \infty } f^n \left( x \right) = p$. Where $f^n \left( x \right)$ denotes the composite of functions , $n$ times A: Hint: if $|f'(x)| < 1-\epsilon$ for $|x - p| < \delta$, what can you say about the relation of $|f^{n+1}(x) - p|$ to $|f^n(x) - p|$?
[ "serverfault", "0000639361.txt" ]
Q: ModSecurity on IIS: Single threaded? I installed ModSecurity on a web server running IIS 8.5, and noticed the response time has increased 15 times (0.15 ms/request vs. 2.2 ms/request), even with SecEngine set to off. It seems that IIS is running on single-threaded mode when ModSecurity is installed, because IIS Worker Process only uses around 15% of CPU with ModSecurity, but it can use up to 95% of CPU without it. I'm using the conf file from the CSR installed by ModSecurity. Am I missing some configurations? A: I've managed to confirm your observations (and mine) by looking into the code of ModSecurity IIS module, on GitHub. I found that the code inside CMyHttpModule::OnSendResponse, CMyHttpModule::OnPostEndRequest and CMyHttpModule::OnBeginRequest is wrapped inside EnterCriticalSection(&m_csLock); ... LeaveCriticalSection(&m_csLock); That, coupled with the singleton approach of CMyHttpModuleFactory::GetHttpModule() and the fact that m_csLock is a variable of CMyHttpModule only initialized in its constructor (called only once, because it uses the same instance for all requests), means that all the requests which arrive on different threads are put on hold and executed one by one. I've also created a ticked for this issue on ModSecurity project page, on GitHub.
[ "stackoverflow", "0016507700.txt" ]
Q: Datagridview column limit I have a datagridview table that I need to display some data in. In certain instances, I exceed the column number limit and get the following error: Sum of the columns' FillWeight values cannot exceed 65535 Is there any other tool that I could use to overcome this constraint? A: Open a grid event columnAdded. private void dataGridViewName_ColumnAdded(object sender, DataGridViewColumnEventArgs e) { e.Column.FillWeight = 10; // <<this line will help you } A: The default fill weight for a column in the DataGridView is 100. This combined with the maximun combined fill weight for the grid of 65535 means that with AutoGenerateColumns set to true you cannot have more than 655 columns in your data source. If you need more columns than this then the only solution is to set AutoGenerateColumns for the grid to false, and then manually add the columns with a different fill weight (I'm not sure if 0 is a valid fill weight, so you may need to use 1). It might be worth your while considering a different design - having so many columns in a DataGridView won't be very usable, the performance of the DataGridView is only tuned for up to 100 columns (I got that figure from this forum post by the DataGridView program manager)
[ "stackoverflow", "0058637854.txt" ]
Q: Xml and Java coding not Build Properly Yesterday, I downloaded a Project which was in eclipse and i imported it in my android studio may be due to this or some other reason today when i opened my android studio recent projects it was showing error in gradle file with some other language i searched for the error which was "File was Loaded in Wrong Encoding UTF-8 " and got a method to change from file Please help me out what should i do i tried searching every where but could not get a fine result which worked for me. Here is my sample code of .xml file which is don't know in which format and why ���� 3 0abc_background_cache_hint_selector_material_dark I ConstantValue 1abc_background_cache_hint_selector_material_light (abc_btn_colored_borderless_text_material abc_btn_colored_text_material abc_color_highlight_material !abc_hint_foreground_material_dark "abc_hint_foreground_material_light !abc_input_method_navigation_guard +abc_primary_text_disable_only_material_dark ,abc_primary_text_disable_only_material_light abc_primary_text_material_dark abc_primary_text_material_light abc_search_url_text abc_search_url_text_normal abc_search_url_text_pressed abc_search_url_text_selected abc_secondary_text_material_dark !abc_secondary_text_material_light abc_tint_btn_checkable abc_tint_default abc_tint_edittext abc_tint_seek_thumb abc_tint_spinner abc_tint_switch_track accent_material_dark accent_material_light !background_floating_material_dark "background_floating_material_light background_material_dark background_material_light (bright_foreground_disabled_material_dark )bright_foreground_disabled_material_light 'bright_foreground_inverse_material_dark (bright_foreground_inverse_material_light ! bright_foreground_material_dark " bright_foreground_material_light # button_material_dark $ button_material_light % cardview_dark_background & cardview_light_background ' cardview_shadow_end_color ( cardview_shadow_start_color ) colorAccent * colorPrimary + colorPrimaryDark , %design_bottom_navigation_shadow_color - design_default_color_primary . !design_default_color_primary_dark / design_error 0 design_fab_shadow_end_color 1 design_fab_shadow_mid_color 2 design_fab_shadow_start_color 3 !design_fab_stroke_end_inner_color 4 !design_fab_stroke_end_outer_color 5 !design_fab_stroke_top_inner_color 6 !design_fab_stroke_top_outer_color 7 It was a Fine Working Projects and every thing was working but dnt know what happned tried to reset that was also not working A: Searched Alot Tried to make Sdk Locations Update Updated Gradle due to which all my class files were back to normal form but this Xml File was Not re-formatted So At last i created a new Xml File. But After Some search i come to a result that it might me due to Unwanted Closer of my Android Studio Or may be my battery drained due to which my Android Studio doesn't Closed Properly. If Any One Know After Every update i can do one more thing so that i can re-arranged my xml file to original format I will Update My Answer if that Worked For me Thank You.
[ "stackoverflow", "0053090294.txt" ]
Q: How to define sequelize associations in typescript? I have a Product table and an AccountingPeriod table, with a belongsTo relationship from Product.manufacturingPeriodId to AccountingPeriod.id. The code below compiles but blows up with "Naming collision between attribute 'manufacturingPeriod' and association 'manufacturingPeriod' on model Product. To remedy this, change either foreignKey or as in your association definition" at run time. If I change as in the association code at the very bottom as instructed, I also blow up, but this time with "AccountingPeriod is associated to Product using an alias. You've included an alias (accountingPeriod), but it does not match the alias defined in your association". That second error message is especially puzzling, since I don't specify an alias named accountingPeriod. Doh! Seems like a Catch-22 to me. Of course, I can remove ProductAttributes.manufacturingPeriod, put back manufacturingPeriodId: number; and rename manufacturingPeriod back to manufacturingPeriodId in the options object in the call to sequelize.define(). That compiles and runs just fine, but then I can't code something like myproduct.manufacturingPeriod.startDate in typescript. I've tried various other approaches. All have failed, so I'm raising the white flag of surrender. Can anyone help me out? I'm experienced with sequelize but relatively new to typescript and I'm just not seein' it. import * as Sequelize from 'sequelize'; import {ObjectRelationalManager as orm} from '../index'; import {AccountingPeriodInstance} from './accounting-period'; export interface ProductAttributes { id?: number; name: string; manufacturingPeriod: AccountingPeriodInstance; } export interface ProductInstance extends Sequelize.Instance<ProductAttributes>, ProductAttributes {} export default ( sequelize: Sequelize.Sequelize, dataTypes: Sequelize.DataTypes ): Sequelize.Model<ProductInstance, ProductAttributes> => { return sequelize.define<ProductInstance, ProductAttributes>( 'Product', { id: { type: dataTypes.INTEGER, field: 'id', allowNull: false, primaryKey: true, autoIncrement: true }, name: { type: dataTypes.STRING(20), field: 'name', allowNull: false }, manufacturingPeriod: { type: dataTypes.INTEGER, field: 'manufacturingPeriodId', allowNull: false, references: { model: 'AccountingPeriod', key: 'id' }, onDelete: 'NO ACTION', onUpdate: 'NO ACTION' } }, { tableName: 'Product' } ); }; export function createAssociations(): void { orm.Product.belongsTo(orm.AccountingPeriod, { as: 'manufacturingPeriod', // foreignKey: 'manufacturingPeriodId', targetKey: 'id', onDelete: 'NO ACTION', onUpdate: 'NO ACTION' }); } A: Found the answer myself. Sequelize had already created properties for relationships, so it was just a matter of declaring them for the typescript compiler in the ProductInstance definition: export interface ProductInstance extends Sequelize.Instance<ProductAttributes>, ProductAttributes { manufacturingPeriod: AccountingPeriodInstance; } While debugging I also noticed the handy getXXX, setXXX, createXXX, addXXX, removeXXX, hasXXX, and countXXX accessor functions that sequelize automatically creates for relationships; I'd forgotten about them. After a little digging I found their typescript definitions in the type definition file from @types/sequelize: export interface ProductInstance extends Sequelize.Instance<ProductAttributes>, ProductAttributes { manufacturingPeriod: AccountingPeriodInstance; getAccountingPeriod: Sequelize.BelongsToGetAssociationMixin<AccountingPeriodInstance>; setAccountingPeriod: Sequelize.BelongsToSetAssociationMixin<AccountingPeriodInstance, number>; createAccountingPeriod: Sequelize.BelongsToCreateAssociationMixin<AccountingPeriodAttributes>; } In this particular case the relationship was belongsTo, so getXXX, setXXX, createXXX are the only 3 functions. But many more exist in the form {RelationShipType}{Add}AssociationMixin<TInstance>, {RelationShipType}{Remove}AssociationMixin<TInstance>, etc.
[ "ru.stackoverflow", "0001174238.txt" ]
Q: Почему не работает from Пытаюсь понять Intra-package References Дерево проекта: project/ __init__.py main.py folder/ __init__.py module_1.py module_2.py В "module_2.py пишу: def one(): return 1 В "module_1.py пишу: from . import module_2 print(module_2.one()) остальные файлы пустые ошибка A: При запуске скрипта интерпретатор не знает родительский пакет, и потому относительный импорт не работает. Если скрипт не верхнего уровня (а данном случае это так), то можно запустить скрипт как модуль: python -m folder.module_1, тогда питон будет знать родительский пакет. Еще вариант явно провисать в модуле родительский пакет до относительного импорта: if __name__ == "__main__" and __package__ is None: __package__ = 'folder' В таком случае даже python folder/module_1.py будет работать при условии, что директория верхнего уровня указана в PYTHONPATH. Подробности описаны тут
[ "superuser", "0000165550.txt" ]
Q: Change password timeout on Linux? If I type in the wrong password at login, then the system forces me to wait for about a second before I can retry. Is there a way to reduce this timeout? Also, is there a global timeout setting for su and sudo or do I have to change those timeouts using a different method? A: Checking out /etc/login.defs on Ubuntu 11.10 I see that the config option that b0fh mentions has been moved to the /etc/pam.d/login file as: auth optional pam_faildelay.so delay=3000000 which I changed from 3 sec. to half a second in order to lessen the effect of my bad habit of often getting my password wrong on the first go. (I consider the added risk of a brute-force attack taking one-sixth of the time it would have taken otherwise is a negligible factor) A: change the FAIL_DELAY line in /etc/login.defs. That should affect both login and su. But why would you want to do that ?
[ "stackoverflow", "0012779502.txt" ]
Q: Xcode4.5 assembler fails to compile files that Xcode4.4 handled perfectly After update xcode to 4.5 version I have an error Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1 I read about error like this after update, but changing the architecture in target's builds settings doesn't help. It's work on simulator but not on device. The whole error CompileC /Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Intermediates/Jasiu2.build/Debug-iphoneos/Jasiu2.build/Objects-normal/armv7/maxvid_decode_arm.o Classes/AVAnimator/maxvid_decode_arm.s normal armv7 assembler-with-cpp com.apple.compilers.llvm.clang.1_0.compiler cd /Users/psitkowski/Xcode/ksiazki/kopie/Jasiu2 setenv LANG en_US.US-ASCII setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x assembler-with-cpp -arch armv7 -fmessage-length=0 -Wno-trigraphs -fpascal-strings -O0 -Wno-missing-field-initializers -Wno-missing-prototypes -Wreturn-type -Wformat -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wno-shorten-64-to-32 -Wno-newline-eof -DDEBUG=1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.0.sdk -Wdeprecated-declarations -g -Wno-sign-conversion -miphoneos-version-min=5.1 -iquote /Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Intermediates/Jasiu2.build/Debug-iphoneos/Jasiu2.build/Jasiu2-generated-files.hmap -I/Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Intermediates/Jasiu2.build/Debug-iphoneos/Jasiu2.build/Jasiu2-own-target-headers.hmap -I/Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Intermediates/Jasiu2.build/Debug-iphoneos/Jasiu2.build/Jasiu2-all-target-headers.hmap -iquote /Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Intermediates/Jasiu2.build/Debug-iphoneos/Jasiu2.build/Jasiu2-project-headers.hmap -I/Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Products/Debug-iphoneos/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Intermediates/Jasiu2.build/Debug-iphoneos/Jasiu2.build/DerivedSources/armv7 -I/Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Intermediates/Jasiu2.build/Debug-iphoneos/Jasiu2.build/DerivedSources -F/Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Products/Debug-iphoneos -MMD -MT dependencies -MF /Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Intermediates/Jasiu2.build/Debug-iphoneos/Jasiu2.build/Objects-normal/armv7/maxvid_decode_arm.d --serialize-diagnostics /Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Intermediates/Jasiu2.build/Debug-iphoneos/Jasiu2.build/Objects-normal/armv7/maxvid_decode_arm.dia -c /Users/psitkowski/Xcode/ksiazki/kopie/Jasiu2/Classes/AVAnimator/maxvid_decode_arm.s -o /Users/psitkowski/Library/Developer/Xcode/DerivedData/Jasiu2-gskaidiujznurtdqnebvtogjtdnd/Build/Intermediates/Jasiu2.build/Debug-iphoneos/Jasiu2.build/Objects-normal/armv7/maxvid_decode_arm.o /Users/psitkowski/Xcode/ksiazki/kopie/Jasiu2/Classes/AVAnimator/maxvid_decode_arm.s:65:2: error: invalid instruction strneh r8, [r10], #2 ^ ... About 100 lines like above ... /Users/psitkowski/Xcode/ksiazki/kopie/Jasiu2/Classes/AVAnimator/maxvid_decode_arm.s:474:2: error: invalid instruction stmeqia r10!, {r0, r1} ^ Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1 I have a error like this before, when I forgot add libz.dylib in build phases. Have you got any idea how to fix it? Thanks a lot, A: Yes, Xcode 4.5 has made some changes that break compilation of ASM code. There fix is easy, just add the -no-integrated-as flag to the compilation options for the maxvid_decode_arm.s file in AVAnimator. Like so: Choose the project file in the left window that lists files (it is the one at the top with the blue icon). Select your Target in the "TARGETS" list. Select the "Build Phases" Tab. Double click on maxvid_decode_arm.s, then add -no-integrated-as by pasting into the list that comes up.
[ "stackoverflow", "0036989795.txt" ]
Q: Are there any loops or references is Batch? I'm currently trying to learn Batch scripting and i wanted to know if there are any loops or references in Batch (example down below). In C# there are loops like while (true) { Tasks } and for (int i=0; i<value; i++) { // do ... } and foreach (var item in collection) { // do ... } and do { // do ... } while (true) and if (true) { // do ... } else { // do else ... } and try { // try to do ... } catch (Exception e) { // do if try fails ... } finally { // do anyways ... } and switch (value) { case 1: /* do */ break; case...; } I want to know if these do exist in Batch and how the syntax looks or how I can use it. Thanks MC A: There are a few types of loops. Most involve the for keyword. Type help for in a cmd console for more info. The most basic is for %%x in (tokenset) do ( rem // act on each token ) The batch equivalent of for (var i=0; i<10; i++) in other languages is for /L. for /L %%x in (0,1,10) do ( rem // 0..10 ) There's no while or do until loop, but there is goto label. For example: set x=0 :loop set /a x+=1 if %x% leq 9 goto loop And for looping through the contents of a file or the output of a command, there's for /F. for /f "usebackq delims=" %%x in ("filename.txt") do ( rem // act on each line of text ) for /f "delims=" %%x in ('command') do ( rem // act on each line of output ) In order of efficiency, for and for /L are fastest. But if you break out of for /L using goto, the script continues to iterate through the loop until complete, but skipping the commands within. This can affect performance if you're using for /L %%I in (0,1,1000000) and use goto to try to break out of it after a few iterations. Example: for /L %%I in (0,1,10) do ( echo %%I ) is much faster than... for /L %%I in (0,1,1000000) do ( echo %%I if %%I gtr 9 goto next rem // continues iterating 1000001 times, but only echoes 11 lines. ) :next for /F is a little slower, and goto is slowest. You had also mentioned if and switch. if, yes. There is if. Type help if from a cmd console for full details. Examples: set /a "var = 5 << 2" if %var% gtr 30 echo What a big number! set "var=foo" if /I "%var%"=="Foo" echo Case insensitive match worked with /I There's also conditional execution, which comes in very handy. Rather than checking if errorlevel n, you can check for zero / non-zero status with && or ||. Example: (echo "The quick brown fox") | findstr /i "brown" >NUL && ( echo Contained the word "brown". ) || ( echo Didn't contain the word "brown". ) There's no switch...case, but you can use goto for some creative processing. @echo off & setlocal :begin echo 1: option 1 echo 2: option 2 echo 3: option 3 set /P "opt=Enter a selection: " for %%I in (1 2 3) do if "%opt%"=="%%I" goto run%%I echo %opt%: invalid choice. pause goto begin :run1 echo Do stuff! goto begin :run2 echo Do something else. goto begin :run3 echo Bye! exit /b
[ "mathoverflow", "0000339789.txt" ]
Q: Every possible number of partitions by restricting parts? Write $p(n)$ for the number of integer partitions of $n$. For $S \subseteq \{1, \ldots, n\}$, let $p_S(n)$ be the number of partitions of $n$ with all parts in $S$. So $p(n) = p_{\{1,\ldots,n\}}(n)$. Conjecture: Given positive integers $n$ and $k$ with $0 \le k \le p(n)$, there is an $S \subseteq \{1, \ldots, n\}$ such that $p_S(n)=k$. I have verified this through $n=20$. Some very loose intuition supporting the conjecture is that the number of subsets grows much faster than $p(n)$. This conjecture is inspired by David Newman's question where he wonders about $S$ with $p_S(n)=p(n)/2$ or $(p(n)\pm1)/2$. My non-answer there suggests that a greedy algorithm is enough to find the $S$ he wants, verified for even $n$ up to 50. A: The conjecture seems to hold. For brevity, denote $[k,n]=\{k,k+1,\dots,n\}$ and $[n]=[1,n]$. Start with $S = [n]$. Algorithm: Given $0\leq k\leq p(n)$, consider the numbers $1,2,\dots,n$ one by one, removing the number if the remaining set $S$ satisfies $p_S(n)\geq k$. After all $n$ numbers are considered, we are done. Let $S_m$ be the set obtained after considering the numbers up to $m$. Hence, the algorithm reads as follows: $S_m=S_{m-1}\setminus\{m\}$ if $p_{S_{m-1}\setminus\{m\}}(n)\geq k$, and $S_m=S_{m-1}$ otherwise. We claim that at each step, the inequality $$ p_{S_m\cap[m]}(n)\leq k \qquad(*) $$ holds. If $(*)$ is proved, we will get $k\leq p_{S_n}(n)\leq k$, as required. We prove $(*)$ by induction on $m$. Clearly, it holds for $m=0$. Assume now that $p_{S_{m-1}\cap[m-1]}(n)\leq k$. If $S_m=S_{m-1}\setminus\{m\}$, then $S_{m-1}\cap[m-1]=S_m\cap[m]$, and $(*)$ holds. Otherwise, $S_m=S_{m-1}$, which means that $p_{S_{m-1}\setminus\{m\}}(n)\leq k-1$. So, in order to finish this case, it suffices to show that $$ p_{S\cap[m]}(n)\leq p_{S\setminus\{m\}}(n)+1 \qquad(**) $$ for every $S\supseteq[m,n]$ (and apply it to $S=S_{m-1}$). If $m=n$, the inequality is obvious. Otherwise, we will show even the version without `$+1$'. We present an ``injective'' proof, after taking the complements. Namely, to each partition with parts in $S$, at least one of which equals $m$, we assign a partition with parts in $S$, at least one of which exceeds $m$, so that this correspondence is injective. This will prove $$ p_S(n)-p_{S\setminus\{m\}}(n)\leq p_S(n)-p_{S\cap[m]}(n), $$ which yields $(**)$. The partitions containing both $m$ and $>m$ correspond to themselves. Now take any partition with maximal element $m$. If it contains a unique copy of $m$, let $a(<m)$ be the minimal element of the partition; replace now $m$ and $a$ by $m+a$. Finally, if the partition contains exactly $d>1$ copies of $m$, replace them by $dm$. Clearly, this correspondence is injective, as required.
[ "stackoverflow", "0005677518.txt" ]
Q: Active Record pattern, Repository pattern and testability (in java) What would be the drawback (in terms of testability for example) to the following approach which intends to get the best from Active Record pattern and Repository pattern ? Each persistent object exposes save() and delete() method, but no static methods to load itself, or to load a list of similar objects : loading from upper layers is done by directly calling a repository, to avoid static methods in persistent objects. The "save()" and "delete()" methods are only facades, they are delegated to the repository. Is testability really a concern with this approach ? Even with pure Active Record approach : are there information systems where database logic represents only a small part of the whole business logic, and where it would be interesting to mock the database access ? EDIT : This approach needs that persistent objects inherit from an AbstractPersistentObject which implements "save()" and "delete()", and it prevents business inheritance, but I read it was better to avoid business inheritance, and to replace it with composition, so it may be an advantage, and not a drawback...? EDIT2 : Maybe this article will explain better which issues I am trying to solve : http://moleseyhill.com/blog/2009/07/13/active-record-verses-repository/ A: There are two things that raise some concern. The first one is this quote (emphasis mine): [...] are there information systems where database logic represents only a small part of the whole business logic, and where it would be interesting to mock the database access? Are you putting business logic in your database? If so: don't do it, it makes it very hard to mock your database. You'd have to duplicate (and maintain!) all of the business logic from the database to your mocks, otherwise your tests are useless. But how do you know if the mocks correctly implement the business logic? You could write unit tests for your mocks, or reuse the unit tests of your database (you do have them, right?), but that's an approach I'd try to avoid at all costs! Let me repeat: don't ever (have to) write unit tests for your mocks. If you find yourself in such a situation, take a few steps back and review your design, because there's something very wrong. Putting business logic in the database will only create unnecessary coupling between your model and the database, and immensely complicate your testing layer. Separation of concerns is key here: the model focuses on business logic only and the database focuses on persistence only, nothing else. Which brings me to my next concern: why do you need save() and delete() methods, which are persistence-related, on your domain model? Persistence doesn't belong in the domain model. I know, you said that these methods will delegate to a repository, so the domain model (hopefully) doesn't contain the actual persistence logic. But how does it know which repository it should delegate to? If you are calling a service locater in the save() method, you're making it impossible to save the entity to multiple repositories. You're also hiding the dependency on the repository from the caller, which I consider to be a bad thing. To solve these issues, you could pass a repository instance to the save() method, like this: public class Foo extends AbstractPersistentObject { public void saveTo(IFooRepository repository) { repository.save(this); } } But a method like this implies that the caller already has a repository instance, so he might as well call the save() method directly on the repository. Any persistence methods on the domain model would be obsolete. Perhaps I'm oversimplifying your problem. What is it you are trying to achieve? Do you only want the entity.save() syntax, or are you trying to solve a bigger problem?
[ "stackoverflow", "0029152031.txt" ]
Q: Android prevent intent restoration after Destroy on back button I'm running into an unpleasant issue I don't know how to solve properly. Scenario: MainActivity has a method handleIncomingIntent() This method parses the Extras coming in the incoming intent (for service, or broadcast receiver) and opens Child Activities based on an intent data. So, when the incoming Intent has data of type A it will startActivity(ActivityA.class), if of type B then startActivity(ActivityB.class) if no data it will stay in MainActivity Problem is when device is low on memory, MainActivity is destroyed, while in ActivityA or ActivityB. Therefore when BackButton is used - the MainActivity gets restored and it's incoming Intent is restored at the same state as before handling it despite the fact I'm doing incomingIntent.removeExtras(KEY) in the end of my handleIncomingIntent() method. So the outcome is - it's starting the Child Activity once again and it's a loop! I realize that I can store some isIntentConsumed flag into memory inside onDestroy() and then read it restoreSavedState() and use it to dismiss the intent since it's already consumed. I just feel there must be a better way than a "bandaid" that I just described. Kind Regards, Pavel A: If the stopped Activity is destroyed due to system constraints other than normal conditions(user presses back or activity finish itself), the method onSaveInstanceState(Bundle savedInstanceState) will be called. When user navigates back to this kind of activity, onRestoreInstanceState(Bundle savedInstanceState) will be called and the previous saved bundle will be passed as parameter to both onRestoreInstanceState() and onCreate(). So you can check the actual parameter of onCreate(Bundle savedInstanceState), if savedInstanceState != null you can know the activity is recreated. Hope helped.
[ "stackoverflow", "0039646311.txt" ]
Q: Converting multiple rows of data to a single column of data I have a basic excel spreadsheet with columns of data that needs to be exported as a single column of data. I've been cutting and pasting/transposing the rows, but it's tedious. Any help would be greatly appreciated. Results should go across first each row. Sample data below: 4619980.95 1040503.25 823644.03 1039799.69 1033153.29 9925740.32 2235456.21 1769547.72 2233944.65 2219665.26 7868405.05 1772107.1 1402768.74 1770908.85 1759589.19 2707020.09 609669.87 482603.92 609257.63 605363.25 4331232.14 975471.8 772166.28 974812.21 968581.21 4186857.73 942956.07 746427.4 942318.47 936295.17 7363094.64 1658302.06 1312682.67 1657180.76 1646588.05 4764355.35 1073018.98 849382.91 1072293.43 1065439.33 A: For a formula answer use INDEX(): =INDEX(A:XX,INT((ROW(1:1)-1)/MATCH(1E+99,$1:$1))+1,MOD(ROW(1:1)-1,MATCH(1E+99,$1:$1))+1) As this formula is copy/dragged down it will reference the next cell to the right till it comes to the last cell. Then it will move down to the next row. It does require that the number of columns in row 1 is the same as all the other rows.
[ "stackoverflow", "0006933347.txt" ]
Q: How should one use Disruptor (Disruptor Pattern) to build real-world message systems? As the RingBuffer up-front allocates objects of a given type, how can you use a single ring buffer to process messages of various different types? You can't create new object instances to insert into the ringBuffer and that would defeat the purpose of up-front allocation. So you could have 3 messages in an async messaging pattern: NewOrderRequest NewOrderCreated NewOrderRejected So my question is how are you meant to use the Disruptor pattern for real-world messageing systems? Thanks Links: http://code.google.com/p/disruptor-net/wiki/CodeExamples http://code.google.com/p/disruptor-net http://code.google.com/p/disruptor A: One approach (our most common pattern) is to store the message in its marshalled form, i.e. as a byte array. For incoming requests e.g. Fix messages, binary message, are quickly pulled of the network and placed in the ring buffer. The unmarshalling and dispatch of different types of messages are handled by EventProcessors (Consumers) on that ring buffer. For outbound requests, the message is serialised into the preallocated byte array that forms the entry in the ring buffer. If you are using some fixed size byte array as the preallocated entry, some additional logic is required to handle overflow for larger messages. I.e. pick a reasonable default size and if it is exceeded allocate a temporary array that is bigger. Then discard it when the entry is reused or consumed (depending on your use case) reverting back to the original preallocated byte array. If you have different consumers for different message types you could quickly identify if your consumer is interested in the specific message either by knowing an offset into the byte array that carries the type information or by passing a discriminator value through on the entry. Also there is no rule against creating object instances and passing references (we do this in a couple of places too). You do lose the benefits of object preallocation, however one of the design goals of the disruptor was to allow the user the choice of the most appropriate form of storage. A: There is a library called Javolution (http://javolution.org/) that let's you defined objects as structs with fixed-length fields like string[40] etc. that rely on byte-buffers internally instead of variable size objects... that allows the token ring to be initialized with fixed size objects and thus (hopefully) contiguous blocks of memory that allow the cache to work more efficiently. We are using that for passing events / messages and use standard strings etc. for our business-logic.
[ "stackoverflow", "0007870374.txt" ]
Q: Bind / Live Load Event on Dynamic HTML img Not Working In this example, I can get the following code to create the dynamic image in div#add element when I click the button, but the load event for the img does not work. <html> <head> <title>None!</title> <script type="text/javascript" src="Scripts\jquery-1.6.2.min.js"></script> </head> <body> <button id="click">Click</button> <div id="add"></div> <script> $(document).ready(function(){ $('#click').click(function() { $('div#add').append('<img src="./images/imagename.jpg" />'); }); $('img').bind('load',function(){ alert('test'); }); }); </script> </body> </html> I have also tried setting the onload event on the dynamic img but I did not get the event to fire. Any help is much appreciated. Update (2011-10-24 18:55 EST): It appears that JQuery documentation for Load-Event states the following. Caveats of the load event when used with images A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are: -It doesn't work consistently nor reliably cross-browser -It doesn't fire correctly in WebKit if the image src is set to the same src as before -It doesn't correctly bubble up the DOM tree -Can cease to fire for images that already live in the browser's cache I guess using the load event is not a fail safe, cross-browser solution. Update (2011-10-28 15:05 EST): Thanks to @Alex, I was able to use his waitForImages plugin and make a listener (I'm not sure if that is the right term) to determine when an image has been loaded. <html> <head> <title>None!</title> <script type="text/javascript" src="Scripts\jquery-1.6.2.min.js"></script> <script type="text/javascript" src="Scripts\jquery.waitforimages.js"></script> </head> <body> <button id="click">Click</button> <div id="add"></div> <script> $(document).ready(function(){ setInterval(function(){ $('div#add img.art').waitForImages(function() { $('div#add img.load').hide(); $(this).show(); }); }, 500); $('#click').click(function() { $('div#add').append('<img class="load" src="./images/loading.gif" /><img style="display:none;" width="199" class="art" src="./images/imagename.jpg" /><br />'); }); }); </script> </body> </html> So right now there is a maximum of 500 ms lag in determining if an image has been loaded. Does this seem reasonable? Is this the best way to see if a dynamically created img tag has been loaded? Outstanding: I have to stop the setInterval function from triggering after all of the images have been loaded. I still have to work out the details on that. A: Change bind() to on() and rejig the arguments accordingly. When you simply bind(), it binds to all elements in the DOM. When you use on(), it looks for events bubbling to your common ancestor and then checks their origin and fires any attached events. This means it will handle all future img elements.
[ "es.stackoverflow", "0000176990.txt" ]
Q: ¿Como llamar a una función después que se ejecute una función de datatable? Quiero ejecurtar una funcion para realizar x acción despues de realizar una busqueda, mostrar datos o despues de usar la paginación de DataTable pero no se como hacerlo alguien me puede ayudar ? Muestro el codigo que me lista los datos table = $('#table').DataTable({ "scrollX": true, "scrollY": "245px", "lengthMenu": [ [5, 15, 25, 50, 100, -1], [5, 15, 25, 50, 100, "Todo"] ], "scrollCollapse": false, "ordering": false, "processing": true, //Feature control the processing indicator. "serverSide": true, //Feature control DataTables' server-side processing mode. "order": [], //Initial no order. "language": { "lengthMenu": "Mostrar _MENU_ registros por pagina", "zeroRecords": "No se encontraron resultados en su busqueda", "searchPlaceholder": "Buscar registros", "info": "Mostrando de _START_ al _END_ de _TOTAL_ registros", "infoEmpty": "No existen registros", "infoFiltered": "", "search": "Buscar:", "processing": "Procesando...:", "paginate": { "first": "Primero", "last": "Último", "next": "Siguiente", "previous": "Anterior" }, }, // Load data for the table's content from an Ajax source "ajax": { "url": "<?php echo base_url(); ?>planilla/ajax_list", "type": "POST" }, //Set column definition initialisation properties. "columnDefs": [{ "targets": [-1, -44, -43], //last column "orderable": false, //set not orderable }, ], }); tabla con datatable A: $('#table').DataTable().on("draw", function(){ //Funcion }) El evento draw se ejecuta despues de que se pinta la tabla
[ "stackoverflow", "0005644029.txt" ]
Q: Storing data with leading zeros in an integer column for Django I need to be able to insert numbers like 098532 into my table. This is the exact same question as this but I actually need to store it with the leading zeros as I will be using the data for 3rd party API calls. The given answer was to format the output which doesn't really solve my problem. Is the best solution to change the datatype of the column to a CHAR field? A: I think your best bet is to store it as a string in a charfield and then cast it when you need something else. i.e. num = "051" int(num) if you need it as an int. Could you give a little more information about what the api expects and why you need the leading zeroes?
[ "stackoverflow", "0032905168.txt" ]
Q: How to get odoo 8 without all business modules stuffs? I want to deeply understand how ODOO work so I need to install just ODOO core the basic that power the machinery without all business modules stuff like accountant, HR, Sale and all that, just a clean and lightweight ( not the 300MB size package) installation that work, so I can login and log out and build my own HR module if I want (this is not my aim of course). So in order to that can you guys help me figure out which module compose the core of ODOO? A: If you are trying to do this installation on your local machine by downloading and installing all the dependencies , you just need to write this command: ./odoo.py -d DBNAME --db-filter DBNAME Parameters: -d : It will create the database with DBNAME --db-filter: It will choose this newly created database to login. This will only install the "base" module which you are quoting here as "core". No other module like sale or account will be installed by itself. However, if you wish to install new module with command then : ./odoo.py -d DBNAME --db-filter DBNAME -i MODULENAME Or you can install it via "Apps" menu as well. I hope you have got your answer.
[ "graphicdesign.stackexchange", "0000013944.txt" ]
Q: Photoshop - Multiple layer styles of the same type I want to style a layer with layer styles in Photoshop. The problem is that I want to add multiple inner drop shadows. I saw that you can do Right Click > Rasterise Layer Style, but then I can't change it anymore. Best would be if I could link a separate layer with it and apply the style to this one. Can anyone help me out here? A: Method 1 — Groups Photoshop CS6 can have layer styles applied to groups. Groups can be nested. This is probably the best way to do it, because it's neat and everything scales nicely when you scale the document (for Retina etc). Method 2 — Smart Objects Once you've applied some layer styles to a shape, you can convert it to a Smart Object and then apply more layer styles. You can still edit the layer styles inside the Smart Object by double clicking it. Not ideal, because Smart Objects generated in Photoshop bitmap scale, so this technique isn't good if you intend to make Retina versions of images. It's also quite difficult to edit, because you have to open the Smart Object to make changes. Works in Photoshop CS5 though. Method 3 — Shape Layers & Clipping Mask You can also use shape layers and a clipping mask to do pretty much anything layer styles can do. Need a blurry inner shadow? Use Mask Feathering to blur your shape layers. Easy! The only drawback is if you need to clip the result to another vector layer. Method 4 etc There's other ways to do this that don't require rasterising... let me know if the methods above don't suit. A: To do this, I would duplicate the layer, bring it to the top, and set its Fill to 0%: This will set the Fill to be transparent but the layer effects will remain. Then you can change the settings of the top layer effect so that you can have two Inner Shadows. Here's an example with the shadows set to red and blue to show the result:
[ "stackoverflow", "0052700951.txt" ]
Q: How to match a number with the numbers in array in vanilla JavaScript? I'm making a filter in JS 5. In short: Bubble have ids, attributes. I take the bubble ID and I match it with the array of objects. if the bubble id matches with one of the id from the array of objects, I want to show the object information/id. The user clicks a bubble, and I get the bubble id and store it. The bubble id will then need to be compared within the object/JSON and if the bubble id is same as one of the items in the object, it should display the object id and its information. So far, I managed to get the obj ID, and the numbers in an array I think, but it doesn't quite seem right. How can I fix this so when I click the number it matches the number within the array of objects and takes the appropriate one and displays that object info? Codepen: https://codepen.io/Aurelian/pen/xyVmgw?editors=0010 JS code: var dataEquipmentList = [ { "equipmentId": 16, "equipmentTitle": "Horizontal Lifelines & Anchors", "equipmentMainBgImg": "https://www.yorkshirewildlifepark.com/wp-content/uploads/2016/06/lion-country-banner-1.jpg", "productList": [ { "rowId": 1, "toolList": [ { "toolPicture": "https://youtube.com/", "toolName": "Tracoda", "toolModelNumber": "ET 10", "toolDescription": "Chest belt fitted", "toolUrl": "https://google.com/" }, { "toolPicture": "https://youtube.com/", "toolName": "Tracoda", "toolModelNumber": "ET 10", "toolDescription": "Chest belt fitted", "toolUrl": "https://google.com/" } ] }, { "rowId": 2, "toolList": [ { "toolPicture": "https://youtube.com/", "toolName": "Tracoda", "toolModelNumber": "ET 10", "toolDescription": "Chest belt fitted", "toolUrl": "https://google.com/" } ] } ] }, { "equipmentId": 17, "equipmentTitle": "DDDDD Lifelines & Anchors", "equipmentMainBgImg": "http://www.waterandnature.org/sites/default/files/styles/full/public/general/shutterstock_creative_travel_projects.jpg?itok=MsZg16JU", "productList": [ { "rowId": 1, "toolList": [ { "toolPicture": "https://youtube.com/", "toolName": "Tracoda", "toolModelNumber": "ET 10", "toolDescription": "Chest belt fitted", "toolUrl": "https://google.com/" }, { "toolPicture": "https://youtube.com/", "toolName": "Tracoda", "toolModelNumber": "ET 10", "toolDescription": "Chest belt fitted", "toolUrl": "https://google.com/" } ] }, { "rowId": 2, "toolList": [ { "toolPicture": "https://youtube.com/", "toolName": "Tracoda", "toolModelNumber": "ET 10", "toolDescription": "Chest belt fitted", "toolUrl": "https://google.com/" } ] } ] } ] function getEquipmentIds() { for(var keys in dataEquipmentList) { var key = dataEquipmentList[keys]; } } getEquipmentIds(); ////////// // Mindmap Code ////////// function filterBubbles() { var equipmentList = document.querySelectorAll('.pt-bubble'); equipmentList.forEach(function(item) { var equipmentId = item.getAttribute('data-equipment-id'); item.addEventListener('click', function(){ //console.log(equipmentId); for(var keys in dataEquipmentList) { var keyArray = []; var key = dataEquipmentList[keys].equipmentId; keyArray.push(keys); console.log(keyArray); for (var i=0; i < keyArray.length; i++) { if (equipmentId === keyArray[i]) { console.log(equipmentId + " It's a match with " + keyArray[0]); } } // if(equipmentId === keyArray) { // console.log(equipmentId + "It's a match with " + key); // } else { // console.log("else" + key); // } } }) }) } filterBubbles(); A: I guess you will need the Array.prototype.filter() method. here's how to use it: just change the outer for loop within item.addEventListener('click', function() with let result=dataEquipmentList.filter((item)=>{ return item.equipmentId==equipmentId; }); console.log(result[0].equipmentId+'\n'+result[0].equipmentTitle); //17 //DDDDD Lifelines & Anchors it means filtering all the items that match the callback returning true, from an array. Here there can be only one item, so you can access it with result[0]. I have tested and it seems working well. note: you need == here because the id propertys in your buttons are strings. or you can check the filter method here:Array.prototype.filter(). hope this would help you.
[ "stackoverflow", "0023489845.txt" ]
Q: PHP Warning: DOMDocument::load(): I/O warning : failed to load external entity I read everything I could about this error without being able to find any solution. I have a simple page that looks like this: $xmlfile = "/var/www/marees.xml"; //Fichier dans lequel récupérer les données $ent = new DOMDocument(); $ent->load($xmlfile); if(!(@$ent->load($xmlfile))) { echo "Unable to load : " . $xmlfile; exit(); } I get three times out of four, randomly this error: PHP Warning: DOMDocument::load(): I/O warning : failed to load external entity "/var/www/marees.xml" in /var/www/marees/test2.php on line 7 When I restart Apache, the script works fine for 5 minutes, then the error starts to appear. XML file weighs 595 kB, is present and readable. What might be the problem? A: add this command to the top of your script: libxml_disable_entity_loader(false); For more details see this link.
[ "stackoverflow", "0042201822.txt" ]
Q: Spark DataFrame query between 2 specific Time Range I have a spark dataframe with a column having Date in the format dd-MMM-yyyy hh:mm. How to do TimeRange query like - Find all the rows between 2 dates and within specific time range of 4PM to 1AM. This is possible in sql by using DatePart Specific Time Range Query in SQL Server How to do the same in Spark Dataframe. For example, I want to find all the rows between 23-MAR-2016 till 25-MAR-2016 , within time range from 13:00:00 till 18:00:00 only. So I must get only one row as result. var input = spark.createDataFrame(Seq( (13L, "Abhi c", "22-MAR-2016 09:10:12"), (11L, "VF", "23-MAR-2016 16:24:25"), (12L, "Alice Jones", "24-MAR-2016 19:20:25") )).toDF("id", "name", "time") input.filter("time between '23-MAR-2016' and '25-MAR-2016'").show() +---+-----------+--------------------+ | id| name| time| +---+-----------+--------------------+ | 11| VF|23-MAR-2016 16:24:25| | 12|Alice Jones|24-MAR-2016 19:20:25| +---+-----------+--------------------+ My Above query only filtered the date and even I can give time but how to get rows within a time range of each day. A: You can do something like this: import org.apache.spark.sql.functions.unix_timestamp var input = spark.createDataFrame(Seq( (13L, "Abhi c", "22-MAR-2016 09:10:12"), (11L, "VF", "23-MAR-2016 16:24:25"), (12L, "Alice Jones", "24-MAR-2016 19:20:25") )).toDF("id", "name", "time") val h = hour(unix_timestamp($"time", "dd-MMM-yyyy hh:mm:ss").cast("timestamp")) input.withColumn("hour", h).filter("time BETWEEN '23-MAR-2016' AND '25-MAR-2016' AND hour BETWEEN 13 AND 18").show() +---+----+--------------------+----+ | id|name| time|hour| +---+----+--------------------+----+ | 11| VF|23-MAR-2016 16:24:25| 16| +---+----+--------------------+----+
[ "stackoverflow", "0014208944.txt" ]
Q: C# Right click on TreeView nodes I have a TreeView with the parent node : Node0. I add 3 subnodes: Node01 Node02 Node03 I have a popup menu that is associate to each of the subnodes. My problem: If I right-click directly to one of the subnodes, my popup does not display. So I have to Select the Subnode first and Right-click to have the popup displayed. How can I change the code so that the Direct Right-Click on a specific SubNode open the PopupMenu? The popupMenu have only OpenMe menu in the list. When clicking on this menu, a windows is supposed to open and this windows should be associated to the submenu I have clicked. How to get the Event of the right-click submenu and display Form with it? EDIT: Look at this private void modifySettingsToolStripMenuItem_Click(object sender, EventArgs e) { try { String s = treeView1.SelectedNode.Text; new chartModify(s).ShowDialog(); } catch (Exception er) { System.Console.WriteLine(">>>" + er.Message); } } The line String s = treeView1.SelectedNode.Text; gets the name of the selected node and not the node that have been right-clicked. So here I have to modify this piece of code with the private void treeview1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Button == MouseButtons.Right) MessageBox.Show(e.Node.Name); } I modify it like this: try { TreeNodeMouseClickEventArgs ee; new chartModify(ee.Node.Name).ShowDialog(); } but it does not work : Error:Use of unassigned local variable 'ee' EDIT #2: Finaly got the solution public string s; private void modifySettingsToolStripMenuItem_Click(object sender, EventArgs e) { try { new chartModify(s).ShowDialog(); } catch (Exception er) { System.Console.WriteLine(">>>" + er.Message); } } and then private void treeview1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Button == MouseButtons.Right) { s = e.Node.Name; menuStrip1.Show(); } } it works, Thanks A: You can try using the NodeMouseClick Event it uses the TreeNodeClickEventArgs to get the Button and the Node that was clicked. private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if(e.Button == MouseButtons.Right) MessageBox.Show(e.Node.Name); } Modified Code to show Popup and created Form public partial class Form1 : Form { string clickedNode; MenuItem myMenuItem = new MenuItem("Show Me"); ContextMenu mnu = new ContextMenu(); public Form1() { InitializeComponent(); mnu.MenuItems.Add(myMenuItem); myMenuItem.Click += new EventHandler(myMenuItem_Click); } void myMenuItem_Click(object sender, EventArgs e) { Form frm = new Form(); frm.Text = clickedNode; frm.ShowDialog(this); clickedNode = ""; } private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Button == MouseButtons.Right) { clickedNode = e.Node.Name; mnu.Show(treeView1,e.Location); } } }
[ "judaism.stackexchange", "0000089369.txt" ]
Q: Tehillim 119 -- what vav's to pronounce I was saying Tehilim recently and I got up to 119, and when I reached the first "Aydosecha" I remembered that sometimes the vav is pronounced (a.k.a, there's a cholam above the normal vav), so it would sound like "Aydvosecha", and sometimes the vav is the actual cholam, so the pronunciation is "Aydosecha". Some Tehilim's have them marked pretty clearly, but others (like the one I'm using) don't, and I think there's some siman to remember which vav's to say (I saw it in an old Tehillim a while ago), but I forgot it, so does any know the siman or at least which vav's to pronounce? A: The trick here (if the dot-above-the-Vav's location is ambiguous) is that if the Vav is a mater lectionis, then it is serving as the vowel for the previous letter. Thus if the previous letter has a vowel already, it must be the Vav is a consonant. In your case, the Dalet has a Shva, so the Vav is a consonant. On the other hand, in Tehillim 78:56 it says וְעֵדוֹתָיו where the Dalet has no Vowel, and thus the Vav is a mater lectionis. Ideally, of course, the printer should be careful to mark the dot off to the left a bit if the Vav is a consonant like with any other consonant.
[ "stackoverflow", "0023483814.txt" ]
Q: WPF Multitab editor Save feature I am implementing a text editor in WPF and I have a reached a stage where I can open multiple files in tabs in my application. The code is as below. Now I need to implement the save feature for my text editor. For this I need to know which particular Tab is active for me to save that File alone. How will I do this functionality? Also my tabs do not have a close button('X'). How will I implement a close button functionality in WPF? Any help is appreciated. public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Open_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.DefaultExt = ".txt"; dlg.Filter = "Text Files(*.txt)|*.txt"; Nullable<bool> result = dlg.ShowDialog(); mode openfile = mode.openFile; if (result.HasValue == true) { if (File.Exists(dlg.FileName)) AddTabitem(dlg.FileName, openfile); else MessageBox.Show("NoSuch file exsists", "OpenError"); } } private void AddTabitem(string filePath, mode fileMode) { TextRange range; FileStream fStream; if (fileMode == mode.openFile) { if (File.Exists(filePath)) { RichTextBox mcRTB = new RichTextBox(); rtbList.Add(mcRTB); TabItem tab = new TabItem(); try { range = new TextRange(mcRTB.Document.ContentStart, mcRTB.Document.ContentEnd); fStream = new FileStream(filePath, FileMode.OpenOrCreate); range.Load(fStream, DataFormats.Text); fStream.Close(); } catch(Exception) { MessageBox.Show("Unable to open specified file.", "Open File error", MessageBoxButton.OK); } tab.Header = ExtractFileName(filePath); tab.Content = mcRTB; EditorTabcontrol.Items.Insert(EditorTabcontrol.Items.Count, tab); EditorTabcontrol.SelectedIndex = EditorTabcontrol.Items.Count - 1; } } } <ScrollViewer VerticalScrollBarVisibility="Auto"> <TabControl Width="648" Name="EditorTabcontrol" AllowDrop="True"/> </ScrollViewer> A: The EditorTabcontrol (of type TabControl) has a SelectedItem property, you can use that to identify which editor is currently active. From there you can get it's content. To add a close (x) button you need can set the TabItem's Header property to a StackPanel (a horizontal one) instead of a simple string, and add a string (the filename) and button (with the text X or an appropriate image) to the Stackpanel. Then handle the Click event for the button.
[ "stackoverflow", "0046089583.txt" ]
Q: Web AppBuilder for ARCGIS unknown error : [TypeError: must start with number, buffer, array or string] I am trying to log in my arcgis web appbuilder version 2.5 but its getting failed by showing some error ([TypeError: must start with number, buffer, array or string]) in my terminal. see below image.. When I log in using arcgis web appbuilder version 2.3. Its successful. A: I think this may be an issue with your OS and Node.js version not jiving with the npm package versions that the proxy server is using (see server/package.json) - I would recommend opening an issue with Esri Support to try to get to the bottom of the specific issue.
[ "stackoverflow", "0054069406.txt" ]
Q: Exporting data from Azure Cosmos DB (where type is MongoDB API) I need to export data from Azure Cosmos DB in CSV or JSON format to my local system. Can anyone help me with that? A: You could use cosmos db Migration Tool,please refer to this official article: https://docs.microsoft.com/en-us/azure/cosmos-db/mongodb-migrate Or you could use Azure Data Factory for cosmos db mongo api to export data from cosmos db into azure blob storage csv file,please refer to this document: https://docs.microsoft.com/en-us/azure/data-factory/connector-azure-cosmos-db-mongodb-api
[ "stackoverflow", "0013107167.txt" ]
Q: Don't know how many graphs to generate until run time. (Can't hardcode solution then) I am creating an energy usage/analysis/management application for the University I attend. There is already a database online that is continuously updated with the latest electricity meter ratings for each building. My application will have a page where all buildings are listed and can be clicked on. When a user chooses a building, the application will grab the electricity meter readings for that building and generate graphs for each meter using the 'Highcharts' charting library. The backend of the application is written in Ruby (with Rails). In the HTML view that displays the page consisting of the graphs for a specific builing, I put <div id="graphContainer"> </div> in order to generate a graph. Currently, I can generate one graph per building page just by hardcoding one instance of the above code in the view. However, each building can have multiple electricity meters. Having not that much experience in HTML, I have no idea how to generate the graphs when I don't know how many I need until run time. Can anyone point me in the right direction? A: Given a <div id="graphContainer"></div> you can target it with a highchart using chart1 = new Highcharts.Chart({ chart: { renderTo: '#graphContainer', // <=== this selector here type: 'bar' }, //... more options and graph data }); You don't have to have the HTML for #graphContainer in your view initially either. You could have some <div id="graphs-container"></div> in your view and then via Javascript (jQuery below) you can build the container and highchart for each of the graphs needed at runtime with a simple loop. $(function(){ var highcharts = []; for (var i=0; i<charts.length; i++) { $('#graphs-container').append($('<div id="graph-container-' + (i+1) + '"/>'); var highchart = new Highcharts.Chart({ chart: { renderTo: '#graph-container' + (i+1), // <=== this selector here type: 'bar' }, //... more options and graph data for chart[i] }); highcharts.push(highchart); }); }); All you'd need to do is modify the above to suit your needs by sending charts to the view likely as JSON data containing everything required to render each specific graph in terms of the Highchart options needed and datasets. The Highcharts documentation is a great place to look, but as you suggested you also seem to have more learning in general to be doing before you're comfortable with al this stuff. http://www.highcharts.com/documentation/how-to-use
[ "cooking.stackexchange", "0000029318.txt" ]
Q: How to avoid chicken getting too tender when cooking in a crock pot? I'd like to cook chicken in my Crockpot but just about every time it comes out so well done that it shreds when you try to cut it. How can I make it so it's not as well done; more like it comes out when cooked in an oven? A: Funny you should ask about this as I have just been experimenting with tough old chickens. Your chicken is falling apart because the connective tissues in the meat are being turned into gelatin. Cooking meat in a wet environment at low temperatures causes the connective tissues (collagen) in the meat to dissolve into delicious gelatin and makes the meat more tender. Cooking at the lower temperatures means that the meat can cook for longer without over heating and maximize the gelatin conversion. This is often a very desirable thing. Cheap, tough meat can be made delicious. Crockpots are designed to make this very easy. Roasting in the oven is hot and dry. The meat cooks faster, not very much gelatin is converted and the meat holds together better (or is tough depending on the meat). The solution is simple: Don't cook your chicken as long. To taste done, your chicken needs to reach 140F. To be safe from bacteria, your chicken has to get up to 165F. (Actually, it can be safe at as low as 135F but you have to hold it at those temperatures longer to kill the bad bugs. This document has the whole time chart.) You should use a thermometer to determine when the interior of your chicken is done and then stop cooking it. How long it will take to get your chicken to those temps will depend on your recipe, how much meat there is, what shape it is, and the properties of your crock pot. Keep in mind that a crockpot is still wet cooking (braising) where an oven is usually dry. The outside of the chicken will never be as browned or crispy from a crockpot as from an oven. A: Crock pot cooking is usually essentially braising--it sounds like you are getting a good outcome for a braised chicken. The problem is that you are up against a time/temperature curve. So unless you monitor the chicken, and remove it from the crockpot when it is just done to your liking, it is eventually going to get up to the appliance's set temperature. Over time, in a moist environment, the collagen in the chicken will break down, and the chicken will shred easily A: Besides the answers already given -- if you cool down slow cooked meat, it'll firm back up again (although, without the collagen), and can then be reheated later. The problem is getting the chicken out of the crockpot so that it can cool down in a timely manner. I use something that's a cross between a slotted spoon and a spider; it's relatively flat, but with holes in it to drain. Move it to a plate to cool down for a bit, then transfer to the fridge. The next day, you can slice it without it completely shreding on you. (although, it'll still be really tender). As has already been mentioned, it helps to pull it out before it's cooked too far ... but this can give you a larger time window to deal with, or to recover something that's cooked past where you'd like.
[ "math.stackexchange", "0003091608.txt" ]
Q: Understanding the definition of a measurable function I’m having trouble understanding the definition of a probability measurable function. The definition says that the preimage of events in the sigma algebra on the range must be an event in the sigma algebra on the domain. Why is this definition significant? What’s it trying to say? A: Assume $X$ is a probability space, and $f:\>X\to{\mathbb R}$ is some scalar function. For a given number $a\in{\mathbb R}$ we want to be able to talk about the probability $P\bigl[f(x)\leq a\bigr]$. This probability is equal to the measure of the set $f^{-1}({\mathbb R}_{\leq a})\subset X$:$$P\bigl[f(x)\leq a\bigr]=\mu\left( f^{-1}\bigl({\mathbb R}_{\leq a})\right)\ ,$$ and similarly $$P\bigl[a\leq f(x)\leq b]=\mu\left( f^{-1}([a,b])\right)\ .$$ Therefore we need the property that $f^{-1}$ of measurable sets in ${\mathbb R}$ is measurable in $X$.
[ "stackoverflow", "0022864740.txt" ]
Q: PHP PFBC Select value to be different than Shown (PHP form Build Class) PFBC is a simple yet totally undocumented framework that is really useful to get started, it is less complex than other frameworks and looks really nice Out of the box. http://code.google.com/p/php-form-builder-class/ I have the following two arrays in PHP: $area = [0=>"name", 10=>"name2", 11=>"name3"]; $ppl = [0=>"name", 1=>"name2", 2=>"name3"]; I want to use them as select, where the user will be able to choose between the names. This is the code I use for each: $form->addElement(new Element\Select(htmlentities("Area type:"), "area", $area, array("required" => 1) )); $form->addElement(new Element\Select(htmlentities("Person:"), "ppl", $ppl, array("required" => 1) )); I was expecting to have this: <select id="area" required="" name="area"> <option value="1"> name </option> <option value="10"> name2 </option> <option value="11"> name3 </option> </select> Wich i got for the first array ($area) but for the second array ($ppl) i've got:} <select id="ppl" required="" name="ppl"> <option value="name"> name </option> <option value="name2"> name2 </option> <option value="name3"> name3 </option> </select> -- I need the numeric code as value since i will use what the user chooses to query a database by that id Any ideas of what might happen? A: So i found the problem: Somwhere along the way while PFBC creates the Select element, it uses the third parameter (in my example, $area or $ppl) to generate an internal property called options, probably to cover itself against single arrays of the type ["name", "name2", "name3"], inside OptionElement.php the following code is causing problems. public function __construct($label, $name, array $options, array $properties = null) { $this->options = $options; if(!empty($this->options) && array_values($this->options) === $this->options) $this->options = array_combine($this->options, $this->options); parent::__construct($label, $name, $properties); } The error is here: array_values($this->options) === $this->options in my second array, $ppl, i have a perfectly indexed table starting from zero $ppl = [ 0 => "name", 1 => "name2", 2 => "name3" ] this triggers the control to think i have a simple array instead of custom keys, as: $array_values($ppl) === $ppl returns boolean(true) The second array, $area is different, since it has missing keys: $area = [ 0 => "name", 10=> "name2", 11=> "name3" ] So $array_values($area) === $area returns boolean(false) My solution, before touching PFBC (might be a bug, there has to be a better way to detect this case): Change the database so $ppl starts from 1 instead of 0 $ppl = [ 1 => "name", 2 => "name2", 3 => "name3" ] Incidentally then $array_values($ppl) === $ppl returns boolean(false) And now my Select works as i expected: <select id="person" required="" name="person"> <option value="1"> name </option> <option value="2"> name2 </option> <option value="3"> name3 </option> </select> Hope this helps!
[ "stackoverflow", "0032577365.txt" ]
Q: How to Retrieve Facebook Post details? I can successfully query for a post with this code, unfortunately, the only information it return is the created_time, message, and id. How do I get the other information like title, desc, link and image? FB.api( '/1494363804210145_10152988081617735', function(response) { if (response && !response.error) { $("#postTitle").val(response.caption); // doesn't works $("#postMessage").val(response.message); // works $("#postDesc").val(response.description); // doesn't works $("#postLink").val(response.link); // doesn't works $("#postImage").val(response.picture); // doesn't works writeFeedback("Post is loaded."); }else{ writeFeedback("Error Reading Post: "+response.error.message); } } ); A: You have to pass the fields you want to be returned from the Graph API specifically. This was introduced with v2.4. See https://developers.facebook.com/docs/apps/changelog#v2_4 Declarative Fields To try to improve performance on mobile networks, Nodes and Edges in v2.4 requires that you explicitly request the field(s) you need for your GET requests. For example, GET /v2.4/me/feed no longer includes likes and comments by default, but GET /v2.4/me/feed?fields=comments,likes will return the data. For more details see the docs on how to request specific fields.
[ "stackoverflow", "0004902586.txt" ]
Q: Impact of Share Button on Web Page Performance On a few websites that I maintain, I noticed that adding a share button like AddThis to a page varyingly slows down page loading, sometimes significantly. What is the explanation for this and what can be done to keep share buttons while not incurring page loading performance penalty for this? A: add the script call to the bottom of your page, that's what i do, right on top of </body>. ... all my html ... <!-- AddThis Button BEGIN --> <div class="addthis_toolbox addthis_default_style "> <a href="http://www.addthis.com/bookmark.php?v=250&amp;username=xa-4d4c6a9028bcda9b" class="addthis_button_compact">Share</a> <span class="addthis_separator">|</span> <a class="addthis_button_preferred_1"></a> <a class="addthis_button_preferred_2"></a> <a class="addthis_button_preferred_3"></a> <a class="addthis_button_preferred_4"></a> </div> <!-- AddThis Button END --> ... all my html ... <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4d4c6a9028bcda9b"></script> </body> </html> Edit: By moving the script call to the bottom of the page your page will load before the script and your users will not feel the impact.
[ "stackoverflow", "0051995062.txt" ]
Q: laravel select notifications for user by data field i have default laravel notifications data field and default notification table only try to select some notification for user based on his notification data value i jhave created this function in User Model public function notifications_data($col) { $notifications = $this->notifications()->where('data' , function ($q) use ($col){ $q->where('appointment_id','0'); // query data as table })->get(); return ($notifications); } i have saved value in notification table col data { "type":"Appointment", "appointment_id":"0", "date":null, "updated_by":"","status":"0" } How do i get this to get all notifications with status = 0 or appointment_id = 0 A: Maybe this works: public function notifications_data($col) { $notifications = $this->notifications() ->where('data','LIKE','%"appointment_id":"0"%') ->orWhere('data','LIKE','%"status":"0"%') ->get(); return ($notifications); }
[ "stackoverflow", "0052685400.txt" ]
Q: Why is my discord.js bot replying to itself, even when I put in a check? I have been spending the last 30 minutes trying to figure out why my bot keeps on replying to itself, even when I have put in a check to prevent this. This is my code: if (message.content.startsWith(prefix + 'rps ')) { if(!message.author.equals(bot.user)) { let theirInp = message.content.substring(prefix.length + 4) let botInp = rpsTab[Math.floor(Math.random() * rpsTab.length)]; if (!theirInp == "") { if (wins[botInp] == theirInp) { message.channel.send("I won!") } else if (botInp == theirInp) { message.channel.send("We tied!") } else { message.channel.send("You won!") } } } } A: You can use a different conditional expression. if(!message.author.bot){...}
[ "magento.stackexchange", "0000006340.txt" ]
Q: Checkout session clears after first step on Onepage I have the same problem as here: Cart dropping all items / cart session clears Although the answer seems to work for the questioner, for me it doesn't. I have really tried "everything" now: Set session.gc_maxlifetime to 12 hours Changed Magento session storage from db to files Set all Magento cookie validation settings to "No" Cleaned all caches, and cache storage (memcached) Validated that the session lifetime in cookie is using the gc_maxlifetime setting In detail, the session gets cleared after some seconds of inactivity. If I do a fast "developer checkout" within a few seconds, I have no problems to checkout. But as you surely know not all customers are fast in typing and so on. The furthermore strange thing is, that after this happened once, it is working again for the next one or two times. I would really appreciate any kind of idea to this. A: This really sounds like garbage collection to me. Instead of setting GC timeout, move sessions to Memcached or to MySQL. Make sure you're not running filesystem sessions on TmpFS. If this is happening only in Production, again, this hints to me like a garbage collection issue. If the issue persists I would suggest that you disable all local modules and switch to the default theme as a means of debugging.
[ "stackoverflow", "0060125906.txt" ]
Q: Including a foreign function in you own R package's source code I am currently facing the following situation: in an R package I am developing I am using two functions from the tidytext package. Thus, currently tidytext is part of the Imports in my DESCRIPTION file. The 'problem' is that tidytext has a lot of dependencies whereas I would like to keep the dependencies of my package low. In fact the two functions from tidytext I am using rely solely on the base package. Therefore, I am wondering if its OK to simply include these functions in my own package's source code? I would not export them as they are only 'helpers' for some user facing functions. Is there any issue with this approach (thinking of licenses for example)? A: tidytext is published with a MIT licence which grants you the following rights [emphasis is mine]: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: But you have to follow this: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. As long as you do this you should be fine Edit: related SE question
[ "emacs.stackexchange", "0000024704.txt" ]
Q: convert rmarkdown (rmd) files to orgmode? Anyone know of a way to convert rmarkdown (rmd) files to orgmode? im preparing a R course and lots of cool examples in R are in rmd format so it could be very useful to me. I tried via pandoc but results were not great A: Ok so for anyone interested here is the solution i found in R (via the GUI or through R -e command line), first convert the Rmd files to md files: require(knitr) # required for knitting from rmd to md require(markdown) # required for md to html knit('test.rmd', 'test.md') # creates md file then use pandoc to convert the md files to org: pandoc -o test.org test.md this gives an almost 1:1 org file
[ "stackoverflow", "0010802733.txt" ]
Q: How to store a javascript array in PHP session? I have an array in my javascript function having string values like 1,2,3,4... etc. I want to store this array in PHP's session. I searched it and they say to use JSON but I am getting the way how to use JSON. Suppose my array's name is: myArray and I want to do something like this: $_SESSION['myArray'] = myArray; Is there anyway of doing that? Please provide some working code sample if possible. A: Your JavaScript is running on the client, your PHP is running on the server. You need to send the data over HTTP. To get data from a JavaScript array to a PHP session you need to: Serialise the data (either to a collection of inputs in a form, or to a string. The JSON object can help with the latter so long as you don't have data types that JSON doesn't support). Send the data to PHP (either by submitting a form, or using Ajax) Read the data back in PHP (probably from $_POST) Optionally deserialise it back to a data structure Store it in $_SESSION
[ "askubuntu", "0000580427.txt" ]
Q: OpenStack deployment with MAAS, Juju and Autopilot I have a problema with my cluster installation. I intend to install OpenStack on my ready set of machines, where each one has 2 NIC and 2 hard disks. I installed the MAAS controller and Juju on a seventh machine and deployed the landscape scalable bundle. After logging-in into Landscape, it states that the fourth requirement is not fulfilled, because of the lack of a least one machine with two disks and two network interfaces. MAAS states that I have six machines but the size of disk is of one disk only. I tried to deploy ubuntu on one of them and the second hard disk is present as 'sdb', even though not formatted. MAAS also stats every node has two network interfaces. What am I doing wrong? I cannot figure out! Should I try to deploy OpenStack with Juju manually? A: Landscape queries MAAS to determine which nodes have multiple network devices. Does MAAS show at least one of the nodes as having two or more MAC addresses connected to networks e.g. if you go on the node page, it should say something like 'AA:BB:CC:DD:EE:FF (on maas-eth1)' If your nodes are on a secondary network which is not MAAS managed, you will have to manually add that network and associate the MAC addresses with it. See the MAAS docs for help on doing that.
[ "stackoverflow", "0034996799.txt" ]
Q: Which data structure is like a combination of a doubly-linked list and an array? Is there any already created structure which would be simply basic array of doubly linked list nodes? I mean then you use get(int index) it would return element directly from array (array[i].element). With this structure I could easily do foreach too because every element would be linked to each other, so I would not need to think about blank array places. Q: Why I need this ? A: I have unlimited memory, I know how big array I need and I want that structure would be fastest. A: Here is a small C++11 container guide, just set your constraints and follow the arrows: IMO std::deque is the most probable candidate. In case you want to create something yourself, here is an example of how could it look like: struct Node{ // constructor Node (int v, Node* n = 0, Node* p = 0) : value(v), next(n), prev(p) { } // data member int value; // pointer to next node Node* next; // pointer to previous node Node* prev; }; size_t number_of_nodes = 10; Node* ptr = new Node[number_of_nodes]; A: Based on your description, I think the most fitting data structure would be a double-ended queue; or, in C++, a std::deque. How it's like a doubly-linked list: Stores back and front pointers {push,pop}_{front,back} are O(1) Doesn't need reallocs when expansion is necessary How it's like an array: Allows subscript indexing O(1) random access The get operation you're looking for is operator[] or std::deque::at. Some considerations are that insertion/removal of elements not on polar ends of the structure (i.e., somewhere in the middle) are average case O(n) on the number of elements for the same reason it's O(n) to remove an element from a basic array. Obligatory basic-use-case
[ "pets.stackexchange", "0000026159.txt" ]
Q: Very lazy puppy Three days ago I got a pup from a shelter home. He is 3 months old. The mum is a mixed breed with some Border Collie in her. He looks like a German Shepherd and also like he's going to be quite a big dog (massive paws). He seems fast to learn things but he seems extremely lazy. His favourite activities are barking when other dogs bark in the neighborhood and chewing, anything else he won't do for more than a couple of minutes. He likes to tug but it very quickly gets tired and gets back to lying on the ground and he's got almost no interest in chasing. With a lot of effort you can tease him into a bit of a fight play (he's super gentle with play bites). He also seems super tired after a 30 min walk. Question: Its it normal for a pup this age to be that exhausted? A: Your puppies energy levels your described are what I would be expected from a 3-month-old. I would recommend exercising your puppy less at this stage. 1. Sleep Most dogs sleep ~14 hours a day, most puppies will sleep up to 20 hours a day. Don't forget your puppy is still an infant and like you said he has a lot of growing to do! Sleep is important for the growth of your pup. 2. Exercise I'm sure if you look around you may find different rules for exercise. I have always followed the rule of 5 minutes per month for a growing puppy at a time (can be multiple times per day). i.e if your puppy is 3 months old - they should be doing at most 15 minutes of exercise at a time. Longer than this can be overly demanding on your puppy and some vets believe could stunt the growth and create joint problems for larger breeds. Being part collie he will need plenty of exercises later - but for now, a lot of his energy should be growing big and healthy. Personally, I have a 9-month old collie x GSP. He was very similar to your dog at 3 months when he would urgently need a rest after doing any exercise or training. From about 4-5 months he had more energy than he knew what to do with! He now gets 2x 45 min walks a day, is 30 kilos(and still growing!) and still won't stop chasing birds around the yard once we get home! Of course, if you are worried about any change in the behaviour of your pet - you know them the best, and it is always safest to use your own discretion when seeking professional help. (Some of these sources could be improved - I will try and update when I have the chance) A: Following up on mhwombat's answer... My parents once picked up a "labrodoodle" puppy from a puppy mill, because they thought it sounded cool. I was sooo mad at them. This was the most lethargic puppy I'd ever seen in my life. Quite clearly sick. I spent an entire 4th of July with it on my tummy trying to pet and cool it, and generally comfort it. When they took it to the vet's the next day, of course it turned out it was not only sick, but chock full of parasites. (little bit of space here to simmer down...) He's been a perfectly normal energetic pup since then. The point here is that this is indeed unusual enough that you really ought to get the dog checked out. It probably won't be as bad as that labradoodle (that was super obvious), but its possible the shelter had a disease going around, or a parasite problem, and the puppy has picked that up. Either of those problems the vet should be able to get something to make the poor boy all better after a couple of days. Another possibility that occurred to me is spaying/neutering. Many shelters these days insist on doing that themselves before handing over a pet, so that they know for sure it was done. Its perfectly natural for an otherwise energetic puppy to be lethargic for a few days after the operation. Particularly for spaying, which is I understand far more intrusive. A: That doesn't sound normal to me. Border collies can be calm and dignified, but I would expect even an adult one to have more energy than that. I would take him to a vet.
[ "stackoverflow", "0018680587.txt" ]
Q: AS3/Arrays: impossible duplication after "splice" I have a function that gets questions from an array called quizQuestions, displays the choosed question, splice it from the array and pushes the question and correct answer to a new array to be used later in the results screen: // The questions are stored in an array called "quizQuestions" function makeQuestion() var randNum:Number = Math.round(1 + (quizQuestions.length - 1) * Math.random()); mc_quiz.question.text = quizQuestions[randNum][0]; answer = quizQuestions[randNum][1]; quizQuestions.splice(randNum,1); printQuestions.push(new Array(mc_quiz.question.text, answer)); } It runs fine but time to time, a question is asked twice. You can continue with the test but the result doesn't show the info. In fact, it only shows the results for the questions answered before the duplication. I have checked visually and with a "duplicated elements finder" and there are no duplicated questions in the array. Could the splice non being executed time to time? Can you see any "bug" in the function? Could it happen due to hardwer issue? Thanks in advance. A: Your random number generation is not only mathematically wrong (i.e. it won't generate truly random items), it will also from time to time generate a number that is beyond the array's bounds. To explain this: 1+(array.length-1) * Math.random() will generate any number greater or equal to 1 (this will also result in the first item of the array never to be returned, because arrays are 0-based), up to a fraction less than the actual length of the array. If you Math.round() the highest possible result, it will round up to the next highest integer, which is the full length again - and if you access array[array.length], an error is thrown, which is probably responsible for the weird behavior you are seeing. Here's a possible solution: Math.round() creates random number bias, anyway (see @OmerHassans link), so you're better off using int() or Math.floor(). Also, Math.random() is defined as 0 <= n < 1, so it will never return 1. Therefore, you can simplify your random index generator to int(Math.random()*array.length) => any integer smaller than the length of the array. splice(), then, returns an array of the items that were removed, so you can pass its first item, instead of creating a new array. function getRandomItem( arr:Array ):* { var rand:int = Math.random()*arr.length; return arr.splice( rand, 1 )[0]; } function makeQuestion():void { var q:Array = getRandomItem( quizQuestions ); mc_quiz.question.text = q[0]; answer=q[1]; printQuestions[printQuestions.length] = q; } FYI: It won't matter much in this context, but you get much faster performance by replacing array.push(item) with array[array.length]=item;.
[ "stackoverflow", "0008367902.txt" ]
Q: Calling a C DLL in 64-bit Excel for use in VBA I need to call a DLL in 64-bit Excel for use in VBA. i.) I've been told I can't use a 32-bit dll in a 64-bit program, is this true? ii.) Does anyone know of an example they know to be working demonstrating loading a dll into VBA. At the moment they're not even loading. I can call the DLL's fine from within C++. The example code is as follows and compiles fine in 64 bit mode. I've tried registering the function. The VBA error is "compile error: expected lib" Failing calling function in VBA Public Declare PtrSafe Function getNumber_Lib "C:\Users\james.allsop\Documents\Visual Studio 2010\Projects\DynamicLibrary\x64\Debug\MathFuncsDll.dll" () As Integer The following all compiles and runs. MathFuncsDll.h // MathFuncsDll.h // Returns a + b __declspec(dllexport) double Add(double a, double b); // Returns a - b __declspec(dllexport) double Subtract(double a, double b); // Returns a * b __declspec(dllexport) double Multiply(double a, double b); // Returns a / b // Throws DivideByZeroException if b is 0 __declspec(dllexport) double Divide(double a, double b); __declspec(dllexport) double getNumber(); MathFuncsDll.cpp #include "MathFuncsDll.h" double Add(double a, double b) { return a + b; } double Subtract(double a, double b) { return a - b; } double Multiply(double a, double b) { return a * b; } double Divide(double a, double b) { if (b == 0) { return -1.0; } return a / b; } double getNumber() { return 1000; } MyExecRefsDll.cpp // MyExecRefsDll.cpp : Defines the entry point for the console application. // // MyExecRefsDll.cpp // compile with: /EHsc /link MathFuncsDll.lib #include <iostream> // Returns a + b __declspec(dllimport) double Add(double a, double b); // Returns a - b __declspec(dllimport) double Subtract(double a, double b); // Returns a * b __declspec(dllimport) double Multiply(double a, double b); // Returns a / b // Throws DivideByZeroException if b is 0 __declspec(dllimport) double Divide(double a, double b); __declspec(dllimport) double getNumber(); int main() { double a = 7.4; int b = 99; std::cout << "a + b = " << Add(a, b) << "\n"; std::cout << "a - b = " << Subtract(a, b) << "\n"; std::cout << "a * b = " << Multiply(a, b) << "\n"; std::cout << "a / b = " << Divide(a, b) << "\n"; return 0; } Any help would be greatly appreciated! James A: Your declaration in VBA contains an error. It should be: Public Declare PtrSafe Function getNumber Lib "C:\Users\james.allsop\Documents\Visual Studio 2010\Projects\DynamicLibrary\x64\Debug\MathFuncsDll.dll" () As Integer instead of: Public Declare PtrSafe Function getNumber_Lib "C:\Users\james.allsop\Documents\Visual Studio 2010\Projects\DynamicLibrary\x64\Debug\MathFuncsDll.dll" () As Integer Note the removed underscore. And yes, you cannot call 32-bit DLLs from 64-bit applications and vice versa. That's a general restriction for all applications, not just for VBA or Excel.
[ "bicycles.stackexchange", "0000017507.txt" ]
Q: Pinch flats: hardtail vs full suspension. Differences? I ride a hardtail, and I wonder if a full suspension prevents pinch flats in the rear wheel. I don't get pinch flats; but I want to know what to expect from a hardtail vs full suspension. I'm a heavy man (100 kgs) and like to go fast (60+ k/h) in bad dirt roads (not downhill), and my main worry is getting a pinch flat (or blow out). I use 40 psi in my rear wheel (26x2.10). A: Honestly this has more to do with how you let your bike "float" underneath you over obstructions than it does with rear suspension or the lack thereof. Since you can potentially go faster on a full suspension over rough terrain than you can on a hardtail I would say you're just as likely to get pinch flats. You just have to unweight the back of the bike and stay loose as you cross rocks/roots/whatever. That's a crucial key not only in reducing pinch flats, but in going faster over technical terrain as well. Short answer, just as likely on either platform depending on your riding style. A: Full suspension will not, by itself, prevent pinch flats. Since pinch flats are something that occur from the way the tire and tube move in regards to the rim, adding suspension won't change that. Now, adding suspension could move some of the pressure forward, depending on the pivots are arranged. If you're riding at 40psi on a 2.10 tire, you should be fine on just dirt roads; however, if you hit a really nice square edged pot hot at that speed you're probably going to flat on either type of bike. Preventing pinch flats is usually more about tire pressure and deformation of the tire than anything else.
[ "stackoverflow", "0005529074.txt" ]
Q: Retrieving a javascript processed Web page What am I asking for is the ability to download a rendered / processed page via Google Chrome or Firefox I think. For example, I don't want: hendry@x201 ~$ w3m -dump http://hello.dabase.com FAIL I want: $ $answer http://hello.dabase.com Hello World A: You should be able to do it using PhantomJS. It is running WebKit without the visuals, but you get the same fast and native supports for JavaScript, HTML/DOM, CSS, SVG, Canvas, and many others. Disclaimer: I started PhantomJS.
[ "math.stackexchange", "0002812746.txt" ]
Q: Continuity of evaluation map for characters of a LCA group First I will remind this definition. If $G$ is a LCA (i.e. locally compact, abelian and Hausdorff) topological group, then its dual group $\Gamma$ is the set of all continuous group homomorphisms (characters) $\gamma:\Gamma\to S$ (where $S$ is the unit sphere, with its operation given by complex multiplication), with its own operation given by $(\gamma_1+\gamma_2)(s)=\gamma_1(s)\gamma_2(s)$ and its topology is the induced topology from the weak-star topology of $L^{\infty}(G)$. In other words, if $(\gamma_i)$ is a net in $\Gamma$, we have $\gamma_i\to \gamma$ iff $\hat{f}(\gamma_i)=\int_G f(t)\gamma_i(-t)dt\to \int_G f(t)\gamma(-t)dt=\hat{f}(\gamma)$ for all $f\in L^1(G)$. I am having trouble with the following result: Let $G$ be a LCA group and let $\Gamma$ be its dual group. Then the map \begin{align*}G\times \Gamma &\to S \\ (t,\gamma)&\mapsto \gamma(t) \end{align*} is continuous. In Rudin's Fourier analysis on groups, the author simply says that since the map $(x,\gamma)\mapsto\hat{f}_x(\gamma)=\int_{G}f(t-x)\gamma(-t)dt$ is continuous (so in particular, $\gamma \mapsto \hat{f}(\gamma)$ is continuous), and the relation $$\hat{f}(\gamma)\gamma(x) =\hat{f}_x(\gamma)$$ holds, then($*$) $(x,\gamma)\mapsto \gamma(x)$ is continuous. But I fail to understand the implication ($*$). In general, if $(a_n)$ and $(b_n)$ are two sequences of complex numbers such that $a_nb_n\to ab$ and $a_n\to a$, then I can deduce that either $b_n\to b$ or $a=0$. However I cannot rule out the possibility that $a=\hat{f}(\gamma)=0$, so how do I proceed? Perhaps it depends on the fact that $\hat{f}(\gamma)$ depends only on $\gamma$ and not on $x$? I would be satisfied if I could only get an intuitive idea of why this is true. A: The solution lies on the fact that the relation $$\hat{f}(\gamma)\gamma(x)=\hat{f}_x(\gamma) $$ holds for all $f\in L^1(G)$. Now, suppose $(x_i)$, $(\gamma_i)$ are nets such that $x_i\to x$, $\gamma_i\to \gamma$. We know that $\hat{f}(\gamma_i)\gamma_i(x_i)\to \hat{f}(\gamma)\gamma(x)$ for all $f$. But $\hat{f_0}(\gamma)\neq 0$ for some $f_0\in L^1(G)$ - for instance, let $f_0(x)=\gamma(x)\chi_{K}(x)$ where $K$ is a compact subset of $G$. (On a more theoretical side, if $\hat{f}(\gamma)=0$ for all $f$, then the character $\gamma$ could only be identified with a multiplicative functional that is identically $0$ - but $0$ is excluded from the spectrum of $L^1(G)$ - in other words, its kernel is not a maximal ideal of $L^1(G)$). We now have: $$|\hat{f}_0(\gamma_i)\gamma_i(x_i)-\hat{f}_0(\gamma)\gamma(x)|\geq |\hat{f}_0(\gamma)\gamma_i(x_i)-\hat{f}_0(\gamma)\gamma(x)|-|\hat{f}_0(\gamma_i)\gamma_i(x_i)-\hat{f}_0(\gamma)\gamma_i(x_i)|= \\ =|\hat{f}_0(\gamma)||\gamma_i(x_i)-\gamma(x)|-|\gamma_i(x_i)||\hat{f}_0(\gamma_i)-\hat{f}_0(\gamma)| $$ as $i\to \infty$, (notice that $|\gamma_i(x_i)|=1$ for all $i$) $$0\geq |\hat{f}_0(\gamma)|\limsup_{i\to \infty}|\gamma_i(x_i)-\gamma(x)|-0 $$ and since $\hat{f}_0(\gamma)\neq 0$, we are done.
[ "stackoverflow", "0044614474.txt" ]
Q: Select into an exisiting table using FoxPro Hi I am currently using FoxPro and may I know if there is any possible chance to select into exisiting table by overwritting it. For example: I wanted to achieve this: SELECT * FROM table1 WHERE criteria INTO TABLE table1. Thanks in advance. A: No. How about use table1 excl delete from table1 where !criteria pack in table1
[ "stackoverflow", "0017529125.txt" ]
Q: Writing "\\" inside a string I want to do something like: string s = "\\blabla"; when you write "\" it means there will only be a single '\'. How do I write the string so there will actually be 2 '\' meaning "\" ? A: This works without a problem: string s = "//blabla"; If you mean the backslash instead, you can use a verbatim string literal (using the @ symbol to avoid processing escape symbols): string s = @"\\blabla"; Alternatively you can escape the escape character itself: string s = "\\\\blabla"; A: '/' is not the escape char, so you can simply write "//" The escape char is '\' and, to use it properly, you can refer to the MSDN instructions.
[ "rpg.stackexchange", "0000028025.txt" ]
Q: What is the Marshal's Quarry? While building a character for the newest season of encounters, a Paladin(Blackguard), I decided to take the Sentinel Marshal Theme. As part of the entry features for the theme you receive the Marshall's Interdiction encounter power. The power states: Effect: The target is immobilized until the end of your next turn. You also mark the target until you end your turn without hitting or missing it with an attack. In addition, you designate the enemy as your marshal’s quarry until the end of the encounter. - Dragon #407. However, Marshal's Quarry isn't listed anywhere in the compendium or described in the original Dragon article beyond reference the Marshal's interdiction power referencing it. I assume it works similarly to the Hunter's Quarry power of the Ranger class, but if anyone had any sort of errata, faqs, or just anything from the designers/publishers clarifying it I would appreciate it. A: The Marshal's Quarry is just an extra status effect. This power does three things: Immobilizes the target til the end of your next turn. Marks the target until you stop attacking it Designates it as your Marshal's Quarry. Marshall's Quarry has little effect unless you take the utility powers associated with the theme. Much like the Ranger's "Hunter's Quarry" it designates the target as a pursuit target. The utility power benefits specific to the mechanic are as follows: L2: shift a square closer to your quarry as free action(+2 speed, +2 def vs OAs all the time) L6: get some temp HP if you hit your quarry (defense bonus with any hit) L10: regain power when you kill your quarry (free healing and save you get with any kill you use this on). The only other mechanic that is related to this is that at L10 you get a +2 to saves against status effects applied by your quarry. But that's it, so these four things are all this effect does.
[ "stackoverflow", "0015309882.txt" ]
Q: How do you get a form to never go to full screen when double clicked in C# I have a C# form that always goes to the full screen mode when i double click it. The form has no border and moves. A: Set the maximum width & height of the form. You use the MaximumSize property of the form. this.MaximumSize = new System.Drawing.Size(500, 500); or this.MaximumSize = this.Size; http://msdn.microsoft.com/en-us/library/system.windows.forms.form.maximumsize.aspx
[ "stackoverflow", "0010119683.txt" ]
Q: Error when showing a jpeg image with GD library inside a webpage I've created an image class to display and convert images on the site with GD library. when I want to show jpeg images without any HTML code in the site everything will be OK because I set header('Content-Type: image/jpeg'). My code is like below: $filepath = 'path to the image file'; $info = getimagesize( $filepath ); $this->type = $info[2]; if( $this->type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filepath); // set the resource image } if( $this->type == IMAGETYPE_JPEG ) { $type = 'image/jpeg'; } header('Content-Type: ' . $type ); if( $this->type == IMAGETYPE_JPEG ) { imagejpeg( $this->image ); } This code works perfectly, but how should I show images if I want to show them inside HTML codes (ob_start did not work). A: Request that script from a different file like any regular image: <img src="path/to/the/file/that/outputs/the/image.php">
[ "dsp.stackexchange", "0000046889.txt" ]
Q: Minimizing profile curvature of 2D image I have 2D grayscale image representing terrain heights. I am in search for (fast) algorithm to minimize profile curvature of this image on selected scales (in scale-space sense). Profile curvature is function of partial derivatives: $$P_c = - \frac{(dx^2 \times dxx + 2 \times dx \times dy \times dxy + dy^2 \times dyy)}{((dx^2 + dy^2) \times (dx^2 + dy^2 + 1)^{1.5})}$$ and its geometrical meaning is nicely explained by this image: I came up with completely ad-hoc iterative approach to minimize curvature at specified scale, but I am little bit lost when trying to apply this accross all scales (I am trying to utilize Gaussian / Laplacian image pyramids). It works by adjusting heights by adding height offset according to profile curvature at given point (height offset is negative in convex areas and positive in concave areas). Results for single scale are not completely hopeless though: Original data: Processed data: Result of this procedure should be formation of sharp V-shaped ridges and valleys. Is there any mathematically sound approach how to solve this kind of problems ? Any tips are appreciated ! A: I am in search for (fast) algorithm to minimize profile curvature of this image on selected scales (in scale-space sense). ... ... to minimize curvature at specified scale, [...], trying to apply this accross all scales (I am trying to utilize Gaussian / Laplacian image pyramids). It works by adjusting heights by adding height offset according to profile curvature at given point (height offset is negative in convex areas and positive in concave areas). Modifications of curvature are basically modifications of a "signal's" dynamics. In effect, what you are trying to say is "If the signal is rising (or falling) faster (or slower) than some threshold then...do something different". This "do something different" can be anything from "don't respond" to "respond slower" or "respond faster" and so on. In one dimension, the Douglas-Peucker algorithm does more or less what you are after. The algorithm takes only one parameter which you can relate to the scale of observation but essentially modifies the local slope so that it remains within certain limits. Variants that do surface simplification, or mesh simplification exist too (or this, in the case of contours) which use some expression of "cost" or "stress" to decide which element to remove during the simplification. If you are "tied" to a height map (i.e. implicit 3D data), then you are looking at removing data (i.e. decimation) and interpolating / filtering. For example, you can use your $P_c$ to "mark" the areas of high or low curving slope in one pass and compute the "fill-in" values of each patch on a second pass. For examples of these approaches, you might want to take a look at this or this or more generally this. Hope this helps.
[ "stackoverflow", "0028618785.txt" ]
Q: Tail multiple files shown by separate colors? I follow multiple log files like this: tail -f /var/log/apache2/tv7r9r3falz0_error.log protected/runtime/application.log Is there a way to color each file so I don't have to rely on finding the headers: ==> protected/runtime/application.log <== I know about multitail, but I want to freely scroll. A: This will print the output in two different colors depending on which log file it comes from: tail -f log1 log2 | awk $'/==> log1/{print "\033[0m\033[1;33;40m";} /==> log2/{print "\033[0m\033[1;35;40m";} 1' Update by Elliot Chance: Thats the start I needed, here was the working version: tail -f /var/log/apache2/tv7r9r3falz0_error.log protected/runtime/application.log | awk '/==> /{print "\033[0m\033[1;36;40m";} /==> p/{print "\033[0m\033[1;33;40m";} {print $0}'
[ "stackoverflow", "0005352592.txt" ]
Q: Why does my margins collapse even though I have borders around everything? Here is the code: <html> <head> <title></title> <style type="text/css"> * {border: 0px; padding: 0px;} #greenbox { margin: 20px; border: 5px solid green; } #redbox { margin: 20px; border: 5px solid red; } #bluebox { border: 5px solid blue; margin-left: 20px; margin-right: 20px; margin-bottom: 20px; margin-top: 20px; /*COLLAPSES - why??*/ } </style> </head> <body> <div id="greenbox"> <div id="redbox"> red box </div> <div id="bluebox"> bluebox </div> </div> </body> </html> Basically, it's a green box, which contains a red box and a blue box inside it. Why isn't the vertical space between the red box and blue box 40px? I understand that the bottom-margin of the red box and the top margin of the blue box have 'collapsed', but it was my understanding that margins do not collapse if you have a border, or padding (I've tried both - still the same result. A: Margins do not collapse through borders. They do collapse through each other. See this example: <style> body { background: black; } .red { background: red; } .blue { background: blue; } .border { border: solid white 1px; } div { margin: 20px; min-height: 30px; width: 50% } </style> <div class="red"> <div class="blue"> </div> </div> <div class="red border"> <div class="blue border"> </div> </div> When the border is present, the margin on the top of the blue div pushes the top of the blue div away from the top of the red div that it is inside. When the border is not present, the margin goes through the edge and collapses into the margin around the red div. Your two margins are touching each other with no border between them — so they collapse.
[ "stackoverflow", "0029094073.txt" ]
Q: Android samples comments BEGIN_INCLUDE END_INCLUDE While reading some android samples I usually see comments like // BEGIN_INCLUDE (something) // END_INCLUDE (something) However, my current IDE — Android Studio 1.1 — can not recognise them (or maybe I do something wrong). I guess, they serve as some kind of code region marks (like //<editor-fold desc="Region name"> // some code //</editor-fold> in AndroidStudio/IntellijIDEA), but such syntax is much like c++ preprocessor directives. So the question: should I know something important about these comments (besides obvious commenting function) that could improve my code in any way? A: It's for documentation purposes, used for identifying snippets to include in target documentation. It's not really useful when editing the code; it's useful for avoiding repetition by generating documentation from actual code. {@sample} and {@include} These tags copy sample text from an arbitrary file into the output javadoc html. The @include tag copies the text verbatim from the given file. The @sample tag copies the text from the given file and strips leading and trailing whitespace reduces the indent level of the text to the indent level of the first non-whitespace line escapes all <, >; and & characters for html drops all lines containing either BEGIN_INCLUDE or END_INCLUDE so sample code can be nested Both tags accept either a filename and an id or just a filename. If no id is provided, the entire file is copied. If an id is provided, the lines in the given file between the first two lines containing BEGIN_INCLUDE(id) and END_INCLUDE(id), for the given id, are copied. The id may be only letters, numbers and underscore (). Four examples: {@include samples/SampleCode/src/com/google/app/Notification1.java} {@sample samples/SampleCode/src/com/google/app/Notification1.java} {@include samples/SampleCode/src/com/google/app/Notification1.java Bleh} {@sample samples/SampleCode/src/com/google/app/Notification1.java Bleh} https://code.google.com/p/doclava/wiki/JavadocTags
[ "math.stackexchange", "0003773538.txt" ]
Q: Help with proving/disproving an inequality $\textbf{Question:}$Let $x_1,x_2,x_3,x_4 \in \mathbb{R}$ such that $(x_1^2+1)(x_2^2+1)(x_3^2+1)(x_4^2+1) =16 $. Is it then true that $x_1x_2+x_1x_3+x_1x_4+x_2x_3+x_2x_4+x_3x_4- x_1x_2x_3x_4 \le 5$, with equality $\iff x_1=x_2=x_3=x_4=\pm 1$? Rough calculations seem to suggest that this is indeed the case, but I am unable to prove it. For some context, this question is actually related to USAMO $2014$ P$1$. The original question was that: given a polynomial $P(x)=x^4+ax^3+bx^2+cx+d,$ and $ b-d \ge 5$, where all $4$ roots $x_1,x_2,x_3,x_4$ of $P(x)$ are real, find the smallest value of the expression $(x_1^2+1)(x_2^2+1)(x_3^2+1)(x_4^2+1)$. Indeed, I managed to prove that this expression is at least $16$. But to show that the minimum value of $16$ is actually attainable, I have to find a construction of some polynomial $P(x)$ satisfying the conditions of the question. While it is indeed obvious to see that setting $ x_1=x_2=x_3=x_4=1$ or $ x_1=x_2=x_3=x_4=- 1$ both works ( just expand $(x-1)^4$ and $(x+1)^4$ respectively), are there other non-trivial values that would work too? In particular, using $\textbf{Vieta's formula}$ gives us that $b=x_1x_2+x_1x_3+x_1x_4+x_2x_3+x_2x_4+x_3x_4$ and $d=x_1x_2x_3x_4$, so the complicated looking expression in the first paragraph is actually just equivalent to $b-d$. A: Since $$(a^2+b^2)(c^2+d^2)=(ac+bd)^2+(ad-bc)^2,$$ we obtain: $$16=\prod_{k=1}^4(1+x_k^2)=((1-x_1x_2)^2+(x_1+x_2)^2)((1-x_3x_4)^2+(x_3+x_4)^2)=$$ $$=((x_1+x_2)(x_3+x_4)-(1-x_1x_2)(1-x_3x_4))^2+$$ $$+((1-x_1x_2)(x_3+x_4)+(1-x_3x_4)(x_1+x_2))^2\geq$$ $$\geq((x_1+x_2)(x_3+x_4)-(1-x_1x_2)(1-x_3x_4))^2=$$ $$=(x_1x_2+x_1x_3+x_1x_4+x_2x_3+x_2x_4+x_3x_4- x_1x_2x_3x_4 -1)^2.$$ Can you end it now? The equality occurs for $$(1-x_1x_2)(x_3+x_4)+(1-x_3x_4)(x_1+x_2)=0,$$ which is $$x_1+x_2+x_3+x_4=x_1x_2x_3+x_1x_2x_4+x_1x_3x_4+x_2x_3x_4$$ and for $$x_1x_2+x_1x_3+x_1x_4+x_2x_3+x_2x_4+x_3x_4- x_1x_2x_3x_4 -1=4.$$ We have for example also the following case of the equality occurring: $$(x_1,x_2,x_3,x_4)=\left(5,\frac{-5+\sqrt5}{2},\frac{-5-\sqrt5}{2},0\right).$$ A: Using the Cauchy-Schwarz inequality, we have $$(x_1^2+1)(x_2^2+1)(x_3^2+1)(x_4^2+1)$$ $$= [(x_1+x_2)^2+(1-x_1x_2)^2][(x_3+x_4)^2+(x_3x_4-1)^2]$$ $$\geqslant [(x_1+x_2)(x_3+x_4)+(1-x_1x_2)(x_3x_4-1)]^2$$ $$=(x_1x_2+x_1x_3+x_1x_4+x_2x_3+x_2x_4+x_3x_4-x_1x_2x_3x_4-1)^2.$$ Thefore $$(x_1x_2+x_1x_3+x_1x_4+x_2x_3+x_2x_4+x_3x_4-x_1x_2x_3x_4-1)^2 \leqslant 16,$$ or $$x_1x_2+x_1x_3+x_1x_4+x_2x_3+x_2x_4+x_3x_4- x_1x_2x_3x_4 \leqslant 5.$$
[ "magento.stackexchange", "0000009916.txt" ]
Q: Filter shipping methods based on order weight Currently my shipping methods configuration is like this: Free delivery (customer pays cash in the physical store and picks up his goods) Normal shipment (customers makes a bank transfer and gets his goods with regular shipping prices. I used default table rates "weight/destination"). Cash on delivery (customers gets goods via shipping service and pays his goods to the delivery service. I used MatrixRate extension to get another "weight/destination" table rate For payment methods i configured only "Bank transfer payment" named "Payment" with instructions. I didnt use multiple payment methods here, because everything is defined with shipping method selection. My first question is .... is this a good practise? Or should I consider another option... Basicaly the customer only needs to know the shipping fee... and the store owner in Magento can see information from selected shipping method. But there are some filters I need to implement. The store owner wants "Cash on delivery" to be disabled in case total order weight is below 100. Can someone help me implement this filter, because I am not comfortable to use an extension just for this one filter. Thank you in advance. A: You can observe the event payment_method_is_active. Something like this: public function checkCashOnDelivery($observer){ $method = $observer->getEvent()->getMethodInstance(); if ($method->getCode() == 'CashOnDelivery Code here'){ //I don't know the code. Just check it in the payment method and add it here $quote = $observer->getEvent()->getQuote(); if ($quote->getSubtotal() < 100){ //or $quote->getGrandTotal() to include shipping cost $result = $observer->getEvent()->getResult(); $result->isAvailable = false; } } } read this to see how to use event observers.
[ "stackoverflow", "0054048320.txt" ]
Q: ValueError: Error when checking : expected dense_1_input to have 2 dimensions, but got array with shape (1, 16, 16, 512) I'm having the following error: ValueError: Error when checking : expected dense_1_input to have 2 dimensions, but got array with shape (1, 16, 16, 512) which occurs at this line: img_class = model.predict_classes(feature_value) Any idea on how I can solve the issue? This is the full script: from keras.applications import VGG16 from keras.preprocessing.image import ImageDataGenerator from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array from keras.applications.vgg16 import preprocess_input from keras.applications.vgg16 import decode_predictions from keras.layers import Input, Flatten, Dense from keras.models import Model from keras import models from keras import layers from keras import optimizers import ssl import os import cv2 import numpy as np import matplotlib # Force matplotlib to not use any Xwindows backend matplotlib.use('Agg') import matplotlib.pyplot as plt # path to the training, validation, and testing directories train_directory = '/train' validation_directory = '/valid' test_directory = '/test' results_directory = '/results' number_of_training_samples = 1746 number_of_validation_samples = 108 number_of_test_samples = 510 batch_size = 20 ssl._create_default_https_context = ssl._create_unverified_context # get back the convolutional part of a VGG network trained on ImageNet conv_base = VGG16(weights='imagenet',include_top=False,input_shape=(512,512,3)) conv_base.summary() # preprocess the data # rescale images by the factor 1/255 train_data = ImageDataGenerator(rescale=1.0/255) validation_data = ImageDataGenerator(rescale=1.0/255) test_data = ImageDataGenerator(rescale=1.0/255) train_features = np.zeros(shape=(number_of_training_samples,16,16,512)) train_labels = np.zeros(shape=(number_of_training_samples)) train_generator = train_data.flow_from_directory( train_directory, target_size=(512,512), batch_size=batch_size, class_mode='binary', shuffle=True) i = 0 for inputs_batch, labels_batch in train_generator: features_batch = conv_base.predict(inputs_batch) train_features[i*batch_size:(i+1)*batch_size] = features_batch train_labels[i*batch_size:(i+1)*batch_size] = labels_batch i += 1 if i * batch_size >= number_of_training_samples: break train_features = np.reshape(train_features, (number_of_training_samples,16*16*512)) validation_features = np.zeros(shape=(number_of_validation_samples,16,16,512)) validation_labels = np.zeros(shape=(number_of_validation_samples)) validation_generator = validation_data.flow_from_directory( validation_directory, target_size=(512,512), batch_size=batch_size, class_mode='binary', shuffle=False) i = 0 for inputs_batch, labels_batch in validation_generator: features_batch = conv_base.predict(inputs_batch) validation_features[i*batch_size:(i+1)*batch_size] = features_batch validation_labels[i*batch_size:(i+1)*batch_size] = labels_batch i += 1 if i * batch_size >= number_of_validation_samples: break validation_features = np.reshape(validation_features, (number_of_validation_samples,16*16*512)) test_generator = test_data.flow_from_directory( test_directory, target_size=(512,512), batch_size=batch_size, class_mode='binary', shuffle=False) # define the Convolutional Neural Network (CNN) model model = models.Sequential() model.add(layers.Dense(1024,activation='relu',input_dim=16*16*512)) model.add(layers.Dense(1,activation='sigmoid')) # compile the model model.compile(loss='binary_crossentropy', optimizer=optimizers.Adam(lr=0.01), metrics=['acc']) # fit the model to the data history = model.fit(train_features, train_labels, epochs=1, batch_size=batch_size, validation_data=(validation_features,validation_labels)) # save the model model.save('benign_and_melanoma_from_scratch.h5') # generate accuracy and loss curves for the training process (history of accuracy and loss) acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] number_of_epochs = range(1,len(acc)+1) plt.plot(number_of_epochs, acc, 'r', label='Training accuracy') plt.plot(number_of_epochs, val_acc, 'g', label='Validation accuracy') plt.title('Training and validation accuracy') plt.legend() plt.savefig('accuracy.png') plt.close() plt.plot(number_of_epochs, loss, 'r', label='Training loss') plt.plot(number_of_epochs, val_loss, 'g', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.savefig('loss.png') # evaluate the model # predict classes for root, dirs, files in os.walk(test_directory): for file in files: img = cv2.imread(root + '/' + file) img = cv2.resize(img,(512,512),interpolation=cv2.INTER_AREA) img = np.expand_dims(img, axis=0) img = img/255.0 feature_value = conv_base.predict(img) feature_value= np.reshape(feature_value,(1,16,16,512)) img_class = model.predict_classes(feature_value) prediction = img_class[0] Thanks. A: You're trying to predict using a 4D array: feature_value= np.reshape(feature_value,(1,16,16,512)) But you trained the network on a 2D array: train_features = np.reshape(train_features, (number_of_training_samples,16*16*512)) You should be predicting using the same shapes you trained the model on: feature_value= np.reshape(feature_value,(1,16*16*512))
[ "stackoverflow", "0005319179.txt" ]
Q: QWidgetAction : how to make the menu disappear after the user completes his input In my QMenuBar, I have several menus. One of those menus has a QWidgetAction in it. It shows up fine, but the problem is that once the user completes his input, I want the menu to disappear (as is the normal behavior for a classical QAction). However, I am not sure on how to do that. In my QWidgetAction, there is a button the user presses when he is done; I can therefore bind to this button's clicked() signal. In the slot, I tried to setFocus() an element outside the menu but the menu still doesn't disappear. How to tell the menu to close itself when my users finish interacting with the QWidgetAction? Thanks A: QMenu inherits QWidget, so calling yourMenu->hide() should do the work. Hope this helps.
[ "stackoverflow", "0030971978.txt" ]
Q: Kendo UI Excel export, generating multiple files, not refreshed properly? I have a single page app, that often creates new data from an array var searchData = new kendo.data.DataSource({data: buildData}); and then displays it in a grid, this all looks good except the excel export missbehaves as follows: run one search and the excel export works fine. run a second search and the excel export downloads 2 files, the first being a repeat of the results of the first search, the second file being the new search. run a third search and the excel exports three files.... and so on... it appears the refresh isn't working for me, but i don't have any idea why not? if(searchedArray) { searchedArray.forEach(function (row) { buildData.push({r:rowCount,w:row['w'],n:'1',nl:'2',o:row['o'],t:row['t'],d:row['d']; rowCount++; }); } var searchData = new kendo.data.DataSource({data: buildData}); var sGrid=null; sGrid = $("#searchedgrid").kendoGrid({ toolbar: ["excel"], excel: { fileName: "filename.xlsx", proxyURL: "http://demos.telerik.com/kendo-ui/service/export", filterable: true }, dataSource: searchData, sortable: { mode: "multiple", allowUnsort: true }, schema: { model: { fields: { r: { type: "number" }, w: { type: "number" }, n: { type: "string" }, nl: { type: "string" }, o: { type: "string" }, t: { type: "string" }, d: { type: "date" } } } }, height: sHeight, scrollable: true, pageable: false, selectable: "multiple cell", allowCopy: true, columns: [ { field: "r",width: 40,title: "Rank",template:'<center>#=r#</center>'}, { field: "w",width: 50,title: "Weight",template:'<center>#=w#</center>'}, { field: "n", title: "Number", width: "80px",template:'<center>#=n#</center>'}, { field: "nl", title: "&nbsp;", width: "14px",template:'<center><a href="#=nl#" onclick="javascript:void window.open(\'#=nl#\',\'details\',\'width=800,height=600,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=0,top=0\');return false;"><div class="ambLink" id="detaillink" title="View details"></div></a></center>',sortable:false}, { field: "o",width: 200,title: "Owner"}, { field: "t",width: 400,title: "Title", attributes: {style: 'white-space: nowrap '} }, { field: "d",width: 70,title: "Filed",template:'<center>#=d#</center>'} ] }).data("kendoGrid"); $("#searchedgrid").data('kendoGrid').refresh(); A: It worked for me by adding the .html('') after the selector: $("#grid").html('').kendoGrid({ ... });
[ "stackoverflow", "0002688675.txt" ]
Q: connecting to firewalled MS-SQL server that requires Windows Authentication via proxy? So I need to connect to a mssql server via Windows Authentication from a Unix server. Here are the obstacles: The db admin created a service account but made it Windows-Auth only, meaning I can't pass the username and password directly to the server to connect. The admin also added my host's server to the firewall so that it would only accept requests from my host machine. My host server has mssql enabled via freetds/sybase-dblib, but has the default 'secure-connections: Off' still set. I have a similar set up on my personal machine, but with secure-connections on, but I can't connect that way since I'm firewalled. So I'm wondering if it's possible to set up a proxy of sorts on my host so that I can start the connection on my personal machine using my local freeTDS library, but have the request pass to the host which would (in my dream world) not require secure connections to be on but simply would pass the request along so that it came from my non-firewalled host but using the correct authentication method. If anyone is not familiar with how Windows-Authentication works, it's a type of Kerberos authentication where the client machine makes the request to the remote server so that credentials are never actually sent (and thus can't be compromised by a man-in-the-middle). So I'm very doubtful that this can be done, since at some level my host machine has to do the actual work. But i thought I'd ask since I'm not totally clear on the deeper mechanics and because I really want to get this to happen. I guess another way of looking at it is I want to use my host as a kind of VPN. Also, I am working with my host admins to find a more long-term solution but I need to see the database as soon as possible so I can have something working when the problem gets fixed. A: Why don't you try SSH port forwarding? Ie. you connect to your host server, and tell it to forward a local port to the sql server. Then you connect on your local machine using localhost:port and your connection will be tunneled over ssh through your host server. If your local machine is a Windows machine then just download PuTTY and follow these instructions to set up port forwarding : http://www.cs.uu.nl/technical/services/ssh/putty/puttyfw.html. The question is of course whether your Windows credentials will be passed, but in theory this should work :p.
[ "stackoverflow", "0060394048.txt" ]
Q: Lumen Routes shows 404 except root route I am using Lumen for the first time. I placed my lumen files in folder Test and kept the folder inside /var/www/html path in server. My PHP version is 7.4.3 I have the following routes: $router->get('/key', function() { return str_random(32); }); $router->get('/', function () use ($router) { return $router->app->version(); }); Below is my htaccess: <IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule> But whenever I try to access http://xx.xxx.xxx.xxx/Test/public/key it shows The requested URL was not found on this server. But if I try to access http://xx.xxx.xxx.xxx/Test/public/ it returns me Lumen (5.7.8) (Laravel Components 5.7.*) How can I make all other routes also to work? A: I searched for < Directory /var/www/ > in /etc/apache2/apache2.conf file and changed the below AllowOverride None to AllowOverride All and restarted the apache. It solved my issue.
[ "stackoverflow", "0052573255.txt" ]
Q: How does the ternary operator work in this recursive code? In the last call on the stack, num will equal 0, so why doesn't the code return 0? public static int Add(int num) { return(num == 0 ? 0 : num + Add(num - 1)); } int num = 7; A: I believe your confusion lies in the fact that the last return statement does not directly return 0 to the main(). Instead the return statement will return to the caller of the function. In this case the caller will be itself. Here's a visualization with the extremely simple case of passing 1 to Add(): //num == 1 //Since num != 0, we will return num + Add(num - 1) //But the compiler doesn't know what Arr(num -1) is return num + ______; In the blank space is where the result of Add(num -1) will go. The current call to Add() is pushed onto the stack and a new call to Add(num -1) is called: public static int Add(int num) { return(num == 0 ? 0 : num + Add(num - 1)); } Here num == 0 so the method returns 0. But not to the main. It returns it to the previous call to Add(), right where the theoretical blank is. So: return num + ______; Becomes return num + 0; Since this is the last call on the stack, this returns to the main, with a result of 1, which is correct for the simply case of calling Add(1)
[ "stackoverflow", "0005041567.txt" ]
Q: problem showing object in SimpleExpandableActivity android Hello i have a simple expandable list activity that was working fine until i changed this: List<Map<String, String>> groupData = new ArrayList<Map<String, String>>(); for this: List<Map<String, Image>> groupData = new ArrayList<Map<String, Image>>(); i guess that when you set the TextView items in the Simple expandable list adapter's constructor the textview is expecting to get Strings instead of objects. Is there some way to work this arround ? Or do i have to get stuck with strings? Here's some code: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.expandable_list_layout); List<User> header = new ArrayList<User>(); header.add(new User("John")); header.add(new User("Smith")); header.add(new User("Anderson")); header.add(new User("Trinity")); header.add(new User("Morfeo")); List<String> gretting = new ArrayList<String>(); gretting.add("Hello"); List<Map<String, User>> groupData = new ArrayList<Map<String, User>>(); final List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>(); for (User user : header) { Map<String, User> curGroupMap = new HashMap<String, User>(); groupData.add(curGroupMap); curGroupMap.put(NAME, user); List<Map<String, String>> children = new ArrayList<Map<String, String>>(); for (String word : gretting) { Map<String, String> curChildMap = new HashMap<String, String>(); children.add(curChildMap); curChildMap.put(NAME, word); } childData.add(children); } //our adapter mAdapter = new SimpleExpandableListAdapter( getApplicationContext(), groupData, R.layout.simple_expandable_list_item_1, new String[] { NAME }, new int[] { R.id.header_text1 }, childData, R.layout.simple_expandable_list_item_2, new String[] { NAME }, new int[] { R.id.text1 } ); ExpandableListView lv = (ExpandableListView)findViewById(R.id.list); lv.setAdapter(mAdapter); } } So the final question is: do i have to implement my own simple expandable list adapter to be able to set the text by myself? EDIT: Here is the trace of the error: 02-21 08:56:54.128: ERROR/AndroidRuntime(277): java.lang.ClassCastException: se.madcoderz.categoryObject.User 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.SimpleExpandableListAdapter.bindView(SimpleExpandableListAdapter.java:249) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.SimpleExpandableListAdapter.getChildView(SimpleExpandableListAdapter.java:229) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.ExpandableListConnector.getView(ExpandableListConnector.java:450) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.AbsListView.obtainView(AbsListView.java:1315) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.ListView.makeAndAddView(ListView.java:1727) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.ListView.fillDown(ListView.java:652) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.ListView.fillSpecific(ListView.java:1284) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.ListView.layoutChildren(ListView.java:1558) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.AbsListView.onLayout(AbsListView.java:1147) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.view.View.layout(View.java:7035) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.LinearLayout.onLayout(LinearLayout.java:1042) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.view.View.layout(View.java:7035) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.view.View.layout(View.java:7035) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.LinearLayout.onLayout(LinearLayout.java:1042) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.view.View.layout(View.java:7035) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.view.View.layout(View.java:7035) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.view.ViewRoot.performTraversals(ViewRoot.java:1045) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.view.ViewRoot.handleMessage(ViewRoot.java:1727) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.os.Handler.dispatchMessage(Handler.java:99) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.os.Looper.loop(Looper.java:123) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at android.app.ActivityThread.main(ActivityThread.java:4627) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at java.lang.reflect.Method.invokeNative(Native Method) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at java.lang.reflect.Method.invoke(Method.java:521) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 02-21 08:56:54.128: ERROR/AndroidRuntime(277): at dalvik.system.NativeStart.main(Native Method) 2nd EDIT It's almost working but the listItems are not visible even if they're there: public class CategoriesAdapter2 extends SimpleExpandableListAdapter { private List<? extends List<? extends Map<String, User>>> mChildData; private String[] mChildFrom; private int[] mChildTo; public CategoriesAdapter2(Context context, List<? extends Map<String, ?>> groupData, int groupLayout, String[] groupFrom, int[] groupTo, List<List<Map<String, User>>> childData, int childLayout, String[] childFrom, int[] childTo) { super(context, groupData, groupLayout, groupFrom, groupTo, childData, childLayout, childFrom, childTo); mChildData = childData; mChildFrom = childFrom; mChildTo = childTo; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { View v; if (convertView == null) { v = newChildView(isLastChild, parent); } else { v = convertView; } bindView(v, mChildData.get(groupPosition).get(childPosition), mChildFrom, mChildTo, groupPosition, childPosition); return v; } private void bindView(View view, Map<String, User> data, String[] from, int[] to, int groupPosition, int childPosition) { int len = to.length - 1; for (int i = 0; i < len; i++) { TextView v = (TextView) view.findViewById(to[i]); if (v != null) { v.setText(data.get(from[i]).getName()); } } } } A: Now it's working but i don't like the solution. I made a new class and extended BaseExpandableListAdapter, the same superclass SimpleExpandableListAdapter extends. I don't like this solution, if there's a better solution please let me know. Thanks.
[ "cstheory.stackexchange", "0000040739.txt" ]
Q: What is the deterministic complexity of counting the number of global minimum cuts on an unweighted undirected graph? I know as a consequence of Karger's algorithm that the number of minimum cuts is bounded by $\binom{n}{2}$. In the comments of Counting the number of distinct s-t cuts in a oriented graph It says that due to this consequnce, the cuts of an unweighted graph can be listed in polynomial time, but the claim is unreferenced. A: If you want exact minimum cuts then one can construct a cactus representation of the minimum cuts deterministically in polynomial time and use that to enumerate all minimum cuts. See below for a reference. https://www.sciencedirect.com/science/article/pii/S0196677499910398 More interesting and difficult case is $\alpha$-approximation mincuts for $\alpha > 1$. One can use Karger's randomized algorithm for this purpose. Simply run it sufficiently many time. However, if you want a deterministic algorithm, one can do it via tree packings. See Thorup's paper on k-cuts. https://dl.acm.org/citation.cfm?id=365415
[ "salesforce.stackexchange", "0000226178.txt" ]
Q: Can you include a related list in a lightning component similar to visualforce ? I have been googling around and haven't found a way to show the history related list of an object inside a component. Is it possible or would it have to be custom built? A: There's no out of the box component available for displaying a related list on a custom lightning component. If you were building a standard record page, you could have done it using Standard Lightning Page Related List Component. In order to display a related list on a custom lightning component, you may rather like to use lightning:datatable and customize it to your requirements. A: I created a custom related list for lightning. Maybe will be helpful https://github.com/artyom-bazyk/singleRelatedList
[ "stackoverflow", "0005092377.txt" ]
Q: SQL reporting services datasource not visible in designer. Why? and How do I fix it? So Im maintaining some reports in a VS2005 .NET project. The reports use object classes from a business layer as datasets but they arent listen in the menu in the report designer. I have no clue why not but it makes dealing with them a pain. To add or manipulate the datasets I am forced to use notepad to edit the nodes to add fields and whatnot. We are using that microsoft report viewer tool instead of a reports server (not that that has anything to do with it). But anyway, Why cant I see the datasets in the designer tool. Im guessing maybe the person who initialy developed the reports might have used a newer version of visual studio and then just added them to the TFS project. I get the benefits of business layer objects and whatnot in the appcode but im ready to start just referencing the DB Procs directly from the reports and chop the current datasouces out of the report code. BUT... finding a way to at least view them from within vs2005 would be awesome for me actually meeting some of these deadlines. Thoughts? A: That has happened to me when a data-source named/referenced in the datasets doesn't exist. (I did a find and replace in the code and I forgot that the text was also included in the name of my primary data-source for the report, so it changed the name referenced in all of those datasets.... It didn't change the name of the actual data-source because I hadn't highlighted it in my find/replace selection).... <DataSet Name="Facility"> <Fields> <Field Name="facility_id"> <DataField>Facility_ID</DataField> <rd:TypeName>System.Guid</rd:TypeName> </Field> <Field Name="facName"> <DataField>facName</DataField> <rd:TypeName>System.String</rd:TypeName> </Field> </Fields> <Query> <DataSourceName>Database</DataSourceName> <CommandText>select distinct name facName, Facility_ID<br>from Location<br>where<br>Facility_ID = Location.FacilityId and<br>facility_ID = upper(@fac)<br></CommandText> <QueryParameters> <QueryParameter Name="@fac"> <Value>=Parameters!fac.Value</Value> <rd:UserDefined>true</rd:UserDefined> </QueryParameter> </QueryParameters> <rd:UseGenericDesigner>true</rd:UseGenericDesigner> </Query> </DataSet> <DataSourceName>Database</DataSourceName> "Database" needs to be a data-source that actually exists, meaning... you see it in design view? If this doesn't help please give some more details. Thanks.
[ "stackoverflow", "0046245276.txt" ]
Q: Laravel : How to customize title of email when sending email with Mailable? I write a mailable to send email when user registers,I do it following the document(https://laravel.com/docs/5.5/mail): first,generating a mailable: php artisan make:mail UserRegistered Ok,thus there is a UserRegistered.php file in the app/Mail directory,and I write the build() method like this: public function build() { return $this->view('emails.activate-user') ->with([ 'name' => $this->user->name, 'url' => route('activateUser',['token'=>$this->user->confirmation_token]) ]); } The email can be sent successfully,the title of the email is User Registered,I want to customize the title ,how to do it? A: You have to use subject method public function build() { return $this->view('emails.activate-user') ->subject("My mail title") ->with([ 'name' => $this->user->name, 'url' => route('activateUser',['token'=>$this->user->confirmation_token]) ]); } Or update your mails class's constructor public function __construct() { $this->subject('Sample title'); }
[ "stackoverflow", "0055771573.txt" ]
Q: Extracting year and month from Date in R So i have a dataframe in R: Date 2002-01-24 2003-02-25 2004-03-26 and when i check the data type of the Date column, str(df$Date) it is of "Date" type. Now, i want to create a new column named "Month", which i would take the portion of year and month in the Date column, without the day. Date Month 2002-01-24 2002-01 2003-02-25 2003-02 2004-03-26 2004-03 The way i did it is below: df$Month <- format(as.Date(df$Date), "%Y-%m")) but when i run str(df$Month) it says it is of "chr" type instead of "Date". Is there any ways to keep it in the "Date" data type instead of being converted to chr? A: The Date class describes a particular day. (BTW, the internal representation is the number of days since 1970-01-01.) So, you can‘t have a Date without specifying a day. If you want to keep the Date class when denoting a particular month you can round down to the first day of the month: lubridate::floor_date(as.Date("2019-04-19"), "month") which will return 2019-04-01. With OP's data: df <- data.frame(Date = as.Date(c("2002-01-24", "2003-02-25", "2004-03-26"))) df$Month <- lubridate::floor_date((df$Date), "month") df Date Month 1 2002-01-24 2002-01-01 2 2003-02-25 2003-02-01 3 2004-03-26 2004-03-01 str(df) 'data.frame': 3 obs. of 2 variables: $ Date : Date, format: "2002-01-24" "2003-02-25" "2004-03-26" $ Month: Date, format: "2002-01-01" "2003-02-01" "2004-03-01" This is very handy for plotting monthly aggregates.
[ "stackoverflow", "0063474610.txt" ]
Q: Can webhook target GCP PubSub directly? We're using webhooks to listen to Jira issue events. Anytime activity on a ticket occurs, the JIRA API notifies an HTTP endpoint running inside a Google Cloud Function. In this Cloud Function, we are simply forwarding the request unaltered into Pub/Sub via: def forward_to_pubsub(request): publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(project_id, topic_id) # Request body contains user, project, issue basically everything we care about jira_body = request.json publisher.publish(topic_path, data=json.dumps(jira_body).encode('utf-8')) This seems like an unneeded hop. Is there anyway to configure Pub/Sub to be the target of a HTTP webhook? Can't figure out from docs either way. A: No, it's not possible. Pub/Sub topics don't have corresponding HTTP endpoints that can be used as webhooks. If you want to trigger a Pub/Sub topic from an end-user application, you need to use a front-end server between them: See https://cloud.google.com/pubsub/docs/overview#endpoints for more details.
[ "diy.meta.stackexchange", "0000000772.txt" ]
Q: Adjust FAQ for cost of a job Please adjust the FAQ: Note, the following are considered off-topic: The cost of a job or the price of tools as these will vary between locations and over time. to include a clear comment regarding questions about tipping contractors being off-topic. A: Part of the challenge with a list like this is that it will never explicitly describe every single off topic question, and trying to do so would result in a l,000 item list that no one would ever read. Instead, we've tried to keep it high level and broad, when possible removing or consolidating items. So I'm inclined to decline this request, but I'm happy to follow the community if they disagree with me.
[ "gardening.stackexchange", "0000022537.txt" ]
Q: Methods for saving amaryllis bulb infected with narcissus bulb fly One of my amaryllis bulbs is infected with the narcissus bulb fly : ( It was planted and it started seeing white mould forming around the bulb. I took the bulb out and sure enough it was starting to rot on its side. By pressing on the decayed area I found a maggot. I know most people recommend discarding the bulb, but I rather try to save it. The damage seems to be mostly on the outside layers, since it is a big bulb. I know most likely the mother planted two eggs on the bulb, though, so there might be another maggot eating away the bulb where I can't see it. So my questions are: Has anyone actually saved an infected bulb? What method was used? If I use the method of soaking the bulb in hot water (43c - 44c) for 40 minutes, do I need to keep the water constantly at that temperature? Can I cut the decayed part of the bulb (mostly on its outside) and plant it again? Wouldn't it rot (like it was doing before) not having its protective layers? I have seen some people slice the bulb completely to get the worm out but I could not find a description of the whole method. How does this method work? Can I plant the halves afterwards? Thanks in advance. A: I saved a batch of specialty daffodils I had received, as they arrived infected, and I was unable to get a replacement. I decided to go for it and try to save them, instead of getting a refund. Because Daffodil and Amaryllis bulbs are very similar in form, this answer will likely be closely applicable to your situation. I have the reference guide 'Plant Propagation', by the American Horticultural Society, and I used the method of bulb chipping in that book. I will quote that here: 1. Dig up a healthy bulb when dormant and clean it. Remove any papery outer skin and trim back the roots with a clean, sharp knife without cutting into the basal plate. Cut back the growing tip. 2. Holding the bulb with the basal plate uppermost, cut it into 8-16 similarly sized sections ("chips"), depending on the size of the bulb. Make sure that each chip retains a piece of the basal plate. 3. Soak the chips in a fungicidal solution, made up according to the manufactures instructions, for up to 15 minutes to kill any bacteria or fungal spores. Allow the chips to drain on a rack for about 12 hours. 4. Place the chips in a clear plastic bag containing ten parts vermiculite to one part water. Inflate the bag, then seal and label it. Keep the bag in a dark place at 68°F (20°C). Check the bag periodically and remove any chips that show signs of rot. 5. After about 12 weeks, bulblets should form just above the basal plate. Pot the chips individually in 3in (8cm) pots in free-draining soil-based potting mix. Insert each chip with its basal plate downward and the bulblets covered by about 1/2" (1cm) of soil mix. Leave the scales exposed, they will slowly rot away as the bulblets develop. Grow on in a sheltered position, in conditions appropriate to the individual species. Note: This guide specifically states using dormant bulbs, but my infected plants were sprouted, and it worked for them too. Just cut the entire top growth off. Some of the bulbs had no material left that was healthy enough to use, because of how this larva burrows. I had enough, however, that I got a fair survival rate, and in 3 years, they were at blooming size. picture of bulblet formed in the chip of a daffodil bulb:
[ "electronics.stackexchange", "0000145674.txt" ]
Q: Amplitude Modulation Frequency In am receivers, we detect the modulating signal by using envelope detector. So, the diode rectifies the signal, and the detected signal has doubled frequency than the original. Does this mean we will hear distorted sounds, if we connect audio amplifier. Is it possible to decrease the frequency by two? A: In AM you have a waveform typically formed like this: Rectification chops off the negative portion of that signal, thus: Filtering then removes the high frequency component: A capacitor then removes the DC offset: Nowhere in that does the frequency change. Even if you were to use full-wave rectification, only the frequency of the carrier would change - the modulated signal frequency will be just the same as it was. In the image you provided in your comments: The modulated signal is modulated twice - once on the positive axis, and once on the negative axis. This is the same as the top image above. However, the modulating signal has an amplitude that crosses the zero axis, so you actually end up with two signals crossing over each other, like this: When you then rectify and filter that waveform you get just the positive portions of both waves: With pure audio modulation (modulating two audio signals together) this can be desirable as it produces very noticeable affects and artefacts (you would never typically demodulate this signal, it would be the finished audio product in its own right). In RF modulation though it's not wanted, so the incoming signal should have an amplitude of no more than 50% of the carrier frequency, and be off-set to half-way up (and down) the carrier wave so the two sides of the wave don't cross over.
[ "stackoverflow", "0017996616.txt" ]
Q: Where to place angular element so it can effected all scopes I have this code which is a contenteditable placeholder by CraigStuntz. My question is where should I put this code so all the div which contain contenteditable will get effected. I tried to put under app.controller('myCtrl', function(){}); but it only works with the direct scope. No nested scope is working. angular.element(document.querySelectorAll('div[contenteditable]')).bind('change keydown keypress input', function() { if (this.textContent) { this.setAttribute('data-contenteditable-placeholder', 'true'); } else { this.removeAttribute('data-contenteditable-placeholder'); } }); A: Try using a directive like this. angular.module('angularProject.directives', []) .directive('placeholder', function() { return { restrict:'A', link: function(elem) { elem.bind('change keydown keypress input', function() { elem.setAttribute('data-contenteditable-placeholder', 'true'); }); } } }); You can then place it in any of your divs like this. <div placeholder></div> I haven't tested this.
[ "apple.stackexchange", "0000269586.txt" ]
Q: Automator Service: Parent of input from files or folders I cannot find any information on this, so I hope somebody with experience can fill in the gap. I am writing a simple Automator Service, and I can’t get past the first step. The script is a Service Service receives selected files or folders in Finder.app Run AppleScript The script is on run {input,parameters} set test to container of input -- Can’t make container into type reference. display dialog test as string return input end run The input parameter has the selected file or folder, and all I want to do at this stage is to get the parent folder of the selected item. Everything I try, which is from countless near solutions on the web fail in this, telling me that I can’t make the container into a reference. I have no idea what I should be doing, and I can’t find any information on this. How can I get the parent folder using Automator? A: The curly-brace portion of on run {input, parameters} creates a list and as such you need to address input as a list. The following example assumes only one file or folder gets passed to the Service: on run {input, parameters} tell application "System Events" set thePath to POSIX path of (container of (item 1 of input)) end tell return thePath end run Can your Service receive more then one file or folder at a time? ... If yes, then you'll need to incorporate the code below. The following example assumes multiple files or folders gets passed to the Service: on run {input, parameters} set pathList to {} repeat with itemNum from 1 to count of input tell application "System Events" copy POSIX path of (container of (item itemNum of input)) to end of pathList end tell end repeat return pathList end run Reference: Getting the path of the parent folder of a file?
[ "math.stackexchange", "0003124426.txt" ]
Q: Hamiltonian Prove. Let G be a graph of order $n$ with $e(G)>{n\choose2}-(n-2)$. Prove that $G$ is Hamiltonian. On my way use induction, the basis step is clear. But induction step assume that $G_1=G+x$ for all $x\notin V(G)$ with $e(G_1)>{n+1\choose2}-(n+1-2)$, For induction hypothesis when should i use it? Remark $e(G)=|E(G)|$. A: Let $G$ be a graph of order $n\gt3$ and size $e(G)\gt\binom n2-n+2=\binom{n-1}2+1$. By the inductive hypothesis, the proposition holds for all graphs of order less than $n$. Claim. $G$ contains a vertex $x$ of degree $\deg(x)\gt\frac{n-1}2$. Proof. Otherwise we would have $$2e(G)=\sum_{x\in V(G)}\deg(x)\le\frac{n(n-1)}2=\binom n2$$ so that $e(G)\le\frac12\binom n2$, but this contradicts our hypothesis that $e(G)\gt\binom n2-n+2\gt\frac12\binom n2$. Choose a vertex $v\in V(G)$ of degree $d(x)=d\gt\frac{n-1}2$. Then $G-x$ is a graph of order $n-1$, and $$e(G-x)=e(G)-d\gt\binom{n-1}2+1-d.$$ Case 1. $d\le n-2$. Then $e(G-x)\gt\binom{n-1}2+1-(n-2)=\binom{n-1}2-(n-1)+2$. Therefore, by the inductive hypothesis, the graph $G-x$ has a Hamiltonion circuit $C$. Since $\deg(x)\gt\frac{n-1}2$, the vertex $x$ is joined to two consecutive vertices of $C$, so there is also a Hamiltonian cycle in $G$. Case 2. $d=n-1$, i.e., $x$ is joined to all other vertices of $G$. If $G-x$ is a complete graph, then $G$ is a complete graph and there's nothing to prove. Otherwise, let $u,v$ be two nonadjacent vertices of $G-x$, and let $H=G-x+uv$, a graph of order $n-1$ and size $e(H)=e(G-x)+1\gt\binom{n-1}2+2-d=\binom{n-1}2-(n-1)+2$. By the inductiove hypothesis, the graph $H$ has a Hamiltonian circuit $C$. If $uv\in E(C)$ then $C-uv+ux+xv$ is a Hamiltonian circuit of $G$. If $uv\notin E(C)$, choose any edge $yz\in E(C)$; then $C-yz+yx+xz$ is a Hamiltonian circuit of $G$. Remark. This is best possible; for each $n\ge2$ there is an obvious example of a non-Hamiltonian graph with $n$ vertices and $\binom{n-1}2+1$ edges.
[ "stackoverflow", "0007545299.txt" ]
Q: (distutil + shutil) * copytree =? I'd like the ignore pattern that shutil's copytree function provides. And I want the src tree to replace all existent files/folders in the dest directory like distutil.dir_util.copy_tree. I'm a fairly new Python user, and can't seem to find any posts on this. A: I was going to say this earler but I didn't. http://docs.python.org/library/shutil.html has a version of the copytree function. I looked at it to see if it would just replace existing files and from what I could tell it would overwrite existing files, but it fails if any of the directories already exist. Due to os.mkdirs failing if the directories already exist. The needed imports: import os import os.path import shutil taking _mkdir from http://code.activestate.com/recipes/82465-a-friendly-mkdir/ (a commenter over there mentions that os.mkdirs has most of the same behavior but doesn't notice that _mkdir doesn't fail if any of the directories to be made already exist) def _mkdir(newdir): """works the way a good mkdir should :) - already exists, silently complete - regular file in the way, raise an exception - parent directory(ies) does not exist, make them as well """ if os.path.isdir(newdir): pass elif os.path.isfile(newdir): raise OSError("a file with the same name as the desired " \ "dir, '%s', already exists." % newdir) else: head, tail = os.path.split(newdir) if head and not os.path.isdir(head): _mkdir(head) #print "_mkdir %s" % repr(newdir) if tail: os.mkdir(newdir) Although it doesn't take a mode argument like os.mkdirs, copytree doesn't use that so it isn't needed. And then change copytree to call _mkdir instead of os.mkdirs: def copytree(src, dst, symlinks=False): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) # os.makedirs(dst) _mkdir(dst) # XXX errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks) else: shutil.copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error), why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so that we can # continue with other files except Error, err: errors.extend(err.args[0]) try: shutil.copystat(src, dst) except WindowsError: # can't copy file access times on Windows pass
[ "anime.stackexchange", "0000013584.txt" ]
Q: Why did the man steal the protagonist's lump? In the 1929 anime Kobu Tori, The protagonist has his facial deformation taken away by the tengu for being good entertainment and a welcome guest. When the antagonist follows in his footsteps, he goes to the tengu also to get rid of the lump on his own face. Kobu Tori is a silent film, so I wasn't able to translate the dialogue and I don't understand why does the antagonist steals the protagonist's lump Is it to return it to him? To sell it? A: According to Wikipedia: An old man has a lump or tumor on his face. In the mountains he encounters a band of tengu making merry and joins their dancing. He pleases them so much that they want him to join them the next night, and offer a gift for him. In addition, they take the lump off his face, thinking that he will want it back and therefore have to join them the next night. An unpleasant neighbor, who also has a lump, hears of the old man's good fortune and attempts to repeat it, and steal the gift. The tengu, however, simply give him the first lump in addition to his own, because they are disgusted by his bad dancing, and because he tried to steal the gift. The mean old man doesn't want to steal it, he wants to get rid of it like the protagonist did.
[ "gis.stackexchange", "0000312614.txt" ]
Q: Converting MSSQL linked MapInfo Tab file to a shapefile using ogr2ogr I have some tab files that are actually references to a view in a MS SQL Server table. It looks like begin_metadata "\IsReadOnly" = "FALSE" "\MapInfo" = "" "\MapInfo\TableID" = "055372be-523f-430a-b603-bbd462ad3efd" "\DATALINK" = "" "\DATALINK\ConnectionString" = "DSN=xxx_GIS;UID=sa;APP=MapInfo Professional®;WSID=AS00769;DATABASE=xxx_GIS" "\DATALINK\Query" = "select ""assetID"", ""assetName"", ""ward"", ""locality"", ""GID"", ""location"", ""assetClass"", ""assetSubClass"", ""assetType"", ""hierarchy"", ""dimensionsLength"", ""MI_PRINX"", ""MI_STYLE"", ""OBJECT"" from ""NGSC_GIS"".""dbo"".""v" "\DATALINK\Query\+1" = "w_ASSET_Bridge""" end_metadata In QGIS the view is like <layer-tree-layer expanded="1" source="dbname='xxx_GIS' service='xxx_GIS' estimatedmetadata=true disableInvalidGeometryHandling='0' table=&quot;dbo&quot;.&quot;vw_ASSET_Bridge&quot; (SP_GEOMETRY) sql=" id="vw_ASSET_Bridge_1a8f7b4e_d11d_4a9e_b5ba_773aafe7014b" checked="Qt::Checked" providerKey="mssql" name="vw_ASSET_Bridge"> <customproperties/> </layer-tree-layer> <layer-tree-layer expanded="1" source="../../GIS/Data/ASSET_Bridge.TAB" id="ASSET_Bridge_b0c1d436_6728_428f_a1dc_f22c15fe8c38" checked="Qt::Checked" providerKey="ogr" name="ASSET_Bridge"> <customproperties/> </layer-tree-layer> Using the advice in https://alastaira.wordpress.com/ogr2ogr-patterns-for-sql-server/ I see the command should be something like ogr2ogr -f “ESRI Shapefile” “C:\scratch\vw_ASSET_Bridge.shp” “MSSQL:server=xxx_GIS;database=xxx_GIS;trusted_connection=yes;” -sql “SELECT [ID],[GeoType],[GeoName],GEOMETRY::STGeomFromWKB([GeoShapes].STAsBinary(),28354) As [GeoShape] FROM dbo.vw_ASSET_Bridge WHERE [GeoShapes].STGeometryType() = ‘POINT'” -overwrite -a_srs “EPSG:28354” But I am not sure what should be used for the tags in [] A: Figured it out...KISS principle as a lot of what Mapinfo/tab format required wasn't necessary in OGR C:\OSGeo4W\bin\ogr2ogr.exe -f "MapInfo File" bridges.tab "MSSQL:Server=xxxxx;Database=_gis;User ID=user;Password=pass" -sql "SELECT * FROM dbo.vw_ASSET_Bridge" -a_srs EPSG:28354 -t_srs EPSG:4326 >>bridge_log.txt
[ "stackoverflow", "0050610694.txt" ]
Q: how to pass values from a javascript function to a variable I need to pass the value of the javascript function below to a variable in javascript but its only shows the value in a console. it does not pass the function values (somevar) to the display variables function functionThatNeedsRowsData(values){ var somevar = values; // console shows the value console.log(somevar); } //Now display the value of (somevar) in a function and pass it to a variable not working var display= functionThatNeedsRowsData(); A: You need to return the value inside the function: return somevar;
[ "stackoverflow", "0012741853.txt" ]
Q: How to completely remove a custom theme from magento May i know how to remove a custom theme from MAGENTO completely. I am using Magento 1.7.0.2 and how to disable it completely. What i did and face problems. I have two custom themes say Theme 1 and Theme 2. Theme one is compatible with 1.7.0.2 and theme 2 with 1.6.x I installed theme 1 as prescribed in the document. then i installed theme 2 as per the document and make changes in the System>configuration>design to make necessary changes. My problem is that- few pages are showing theme 1 and few are theme 2. the home page and one or two product page shows theme1 and few other product pages and checkout page shows theme 2. Then i remove each and every individual file of theme 2. (That i don't want to opt for, as it is very time consuming and problem may occur) Now, i again reinstall the theme 1 just in case if i haven't remove any wrong file of theme 1 itself. ( I follow the same process in documentation) Now the problem is Magento default theme is overtaking few pages of my custom theme 1. The problem never gets end up here at all. That's why i am looking for a solution where i can completely remove or uninstall a custom theme. If not, i want to disable any theme, if possible. I want to know can we test multiple themes on MAGENTO and can switch between them. Regards A: Assuming you have no custom themes set at the product or category level (which if you don't know what I mean, you shouldn't have), all you should have to do is change the values in System > Configuration > Design. As far as removing them, if they were installed properly, i.e. they are their own unique folders in app/design/frontend/{package}/{theme} and skin/frontend/{package}/{theme}. If you are seeing different themes on different pages though, this is probably just a caching issue. Make sure you completely refresh all caches in System > Cache Management.
[ "stackoverflow", "0032297743.txt" ]
Q: Failing to parse numbers from stringstream and output them correctly C++ #include <iostream> #include <vector> #include <string> #include <sstream> using namespace std; int main(){ string a = " test 1234 test 5678"; stringstream strstr(a); string test; vector<int>numvec; int num; while(strstr>>num || !strstr.eof()){ if(strstr.fail()){ strstr.clear(); string kpz; strstr>>kpz; } numvec.push_back(num); } for(int i = 0;numvec.size();++i){ cout<<numvec[i]<<'\t'; } } In this program , i'm trying to parse only the values " 1234" and " 5678" from a stringstream which has string words in it and output those values. I put the values inside an Integer vector , later i'm outputting those values from the vector , however , the output is that in the first few lines , it shows me the values , but then , I get alot of zero , I never saw such error and it looks very interesting , so my questions are: Why I don't get the values " 1234" and " 5678" outputted as wanted? ( which is for the program to show only those values and not the huge array of zeros caused by the error ) and why's this error happening? For the program: http://ideone.com/zn5j08 Thanks in advance for help. A: The problem is that your loop does not have a continue after detecting a failure state, meaning that the value of num gets pushed into numvec even after a failure. Here is how you can fix this: while(strstr>>num || !strstr.eof()) { if(strstr.fail()){ strstr.clear(); string kpz; strstr>>kpz; continue; // <<== Add this } numvec.push_back(num); } Now the value gets pushed into numvec only when strstr is not in a failed state, fixing your problem. Fixed demo.
[ "stackoverflow", "0058573530.txt" ]
Q: Vector size returns 0 after being populated in a for loop I have been working a small c++ app that has to do with lecturers and students getting matched together based on the class they teach/take. Each Lecturer has a vector of students. When a student takes the same class as a Lecturer teaches, then we add that same student to that same lecturer. I have 2 for loops that loop through all lecturers and students and then compares the classes of both and if they match, add that student to the lecturer. After the loops, I am looping through all the lecturers and getting the size of each. But returns back 0 and it should give back 1. (Because one student matches the class for each lecturer). Lecturer.h #pragma once #include <iostream> #include "Person.h" #include "Student.h" #include <vector> #include <string> using namespace std; class Lecturer : public Person { public: // Lecturer(string department, string specialization, string name, int age, char gender) // : department(department), specialization(specialization), name(name), age(age), gender(gender) {} Lecturer() { } Lecturer(string department, string specialization, string name, int age, char gender, string uniClass){ this->department = department; this->specialization =specialization; this->name = name; this->age = age; this->gender = gender; this->uniClass = uniClass; } // Class Methods void addStudent(Student student); // Setter Methods void setDepartment(string dprt); void setSpecialization(string splz); void setName(string nme); void setAge(int ag); void setGender(char g); // Getter Methods string getDepartment(); string getSpecialization(); string getUniClass(); int getStudentsSize(); vector<Student> getStudents(); private: string department; string specialization; vector<Student> students; string uniClass; }; void Lecturer::addStudent(Student student) { cout << student.getName() << endl; students.push_back(student); } int Lecturer::getStudentsSize() { return students.size(); } Student.h #pragma once #include <iostream> #include "Person.h" #include <string> using namespace std; class Student : public Person { public: // Student(string major, string minor, int id, string name, int age, char gender) // : major(major), minor(minor), id(id), name(name), age(age), gender(gender) {} Student() { } Student(string major, string minor, int id, string name, int age, char gender, string uniClass){ this->major = major; this->minor = minor; this->id = id; this->name = name; this->age = age; this->gender = gender; this->uniClass = uniClass; } // Setter Methods void setMajor(string mjr); void setMinor(string mnr); void setId(int _id); void setName(string nme); void setAge(int ag); void setGender(char g); // Getter Methods string getMajor(); string getMinor(); int getId(); string getUniClass(); string getName(); private: string major; string minor; int id; string uniClass; }; string Student::getUniClass() { return uniClass; } main.cpp #include <iostream> #include <string> #include "Person.h" #include "Lecturer.h" #include "Student.h" int main() { vector<Lecturer> lecturers; lecturers.push_back(Lecturer("Computing", "Advanced Programming", "John", 40, 'm', "AB101")); lecturers.push_back(Lecturer("Business", "Finance", "Dave", 42, 'm', "AB102")); lecturers.push_back(Lecturer("Science", "Physics", "Bill", 46, 'm', "AB103")); vector<Student> students; students.push_back(Student("Computer Science", "Maths", 123, "Mike", 20, 'm', "AB101")); students.push_back(Student("Business", "Economics", 142, "Jane", 21, 'f', "AB102")); students.push_back(Student("Engineering", "Physics", 151, "Mary", 19, 'f', "AB103")); for(Lecturer lecturer : lecturers) { for(Student student : students) { //cout << "Name: " << student.getUniClass() << endl; if (lecturer.getUniClass().compare(student.getUniClass()) == 0) { // ADDING A STUDENT THAT MATCHES THE CLASS lecturer.addStudent(student); } } } for(Lecturer lecturer : lecturers) { // EACH LECTURER'S STUDENTS SIZE IS 0 HERE (SHOULD BE 1) cout << lecturer.getStudentsSize() << endl; } } A: You're using values everywhere. That means copies. Your first change is to iterate using references. For example: for (Lecturer& lecturer : lecturers) // ^
[ "stackoverflow", "0053324268.txt" ]
Q: How do you put multiple tkinter widigets into one .grid I am trying to make a date chooser using python. I am using spinboxes, however I was wondering whether I could get all 5 widgets into one grid space, so it seemed like all 5 widgets are really one widget. Hopefully the following code articulates the problem better. import tkinter as tk root=tk.Tk() Day=tk.IntVar() Month=tk.IntVar() Year=tk.IntVar() Label1=tk.Label(root,text="Label Label Label Expanding Row") Label1.grid(row=1,column=1) DayEntry=tk.Spinbox(root,textvariable=Day,bg="white",from_=0, to_=31,width=2) DayEntry.grid(row=2,column=1) MonthEntry=tk.Spinbox(root,textvariable=Month,bg="white",from_=0, to_=12,width=2) MonthEntry.grid(row=2,column=3) YearEntry=tk.Spinbox(root,textvariable=Year,bg="white",from_=2000, to_=20019,width=4) YearEntry.grid(row=2,column=5) Divider1=tk.Label(root,text="/") Divider1.grid(row=2,column=2) Divider2=tk.Label(root,text="/") Divider2.grid(row=2,column=4) root.mainloop() A: The solution is to put all of the widgets in a frame. datepicker = tk.Frame(root) datepicker.grid(row=2, column=0) DayEntry=tk.Spinbox(datepicker,textvariable=Day,bg="white",from_=0, to_=31,width=2) MonthEntry=tk.Spinbox(datepicker,textvariable=Month,bg="white",from_=0, to_=12,width=2) YearEntry=tk.Spinbox(datepicker,textvariable=Year,bg="white",from_=2000, to_=20019,width=4) Divider1=tk.Label(datepicker,text="/") Divider2=tk.Label(datepicker,text="/") DayEntry.grid(row=0,column=1) Divider1.grid(row=0,column=2) MonthEntry.grid(row=0,column=3) Divider2.grid(row=0,column=4) YearEntry.grid(row=0,column=5)
[ "aviation.stackexchange", "0000024054.txt" ]
Q: Could the cabin crew open the lavatory door from outside when someone locked the door from the inside? On a recent flight a passenger locked himself in the lavatory for almost the entire duration of the flight. It was only when the flight was in the final leg of descent that he could be persuaded to come out. In similar situations, can the cabin crew open the door from the outside if it is locked from the inside? A: Apparently yes. It has been mentioned in a number of places. One of the methods given is pretty simple: Step 1: Approach locked lavatory Step 2: Lift "LAVATORY" sign Step 3: Slide the knob into the unlocked position Thats all to it, though they may vary with the aircraft. As @RalphJ points out in the comments, it should go without saying that unless you are cabin crew, you should not be doing this. A: Yes, the flight attendants can lock and unlock the lavatories from the cabin. As far as I know, the specific ways that they do this, which probably vary from one aircraft type to another, aren't published by the airlines as a matter of protecting customers' privacy. Bad day for everybody if a deviant was to use such a method to open an occupied lavatory to get a cheap thrill.
[ "stackoverflow", "0061350598.txt" ]
Q: Django custom user with AbstractUser from django.contrib.auth import get_user_model from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): pass class Landlord(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) #other fields def __str__(self): # **Error is here** return self.user.email When I use email field of my user it has give this error: "Instance of 'OneToOneField' has no 'email' member" what is the reason for error?(And what fields are there in AbstractUser class?) How can I fix the error. A: I am using AbstractBaseUser instead of AbstractUser and the problem didn't come up. also by reading the code of django.contrib.auth.models you can see what fields have been implemented and how. it can be done by holding the control key and clicking on the import address.
[ "stackoverflow", "0058799403.txt" ]
Q: How to enforce developers to use square over than curly brackets? I want to enforce developers in my application to use [] instead of {{}} in element attributes. for example this code should cause an error (in the build/serve/lint time ): <mycomponent id="{{i}}"> the current code is <mycomponent [id]="i"> How I do that? A: As commented, one of the possibilities would be to create a custom TSLint rule and add severity to force developers when compiling throwing the proper errors. You will have a tslint.json in your project for all the core rules and custom ones. Please, check here how to write a custom rule: https://palantir.github.io/tslint/develop/custom-rules/ In other matters be aware that TSLint is being deprecated and ESLint would be its substitute. A: Teach them, be nice and set good examples.