text
stringlengths
64
81.1k
meta
dict
Q: call database connection variables from different classes I'm starting on classes, and now I'm working on a project that involves several classes placed on different folders on the root, and each class connects to the same db. Is there a way to store connection variables somewhere and get them on each class? (like an include option). Been reading about class Customer (that's my example) extends myvariables, but I can't figure if that's the best practice. Can you please give me a hint? A: You could create a static class to do all of the database work for you, and expose the methods you need. public static class DatabaseUtils { private const string ConnectionString = "..."; public static int GetCustomerId(string firstName, string lastName) { try { using (var connection = new SqlConnection(ConnectionString)) using (var command = new SqlCommand("sql stuff")) { var result = command.ExecuteScalar(); if (result == DBNull.Value) return -1; return (int) result; } } catch (Exception ex) { // Log errors + ex } } // Other methods to interact with the database } You could then call a method like: int id = DatabaseUtils.GetCustomerId("My", "Name"); If this is going to eventually be a deployed application, you might want to look at storing the connection string in the app.config so that it can be changed without recompiling the app.
{ "pile_set_name": "StackExchange" }
Q: General wiring questions: high power LEDs, relay and microcontroller I think I understand the Raspbery Pi GPIO pins and most of how this diagram below works, at a high level at least. First question, it's not clear to me exactly how the middle part with the resistors and transistors works. Can anyone help explain how this works in another way? This is essentially flipping the high/low logic from the GPIO pins so a low output from the pi is non-zero voltage to the relay input? source another reference for the middle section To power the LED's on the other end of the relay, I have a wall AC adapter to 28VDC, .9A that will power a 700 mA driver. The driver will connect each of the relay terminals to the LEDs. I will only need one led/relay active at a time. My second question, if I run 8 wires from the relay terminals to power each LED, can I connect them all to the same wire for ground to return? I'd like to have some sort of quick disconnect for the LEDs so they can be easily unplugged, can you have multiple quick connect terminals spliced into a shared ground or is that a bad idea? Any recommendations for quick disconnecting plugs? Still pretty new to all of this so I feel like I could very easily miss anything from "common sense" and "good practice" to "just completely wrong". Here's the LEDs I was planning to use in a series to justify the 700mA current. A: I admit the explanation about the transistor is a little misleading. I wouldn't have chosen to use the term "active low" in this scenario because you have direct control of the GPIO pin, not direct control of the relay. The GPIO pin is active high. All they're saying is you need to turn on the transistor so it can provide a path to ground for the relay's coil. And to do so, you need to drive the GPIO pin high. Here's what the full circuit probably looks like for each GPIO/relay pair: simulate this circuit – Schematic created using CircuitLab When the GPIO of the RPi is driven high (in your code), the 2N222 NPN transistor is turned on. That allows current to flow from the 5V source, through the relay coil, through the transistor, and into ground, which will activate the relay. The author's description of "active low" is actually referring to the spot I marked "V1" in the circuit. When the voltage at that node is low (when the transistor is on or if you just touch a ground wire there), current will flow and the relay will activate. I think she explained it that way because that point in the circuit is physically manifested as a pin you can connect to. R1 is a current-limiter resistor. It prevents too much current from being sourced from the GPIO pin and into the transistor's base. R2 is a pull-down resistor. It forces the base of the transistor low (and thus the transistor off) if the GPIO pin is physically disconnected or high impedance (tri-stated). When the GPIO pin is attached, R2 can be ignored. There is no signal flipping going on. If you wire up your LEDs and current source like so, you can connect them all to the same ground wire: simulate this circuit I'm assuming you've got a handle on how much current these LEDs need. If you're not sure about hooking up your LEDs to a 700mA constant current source, please do more research first (or sit back and enjoy the fireworks). At no time should all of the LEDs be off - unless the current source has been safely disabled. This circuit will work as long as you do as you said and only have one LED on at a time. If you do activate more than one at a time, the current will divide between them. And since LEDs have a negative temperature coefficient, one LED will tend to dominate the current and look brighter than the others.
{ "pile_set_name": "StackExchange" }
Q: Who can use magic items? The rules on using magic items are not at all clear to me. Especially the Spell Completion and Spell Trigger activations are confusing. What kind of character (class, level) can use a wand (spell trigger)? What kind of character can use a scroll (spell completion)? How does the Use Magic Device skill work in all this? For example: Spell Trigger: Spell trigger activation is similar to spell completion, but it's even simpler. No gestures or spell finishing is needed, just a special knowledge of spellcasting that an appropriate character would know, and a single word that must be spoken. Spell trigger items can be used by anyone whose class can cast the corresponding spell. This is the case even for a character who can't actually cast spells, such as a 3rd-level paladin. The user must still determine what spell is stored in the item before she can activate it. Activating a spell trigger item is a standard action and does not provoke attacks of opportunity. My players' characters pried a Wand of Stoneskin (a 4th-level wizard spell) from a dead wizard's hands. The rules of spell trigger say that the item "can be used by anyone whose class can cast the corresponding spell [...]". Does that mean that a 1st-level wizard could use the wand, even though he could only cast the spell at level 7 (being able to cast 4th level spells)? Spell Completion: This is the activation method for scrolls. A scroll is a spell that is mostly finished. The preparation is done for the caster, so no preparation time is needed beforehand as with normal spellcasting. All that's left to do is perform the finishing parts of the spellcasting (the final gestures, words, and so on). To use a spell completion item safely, a character must be of high enough level in the right class to cast the spell already. If he can't already cast the spell, there's a chance he'll make a mistake. Activating a spell completion item is a standard action (or the spell's casting time, whichever is longer) and provokes attacks of opportunity exactly as casting a spell does. How about a Scroll of Stoneskin? The Spell Completion description speaks about "a chance he'll make a mistake" (if the character is not of high enough level in the right class). Does this mean that a 1st level wizard, or even a 20th level fighter, could read and use the scroll (accepting the chance of failure)? Does this involve the Use Magic Device skill? What's this mentioned chance of failure, and what can be the mistake? A: First question: trigger The character needs only to have at least one level of a class which can cast the spell. In this case a first level wizard will be able to trigger any wizard spell. Second question: completion From the SRD: Scrolls To have any chance of activating a scroll spell, the scroll user must meet the following requirements. The spell must be of the correct type (arcane or divine). Arcane spellcasters (wizards, sorcerers, and bards) can only use scrolls containing arcane spells, and divine spellcasters (clerics, druids, paladins, and rangers) can only use scrolls containing divine spells. (The type of scroll a character creates is also determined by his class.) The user must have the spell on her class list. The user must have the requisite ability score. If the user meets all the requirements noted above, and her caster level is at least equal to the spell's caster level, she can automatically activate the spell without a check. This means that the character must be a spell caster of the correct type (arcane or divine): so no a fighter will not be able to use a scroll. If she meets all three requirements but her own caster level is lower than the scroll spell's caster level, then she has to make a caster level check (DC = scroll's caster level + 1) to cast the spell successfully. In this case: yes a first level wizard will be able to try with any arcane scroll (if he has the required Int) but he will have to perform an appropriate caster level with the following consequences: If she fails, she must make a DC 5 Wisdom check to avoid a mishap (see Scroll Mishaps). A natural roll of 1 always fails, whatever the modifiers. Activating a scroll is a standard action (or the spell's casting time, whichever is longer) and it provokes attacks of opportunity exactly as casting a spell does. Use magic device You can use this skill to read a spell or to activate a magic item. Use Magic Device lets you use a magic item as if you had the spell ability or class features of another class, as if you were a different race, or as if you were of a different alignment. This allow to override the first condition: even if you are not of the correct class (or have the wrong alignment and so on) and you have the use magic device skill you can do a check and try anyway. So in this case if your 20th level fighter is trained in use magic device: yes he can use a scroll
{ "pile_set_name": "StackExchange" }
Q: validating date format not working I'm having problem with date validation. In my View, I have a jQuery datepicker - I changed the format from yy/mm/dd to mm/dd/yy and now I get client-side validation errors. For example, The value '02/25/2014' is not valid for Date of Birth. The Javascript: $('#DateOfBirth').datepicker({ changeMonth: true, changeYear: true, dateFormat: "mm/dd/yy", yearRange: "-90:-5" }); The View Model: [Required] [Display(Name = "Date of Birth")] public DateTime? DateOfBirth { get; set; } The View: @Html.TextBoxFor(m=> m.DateOfBirth, "{0:MM/dd/yyyy}", new { @class = "datepicker" }) Any ideas on this? Thanks. UPDATE I overlooked something. The validation actually fails on the server side. So this has nothing to do with jQuery. The ModelState.IsValid == false for me. A: I found the solution here: ASP.NET MVC3 - DateTime format and it had to do with globalization. My locale is en-CA and System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern gives "dd/MM/yyyy". So in Web.config under <system.web> I included <globalization uiCulture="en-US" culture="en-US"/> So the DateTime format is working for me now. P.S. A safe way to pass dates without worrying about specific culture is to use ISO 8601 format - yyyy-MM-dd (or yyyy/MM/dd which also works).
{ "pile_set_name": "StackExchange" }
Q: Remove extra properties from object What would be the best way to remove any additional properties from an object that is not defined in defaults object? var defaults = { color : 'blue', size: 9, price : 40.00, instock : true }, newItem = { color: 'red', size : 4, price : 20.00 extra : invalid // discard this extra1 : invalid // discard this }, item = $.extend( defaults, newObject ) ; Desired output.... { color : 'red', size: 4, price : 20.00, instock : true } A: According to this performance comparison: https://jsperf.com/dictionary-contains-key The most efficient way to do this is: for(attr in newItem) { if(defaults[attr] === undefined) delete newItem[attr]; }
{ "pile_set_name": "StackExchange" }
Q: error when trying to build node.js in windows im trying to build node.js but i have problem . i downloaded 2 versions one from git and one from the site my configuration is : Python 3.2.2 visual studio express 2008 windows xp 32bit the errors when running vcbuild.bat: joyent-node-v0.7.7-49-g06ada03: File "configure", line 344 print "creating ", filename ^ SyntaxError: invalid syntax Failed to create vc project files. node-v0.6.15 File "tools\gyp_node", line 20 print 'Error running GYP' ^ SyntaxError: invalid syntax Failed to create vc project files. what im doing wrong here ? A: I think you have to use python2.6 or 2.7 according to the installation guide in the wiki.
{ "pile_set_name": "StackExchange" }
Q: Shuffling rows of an array as batches I have an array of dimension (m,n). The values in the first column of the array is common to a certain subset of rows, and I would like to randomly shuffle the rows of the entire array while keeping together the rows that share the same value in the first column. If I use numpy.random.shuffle() it shuffles all rows indiscriminately. But I want to ensure all rows with the same value in the first column remain together sequentially in the array. Any ad-hoc methods that I could create seem a bit cumbersome, but here is essentially my goal: Example input: array([[ 120325, 0.053, 4.23], [ 120325, 32.232, 5.2], [ 321, 243.4, 454], [ 321, 4533.4, 232], [ 321, 23.5, 108], [ 27, 0, 454], [ 27, 10, 32.0]]) output (which should be randomly shuffled in batches): array([[ 321, 243.4, 454], [ 321, 4533.4, 232], [ 321, 23.5, 108], [ 27, 0, 454], [ 27, 10, 32.0], [ 120325, 0.053, 4.23], [ 120325, 32.232, 5.2]]) A: You could use itertools.groupby() to accomplish this: x = [[ 120325, 0.053, 4.23], [ 120325, 32.232, 5.2], [ 321, 243.4, 454], [ 321, 4533.4, 232], [ 321, 23.5, 108], [ 27, 0, 454], [ 27, 10, 32.0]] together = [list(i) for _, i in itertools.groupby(x, operator.itemgetter(0))] # [[[120325, 0.053, 4.23], [120325, 32.232, 5.2]], [[321, 243.4, 454], [321, 4533.4, 232], [321, 23.5, 108]], [[27, 0, 454], [27, 10, 32.0]]] random.shuffle(together) final = [i for j in together for i in j] print(final) Output (several runs): [[321, 243.4, 454], [321, 4533.4, 232], [321, 23.5, 108], [27, 0, 454], [27, 10, 32.0], [120325, 0.053, 4.23], [120325, 32.232, 5.2]] [[120325, 0.053, 4.23], [120325, 32.232, 5.2], [321, 243.4, 454], [321, 4533.4, 232], [321, 23.5, 108], [27, 0, 454], [27, 10, 32.0]] [[27, 0, 454], [27, 10, 32.0], [120325, 0.053, 4.23], [120325, 32.232, 5.2], [321, 243.4, 454], [321, 4533.4, 232], [321, 23.5, 108]]
{ "pile_set_name": "StackExchange" }
Q: Activator.CreateInstance Performance Alternative I'm using RedGate to do some performance evaluation. I notice dynamically creating an instance using Activator.CreateInstance (with two constructor parameters) is taking a decent amount of time... is there a better alternative that still utilizes a reflective approach (not explicit instantiation)? A: Use a compiled lambda if you can, its MUCH faster. https://vagifabilov.wordpress.com/2010/04/02/dont-use-activator-createinstance-or-constructorinfo-invoke-use-compiled-lambda-expressions/ A: Don't forget about DynamicMethod Here's example how to create new instance thru default constructor public static ObjectActivator CreateCtor(Type type) { if (type == null) { throw new NullReferenceException("type"); } ConstructorInfo emptyConstructor = type.GetConstructor(Type.EmptyTypes); var dynamicMethod = new DynamicMethod("CreateInstance", type, Type.EmptyTypes, true); ILGenerator ilGenerator = dynamicMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Nop); ilGenerator.Emit(OpCodes.Newobj, emptyConstructor); ilGenerator.Emit(OpCodes.Ret); return (ObjectActivator)dynamicMethod.CreateDelegate(typeof(ObjectActivator)); } public delegate object ObjectActivator(); here's more about performance comparison Measuring InvokeMember... 1000000 iterations in 1.5643784 seconds. Measuring MethodInfo.Invoke... 1000000 iterations in 0.8150111 seconds. Measuring DynamicMethod... 1000000 iterations in 0.0330202 seconds. Measuring direct call... 1000000 iterations in 0.0136752 seconds. A: I have created a solution that can be used as a drop in replacement for Activator.CreateInstance. You can find it on my blog. Example: var myInstance = InstanceFactory.CreateInstance(typeof(MyClass)); var myArray1 = InstanceFactory.CreateInstance(typeof(int[]), 1024); var myArray2 = InstanceFactory.CreateInstance(typeof(int[]), new object[] { 1024 }); Code: public static class InstanceFactory { private delegate object CreateDelegate(Type type, object arg1, object arg2, object arg3); private static ConcurrentDictionary<Tuple<Type, Type, Type, Type>, CreateDelegate> cachedFuncs = new ConcurrentDictionary<Tuple<Type, Type, Type, Type>, CreateDelegate>(); public static object CreateInstance(Type type) { return InstanceFactoryGeneric<TypeToIgnore, TypeToIgnore, TypeToIgnore>.CreateInstance(type, null, null, null); } public static object CreateInstance<TArg1>(Type type, TArg1 arg1) { return InstanceFactoryGeneric<TArg1, TypeToIgnore, TypeToIgnore>.CreateInstance(type, arg1, null, null); } public static object CreateInstance<TArg1, TArg2>(Type type, TArg1 arg1, TArg2 arg2) { return InstanceFactoryGeneric<TArg1, TArg2, TypeToIgnore>.CreateInstance(type, arg1, arg2, null); } public static object CreateInstance<TArg1, TArg2, TArg3>(Type type, TArg1 arg1, TArg2 arg2, TArg3 arg3) { return InstanceFactoryGeneric<TArg1, TArg2, TArg3>.CreateInstance(type, arg1, arg2, arg3); } public static object CreateInstance(Type type, params object[] args) { if (args == null) return CreateInstance(type); if (args.Length > 3 || (args.Length > 0 && args[0] == null) || (args.Length > 1 && args[1] == null) || (args.Length > 2 && args[2] == null)) { return Activator.CreateInstance(type, args); } var arg0 = args.Length > 0 ? args[0] : null; var arg1 = args.Length > 1 ? args[1] : null; var arg2 = args.Length > 2 ? args[2] : null; var key = Tuple.Create( type, arg0?.GetType() ?? typeof(TypeToIgnore), arg1?.GetType() ?? typeof(TypeToIgnore), arg2?.GetType() ?? typeof(TypeToIgnore)); if (cachedFuncs.TryGetValue(key, out CreateDelegate func)) return func(type, arg0, arg1, arg2); else return CacheFunc(key)(type, arg0, arg1, arg2); } private static CreateDelegate CacheFunc(Tuple<Type, Type, Type, Type> key) { var types = new Type[] { key.Item1, key.Item2, key.Item3, key.Item4 }; var method = typeof(InstanceFactory).GetMethods() .Where(m => m.Name == "CreateInstance") .Where(m => m.GetParameters().Count() == 4).Single(); var generic = method.MakeGenericMethod(new Type[] { key.Item2, key.Item3, key.Item4 }); var paramExpr = new List<ParameterExpression>(); paramExpr.Add(Expression.Parameter(typeof(Type))); for (int i = 0; i < 3; i++) paramExpr.Add(Expression.Parameter(typeof(object))); var callParamExpr = new List<Expression>(); callParamExpr.Add(paramExpr[0]); for (int i = 1; i < 4; i++) callParamExpr.Add(Expression.Convert(paramExpr[i], types[i])); var callExpr = Expression.Call(generic, callParamExpr); var lambdaExpr = Expression.Lambda<CreateDelegate>(callExpr, paramExpr); var func = lambdaExpr.Compile(); cachedFuncs.TryAdd(key, func); return func; } } public static class InstanceFactoryGeneric<TArg1, TArg2, TArg3> { private static ConcurrentDictionary<Type, Func<TArg1, TArg2, TArg3, object>> cachedFuncs = new ConcurrentDictionary<Type, Func<TArg1, TArg2, TArg3, object>>(); public static object CreateInstance(Type type, TArg1 arg1, TArg2 arg2, TArg3 arg3) { if (cachedFuncs.TryGetValue(type, out Func<TArg1, TArg2, TArg3, object> func)) return func(arg1, arg2, arg3); else return CacheFunc(type, arg1, arg2, arg3)(arg1, arg2, arg3); } private static Func<TArg1, TArg2, TArg3, object> CacheFunc(Type type, TArg1 arg1, TArg2 arg2, TArg3 arg3) { var constructorTypes = new List<Type>(); if (typeof(TArg1) != typeof(TypeToIgnore)) constructorTypes.Add(typeof(TArg1)); if (typeof(TArg2) != typeof(TypeToIgnore)) constructorTypes.Add(typeof(TArg2)); if (typeof(TArg3) != typeof(TypeToIgnore)) constructorTypes.Add(typeof(TArg3)); var parameters = new List<ParameterExpression>() { Expression.Parameter(typeof(TArg1)), Expression.Parameter(typeof(TArg2)), Expression.Parameter(typeof(TArg3)), }; var constructor = type.GetConstructor(constructorTypes.ToArray()); var constructorParameters = parameters.Take(constructorTypes.Count).ToList(); var newExpr = Expression.New(constructor, constructorParameters); var lambdaExpr = Expression.Lambda<Func<TArg1, TArg2, TArg3, object>>(newExpr, parameters); var func = lambdaExpr.Compile(); cachedFuncs.TryAdd(type, func); return func; } } public class TypeToIgnore { }
{ "pile_set_name": "StackExchange" }
Q: How do I edit a interface for a 4 inch iPhone while not editing the 3.5 inch So I've made this app, and while submitting I needed to grab 4' screenshots. I based my app to run on 3,5 inch devices, so I thought, when I'd run it on a 4' there could be letterboxes. Somehow the interface adapted itself to the 4' screen, but images and labels were misplaced. When I edit the .xib to look good on the 4' screen the exact opposite happens on the 3.5 screen. Stuff get's misplaced. While creating my project ( About 20 .xib's ) I always chose "3.5' screen" instead of "Freeform" or the default "4' screen". Now how do I change it to look good on both screen sizes? Isn't there a way to edit a xib for both sized without having to rebuild it? A: Duplicate each XIB and give it a suffix, for example MyViewController.xib -> MyViewController_568.xib Re-arrange the new XIBs Over-ride initWithNib - (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle { if ([UIScreen mainScreen].bounds.size.height > 480) { nibName = [NSString stringWithFormat:@"%@_568", nibName]; } if (self = [super initWithNibName:nibName bundle:nibBundle]) { } return self; }
{ "pile_set_name": "StackExchange" }
Q: wpf ObjectDataProvider method parameter bind to combobox selected value I'm dealing with a problem in WPF binding. I'm creating a user control which present a datagrid, fiiltered by 2 possible values. The first value is set by a textbox, the second one by a combo box. I'm using an ObjectDataProvider to map a methos with 2 parameters, and the textbox and the combobox should set these 2 parameters. Here's the code. <UserControl x:Class="VisualHorse.Corse" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:VisualHorse" xmlns:system="clr-namespace:System;assembly=mscorlib" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="530" Loaded="UserControl_Loaded"> <UserControl.Resources> <ObjectDataProvider x:Key="HorseDataProvider" ObjectType="{x:Type local:HorseDataProvider}" MethodName="GetCorse" > <ObjectDataProvider.MethodParameters> <x:Static Member="system:String.Empty" /> <x:Static Member="system:String.Empty" /> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </UserControl.Resources> <StackPanel > <Grid Name="GRIDFilter" Height="50"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Label Content="Data corsa" HorizontalAlignment="Center" Name="label1" VerticalAlignment="Center" /> <Label Content="Località" Grid.Column="1" HorizontalAlignment="Center" Name="label2" VerticalAlignment="Center" /> <Label Content="N° Corsa" Grid.Column="2" HorizontalAlignment="Center" Name="label3" VerticalAlignment="Center" /> <Button Content="Filtra" Grid.Column="3" Grid.RowSpan="2" Width="50" Height="30" /> <DatePicker Grid.Row="1" HorizontalAlignment="Center" Name="DPDataCorsa" VerticalAlignment="Center" Width="115" /> <ComboBox Grid.Column="1" Grid.Row="1" HorizontalAlignment="Stretch" Name="CBlocalita" VerticalAlignment="Center" Margin="5,0" > <ComboBox.SelectedValue> <Binding Source="{StaticResource HorseDataProvider}" Path="MethodParameters[0]" BindsDirectlyToSource="true"/> </ComboBox.SelectedValue> </ComboBox> <TextBox Name="TBNumCorsa" Grid.Column="2" Grid.Row="1" Margin="5,0" > <Binding Source="{StaticResource HorseDataProvider}" Path="MethodParameters[1]" BindsDirectlyToSource="true" UpdateSourceTrigger="PropertyChanged" /> </TextBox> </Grid> <DataGrid Name="DGCorse" ItemsSource="{Binding Source={StaticResource HorseDataProvider}}" AutoGenerateColumns="False" Margin="0,10,0,0" CanUserResizeRows="False" SelectionMode="Single"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Path=Localita.descrizione}" Header="Località" /> <DataGridTextColumn Binding="{Binding Path=data, StringFormat=\{0:d\}}" Header="Data Corsa" /> <DataGridTextColumn Binding="{Binding Path=numero}" Header="N° Corsa" /> <DataGridTextColumn Binding="{Binding Path=TipoCorsa.descrizione}" Header="Tipo corsa" /> <DataGridTextColumn Binding="{Binding Path=TipoTerreno.descrizione}" Header="Terreno" /> <DataGridTextColumn Binding="{Binding Path=TipoFantino.descrizione}" Header="Tipo fantino" /> <DataGridTextColumn Binding="{Binding Path=premio, StringFormat=\{0:c\}}" Header="Premio" /> <DataGridTextColumn Binding="{Binding Path=distacchi}" Header="Distacchi" /> <DataGridTextColumn Binding="{Binding Path=distanza}" Header="Distanza" /> <DataGridTextColumn Binding="{Binding Path=TipoPista.descrizione}" Header="Pista" /> <DataGridTextColumn Binding="{Binding Path=Eta.descrizione}" Header="Età" /> </DataGrid.Columns> </DataGrid> </StackPanel> What's wrong with it? Everything works fine if I just bind the textbox property, but trying to bind the Combobox.SeletedValue property to the first method parameter it throws an exception (silently handled by the wpf engine): System.Windows.Data Error: 35 : ObjectDataProvider: Failure trying to invoke method on type; Method='GetCorse'; Type='HorseDataProvider'; Error='No method was found with matching parameter signature.' MissingMethodException:'System.MissingMethodException: Method 'VisualHorse.HorseDataProvider.GetCorse' not found. at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Windows.Data.ObjectDataProvider.InvokeMethodOnInstance(Exception& e)' Any help would be appreciated A: Ok, I found the issue on my approach. Simply, I didn't get that the ComboBox.SelectedValue type depends on how I populate the combobox (wich I did in code behind). Simply modifying the ObjectDataProvider definition in the following way, resolved the problem: <ObjectDataProvider x:Key="HorseDataProvider" ObjectType="{x:Type local:HorseDataProvider}" MethodName="GetCorse" > <ObjectDataProvider.MethodParameters> <system:Int32>0</system:Int32> <x:Static Member="system:String.Empty" /> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> This way the ComboBox.SelectedItem is bound to an Int32 method parameter.
{ "pile_set_name": "StackExchange" }
Q: Control A Representation in Python/Scala In Python "^A" is represented by chr(1). This is what I use as a separator in myfiles. What is the equivalent in Scala.I am reading the file using scala. I want to know how to represent ^A in order to split the data i read from my files. A: ^A is usually used to represent the Start Of Header Character (SOH). It's ascii value is x01. You can create this in code with val c: Char = 1, if it's more clear to you, or if you need it in a string literal you can use the unicode notation '\u0001'
{ "pile_set_name": "StackExchange" }
Q: Why does fermat little theorem work? I'm trying to understand intuitively why (p-1)th power of any integer(not divisible by p) leaves a remainder of 1 when divided by p. (where p is a prime number) I understand that p times any integer becomes a multiple of p and would be divided p. Similarly, can I understand the growth of the exponential function and reason why p-1 th power of any integer is always congruent to 1 mod p. A: Your intuition to understand this result by analogy to a multiple of $p$ being divisible by $p$ will not work in this case. The standard explanation runs like this: For any number $a$ which is not divisible by $p$, we know that $a\equiv A \bmod p$ where $1\le A \le (p-1)$. Next, we look at the products $1\cdot A,\ 2\cdot A,\ 3\cdot A,\dots (p-1)\cdot A$. There are $(p-1)$ such products, and none of them have any factors of $p$. We look at those products and ask if any two of them can have the same value $\bmod p$. The answer is no, because if they did their difference would have to be $0\bmod p$. That is, $c_2\cdot A-c_1\cdot A \equiv 0 \bmod p \iff c_2=c_1$ and that is not the case. We have $(p-1)$ distinct products having values between $1$ and $(p-1)$, so by the pigeonhole principle, each value must occur once. We don't know which product corresponds to which value, but we don't need to. We simply multiply the residues of the products $1$ through $(p-1)$ to obtain $(p-1)!$, and then products $1\cdot A$ through $(p-1)\cdot A$ themselves to obtain $(p-1)!A^{p-1}$, keeping in mind that these two numbers will be equivalent $\bmod p$, viz $$(p-1)!\equiv (p-1)!A^{p-1} \bmod p$$ Since $(p-1)!$ is coprime to $p$, we can divide through to remove it leaving the desired result $$1\equiv A^{p-1}\equiv a^{p-1} \bmod p$$ A: It might help you to study a few specific cases. For example, $a = 10$, $p = 7$. We see that $10^6 = 1000000$ and 999999 divided by 7 is 142857. But let's work through this example using smaller numbers. Obviously $10^2 = 100$. But 98 is a multiple of 7, which means that $10^2 \equiv 2$ $\pmod 7$. And 10 itself is $3 \pmod 7$, so we can calculate $10^3 \equiv ?$ $\pmod 7$ as $2 \times 3 = 6$. And then $10^4 \equiv 6 \times 3 \equiv 4 \pmod 7$. Next we have $10^5 \equiv 4 \times 3 \equiv 5 \pmod 7$. Lastly, $10^6 \equiv 5 \times 3 \equiv 1 \pmod 7$, which we had already confirmed. I chose this example because $10^n$ modulo 7 takes on every value from 0 to 6 except 0. That's not always the case, but it helps to show which values can't be taken on. Now consider instead $p = 14$, which is clearly not prime, and $a$ the same as before. You might be aware of the fact that 14 is not a Fermat pseudoprime. But much more importantly in this example, $\gcd(10, 14) = 2$, so we will see that $10^{13} \not\equiv 1 \pmod{14}$. Then we see that $10 \equiv 10 \pmod{14}$, which is obvious but needs to be said, because $10^2 \equiv 2 \pmod{14}$ just the same as modulo 7. Then $10^3 \equiv 6 \pmod{14}$, $10^4 \equiv 4 \pmod{14}$, $10^5 \equiv 12 \pmod{14}$, $10^6 \equiv 8 \pmod{14}$, $10^7 \equiv 10 \pmod{14}$, $10^8 \equiv 2 \pmod{14}$... whoa, we're back to 2. The common divisor between 10 and 14 is 2, which means that odd numbers (coprime to 2) can't occur in $10^n \equiv ? \pmod{14}$. I hope this helps you understand. You might also want to work through examples where $p$ is composite but nonetheless coprime to $a$. Probably hold off on numbers like 341, 561 for now, though.
{ "pile_set_name": "StackExchange" }
Q: why main method in static nested class runs instead of outer class? In the give code snippet, only the main method of nested static class run, but not of the outer class. Why so? package pack; public class MyOuterClass { public static void main(String[] args) { System.out.println("main method of Outer Class..."); } static class MyInnerClass { public static void main(String[] args) { System.out.println("main method of Static Nested Class..."); } } } A: It depends on your command: java pack.MyOuterClass => Output: main method of Outer Class... java pack.MyOuterClass$MyInnerClass => Output: main method of Static Nested Class...
{ "pile_set_name": "StackExchange" }
Q: How to use for each in jquery? var attr = {node:"<tr> ,id=tr1$<td>,colspan=2,style.width=100%$<div>,id=divlistudcitems$<select>,id=lstListUdcItems,name=lstListUdcItems,size=12,style.width=100%;"} in the above code i will pass the value of attr to a function createHTML where i need to iterate each and every tag (tr,td,div)using jquery for each. Could anyone advice how to acheive this. var root=document.getElementById("target") createHTML(root,attr); A: Try to use this: <xsl:for-each select="subclass"> <xsl:value-of select ="local-name()"/> </xsl:for-each> Or <xsl:for-each select="subclass"> <xsl:value-of select ="name(.)"/> </xsl:for-each>
{ "pile_set_name": "StackExchange" }
Q: How can I change serialized data using the best_in_place gem? I have a model with serialized data and I want to edit this data using the best_in_place gem. This isn't possible by default when using the best_in_place gem. How can this be done? A: It can be done by extending method_missing and respond_to_missing? to forward the requests to the serialized data. Lets say you have your serialized Hash in data. In the class that's containing the serialized data you can for example use this code: def method_missing(method_name, *arguments, &block) # forewards the arguments to the correct methods if method_name.to_s =~ /data_(.+)\=/ key = method_name.to_s.match(/data_(.+)=/)[1] self.send('data_setter=', key, arguments.first) elsif method_name.to_s =~ /data_(.+)/ key = method_name.to_s.match(/data_(.+)/)[1] self.send('data_getter', column_number) else super end end def respond_to_missing?(method_name, include_private = false) # prevents giving UndefinedMethod error method_name.to_s.start_with?('data_') || super end def data_getter(key) self.data[key.to_i] if self.data.kind_of?(Array) self.data[key.to_sym] if self.data.kind_of?(Hash) end def data_setter(key, value) self.data[key.to_i] = value if self.data.kind_of?(Array) self.data[key.to_sym] = value if self.data.kind_of?(Hash) value # the method returns value because best_in_place sets the returned value as text end Now you can access the object.data[:name] using the getter object.data_name and set value using the setter object.data_name="test". But to get this working using best_in_place you need to dynamicly add it to the attr_accessible list. To do this you need to change the behavior of the mass_assignment_authorizer and make the object respond to accessable_methods with an array of method names that should be allowed to be edited like this: def accessable_methods # returns a list of all the methods that are responded dynamicly self.data.keys.map{|x| "data_#{x.to_s}".to_sym } end private def mass_assignment_authorizer(user) # adds the list to the accessible list. super + self.accessable_methods end So in the View you can now call best_in_place @object, :data_name To edit the serialized data of @object.data[:name] // You can also do this for an array using the element index instead of the attribute name: <% @object.data.count.times do |index| %> <%= best_in_place @object, "data_#{index}".to_sym %> <% end %> You dont need to change the rest of the code.
{ "pile_set_name": "StackExchange" }
Q: How to make text of a button change according to a condition(C#) I am working on a project in VS C#, but I need some help. I have a Horizontal Split Container, Panel 1 of which contains a Menu Strip, and Panel 2 contains 2 more panels, Panel 1 of which acts like a Sidebar. I have added a button in the Menu Strip, which aims to hide or show the sidebar, depending on the condition splitContainer2.Panel1Collapsed == false. However, I want the text of the button to change accordingly - eg. from "Hide Sidebar" to "Show Sidebar". How should I do this? Here is all the code: private void hideSidePanelToolStripMenuItem_Click(object sender, EventArgs e) { if (splitContainer2.Panel1Collapsed == false) { splitContainer2.Panel1Collapsed = true; } else splitContainer2.Panel1Collapsed = false; } And here is a Screenshot: Something like this. I am unable to show the list of the View button, because of the program I am using, but I hope you get the point. A: You need to change the .Text property of the Button / ToolStripItem: private void hideSidePanelToolStripMenuItem_Click(object sender, EventArgs e) { if (splitContainer2.Panel1Collapsed == false) { splitContainer2.Panel1Collapsed = true; hideSidePanelToolStripMenuItem.Text = "Show Sidebar" } else { splitContainer2.Panel1Collapsed = false; hideSidePanelToolStripMenuItem.Text = "Hide Sidebar" }
{ "pile_set_name": "StackExchange" }
Q: Proving a set is uncountable. I need to prove that the set of all functions $\mathcal{F}:\mathbb{N}\rightarrow \left \{ 0,1 \right \}$ is uncountable. I'm not too sure at all how to do this. My initial idea was to try and show that $\mathcal{F} \rightarrow \mathbb{N}$ was not a bijection but I'm not clear at all and need some big help. Thanks!!! A: I will NOT make this a proof by contradiction. Let $f_1,f_2,f_3,\ldots$ be any sequence of such sequences. Thus $f_1$ is the sequence $f_1(1),f_1(2),f_1(3),\ldots$. Try to show that the sequence $(1-f_k(k))_{k=1}^\infty$ is not one of the sequences $f_1,f_2,f_3,\ldots$ although is is a member of $\mathcal F$.
{ "pile_set_name": "StackExchange" }
Q: Google Collections ImmutableMap iteration order I need combination of Google Collection ImmutableMap and LinkedHashMap — immutable map with defined iteration order. It seems that ImmutableMap itself actually has defined iteration order, at least its documentation says: An immutable, hash-based Map with reliable user-specified iteration order. However there are no more details. Quick test shows that this might be true, but I want to make sure. My question is: can I rely on iteration order of ImmutableMap? If I do ImmutableMap.copyOf(linkedHashMap), will it have same iteration order as original linked hash map? What about immutable maps created by builder? Some link to authoritative answer would help, since Google didn't find anything useful. (And no, links to the sources don't count). A: I've actually found discussion about this, with answers from library authors: Kevin Bourrillion: What we mean by "user-specified" is "it can be whatever order you want it to be"; in other words, whatever order you provide the entries to us in the first place, that's the order we use. Jared Levy: You can also copy a TreeMap or LinkedHashMap that have the desired order. Yes, I should have believed the javadoc, although I think that javadoc can be better in this case. It seems I'm not first who was confused by it. If nothing else, this Q/A will help Google next time someone searches for "ImmutableMap iteration" :-) A: To be more precise, the ImmutableMap factory methods and builder return instances that follow the iteration order of the inputs provided when the map in constructed. However, an ImmutableSortedMap, which is a subclass of ImmutableMap. sorts the keys. A: You should believe the javadoc. If it is not enough, read the source code or report the bug. A quick view to the source code shows that the map is backed by array and iteration will be done through ImmutableSet that is also backed by an array. So I think the documentation is correct and the order of the elements will be kept as it is.
{ "pile_set_name": "StackExchange" }
Q: Rails where clause in a many to many i have two many to many models and another Storetypes: class Storetype < ActiveRecord::Base has_and_belongs_to_many :stores end Stores: class Store < ActiveRecord::Base belongs_to :group has_many :products end Groups: class Group < ActiveRecord::Base has_many :stores has_many :storetypes end I need to do a query where i get all the stores on a storetype, im doing something like this: @storetype_id = Storetype.first @stores = @group.stores.where(@storetype_id => @group.stores) any thoughts? EDIT The output i need is all the stores that belong to a certain storetype A: Few problems here that I'll point out. I assume you mean Storetype.first when you say @storetype.first. You're confusing the class and an instance of the class. So say I do this: @storetype = Storetype.first I'm creating an instance of the class Storetype, which is your model. Get me? So to answer your question, once I have an instance, I can now simply run @storetype.stores to all the stores on that storetype. See how I went the other way to your method? I also didn't need to use the id of the storetype at all. Much easier and cleaner. For the other part of the relationship, to get all the storetypes of a store, you simply run (with an instance of Store) @store.storetypes
{ "pile_set_name": "StackExchange" }
Q: Can I hire someone to haul my waste monthly? Can I hire an independent contractor to haul my waste in my city of Colusa, California. Someone said there is an exclusive contract that prevents the hauling of ones own waste to a landfill. A: Sec. 14-3 of the city ordinances says that No person may engage in the business of collecting recyclable materials, solid waste or green waste within the city, or haul recyclable materials, solid waste or green waste through a street or public right-of-way in the city, unless that person has been granted a franchise or license to do so by the city. However, a property owner may occasionally transport recyclable materials, solid waste or green waste produced on his or her own premises to a licensed disposal area, subject to the requirements of Section 14-7 pertaining to solid waste transportation So that means you can't contract with someone else to haul your trash. You can do it yourself if you can follow the various regulations pertaining to transportation of waste.
{ "pile_set_name": "StackExchange" }
Q: How to send -Dflag to android app Is there a way to send -D directives to an android app? On desktop java I would just do java -Dsomeflag=value. How would you do this on android? I am building with eclipse. A: I assume you want to do this because you want to have conditional if blocks for debugging. You can set android:debuggable="true" in your manifest: <application android:icon="@drawable/icon" android:name=".SomeApp" android:label="@string/app_name" android:debuggable="true"> and then test for it like this: if(Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "some log statement"); }
{ "pile_set_name": "StackExchange" }
Q: Let A be a real symmetric matrix congruent to $I_n$. Show that all A's eigenvalues are positive. If A is a real symmetric matrix congruent to $I_n$, show that all eigenvalues of A are positive. This exercise induces me to use the Sylvester's Law of Inertia: https://en.wikipedia.org/wiki/Sylvester's_law_of_inertia. The fact that they are congruent implies that they have the same inertia. And since the inertia of $I_n$ has only positive eigenvalues, this induces that A have only positive eigenvalues. But i think that i could solve it in a different way. Here it is: Consider: $x^tAx$. Since A is congruent to the identity matrix, there exists an invertible matrix P such that: $x^tAx=x^t(PIP^t)x = x^t(PP^t)x = (P^tx)^tP^tx= \langle P^tx, P^tx \rangle.$ Since $P^tx \neq0$ and$ \langle P^tx, P^tx \rangle \gt0 $, this shows that $x^tAx \gt0$. Hence, A is a positive-definite matrix and then all its eigenvalues are positive. Is it correct? A: You are on the right track (using inner product) except that eigenvalues of $A$ do not appear in your argument at all. You might want $x$ to be an eigenvector of $A$. You proof is correct. (Except that I would write "Consider $x^tAx$ with $x\neq 0$".) Essentially you are using the following fact: If $A$ is positive definite, then all its eigenvalues are positive. To show the fact above, one just needs to calculate $\langle v,Av\rangle$ with $Av=\lambda v$.
{ "pile_set_name": "StackExchange" }
Q: Automated hyperparmeter optimization in h2o flow ui Is there a way to automate hyper-parameter optimization for models in H2O's Flow UI, such as how python's scikit-learn package includes GridGridSearchCV and RandomizedSearchCV? Thanks A: You can find out how to use Grid Search in Flow here. (Use CV in your grid search by setting nfolds > 1.) H2O also supports Random (Grid) Search through the programmatic APIs, but it's not currently supported via Flow, so I created a JIRA for that. More info on that at the Grid Search section of the H2O User Guide.
{ "pile_set_name": "StackExchange" }
Q: Trying to recreate the .isFunction() from the jQuery source I'm trying to learn some thing from jQuery source by breaking some pieces apart. Right now I'm going over the isFunction. In my code test is instead of jQuery. The problem is that isFunction is telling me that stub is not a function by outputting false stub is a function. I noticed that jquery doesn't use the this in return this.type(obj) === "function" like in my code and instead of writing the code in test.prototype ={, jQuery writes it in jQuery.extend({ maybe that's my problem? I didnt include extend function. Try to keep the answer like jQuery's source code structure I know my code is a little different. Also, Do you know of a smaller library like jQuery that I could use to learn from? I don't need to learn about AJAX and promises right now I just want to learn about structure of code and DOM manipulation.There's so much information in jQuery. var test = function(){ } var class2type = {}; test.prototype ={ type : function(obj){ if(obj == null){ return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, isFunction :function(obj){ return this.type(obj) === "function" } } var stub = function stub(){} console.log(typeof stub) console.log(test.prototype.isFunction(stub)) A: You're missing the declaration for class2type. Basically, what's happening is that class2type[toString.call(obj)] is returning undefined, so test.prototype.type(stub) returns "object", which is not equal to "function", so test.prototype.isFunction(stub) returns false. To fix it, add this to class2type: class2type = { '[object Function]': 'function' };
{ "pile_set_name": "StackExchange" }
Q: Progress bar on scroll not working in Wordpress I'm trying to create a progress bar that fills on scroll. I used a piece of code that I found in W3Schools and made a few changes (and it worked in this code snippet but not on my page). // When the user scrolls the page, execute myFunction window.onscroll = function() { myFunction() }; function myFunction() { var winScroll = document.body.scrollTop || document.documentElement.scrollTop; var height = document.documentElement.scrollHeight - document.documentElement.clientHeight; var scrolled = (winScroll / height) * 100; document.getElementById("progressBar").style.width = scrolled + "%"; } body { margin: 0; font-size: 28px; font-family: Arial, Helvetica, sans-serif; } .header { position: fixed; top: 0; z-index: 1; width: 100%; background-color: #f1f1f1; } .header h2 { text-align: center; } #progressBar { top: 0; left: 0; width: 0%; height: 5px; position: fixed; background-color: red; z-index: 10; } .content { padding: 100px 0; margin: 50px auto 0 auto; width: 80%; } <div class="header"> <h2>Scroll Indicator</h2> <div id="progressBar"></div> </div> <div class="content"> <h3>Scroll Down to See The Effect</h3> <p>We have created a "progress bar" to <b>show how far a page has been scrolled</b>.</p> <p>It also <b>works when you scroll back up</b>.</p> <p>It is even <b>responsive</b>! Resize the browser window to see the effect.</p> <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p> <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p> <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p> <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p> <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p> <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p> <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p> <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p> <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p> <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p> </div> A: So I answer this based on the website you provided, not on the actual code you provided. if you change your css for <section> from: height:100vh; to min-height: 100vh; it is working without breaking anything ;-) cheers
{ "pile_set_name": "StackExchange" }
Q: Cannot defer close request body Any idea why I cannot close request body? Request is returning 200 and no error but req.Body.Close() is throwhing runtime error: invalid memory address or nil pointer dereference clientHttp := &http.Client{} req, err := http.NewRequest("GET", "https://example.com/item/"+strconv.FormatInt(itemID, 10), nil) if err != nil { logrus.Error(err) return models.Company{}, err } resp, err := clientHttp.Do(req) if err != nil { logrus.Error(err) return models.Company{}, err } defer req.Body.Close() // <- panic! A: The application should close the response body, not the request body: defer resp.Body.Close() The req.Body field is set from the last argument to http.NewRequest. The req.Body field is nil because the last argument to http.NewRequest is nil. The transport closes the request body (if it's not nil) per the documentation for Request.Body: For client requests, a nil body means the request has no body, such as a GET request. The HTTP Client's Transport is responsible for calling the Close method. A: req is a GET request. It has no body, so req.Body is nil. That's why you're getting a nil pointer dereference. Do not close req.Body.
{ "pile_set_name": "StackExchange" }
Q: Enable a button in the parent wx.Frame I need help to enable a button in the parent wx.Frame, here i have an example of two classed first class mainFrame has two buttons first one m_buttonlogin to launch the second wx.Frame class instance loginFrame and another disabled button. what i need to do is upon successful login in the child Frame the disabled button turns enabled in the main frame. # -*- coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version Jun 17 2015) ## http://www.wxformbuilder.org/ ## ## PLEASE DO "NOT" EDIT THIS FILE! ########################################################################### import wx import wx.xrc ########################################################################### ## Class mainFrame ########################################################################### class mainFrame ( wx.Frame ): def __init__( self, parent ): wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize ) bSizer1 = wx.BoxSizer( wx.VERTICAL ) self.m_buttonlogin = wx.Button( self, wx.ID_ANY, u"Login", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer1.Add( self.m_buttonlogin, 0, wx.ALL, 5 ) self.m_buttondisabled = wx.Button( self, wx.ID_ANY, u"Dsiabled", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_buttondisabled.Enable( False ) bSizer1.Add( self.m_buttondisabled, 0, wx.ALL, 5 ) self.SetSizer( bSizer1 ) self.Layout() self.Centre( wx.BOTH ) # Connect Events self.m_buttonlogin.Bind( wx.EVT_BUTTON, self.OnLogin ) def __del__( self ): pass # Virtual event handlers, overide them in your derived class def OnLogin( self, event ): loginFrame.Show(self) event.Skip() ########################################################################### ## Class loginFrame ########################################################################### class loginFrame ( wx.Frame ): def __init__( self, parent ): wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize ) bSizer2 = wx.BoxSizer( wx.VERTICAL ) self.m_textCtrlusername = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer2.Add( self.m_textCtrlusername, 0, wx.ALL, 5 ) self.m_textCtrlpassword = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer2.Add( self.m_textCtrlpassword, 0, wx.ALL, 5 ) self.m_buttonOK = wx.Button( self, wx.ID_ANY, u"OK", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer2.Add( self.m_buttonOK, 0, wx.ALL, 5 ) self.SetSizer( bSizer2 ) self.Layout() self.Centre( wx.BOTH ) # Connect Events self.m_buttonOK.Bind( wx.EVT_BUTTON, self.OnOK ) def __del__( self ): pass # Virtual event handlers, overide them in your derived class def OnOK( self, event ): # Enable "m_buttondisabled" button in the mainFrame event.Skip() Thanks. A: An simple way to achieve this is to make use of the parent attribute in the loginFrame. import wx import wx.xrc ########################################################################### ## Class mainFrame ########################################################################### class mainFrame ( wx.Frame ): def __init__( self, parent ): wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) bSizer1 = wx.BoxSizer( wx.VERTICAL ) self.m_buttonlogin = wx.Button( self, wx.ID_ANY, u"Login", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer1.Add( self.m_buttonlogin, 0, wx.ALL, 5 ) self.m_buttondisabled = wx.Button( self, wx.ID_ANY, u"Disabled", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_buttondisabled.Enable( False ) bSizer1.Add( self.m_buttondisabled, 0, wx.ALL, 5 ) self.SetSizer( bSizer1 ) self.Layout() self.Centre( wx.BOTH ) # Connect Events self.m_buttonlogin.Bind( wx.EVT_BUTTON, self.OnLogin ) def __del__( self ): pass # Virtual event handlers, overide them in your derived class def OnLogin( self, event ): loginFrame(self).Show() event.Skip() ########################################################################### ## Class loginFrame ########################################################################### class loginFrame ( wx.Frame ): def __init__( self, parent ): wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.parent = parent self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) bSizer2 = wx.BoxSizer( wx.VERTICAL ) self.m_textCtrlusername = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer2.Add( self.m_textCtrlusername, 0, wx.ALL, 5 ) self.m_textCtrlpassword = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer2.Add( self.m_textCtrlpassword, 0, wx.ALL, 5 ) self.m_buttonOK = wx.Button( self, wx.ID_ANY, u"OK", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer2.Add( self.m_buttonOK, 0, wx.ALL, 5 ) self.SetSizer( bSizer2 ) self.Layout() self.Centre( wx.BOTH ) # Connect Events self.m_buttonOK.Bind( wx.EVT_BUTTON, self.OnOK ) def __del__( self ): pass # Virtual event handlers, overide them in your derived class def OnOK( self, event ): # Enable "m_buttondisabled" button in the mainFrame self.parent.m_buttondisabled.Enable( True ) self.parent.m_buttonlogin.Enable( False) event.Skip() app = wx.App() frame = mainFrame(None) frame.Show() app.MainLoop()
{ "pile_set_name": "StackExchange" }
Q: Can this network system Work properly? I have connected two different LANs with their own ISPs. I have two wireless routers with #1 router lan port connected to lan port of #2 router. Now:- 1 router: - Lan Ip address = 192.168.0.1 Subnet Mask= 255.255.255.0 DHCP=ON POOL= 192.168.0.10 to 192.168.0.110 Added static route to 192.168.1.0 via the gateway 192.168.1.1 ISP=WISHNET BROADBAND. 2 router: - Lan Ip address = 192.168.1.1 Subnet Mask= 255.255.255.0 DHCP=ON POOL= 192.168.1.10 to 192.168.1.110 Added static route to 192.168.0.0 via the gateway 192.168.0.1 ISP=AIRTEL 4G LTE WILL THIS SYSTEM WORK WITHOUT ANY PROBLEMS? PLEASE COMMENT I AM TOTALLY CONFUSED !!! A: Yeah they'll work independently, but they will never see each other as they are are separate networks, for 0.0 to see 1.0 you need one router to be in both IP networks.
{ "pile_set_name": "StackExchange" }
Q: Update query string in url I want to update the url query string by clicking on checkbox. Here's the code, it doesn't work correctly param1=param1=true param1=param1=param1=false param1=param1=param1=param1=true instead of: param1=false param1=true Here's an unrefactored code: if (this.checked) { if (window.location.href.search('[?&]') === -1) { window.history.pushState('object or string', 'Title', window.location.href + '?param1=true'); } else { window.history.pushState('object or string', 'Title', window.location.href.replace(/param1=false|true/i, 'param1=true')); } } else { if (window.location.href.search('[?&]') === -1) { window.history.pushState('object or string', 'Title', window.location.href + '?param1=false'); } else { window.history.pushState('object or string', 'Title', window.location.href.replace(/param1=false|true/i, 'param1=false')); } } A: Consider this: > 'param1=false'.replace(/param1=false|true/i, 'param1=true') "param1=true" > 'param1=true'.replace(/param1=false|true/i, 'param1=true') "param1=param1=true" > 'true'.replace(/param1=false|true/i, 'param1=true') "param1=true" The thing is that your regular expression is accepting either param1=false or just true. You need to put the false|true part in a group (in parentheses) to make the | not apply to the param1= part too. So your regular expression should be /param1=(false|true)/i: > 'param1=true'.replace(/param1=(false|true)/i, 'param1=true') 'param1=true'
{ "pile_set_name": "StackExchange" }
Q: ggplot facet_wrap selected columns of data.frame? I have a data.frame X which contains point/sample coordinates X1 and X2: > head(X) X1 X2 Cluster Timepoint Transcripts MEF ESC Drop_6_6A_0_TACCTAATCTAC 169.3437 20.18623 2 Day 0 49688 0.4366071 0.3260743 Drop_6_6A_0_TCAGCTTGTCAC 155.8880 -16.69927 3 Day 0 47365 0.4554254 0.3350818 Drop_6_6A_0_TCGCAATAAGAT 168.4270 36.50967 2 Day 0 44881 0.4114934 0.2595030 Drop_6_6A_0_AATCTACCAATC 164.3964 -27.17404 3 Day 0 44640 0.4748225 0.3525822 Drop_6_6A_0_GGATTAAGTTCA 162.2900 -24.10504 3 Day 0 36822 0.4723676 0.3391785 Drop_6_6A_0_TGATCTAGTGTC 155.4231 -19.18974 3 Day 0 35889 0.4664174 0.3408899 I would like to add selected markers as columns to X and size the points on a scatter plot according to the associated expression value. NANOG = t(data['NANOG',rownames(X)]) SAL4 = t(data['SAL4',rownames(X)]) COL5A2 = t(data['COL5A2',rownames(X)]) ESRRB = t(data['ESRRB',rownames(X)]) ELN = t(data['ELN',rownames(X)]) POU5f1 = t(data['POU5F1',rownames(X)]) PTN = t(data['PTN',rownames(X)]) CXCL5 = t(data['CXCL5',rownames(X)]) Z = cbind(X, NANOG, SAL4, POU5f1, ESRRB, COL5A2, ELN, PTN, CXCL5) After binding this data, the new data.frame Z looks something like this: > head(Z) X1 X2 Cluster Timepoint Transcripts MEF ESC NANOG NA POU5F1 ESRRB COL5A2 ELN PTN CXCL5 Drop_6_6A_0_TACCTAATCTAC 169.3437 20.18623 2 Day 0 49688 0.4366071 0.3260743 0.0000000 NA 0 0 5.113106 0 1.004522 0.2645434 Drop_6_6A_0_TCAGCTTGTCAC 155.8880 -16.69927 3 Day 0 47365 0.4554254 0.3350818 0.2763494 NA 0 0 3.068572 0 1.309109 1.0395819 Drop_6_6A_0_TCGCAATAAGAT 168.4270 36.50967 2 Day 0 44881 0.4114934 0.2595030 0.0000000 NA 0 0 5.264248 0 0.000000 0.0000000 Drop_6_6A_0_AATCTACCAATC 164.3964 -27.17404 3 Day 0 44640 0.4748225 0.3525822 0.0000000 NA 0 0 3.554919 0 1.592698 0.2916205 Drop_6_6A_0_GGATTAAGTTCA 162.2900 -24.10504 3 Day 0 36822 0.4723676 0.3391785 0.0000000 NA 0 0 3.838676 0 1.536569 1.9954283 Drop_6_6A_0_TGATCTAGTGTC 155.4231 -19.18974 3 Day 0 35889 0.4664174 0.3408899 0.0000000 NA 0 0 4.029014 0 6.187616 0.0000000 Now, I am able to plot individual scatterplots with points sized to corresponding expression values (shown below), but I'm unsure how to do this within one facet_wrap plot. library(gridExtra) g = arrangeGrob( ggplot(Z, aes(X1, X2, color=NANOG)) + ggtitle("NANOG") + geom_point() + xlab(paste0("TSNE1")) + ylab(paste0("TSNE2")) + theme_bw() + theme(axis.line = element_line(colour = "black"), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_gradient(low='light blue', high='red') + ggsave(paste0(outdir, timepoint, ".tsne.",lab,".density.clustered.all.genes.TSNE1.TSNE2.nanog.expression.no.noise.pdf"), height=pdf_height, width=pdf_width+5), ggplot(Z, aes(X1, X2, color=SAL4)) + ggtitle("SAL4") + geom_point() + xlab(paste0("TSNE1")) + ylab(paste0("TSNE2")) + theme_bw() + theme(axis.line = element_line(colour = "black"), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_gradient(low='light blue', high='red') + ggsave(paste0(outdir, timepoint, ".tsne.",lab,".density.clustered.all.genes.TSNE1.TSNE2.SAL4.expression.no.noise.pdf"), height=pdf_height, width=pdf_width+5), ggplot(Z, aes(X1, X2, color=POU5f1)) + ggtitle("POU5F1") + geom_point() + xlab(paste0("TSNE1")) + ylab(paste0("TSNE2")) + theme_bw() + theme(axis.line = element_line(colour = "black"), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_gradient(low='light blue', high='red') + ggsave(paste0(outdir, timepoint, ".tsne.",lab,".density.clustered.all.genes.TSNE1.TSNE2.pou5f1.expression.pdf"), height=pdf_height, width=pdf_width+5), ggplot(Z, aes(X1, X2, color=ESRRB)) + ggtitle("ESRRB") + geom_point() + xlab(paste0("TSNE1")) + ylab(paste0("TSNE2")) + theme_bw() + theme(axis.line = element_line(colour = "black"), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_gradient(low='light blue', high='red') + ggsave(paste0(outdir, timepoint, ".tsne.",lab,".density.clustered.all.genes.TSNE1.TSNE2.ESRRB.expression.pdf"), height=pdf_height, width=pdf_width+5), ggplot(Z, aes(X1, X2, color=COL5A2)) + ggtitle("COL5A2") + geom_point() + xlab(paste0("TSNE1")) + ylab(paste0("TSNE2")) + theme_bw() + theme(axis.line = element_line(colour = "black"), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_gradient(low='light blue', high='green') + ggsave(paste0(outdir, timepoint, ".tsne.",lab,".density.clustered.all.genes.TSNE1.TSNE2.col5a2.expression.pdf"), height=pdf_height, width=pdf_width+5), ggplot(Z, aes(X1, X2, color=ELN)) + ggtitle("ELN") + geom_point() + xlab(paste0("TSNE1")) + ylab(paste0("TSNE2")) + theme_bw() + theme(axis.line = element_line(colour = "black"), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_gradient(low='light blue', high='green') + ggsave(paste0(outdir, timepoint, ".tsne.",lab,".density.clustered.all.genes.TSNE1.TSNE2.eln.expression.pdf"), height=pdf_height, width=pdf_width+5), ggplot(Z, aes(X1, X2, color=PTN)) + ggtitle("PTN") + geom_point() + xlab(paste0("TSNE1")) + ylab(paste0("TSNE2")) + theme_bw() + theme(axis.line = element_line(colour = "black"), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_gradient(low='light blue', high='green') + ggsave(paste0(outdir, timepoint, ".tsne.",lab,".density.clustered.all.genes.TSNE1.TSNE2.ptn.expression.pdf"), height=pdf_height, width=pdf_width+5), ggplot(Z, aes(X1, X2, color=CXCL5)) + ggtitle("CXCL5") + geom_point() + xlab(paste0("TSNE1")) + ylab(paste0("TSNE2")) + theme_bw() + theme(axis.line = element_line(colour = "black"), panel.grid.minor = element_blank(), panel.background = element_blank()) + scale_colour_gradient(low='light blue', high='green') + ggsave(paste0(outdir, timepoint, ".tsne.",lab,".density.clustered.all.genes.TSNE1.TSNE2.cxcl5.expression.pdf"), height=pdf_height, width=pdf_width+5), nrow=2, ncol=4 ) The above code works as anticipated but is very lengthy and not sufficient for a large number, say 100, selected markers.. I am assuming that I would have to somehow melt the Z data.frame? Any help would be greatly appreciated. A: As OP suggested, one approach is to melt the original dataframe Z: library(reshape2) d <- melt(Z, id = 1:5, measure = 6:ncol(Z)) where id can be a vector of integers (of column indices) or strings (of column names) for id variables, and measure is a vector that gives the positions of the various measures (the markers in this case). Then call ggplot: library(ggplot2) ggplot(d, aes(x = X1, y = X2, size = value)) + geom_point() + facet_wrap(~ variable) adding labels and other embellishments as desired. Output using OP's extract from Z:
{ "pile_set_name": "StackExchange" }
Q: scope.$watch within a controller not firing I am using controllerAs syntax like so: .state('operators', { url: '/operators', templateUrl: 'app/features/operators/operators.html', controller: 'OperatorsController', controllerAs: 'vm' }) And have a variable in my controller vm.selectedOperators which I want to watch for changes on: var vm = this; vm.selectedOperators = []; $scope.$watch(function() { return vm.selectedOperators; }, function(current) { console.log(current.length); }); In the view, an expression is used to show the count of items in the variable. {{vm.selectedOperators.length}} item selected This variable gets updated from elsewhere (Its being used by a multi-select table directive I have written which is used on the same view) and I see this expression updating fine in the view. The problem is my watcher in the controller doesn't fire after the variable gets initialised, and I am not sure why. Can anyone offer any help? Thanks UPDATE I should have mentioned, I have already tried using the expression equivalent like so: $scope.$watch('vm.selectedOperators', function (current){ console.log(current); }); But this still does not fire for me A: Concept: There is an optional third argument to the $watch function - objectEquality $watch(watchExpression, listener, [objectEquality]); You must set it to true when you are trying to watch an object otherwise angular will only match the reference of both the objects. By setting it true angular compares the old object and new using angular.equals Read more about it here: https://docs.angularjs.org/api/ng/type/$rootScope.Scope $scope.$watch(function() { return vm.selectedOperators; }, function(current) { console.log(current.length); }, true); Update As @Martijn Welker pointed out in the comment below, $watchCollection can be useful if only single level equality has to be matched instead of complete object tree. $scope.$watchCollection(function() { return vm.selectedOperators; }, function(current) { console.log(current.length); });
{ "pile_set_name": "StackExchange" }
Q: How to use member in both instance method and class method class MyClass:NSObject { var member = "abc" func instanceMethod(){ print("\(member)") } class func classMethod(){ print("\(member)") } } I want to access "member" in both methods. A: The only way to do that will be by using a singleton or a static member of the same type: class MyClass: NSObject { static var sharedInstance : MyClass? var member:String func instanceMethod(){ print("\(MyClass.sharedInstance?.member)" } static func classMethod(){ print("\(sharedInstance?.member)" } }
{ "pile_set_name": "StackExchange" }
Q: How do I use and if statement based around the results of data in html while using python? I am attempting to label items in a csv file based on contents in an html which is being scraped using BeautifulSoup. For some items, more information is required to fulfill what is needed to be presented in said csv file. I am trying to use and if statement to determine what to label something as in the csv file. Here is the code: productid_container = container.find('dt', text="Product Id:") productid = (productid_container.find_next_sibling('dd').text) if prodictid is 'Bonus': productname = ((container["data-product"]) + " Bonus Edition") else: productname = (container["data-product"]) and here is the html. You can see where it says bonus, that is what I have as productid: <dt>Product Id:</dt> <dd> <span class="highlight">Bonus</span> <span class="separator">,</span> </dd> The code later on prints everything to the csv file without adding " Bonus Edition" even when productid is "Bonus". Is there something I am missing? My current theory is that I am not having it check the string properly, but I do not know where to go from there or if that is even the case. A: To determine whether a product is a bonus or not you can do the following: productid_container = container.find('dt', text="Product Id:") productid = (productid_container.find_next_sibling('dd').text) if 'Bonus' in prodictid: productname = ((container["data-product"]) + " Bonus Edition") else: productname = (container["data-product"])
{ "pile_set_name": "StackExchange" }
Q: Problem trying to save iterate request results Currently, I'm having a problem with this loop because it saves the previous result twice in each iteration. modelos_test2 = ['https://www.citibanamexchubb.com/api/chubbnet/auto/models/1/1/2020', 'https://www.citibanamexchubb.com/api/chubbnet/auto/models/8/11/2020', 'https://www.citibanamexchubb.com/api/chubbnet/auto/models/7/8/2020'] json_link = list() for link in modelos_test2: request_link = session.get(link).json() json_link.append(request_link) print(json_link) When I print json_link retrieves me a result like this [{'TIPO': {'ID': '364026216', 'DESC': 'RDX'}}] [{'TIPO': {'ID': '364026216', 'DESC': 'RDX'}}, {'TIPO': [{'ID': '382407568', 'DESC': 'NEON'}, {'ID': '382407577', 'DESC': 'PICK UP RAM'}]}] [{'TIPO': {'ID': '364026216', 'DESC': 'RDX'}}, {'TIPO': [{'ID': '382407568', 'DESC': 'NEON'}, {'ID': '382407577', 'DESC': 'PICK UP RAM'}]}, {'TIPO': {'ID': '381390223', 'DESC': 'MINI COOPER'}}] When the actual outcome should be something like this: [{'TIPO': {'ID': '364026216', 'DESC': 'RDX'}} {'TIPO': [{'ID': '382407568', 'DESC': 'NEON'}, {'ID': '382407577', 'DESC': 'PICK UP RAM'}]} {'TIPO': {'ID': '381390223', 'DESC': 'MINI COOPER'}}] A: It's showing up like that because you're printing after each iteration. Put print(json_link) after the loop and should be fine
{ "pile_set_name": "StackExchange" }
Q: SAS sql . How to use ranks sas sql? I have a table of people and their expenses from different sources. name expenseid amount mike 1 100 mike 2 200 nick 3 100 mike 4 500 peter 5 300 nick 6 150 … … … For each person I need to get the TOP 10 most expensive transactions . Here is what I tried . proc sql; select name, expenseid, amount from table2 qualify row_number over(partition by expenseid order by amount desc) < 11 group by name; quit; But the row_number is not recognized by Sas. How can I improve it ? A: It's not supported by PROC SQL. There is a function to do it in SQL, but I don't think it is officially supported (ie someone in R&D threw it in). Because of that, I would use a more traditional SAS approach. PROC SORT data=table2; by name descending amount; run; data table2(drop=count); set table2; by name; retain count; if first.name then count = 0; count = count + 1; if count < 11; run;
{ "pile_set_name": "StackExchange" }
Q: Highlight date interval in a Qt5 Calendar Widget I want to highlight every day in a CalendarWidget that is between a selected start and end date. My problem is that a CalendarWidget only allows SingleSelection in QTCreator but says that other things can be changed programmatically though. I found some hints to use a QPainter and the paintCell() Method but i till dont know where to begin. The Internet wasn't helpful in my case. I tried to change a single date first on buttonClick but even this didnt work, can you give me an advice how to use this? btn_test_pressed(self): painter = QPainter() painter.setPen(QtGui.QPen(QtCore.Qt.green)) painter.fillRect(QtCore.QRectF(250, 250, 10, 10), 0, 5760) rect = QRect() date = datetime.datetime.now() - datetime.timedelta(1) self.calendarWidget.paintCell(painter, rect, date) A: To update the style of individual dates you can use QCalendarWidget.setDateTextFormat(). Here is a basic implementation of how this is used to highlight a range of dates which can be selected by selecting a begin and and end date while holding the shift key. from PyQt5.QtGui import QPalette, QTextCharFormat from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QApplication, QCalendarWidget class MyCalendar(QCalendarWidget): def __init__(self): super().__init__() self.begin_date = None self.end_date = None self.highlight_format = QTextCharFormat() self.highlight_format.setBackground(self.palette().brush(QPalette.Highlight)) self.highlight_format.setForeground(self.palette().color(QPalette.HighlightedText)) self.clicked.connect(self.date_is_clicked) print(super().dateTextFormat()) def format_range(self, format): if self.begin_date and self.end_date: d0 = min(self.begin_date, self.end_date) d1 = max(self.begin_date, self.end_date) while d0 <= d1: self.setDateTextFormat(d0, format) d0 = d0.addDays(1) def date_is_clicked(self, date): # reset highlighting of previously selected date range self.format_range(QTextCharFormat()) if QApplication.instance().keyboardModifiers() & Qt.ShiftModifier and self.begin_date: self.end_date = date # set highilighting of currently selected date range self.format_range(self.highlight_format) else: self.begin_date = date self.end_date = None if __name__ == "__main__": app = QApplication([]) calendar = MyCalendar() calendar.show() app.exec() Screenshot:
{ "pile_set_name": "StackExchange" }
Q: How to use input obtained from a string in Java? I have the following piece of code, and I'm trying to use the input entered by the user in if/else statements later on: String userGuess = JOptionPane.showInputDialog("The first card is " + firstCard + ". Will the next card be higher, lower or equal?"); How can I use the word they input, i.e. "higher", "lower" or "equal" outside of the if/else statement that this code is in? The code I need their answer for is: if (userGuess == "higher" && nextCard > firstCard) { String userGuess = JOptionPane.showInputDialog(null, "Correct! The current card is a " + nextCard + ". Will the next card be higher, lower or equal?"); correctGuesses++; } EDIT: Thank you for your help, I figured it out! A: Try this code: if (userGuess.equalsIgnoreCase("higher") && nextCard > firstCard) { String userGuess = JOptionPane.showInputDialog(null, "Correct! The current card is a " + nextCard + ". Will the next card be higher, lower or equal?"); correctGuesses++; } else if (userGuess.equalsIgnoreCase("higher") && nextCard == firstCard) { String userGuess = JOptionPane.showInputDialog(null, "Correct! The current card is a " + nextCard + ". Will the next card be higher, lower or equal?"); correctGuesses++; } else if (userGuess.equalsIgnoreCase("lower") && nextCard < firstCard) { String userGuess = JOptionPane.showInputDialog(null, "Correct! The current card is a " + nextCard + ". Will the next card be higher, lower or equal?"); correctGuesses++; } String is not a primitive type. You cannot use == instead use: if (userGuess.equalsIgnoreCase("higher") && nextCard > firstCard) { Take a look at Oracle's documentation on Strings. This should give you further help. Happy coding!
{ "pile_set_name": "StackExchange" }
Q: List(Of T) saved by unknown hero? What prevents a List(Of T) from throwing an arithmetic overflow exception when I set the internal _version field to Integer.MaxValue and add a new item? TL;DR: As you can see when looking at the source code there's no protection against the potential arithmetic overflow. But some-one/thing is setting the value to Integer.MinValue if the value is maximum. <__DynamicallyInvokable()> _ Public Sub Add(ByVal item As T) If (Me._size = Me._items.Length) Then Me.EnsureCapacity((Me._size + 1)) End If Me._items(Me._size++) = item Me._version += 1 End Sub Detailed As the internal item-array of List(Of T) is private, and I wouldn't use reflection to access it, I decided to create a custom list using the original List(Of T) source code. However, I noticed that there were no protection against a potential arithmetic overflow if the version ever reached Integer.MaxValue. Me._version += 1 So I modified the code: Me._version = If((Me._version = Integer.MaxValue), Integer.MinValue, (Me._version + 1I)) Now begins the fun part; Out of curiosity, I set up a test where I used reflection to set the internal _version field to max. Dim flags As BindingFlags = (BindingFlags.Instance Or BindingFlags.NonPublic) Dim list As New List(Of String) Dim _version As FieldInfo = GetType(List(Of String)).GetField("_version", flags) _version.SetValue(list, Integer.MaxValue) Debug.WriteLine("Count: {0}, Version: {1}", list.Count, _version.GetValue(list)) list.Add("str") Debug.WriteLine("Count: {0}, Version: {1}", list.Count, _version.GetValue(list)) I was shocked by the results: Count: 0, Version: 2147483647Count: 1, Version: -2147483648 There's nothing in the source code that sets the field to minimum if maximum is reached. I even looked at the DynamicallyInvokable attribute, but as far as I can tell it's not relevant. <__DynamicallyInvokable()> _ Public Sub Add(ByVal item As T) If (Me._size = Me._items.Length) Then Me.EnsureCapacity((Me._size + 1)) End If Me._items(Me._size++) = item Me._version += 1 End Sub Private Sub EnsureCapacity(ByVal min As Integer) If (Me._items.Length < min) Then Dim num As Integer = IIf((Me._items.Length = 0), 4, (Me._items.Length * 2)) If (num > &H7FEFFFFF) Then num = &H7FEFFFFF End If If (num < min) Then num = min End If Me.Capacity = num End If End Sub <__DynamicallyInvokable()> _ Public Property Capacity As Integer <TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable()> _ Get Return Me._items.Length End Get <__DynamicallyInvokable()> _ Set(ByVal value As Integer) If (value < Me._size) Then ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity) End If If (value <> Me._items.Length) Then If (value > 0) Then Dim destinationArray As T() = New T(value - 1) {} If (Me._size > 0) Then Array.Copy(Me._items, 0, destinationArray, 0, Me._size) End If Me._items = destinationArray Else Me._items = List(Of T)._emptyArray End If End If End Set End Property A: The base class library is written in C#, not in VB.NET. By default, arithmetic operations in C# do not throw overflow exceptions. Instead, they silently wrap the value around, as you have noticed. This decision was probably made for reasons of efficiency; not everyone agrees with it. More information can be found in the following questions: Why doesn't C# use arithmetic overflow checking by default? Why don't languages raise errors on integer overflow by default?
{ "pile_set_name": "StackExchange" }
Q: UIButton: primaryActionTriggered vs. touchUpInside basically I was wondering what's the difference between the .primaryActionTriggered and .touchUpInside controlEvents for UIButton since they seem to be triggered similarly. A: .primaryActionTriggered is not limited to buttons, but to controls in general. For most controls, it will trigger on .valueChanged, except for UIButton, where it is for .touchUpInside, and for UITextField where it is .didEndOnExit.
{ "pile_set_name": "StackExchange" }
Q: Visual c# Read DataGridView data and show in PictureBox im sorry fot being a newbie on this language. Here's my simple situation. I have a DataGrid where i put my inventory items in this way: public void UpdateInventoryListUI() { dGridInvetory.RowHeadersVisible = false; dGridInvetory.ColumnCount = 2; dGridInvetory.Columns[0].Name = "Name"; dGridInvetory.Columns[0].Width = 112; dGridInvetory.Columns[1].Name = "Quantity"; dGridInvetory.Rows.Clear(); foreach (InventoryItem inventoryItem in mainForm1._player.Inventory) { if (inventoryItem.Quantity > 0) { dGridInventory.Rows.Add(new[] { inventoryItem.Details.Name, oggettoInventory.Quantity.ToString() }); } } } Ok it works fine and show me my items. Now i want to create an event that when i select with mouse the Row (entire Row - so the name and the quantity) it shows me in the picture box the image of that item. I need to know how to read the STRING like below: private void dGridInventory_MouseClick(object sender, MouseEventArgs e) { if(// the string "Name" on row is == "Mask_DPS"){ picBoxMask.Image = Properties.Resources.MASK_DPS; labelInfo.Text = "This is a dps Mask!"; } if((// the string "Name" on row is == "Mask_TANK"){ picBoxMask.Image = Properties.Resources.MASK_TANK; labelInfo.Text = "This is a tank mask!; //...and so on! } Can you help me please? Just wanna click on the Row and compare the string in the Row. If is the same then show me the image in my picture box. Thank all and sry for my bad english. A: You are not using the best event for what you want to accomplish. Try using the SelectionChanged event instead: void dGridInventory_SelectionChanged(object sender, EventArgs e) { if (dGridInventory.CurrentRow != null) { if (dGridInventory.CurrentRow.Cells["Name"].Value.ToString() == "Mask_DPS") { // etc... } } } Make sure the event is properly subscribed to the DataGridView control.
{ "pile_set_name": "StackExchange" }
Q: StringIndexOutOfBoundsException from EmbeddedHeadersMessageConverter I'm in the process of moving a simple Kafka consumer application out of an existing framework and feel like spring-cloud-stream is an easy way to do that. I used Initializr to bootstrap the app, which is now using Spring-Boot v1.3.3 and Spring-Cloud-Stream v1.0.0-RC1. The application is extremely simple, all it has to do is pick a message from Kafka, deserialize the JSON encoded object and pass it on to our existing library. To get started I just used the LogSink example, since eventually I won't do much else (just deserialize and pass object to a different method). It all works great: It connects to Kafka, receives the message and passes it (as byte[]) to my sink. However, EmbeddedHeadersMessageConverter logs a StringIndexOutOfBoundsException: 2016-04-11 10:06:50.287 ERROR 11464 --- [pool-1-thread-1] fkaMessageChannelBinder$ReceivingHandler : Could not convert message: 7B2267656E65726174696F6E223A3 [...] java.lang.StringIndexOutOfBoundsException: String index out of range: 2009 at java.lang.String.checkBounds(String.java:373) ~[na:1.8.0_25] at java.lang.String.<init>(String.java:413) ~[na:1.8.0_25] at org.springframework.cloud.stream.binder.EmbeddedHeadersMessageConverter.oldExtractHeaders(EmbeddedHeadersMessageConverter.java:131) ~[spring-cloud-stream-1.0.0.RC1.jar:1.0.0.RC1] at org.springframework.cloud.stream.binder.EmbeddedHeadersMessageConverter.extractHeaders(EmbeddedHeadersMessageConverter.java:104) ~[spring-cloud-stream-1.0.0.RC1.jar:1.0.0.RC1] at org.springframework.cloud.stream.binder.kafka.KafkaMessageChannelBinder$ReceivingHandler.handleRequestMessage(KafkaMessageChannelBinder.java:583) ~[spring-cloud-stream-binder-kafka-1.0.0.RC1.jar:1.0.0.RC1] at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:99) [spring-integration-core-4.2.5.RELEASE.jar:na] at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127) [spring-integration-core-4.2.5.RELEASE.jar:na] at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:69) [spring-integration-core-4.2.5.RELEASE.jar:na] at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:63) [spring-integration-core-4.2.5.RELEASE.jar:na] at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115) [spring-messaging-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45) [spring-messaging-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105) [spring-messaging-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:105) [spring-integration-core-4.2.5.RELEASE.jar:na] at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter.access$300(KafkaMessageDrivenChannelAdapter.java:43) [spring-integration-kafka-1.3.0.RELEASE.jar:na] at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter$AutoAcknowledgingChannelForwardingMessageListener.doOnMessage(KafkaMessageDrivenChannelAdapter.java:171) [spring-integration-kafka-1.3.0.RELEASE.jar:na] at org.springframework.integration.kafka.listener.AbstractDecodingMessageListener.onMessage(AbstractDecodingMessageListener.java:50) [spring-integration-kafka-1.3.0.RELEASE.jar:na] at org.springframework.integration.kafka.listener.QueueingMessageListenerInvoker$KafkaMessageDispatchingSubscriber.onNext(QueueingMessageListenerInvoker.java:221) [spring-integration-kafka-1.3.0.RELEASE.jar:na] at org.springframework.integration.kafka.listener.QueueingMessageListenerInvoker$KafkaMessageDispatchingSubscriber.onNext(QueueingMessageListenerInvoker.java:209) [spring-integration-kafka-1.3.0.RELEASE.jar:na] at reactor.core.processor.util.RingBufferSubscriberUtils.route(RingBufferSubscriberUtils.java:67) [reactor-core-2.0.7.RELEASE.jar:na] at reactor.core.processor.RingBufferProcessor$BatchSignalProcessor.run(RingBufferProcessor.java:789) [reactor-core-2.0.7.RELEASE.jar:na] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_25] at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_25] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_25] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_25] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25] https://github.com/spring-cloud/spring-cloud-stream/issues/209 seems to indicate the problem is missing Kafka headers, which is true, there aren't any. But the solution mentioned there is to add spring.cloud.stream.binder.kafka.mode=raw to my application configuration. Unfortunately that did not work for me. Also, STS actually has auto-completion for the respective properties and it suggested spring.cloud.stream.kafka.binder.mode=raw Neither of the 2 (separately or combined) made any difference, the exception is still being logged. I have used Spring for years, but this would be my first Spring-Boot/Spring-Cloud application. Here's the application code: import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.StreamListener; import org.springframework.cloud.stream.messaging.Sink; import org.springframework.integration.annotation.ServiceActivator; @SpringBootApplication public class UpdateApplication { private static Logger logger = LoggerFactory.getLogger(UpdateApplication.class); public static void main(String[] args) { SpringApplication.run(UpdateApplication.class, args); } @EnableBinding(Sink.class) public static class UpdateHandler { @StreamListener(Sink.INPUT) //@ServiceActivator(inputChannel=Sink.INPUT) public void loggerSink(Object payload) { logger.info("Received: " + payload); } } } I tried both, @ServiceActivator as well as @StreamListener annotation, which in this case does not seem to make a difference. My application.properties looks like this: spring.cloud.stream.bindings.input.binder=kafka spring.cloud.stream.bindings.input.destination=updates spring.cloud.stream.bindings.input.group=update-client spring.cloud.stream.kafka.binder.brokers=brokerName spring.cloud.stream.kafka.binder.zkNodes=zookeeperName spring.cloud.stream.kafka.binder.mode=raw Any help to get rid of this error would be appreciated. As a side note: Since I just started experimenting with spring-cloud-stream I added spring.cloud.stream.bindings.updates.consumer.resetOffsets=true spring.cloud.stream.bindings.updates.consumer.startOffset=earlist to the configuration to avoid having to send new messages every time I restart, but that didn't work. A: Since the RC that option has been moved to the .consumer. configuration option. So, right now you have to do like this: spring.cloud.stream.bindings.input.consumer.mode=raw See more info in the Reference Manual.
{ "pile_set_name": "StackExchange" }
Q: Очистить буфер ввода Пытаюсь написать кроссплатформенную функцию, аналог system("pause"); // Пауза перед закрытием void PauseOnExit(int lang) { PrintVStr(14, lang); getchar(); exit(0); } Все хорошо, но, если пользователь до этого что-то ввел - программа сразу закрывается, т.к. могли остаться непроанализированные символы в буфере ввода. И getchar этот прошлый ввод считывает. Вопос: как, собственно, очистить данный буфер? Решение должно быть кроссплатформенным. A: std::cin.seekg(0, std::ios::end); std::cin.clear();
{ "pile_set_name": "StackExchange" }
Q: Wikitude + Parse.com linker error I'm trying to add Parse to a project using Wikitude framework and I'm facing the "-ObjC" flag linker error. I've found this error before with another library (GPUImage) and I managed to solve using "-force_load library" instead "-ObjC" but this time It seems this in not gonna work. When I add "-force_load path/to/Wikitude.framework" I get: ld: can't map file, errno=22 file '/Users/MyUser/Documents/MyProject/Frameworks/WikitudeSDK.framework' for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation) Any other workaround for this?. A: Well. It was easy. Just had to add the Facebook framework and everything went OK. I hope this helps someone.
{ "pile_set_name": "StackExchange" }
Q: How can I move my Windows DNS from one server to another? How can I move my Windows DNS from one server to another with minimum disruption? Both servers are in the same domain and we do use DHCP for the windows clients but the servers are fixed IP. DNS is Active Directory intergrated. A: It sounds like you have two problems. Moving the DNS zones to a new server and directing clients to the new server. Moving the Zones Assuming the DNS zones are Active Directory-integrated this is just a matter of promoting the new DNS servers to being domain controller computers, as only domain controller computers can run DNS servers hosting AD integrated zones (http://technet.microsoft.com/en-us/library/cc978010.aspx). If you're not using Active Directory integrated zones (i.e. standard zones), you can use a script that I wrote in this answer to migrate the zones from one server to another: Migrate 200 Domains from Win2003 DNS server to another Directing the Clients to the New DNS Servers Windows clients that are statically configured to use the existing DNS servers will require changes to be made, either manually or by using an automated tool such as "netsh". If you've got a lot of statically-configured machines using a script would probably be easiest. Clients that are receiving their DNS server assignments from DHCP are much easier. Change the DNS servers specified in the DHCP scope and wait for the lease expiration time before decommissioning the old DNS servers. Finally, if you've got other operating systems (embedded devices, etc) that have the DNS servers specified be sure that you change them, too. Ideally, you should attempt to dedicate some IP addresses for your DNS servers such that those IPs can be re-assigned to other server computers in the future, rather than having to go through this ordeal ever again. Try and refer to all servers / services by DNS name, in the future, and keep the IP addresses used by the DNS servers free to be re-assigned to new servers in the future. (Don't, for example, also use the DNS server IP addresses as the address specified for some other kind of service program that might not always reside on the same machine as the DNS server software. If necessary, assign secondary IP addresses to the DNS server computers for such purposes.)
{ "pile_set_name": "StackExchange" }
Q: Why is the size of the data type different when the value is directly passed to the sizeof operator? #include <stdio.h> int main() { char a = 'A'; int b = 90000; float c = 6.5; printf("%d ",sizeof(6.5)); printf("%d ",sizeof(90000)); printf("%d ",sizeof('A')); printf("%d ",sizeof(c)); printf("%d ",sizeof(b)); printf("%d",sizeof(a)); return 0; } The output is: 8 4 4 4 4 1 Why is the output different for the same values? A: Constants, like variables, have a type of their own: 6.5 : A floating point constant of type double 90000 : An integer constant of type int (if int is 32 bits) or long (if int is 16 bits) 'A' : A character constant of type int in C and char in C++ The sizes that are printed are the sizes of the above types. Also, the result of the sizeof operator has type size_t. So when printing the proper format specifier to use is %zu, not %d. A: Character constants in C (opposite to C++) have the type int. So this call printf("%d",sizeof('A')); outputs 4. That is sizeof( 'A' ) is equal to sizeof( int ). From the C Standard (6.4.4.4 Character constants) 10 An integer character constant has type int.... On the other hand (6.5.3.4 The sizeof and alignof operators) 4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. So the operand of the sizeof operator in this expression sizeof( 'A' ) has the type int while in this expression sizeof( a ) where a is declared like char a = 'A'; the operand has the type char. Pay attention to that calls like this printf("%d",sizeof(6.5)); use incorrect conversion format specifier. You have to write printf("%zu",sizeof(6.5)); Also in the above call there is used a constant of the type double while in this call printf("%zu",sizeof(c)); the variable c has the type float. You could get the same result for these calls if the first call used a constant of the type float like printf("%zu",sizeof(6.5f));
{ "pile_set_name": "StackExchange" }
Q: Why is one assignment faster than the other? I heard a lot people saying int a = 0; a += 10; is faster than int a = 0; a = a + 10; Why is that? I debugged it with gdb and it was absolutely the same instructions. gdb : First (gdb) list 1 int main() 2 { 3 int counter = 0; 4 counter = counter + 10; 5 return 0; 6 } (gdb) disassemble main Dump of assembler code for function main: 0x00000000004004cc <+0>: push %rbp 0x00000000004004cd <+1>: mov %rsp,%rbp 0x00000000004004d0 <+4>: movl $0x0,-0x4(%rbp) 0x00000000004004d7 <+11>: addl $0xa,-0x4(%rbp) => 0x00000000004004db <+15>: mov $0x0,%eax 0x00000000004004e0 <+20>: pop %rbp 0x00000000004004e1 <+21>: retq End of assembler dump. Second (gdb) list 1 int main() 2 { 3 int counter = 0; 4 counter += 10; 5 return 0; 6 } (gdb) disassemble main Dump of assembler code for function main: 0x00000000004004cc <+0>: push %rbp 0x00000000004004cd <+1>: mov %rsp,%rbp 0x00000000004004d0 <+4>: movl $0x0,-0x4(%rbp) 0x00000000004004d7 <+11>: addl $0xa,-0x4(%rbp) => 0x00000000004004db <+15>: mov $0x0,%eax 0x00000000004004e0 <+20>: pop %rbp 0x00000000004004e1 <+21>: retq End of assembler dump. So why is "(variable) += (value)" faster than "(variable) = (variable) + (value)" ? A: It's not faster. As you see, the generated assembly is identical. Whoever told you one is faster was making up stories. A: As others said, in this case it doesn't matter. However, there are some similar but very different cases: int *f(void); (*f()) = (*f()) + 1; (*f()) += 1; In the 2nd line, f() is called twice, in the 3rd line just once. int * volatile *p; **p = **p + 1; **p += 2; In the 2nd line, the compiler will read *p twice, assuming it may change between accesses (and you'd be reading one place, writing another). In the 3rd, it will read *p once and increment this place. And if you're feeling naughty: #define a *f() int a; a = a + 1; a++; Looks almost exactly as in the question, but behaves like my first example. A: I think you just proved that it is not faster at all for whichever c compiler you are using. However, you may have optimizations running during the compile. Also, other compilers may not do that the same way.
{ "pile_set_name": "StackExchange" }
Q: Why im getting 404 error when i using .html for state? I have this states: first one in partial view and second one is html page and they are in folder View/Account.First one is working but secondone is not.It say 404 page could not be found. How can i configure state for .html page.Any suggestion? .state('account.payoutconfirmation', { url: '/ticketprint', templateUrl: function (stateParams) { return mainTemplateService.getTemplateUrl(stateParams, '/account/payoutconfirmation'); } }).state('account.state', { url: '/printticket', templateUrl: function (stateParams) { return mainTemplateService.getTemplateUrl(stateParams, "/account/state.html") } A: I would say, there could be some typo. Anyhow, in case we are using some mainTemplateService to load the url, we should not use templateUrl, but templateProvider. There is a working plunker This could be the service: .factory('mainTemplateService', ['$templateRequest', function($templateRequest) { return { getTemplateUrl: function(stateParams, urlPart) { var url = "temp" + urlPart; return $templateRequest(url); } } }]) And these are states: .state('account.payoutconfirmation', { url: '/ticketprint', templateProvider: ['$stateParams', 'mainTemplateService', function(stateParams, mainTemplateService) { return mainTemplateService.getTemplateUrl(stateParams, '/account/payoutconfirmation'); }], }) .state('account.state', { url: '/printticket', templateProvider: ['$stateParams', 'mainTemplateService', function(stateParams, mainTemplateService) { return mainTemplateService.getTemplateUrl(stateParams, "/account/state.html") }], }) Check it here Also, check these: Angular and UI-Router, how to set a dynamic templateUrl Trying to Dynamically set a templateUrl in controller based on constant
{ "pile_set_name": "StackExchange" }
Q: Невыполняется остальная часть скрипта jquery Здравстуйте! У меня проблема. У меня есть код jquery, но он выполнятеся почему только первая половина. При нажатии на кнопку с id button срабатывает первая функция которая прячет элемент content за экран, при этом текущее значение id кнопки меняется на id button1. которая в дальнейшем "проворачивает" обратные действия, но пробелма заключается в том, что когда первый раз нажимаешь на кнопку с id button код выполнятеся и значение id меняется на button1. При повторном нажатии получается кнопка имеет другой id которая соответсвенно выполняет другой код, НО выполняется всегда первая функция и получается постоянно content уходит в лево на 999px Вот код. $(document).ready(function(){ $("#button").click(function (){ $('.content').animate({left: "-=999"}, 120); $(this).attr('id','button1'); }); $("#button1").click(function (){ $('.content').animate({left: "+=999"}, 120); $(this).attr('id','button'); }); }); A: Вам стоит использовать как минимум во втором случае функцию не .click(), a .bind()/.live(). Лучше всего вообще использовать .on().
{ "pile_set_name": "StackExchange" }
Q: Django how to set value of hidden input in template How to set value of who and image in template? class CommentForm(ModelForm): who = forms.CharField(widget=forms.HiddenInput()) image = forms.ImageField(widget=forms.HiddenInput()) class Meta: model = Comments fields = ['who', 'image', 'content'] It doesn't work (raw text): <form method='POST' action=''> {% csrf_token %} {% render_field comment_form.content class="form-control form-control-sm" placeholder='Comment..' %} {% render_field comment_form.who class="form-control form-control-sm" value='{{ request.user.profile.pk }}' %} {% render_field comment_form.image class="form-control form-control-sm" value='{{ image.pk }}' %} <input class="btn btn-primary btn-sm" type="submit" value="Add comment"> </form> My views.py: class ProfileView(DetailView): comment_form = CommentForm() queryset = Profile.objects.all() context_object_name = 'me' template_name = 'profile.html' def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) context['comment_form'] = self.comment_form return context A: You need to set the initial property of the form field, after you've instantiated the form in your view. Like so: class ProfileView(DetailView): comment_form = CommentForm() queryset = Profile.objects.all() context_object_name = 'me' template_name = 'profile.html' def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) context['comment_form'] = self.comment_form # This sets the initial value for the field: context['comment_form'].fields['who'].initial = self.request.user.profile.pk return context
{ "pile_set_name": "StackExchange" }
Q: Avoid the removal of "https:" from URLs WordPress is changing all my URLs from: https://www.example.com/... to: //www.example.com/... For example: <link rel="canonical" href="//www.example.com/"/> I don't want this to happen, because it has some side effects with CDN rewriting, and my site is https only. What is the best way to disable this "feature"? A: It was caused by CloudFlare https (which doesn't set the $_SERVER['HTTPS'] variable), I solved it by forcing: $_SERVER['HTTPS'] = 'on'; in the webserver configuration. After doing so I could also disable the CloudFlare Flexible SSL plugin, and get a little performance gain.
{ "pile_set_name": "StackExchange" }
Q: Is it a code smell to set a flag in a loop to use it later? I have a piece of code where I iterate a map until a certain condition is true and then later on use that condition to do some more stuff. Example: Map<BigInteger, List<String>> map = handler.getMap(); if(map != null && !map.isEmpty()) { for (Map.Entry<BigInteger, List<String>> entry : map.entrySet()) { fillUpList(); if(list.size() > limit) { limitFlag = true; break; } } } else { logger.info("\n>>>>> \n\t 6.1 NO entries to iterate over (for given FC and target) \n"); } if(!limitFlag) // Continue only if limitFlag is not set { // Do something } I feel setting a flag and then using that to do more stuff is a code smell. Am I right? How could I remove this? A: There's nothing wrong with using a Boolean value for its intended purpose: to record a binary distinction. If I were told to refactor this code, I'd probably put the loop into a method of its own so that the assignment + break turns into a return; then you don't even need a variable, you can simply say if(fill_list_from_map()) { ... A: It is not necessarily bad, and sometimes it is the best solution. But setting flags like this in nested blocks can make code hard to follow. The problem is you have blocks to delimit scopes, but then you have flags which communicate across scopes, breaking the logical isolation of the blocks. For example, the limitFlag will be false if the map is null, so the "do something"-code will be executed if map is null. This may be what you intend, but it could be a bug which is easy to miss, because the conditions for this flag is defined somewhere else, inside a nested scope. If you can keep information and logic inside the tightest possible scope, you should attempt to do so. A: I'd advise against reasoning about 'code smells'. That's just the laziest possible way to rationalize your own biases. Over time you'll develop a lot of biases, and a lot of them will be reasonable, but a lot of them will be stupid. Instead, you should have practical (i.e., not dogmatic) reasons for preferring one thing over another, and avoid thinking that you should have the same answer for all similar questions. "Code smells" are for when you aren't thinking. If you're really going to think about the code, then do it right! In this case, the decision could really go either way depending on the surrounding code. It really depends on what you think is the clearest way to think about what the code is doing. ("clean" code is code that clearly communicates what it's doing to other developers and makes it easy for them to verify that it is correct) A lot of times, people will write methods structured into phases, where the code will first determine what it needs to know about the data and then act on it. If the "determine" part and the "act on it" part are both a little complicated, then it can make good sense to do this, and often the "what it needs to know" can be carried between phases in Boolean flags. I would really prefer that you gave the flag a better name, though. Something like "largeEntryExists" would make the code a lot cleaner. If, on the other hand, the "// Do Something" code is very simple, then it can make more sense to put it inside the if block instead of setting a flag. That puts the effect closer to the cause, and the reader doesn't have to scan the rest of the code to make sure that the flag retains the value you would set.
{ "pile_set_name": "StackExchange" }
Q: Enforcing ordered communication between actors I have a problem which requires my actors to process messages in the order they were sent. In Akka, messages between actor A and actor B are always guaranteed to arrive in the order sent. This does not appear to be the case in Reliable Actors in Service Fabric. In my test cases, the messages are received in non-deterministic order. I can force ordering by not sending the next message until the first message is processed, but this defeats the entire point. I really want to send and forget the messages, but know that they will be processed in order by the receiving actor. Has anyone seen a pattern for doing this? I think Orleans Actors has the same out of order message possibility. Perhaps an Orleans solution would work here as well. A: Orleans does not guarantee the order of message deliver to actors (unless you send them one at a time as you have already discounted): https://github.com/akka/akka-meta/blob/master/ComparisonWithOrleans.md#messaging-guarantees However, it is possible to control ordering if you're using streams in Orleans (with the correct underlying stream provider): http://dotnet.github.io/orleans/Orleans-Streams/
{ "pile_set_name": "StackExchange" }
Q: NetBeans missing code completion option for C I just installed NetBeans on my Windows machine (usually use Linux), and when I open my C/C++ projects, they build well but none of the syntax is recognized and highlighted. #include, for example, just stays black. Same goes for everything else other than basic C data types (float, int, etc.). When in Options->Editor->Code Completion, the only language I see in the drop-down menu is HTML, but there's an option to import one. Is there a way of fixing this? I tried uninstalling and reinstalling. A: You have to install the c/c++ plugin in "tool"-> "plugin" -> "available plugin". After restarting NetBeans then still in plugin in the tab "installed" you should see c/c++ and it should be active.
{ "pile_set_name": "StackExchange" }
Q: Big O Notation for two code fragments I've have two fragments of code and an explanation of what Big O category they fall into. However, try as I might, I can't tally the explanation with what I can come up either by looking at it or doing sample runs. The first: long count = 0; long n = 1000; long i, j, k; for(i = 0; i < n; i++) for (j = 0; j < i * i; j++) for (k = 0; k < j; k++) count++; Sample runs of this consistently give me N^4, but the answer I've been given is "j can be as large as i^2, which could be as large as N^2. k can be as large as j, which is N^2. The running time is thus proportional to N^N^2^N^2, which is O(N^5)" Second snippet: long i, j, k; long n = 1000; long count = 0; for (i = 1; i < n; i++) for (j = 1; j < i * i; j++) if (j % i == 0) for (k = 0; k < j; k++) count++; For this the notes say "The if statement is executed at most N3 times, by previous arguments, but it is true only O(N^2) times (because it is true exactly i times for each i). Thus the innermost loop is only executed O(N^2) times. Each time through, it takes O(j^2) = O(N^2) time, for a total of O(N^4)" For this the notes seem to be accurate enough for the N^4 (although I keep getting a result of N^4 / 10). I don't follow the modulo calculation only being true i times for each i however, it seems to enter that loop a lot less. So the question is can anyone clarify what I'm not understanding? A: For the first one: sum from i = 0 to n-1 of sum from j = 0 to i*i-1 of sum from k = 0 to j-1 of 1 We know the sum of 1 m times is equal to m, so we can reduce this to sum from i = 0 to n-1 of sum from j = 0 to i*i-1 of j We know the sum 1 + 2 + ... + m = m * (m + 1) / 2, so we can reduce further: sum from i = 1 to n-1 of (i * i - 1) * i * i / 2 = (1/2) * (i * i * i * i - i * i) We can make this easier by taking the (1/2) outside the summation and then splitting up the i * i * i * i and i * i terms; however, the summations are still harder and less well-known than for i alone. It does turn out to be Theta(n^5) hence O(n^5); to at least get an intuitive feeling for why this turns out, recognize that the difference f(n+1) - f(n) = (1/2)(n^4-n^2) which is on the order of n^4, so if f were a continuous function and this difference were the derivative, then the order of f would be one higher. For the second case: sum from i = 0 to n-1 of sum from j = 0 to i-1 of sum from k = 0 to i*j-1 1 Note that j now assumes only i different values for the purposes of the innermost loop: 0, i, 2i, ..., (i-1)i. The inner loop runs for i times as many iterations as the counter value for j. We do this multiplication shifting to avoid introducing a "step" notation so we can use our usual mathematical results. sum from i = 0 to n-1 of sum from j = 0 to i-1 of i*j sum from i = 0 to n-1 of i * (1/2) * i * (i - 1) = (1/2)(i * i * i - i) Again, we can cheat or do the math or we can use our intuition again to (correctly) surmise this turns out to be Theta(n^4).
{ "pile_set_name": "StackExchange" }
Q: How many proteins do all human ribosomes together produce per hour? Very roughly how many proteins (chains) are synthesized in the human body per hour under normal conditions? (And how many ribosomes does the human body have?) A: Regarding protein synthesis rate, here's an attempt at an estimate from bioenergetics: ATP turnover in the human body is consider to be about 100 mol / day. Protein synthesis is estimated to require about 1/4 of ATP consumption in a mammalian cell, and one amino acid elongation requires about 5 ATP, so about 5 mol amino acids are elongated per day, which translates to $1.2 \cdot 10^{23}$ amino acids per hour. An average human protein is about 400 amino acids, which gives about $3 \cdot 10^{20}$ proteins per hour.${}^1$ I think this should be correct within an order of magnitude at least. (Unless I screwed up at some step in the calculation, it's getting late over here :) The most uncertain factor is probably the fractional ATP demand for protein synthesis. ${}^1$ The is correct with the following assumptions. Consider that the proteome has some (any) length distribution $p(n)$ where $n = 1,2,3 \dots$ is the protein length in amino acids, and $\sum_n p(n) = 1$. Let $r(n)$ be the total rate of synthesis of all proteins of length $n$. If we assume that this rate is proportional to protein abundance, $r(n) = t\ p(n)$, where $t = \sum_n r(n)$ is the total protein synthesis rate, then the total rate of amino acids per unit time is $r_{AA} = \sum_n n\ r(n) = t \sum_n n\ p(n) = t\ \mu$ where $\mu$ is the average protein length. Hence the sought total protein synthesis rate is $t = r_{AA} / \mu$.
{ "pile_set_name": "StackExchange" }
Q: TiledMap wont render the code below keeps rendering a black screen...any ideas why? I put the base.tmx in the desktop folder and created it using tiled. did i put the .tmx in the wrong folder? its driving me nuts. public class GameScreen extends ScreenAdapter { OrthographicCamera camera; TiledMap tiledmap; TiledMapRenderer tiledMapRenderer; public void show() { camera=new OrthographicCamera(); camera.setToOrtho(false); camera.update(); tiledmap= new TmxMapLoader().load("base.tmx"); tiledMapRenderer=new OrthogonalTiledMapRenderer(tiledmap); } public void render() { Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); camera.update(); tiledMapRenderer.setView(camera); tiledMapRenderer.render(); } } A: You are not setting width and height of your camera. Also you should override render method of ScreenAdapter correctly with delta parameter. This is the updated version of your code : public class GameScreen extends ScreenAdapter { OrthographicCamera camera; TiledMap tiledmap; TiledMapRenderer tiledMapRenderer; public void show() { float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); camera=new OrthographicCamera(); camera.setToOrtho(false,w,h); camera.update(); tiledmap= new TmxMapLoader().load("base.tmx"); tiledMapRenderer=new OrthogonalTiledMapRenderer(tiledmap); } public void render(float delta) { Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); camera.update(); tiledMapRenderer.setView(camera); tiledMapRenderer.render(); } }
{ "pile_set_name": "StackExchange" }
Q: How to save data in enum type column in CakePHP Possible Duplicate: CakePHP 2.0 - Use MySQL ENUM field with form helper to create Select Input I have a checkbox in my form. That checkbox has an enum type column in database. If that checkbox is checked, I need to save 1 otherwise 0 in that column. I am using CakePHP's save function to save all form values. When I checked that checkbox, the column updated with 1, but if I unchecked and then press the submit button, it's updated with an empty value. How can I save enum type values using checkbox in CakePHP? A: Or you change your column type to tinyint (0/1) (in MySQL for example): ALTER TABLE users CHANGE COLUMN active active tinyint not null default 0; Or, validate if the value is pass (or checked), for example: if($this->request->data['User']['active'] == null) { $this->request->data['User']['active'] = 0; }
{ "pile_set_name": "StackExchange" }
Q: What is the difference between cat source.txt | grep x and grep x source.txt? I saw an example where some one did this: cat source.txt | grep a But I always do it like: grep a source.txt What's the difference between the two? A: The first one is a classical “useless use of cat” (UUOC).
{ "pile_set_name": "StackExchange" }
Q: Rails_admin do not show all included models I have Rails app with some models, frontend and administration with rails_admin. I have these rails_admin settings: # Config/initializers/rails_admin.rb RailsAdmin.config do |config| ... config.included_models = %w[ User Page Event Link Slide Main Partner ] ... end But it's not working, it show only Events, Links, Pages. I do not know where I did mistake. A: Are you using CanCan with rails admin? Maybe you haven't set the ability model to make them manageable. Or maybe you haven't restarted your server.
{ "pile_set_name": "StackExchange" }
Q: How to upload videos in Youtube using refreshtoken in java I am trying to upload videos to Youtube with authorization code. public Credential authorize(List scopes, String credentialDatastore) throws IOException, URISyntaxException { // Load client secrets. URI filePath = new URI (GOOGLE_APIKEY); Reader clientSecretReader =new InputStreamReader(new FileInputStream(filePath.toString())); //Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream(GOOGLE_APIKEY)); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader); // Checks that the defaults have been replaced (Default = "Enter X here"). if (clientSecrets.getDetails().getClientId().startsWith("Enter") || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) { System.out.println( "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential " + "into src/main/resources/client_secrets.json"); System.exit(1); } // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore} FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY)); DataStore datastore = fileDataStoreFactory.getDataStore(credentialDatastore); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore).build(); // Build the local server and bind it to port 8080 LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build(); // Authorize. return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user"); } This is working and the user has to authenticate everytime when the video will be uploaded. Now I want the to upload videos using the accesstoken generated from the refreshtoken which I already have . But need to integrate in my Auth file which has the LocalServerReceiver as uses Jetty server internally. I have written the code to get the accesstoken from refresh token .Please help me to integrate it . public GoogleCredential getCredentials(String clientId,String clientSecret,JsonFactory jsonFactory,HttpTransport transport,String refreshToken) throws IOException{ GoogleCredential credential = new GoogleCredential.Builder() .setClientSecrets(clientId, clientSecret) .setTransport(transport) .setJsonFactory(jsonFactory) .build(); credential.setRefreshToken(refreshToken); // Do a refresh so we can fail early rather than return an unusable credential credential.refreshToken(); String authCode=credential.getAccessToken(); return credential; } A: There was specifically two problems that I was facing during Youtube video upload using google-java-api An instance of jetty server instance which will be listening constantly until the response is coming from Google as mentioned in the redirect url. Though there is a function called setHost() inside new LocalServerReceiver.Builder() class which responsible for creating a local jetty server instance, was throughing a Cannot assign requested address error everytime a host name was given irrespective of the port which did not matter. The whole authorisation process is done in the AuthorizationCodeInstalledApp class's authorize method whose primary functions are as follows Create an url that will ask the user to give access to the app . After successful authentication a code will be received (An instance of jetty server continuously listens untill the code is received ). Exchange the code just received with the accesstoken and refreshtoken for offline upload. Store the credentials that we just received from google. To decouple the whole process I have created a new class ExtendedAuthorizationCodeInstalledApp which extends the original AuthorizationCodeInstalledApp and created each method for each functions in the class.The methods are as follows getAuthorizationFromStorage : Get access token from stored credentials. getAuthorizationFromGoogle : Get the authentication with the credentials from Google creates the url that will lead the user to the authentication page and creating a custom defined name-value pair in the state parameter. The value should be encoded with base64 encoder so we can receive the same code redirected from google after authentication. saveAuthorizationFromGoogle : Save the credentials that we get from google. Create the GoogleAuthorizationCodeFlow object from the credentialDatastorfrom the response received from the google after authentication. Hit google to get the permanent refresh-token that can be used to get the accesstoken of the user any time . Store the tokens like accesstoken and refreshtoken in the filename as userid The code implementation is here Thanks @KENdi for your suggestion...
{ "pile_set_name": "StackExchange" }
Q: How to resolve promises of child controller on route change? I have an Angular Ionic app. I assigned controller, template and its resolve promises in its routes. This is working fine so that my main controller only loads after all the promises of parent controller resolved. But if this route contains another child controller with some promises. Here the problem is the page only need to load after all the promises of parent and child controller resolved. Punker var app = angular.module('testApp', ['ionic']); app.config(function($stateProvider, $urlRouterProvider) { $stateProvider.state('dashboard', { url: "/dashboard", templateUrl: "dashboard.html", controller: 'DashboardController', title: 'Dashboard', resolve: { UserDetails: function(DataService) { return DataService.getUserDetails(1); }, DashboardDetails: function(DataService) { return DataService.getDashboardDetails(); } } }); $urlRouterProvider.otherwise('/dashboard'); }); app.factory('DataService', function($q) { return { getUserDetails: function(id){ var defer = $q.defer(); var userDetails = { name: "Saidh" } defer.resolve(userDetails); return defer.promise; }, getDashboardDetails: function(){ var defer = $q.defer(); var dashboardDetails = { title: "Dashboard" } defer.resolve(dashboardDetails); return defer.promise; } } }); app.controller('HeaderController', function($scope, UserDetails) { console.log(UserDetails);//Error: [$injector:unpr] Unknown provider: $scope.userDetails = UserDetails; }); app.controller('DashboardController', function($scope, DashboardDetails) { console.log(DashboardDetails);//Working: show result $scope.dashboardDetails = DashboardDetails; }); How can I achieve this? A: Simple add nested states, and each state should have it's own resolve: somePromise attribute, here i fork your plunkr and add a timeout so the parent and children view are only shown when the promise is solved Example: $stateProvider.state('header', { url: "/home", templateUrl: "header.html", controller: 'HeaderController', resolve: { UserDetails: function(DataService) { return DataService.getUserDetails(1); } } }); $stateProvider.state('header.dashboard', { url: "/dashboard", controller: 'DashboardController', templateUrl: "dashboard.html", parent: 'header', resolve: { DashboardDetails: function(DataService) { return DataService.getDashboardDetails(); } } }); That way it's very strategist-forward
{ "pile_set_name": "StackExchange" }
Q: Why does SymPy's integrate sometimes produce antiderivative with very long numbers? This is on SymPy 1.1.1 using Python 3.6.5. In SymPy, I always had to use S('...') around the integrand to make it not return a result using floating point numbers, and sometimes to make it actually evaluate the integral. One side effect of this is that SymPy sometimes returns a result with very long whole numbers, e.g., z=symbols('z') integrate(S('1/(cos(z)+sin(z)+2**(1/2))'),z) returns -221108036964586978124740847487718783991180811173992192658 5647118334188786/(-2669010107947987550795474273552499757111 367990811651140108173443831125763*tan(z/2) + 18872751463854612207095892554955468385336360233408060517004 98501499110078*sqrt(2)*tan(z/2) - 7817349615625263300858850180 569529185777319674708450884076749 42332015685*sqrt(2) + 110554018482293489062370423743859391995 5904055869960963292823559167094393) + 1563469923125052660171770036113905837155463934941690176815349 884664031370*sqrt(2)/(-2669010107947987550795474273552499757 111367990811651140108173443831125763*tan(z/2) + 18872751463854612207095892554955468385336360233408060517004985 01499110078*sqrt(2)*tan(z/2) - 78173496156252633008588501805695 29185777319674708450884076749 42332015685*sqrt(2) + 11055401848229348906237042374385939199559 04055869960963292823559167094393) I verified the result above and it is correct. Doing simplify() on the above did not help. I thought at first is that the result needs to be simplified, that is all. If I do not use S'(....)' with sympy, it does not evaluate on this example. >>> integrate(1/(cos(z)+sin(z)+2**(1/2)),z) 1.0*Integral(1/(1.0*sin(z) + 1.0*cos(z) + 1.4142135623731), z) But compare to the small outputs from fricas 1.3.3 integrate(1/(cos(z)+sin(z)+2^(1/2)),z) ((-1)*2^(1/2)*sin(z)+((-1)*2^(1/2)*cos(z)+2))/(2*sin(z)+(-2)*cos(z)) Mathematica 11.3 ClearAll[z] FullSimplify[Integrate[1/(Cos[z] + Sin[z] + 2^(1/2)), z]] -(((1 + I) + (2*I + Sqrt[2])*E^(I*z))/((1 + I) + Sqrt[2]*E^(I*z))) Maple 2018 int(1/(cos(z)+sin(z)+2^(1/2)),z); -2/((2^(1/2)-1)*(tan((1/2)*z)+2^(1/2)+1)) Question: what is in SymPy's integration algorithm that sometimes makes it output such long numbers, while other CAS systems do not for the same integral? Is there a trick in SymPy to make it produce smaller leaf-size result compared to the other CAS systems? Again, SymPy's results are correct. I am just asking why its result on this example have such long numbers. May be if one knows why, it will help better understand things. A: I can guess that the answer comes from "heuristic Risch algorithm" which at some step matches coefficients of many pieces of the (taken apart) expression, and ends up with large coefficients that do the job. In practical terms, simplifying the expression before integration happens to help: >>> integrate(trigsimp(1/(cos(z)+sin(z)+sqrt(2))), z) -sqrt(2)/(tan(z/2 + pi/8) + 1) (One can use simplify here to the same effect, but if you know that trigonometric simplification is in order here, trigsimp is the way to go.) Once the expression is simplified to sqrt(2)/(2*(sin(z + pi/4) + 1)) there is just one trigonometric function left, which is a lot easier than dealing with two. (Aside: using sqrt(2) in place of 2**(1/2) is a better way to avoid premature evaluation of 1/2 to a float than stringifying the entire formula.)
{ "pile_set_name": "StackExchange" }
Q: Div(message box) is not hiding at runtime using jQuery I have a login form as following. <li class="loginlink"> <a id="showlogin" href="#"> <span style="color: #666666">Login</span> </a> <div class="loginbox" style="display: block;"> <fieldset> <label>User Name : </label> <input id="input" type="text" value="" name="input"> </fieldset> <label> <span style="display: inline-block; ...;"> Password :</span> </label> <input id="password_txt" type="password" style="padding:5px;..;" value="" name="password_txt"> <p> <a class="loginlink" onclick="mojarra.jsfcljs(document.getElementById('headerForm'), {'j_idt60':'j_idt60'},'');return false" style="color: #666666;.." href="#">Forgot Password? </a> <a class="loginlink" onclick="mojarra.jsfcljs(document.getElementById('headerForm'), {'j_idt63':'j_idt63'},'');return false" style="..." href="#">Register </a> </p> <div class="loginbuttons"> <input id="loginBtn" type="submit" value="Login" name="loginBtn"> <input id="cancellogin" type="button" value="Cancel"> </div> </div> </li> When you click on showlogin. I use jQuery to display it. Like $('#showlogin').click(function(){ var loginBox = $('.loginbox'); loginBox.show(); $('.loginbox fieldset input').focus(); if (!loginBox.is(':hidden')) { validateUser(); } }); $('#cancellogin').click(function(){ $('.loginbox').hide(); }); function validateUser() { $("#loginBtn").click(function(event){ var userName = $("#input").val(); var password = $("#password_txt").val(); if (userName == "") { $.dialog({ message: "UserName must be entered", imageIcon: false, type: "error", okButtonID: "ok", okButtonValue: "OK" }); return false; } return true; }); //end of click } //end of validateUser() Now what is happening suppose i click on the button the box is shown like Now if i click on login button , then message appears Now if i click on Ok button. Box get disappear. Till here things are ok. Now suppose i close the login form by clicking on cancel button. And again open the form Now again click on login button. The message will appear But now this time if i click on OK button , then the overlay gone but message don't. Why? I get something like this Why this time it is not disappearing? What i am doing wrong? Please help? Thanks A: I think the problem relates to your validateUser() function. You see every time you show the login box you bind a new click handler that contains the code to show the dialog to the login button. function validateUser() { $("#loginBtn").click(function(event){ ... }); } This means the 2nd time the login box is show the dialog is actually shown twice. The 3rd time the dialog is shown 3 times. You probably can't see this because your centering it. If you drop a Javascript alert() function after the line $.dialog.createUI = function (config) { you'll see the 2nd time the login is shown you get 2 alerts! See fiddle for example of this problem. Unless your code does something else within the validate user function I suggest you drop this function and instead bind the click hander when the document is ready. So you end up with something like this: $(document).ready(function () { $("#loginBtn").click(function (event) { var userName = $("#input").val(); var password = $("#password_txt").val(); if (userName == "") { $.dialog({ message: "UserName must be entered", imageIcon: false, type: "error", okButtonID: "ok", okButtonValue: "OK" }); return false; } return true; }); $('#showlogin').click(function () { var loginBox = $('.loginbox'); loginBox.show(); $('.loginbox fieldset input').focus(); // code to call validate user removed from here! }); $('#cancellogin').click(function () { $('.loginbox').hide(); }); });
{ "pile_set_name": "StackExchange" }
Q: How can I set a return URL for an edit link in Visualforce? I have a visualforce page displaying a list of Event objects that need users to update. I have an 'Update link' that takes them to the edit screen for the Event, but upon Save, it brings up the list page. I want to take them to their home page, where this list VF page is nested. <apex:page sidebar="false" showHeader="fale" standardController="User" extensions="UsersEventsExt2"> <apex:pageBlock title="Meetings to Update"> <apex:pageBlockTable value="{!Events}" var="c"> <apex:column headerValue="Click to Update"><apex:outputLink value="{!URLFOR($Action.Event.Edit,c.id)}" target="_blank">Update Meeting</apex:outputLink></apex:column> <apex:column headerValue="Subject"><apex:outputLink value="{!URLFOR($Action.Event.View,c.id)}" target="_blank">{!c.subject}</apex:outputLink></apex:column> < </apex:pageBlockTable> </apex:pageBlock> </apex:page> Thanks! A: When saving a new record, you can use the saveURL parameter: {!URLFOR($Action.Contact.NewContact, c.id, ['saveURL'='/home/home.jsp'])} When editing an existing record, you can use the retURL parameter: {!URLFOR($Action.Event.Edit, c.id, ['retURL'='/home/home.jsp'])}
{ "pile_set_name": "StackExchange" }
Q: Django Rest Framework DELETE returns no content in the body I am using Django Rest Framework and I am making a DELETE request. As opposed to POST, PUT, PATCH, which all return the state of the object post creation/modification, delete does not return anything in the body (just the 204 code). Having this information would be helpful when trying to tie responses back to their original requests. In particular https://github.com/agraboso/redux-api-middleware does a bad job at telling me what succeeded and what errored) Is there a way to force DRF to add information about what was deleted in the body of the response? Thank you! A: Complementing @Linovia's otherwise complete answer with actionable code. In the ViewSet, adding the following will help class WhateverYourModelIsViewSet(viewsets.ModelViewSet): def destroy(self, *args, **kwargs): serializer = self.get_serializer(self.get_object()) super().destroy(*args, **kwargs) return response.Response(serializer.data, status=status.HTTP_200_OK) Few things to be aware of: Returning 204 code will actually drop the data, you have to return something else You need to extract the data from the serializer before you call destroy Edit: Since I first posted my answer, I found myself in need to do the above quite often. A more scalable solution: class DestroyWithPayloadMixin(object): def destroy(self, *args, **kwargs): serializer = self.get_serializer(self.get_object()) super().destroy(*args, **kwargs) return response.Response(serializer.data, status=status.HTTP_200_OK) class WhateverYourModelIsViewSet(DestroyWithPayloadMixin, viewsets.ModelViewSet): # Your implementation pass A: Sure thing. In your view, you'll have to override destroy. Default implementation -by the time of writing this answer- is: def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT)
{ "pile_set_name": "StackExchange" }
Q: How to create a Vector where each entry is a structure with 2 fields I am trying to create a data structure in Java that is a Vector into which some information about an unknown number of entities will go from a database. When it comes to this information, I only care about 2 fields. Also, it is required that when I iterate through this Vector, I can extract these two fields (say, String) in pairs. Schematically speaking, String s1 = Vector[1].Field1, String s2 = Vector[1].Field2 Is this even possible? Does anyone know a more efficient way to achieve this? Note: I would like to keep it in a single Vector because I pass it to another class for processing. A: Use public class Entry { public String field1; public String field2; } List<Entry> vector = ...;
{ "pile_set_name": "StackExchange" }
Q: Is ΩΣ in {simplicial commutative monoids} group completion? Let C be the model category of simplicial commutative monoids (with underlying weak equivalences and fibrations), or equivalently the (∞,1)-category PΣ(Top), where T is the Lawvere theory for commutative monoids. In C, as in any pointed (∞,1)-category with finite limits and colimits, we can define adjoint functors ΣC and ΩC as ΣCX = hocolim [• ← X → •] and ΩCX = holim [• → X ← •]. The category CommMon of commutative monoids sits inside C as a full subcategory (as the constant objects, or the objectwise-discrete presheaves). Consider the two functors CommMon → C given by sending M to ΩCΣCM and to the group completion of M, respectively. Is there a natural equivalence between these functors? (This question is closely related to Chris's question here. A thorough answer to that question would probably yield this immediately.) A: I think an answer is given by the arguments that Segal gives in Section 4 of his paper on "Categories and Cohomology Theories" (aka, the $\Gamma$-space paper), in Topology, v.13. I'll try to sketch the main idea, translated into the context of simplicial commutative monoids. I'll show that if $M$ is a discrete simplicial commutative monoid, then it's group completion is homotopically discrete; according to the comments, this should answer the question. Given a commutative monoid $M$, we can define a simplicial commuative monoid $M'$ as the nerve of the category whose objects are $(m_1,m_2)\in M\times M$, and where morphisms $(m_1,m_2)\to (m_1',m_2')$ are $m\in M$ such that $m_im=m_i'$. We can prolong this to a functor on simplicial commutative monoids. Let $H=H_*|M|=H_*(|M|,F)$ (the homology of the geometric realization of $M$, with coefficients in some field $F$), viewed as a commutative ring under the pontryagin product. Then Segal shows that $H_*|M'|\approx H[\pi^{-1}]$, where $\pi$ denotes the image of $\pi_0|M|$ in $H_0|M]$. His proof amounts to computing the homology spectral sequence for a simplicial space whose realization is $M'$, and whose $E_2$-term is $\mathrm{Tor}_i^H(H\otimes H,F)$, and observing that the higher tor-groups vanish. This means that if $M$ is discrete, then $H_*|M'|$ is concentrated in degree $0$. Since $|M'|$ is a grouplike commutative monoid, the Hurewicz theorem should tell us that $|M'|$ is weakly equivalent to a discrete space, namely the group completion of the monoid $M$. Segal goes on to show that $BM\to BM'$ is a weak equivalence, using the above homology calculation and another spectral sequence. Since $M'$ is weakly equivalent to a group, $\Omega BM\approx \Omega BM'\approx M'$.
{ "pile_set_name": "StackExchange" }
Q: System.Web.UI.WebControls.Image/ImageButton not displaying the image I'm a newbie to Asp.net,learning from the Apress's Begining Asp.net...book.While very curious to see an image given by me on the browser,I'm stuck at the very first step, please help. Configuration : Win7(32-bit),VS2008 Pro/.net 3.5,Firefox as default browser. Now,In created a simple website(not web app) in C#,added three images(.png,.jpg,.gif) to the App_Data folder(using the solutn. explorer of course).Then added the Image control from the toolbox & in the ImageUrl property, selected one of the images->presses f5 to start in debugging mode but every time the browser displays the alternate text given by me. Whats the problem? Thanks. A: Don't put the image in the App_Data folder. Put it anywhere else in the website as anything inside the App_data folder is not accessible via HTTP Requests.
{ "pile_set_name": "StackExchange" }
Q: Files not being copied to media/ folder I'm creating a component. I have put the images, css files, javascript files and other assets in com_mycomponent/media folder. And in my manifest file I have added this: <media destination="com_mycomponent" folder="media"> <filename>index.html</filename> <folder>css</folder> <folder>font-awesome</folder> <folder>images</folder> <folder>js</folder> </media> However, when I access the server, inside the media/com_mycomponent, the directories and files are not there, the directory is completely empty. My component directory structure is: . +-- admin/ +-- media/ +-- site/ +-- mycomponent.xml Directory permission is 755 and it's to the user www-data. Any ideas? Thanks in advance. A: Solved the problem. In my xml file I was adding index.html in the <filename> tag, however there was no index.html file in media/ directory. So basically, everything listed in the xml file must exist in the directory as well.
{ "pile_set_name": "StackExchange" }
Q: Modified Multinomial formula I am trying to compute an explicit formula using Mathematica for the following multinomial expression: \begin{equation} \sum_{n_{1}+n_{2}+...+n_{M}=N}^{M} {N \choose n_{1},n_{2},...,n_{M }} \cdot n_{i} = ? \end{equation} where $i={1,2,...,M}$ and using multinomial[n__] := (Plus @@ {n})!/Times @@ (#! & /@ {n}) but I don't know how make the sumatoria over all the index $n_{k}$. In fact I know the following: \begin{equation} \sum_{n_{1}+n_{2}+...+n_{M}=N}^{M} {N \choose n_{1},n_{2},...,n_{M }} = M^{N} \end{equation} but I think that this previous results can not be used in order to obtain the result at the first equation, it's the reason why I am asking for a code in Mathematica that tries to compute this thing in an analytical way. example: Taking for example M=N=2 and $i=1$ then I have to obtain: \begin{equation} \sum_{n_{1}+n_{2}=2}^{2} {2 \choose n_{1},n_{2}} \cdot n_{1} = {2 \choose 2,0} \cdot 2+{2 \choose 0,2} \cdot 0+{2 \choose 1,1} \cdot 1\end{equation} In fact I I take $i=2$ i would obtain the same: \begin{equation} \sum_{n_{1}+n_{2}=2}^{2} {2 \choose n_{1},n_{2}} \cdot n_{2} = {2 \choose 2,0} \cdot 0+{2 \choose 0,2} \cdot 2+{2 \choose 1,1} \cdot 1\end{equation} A: Given that it doesn't matter which index ($i$) one picks, here's a brute force algebraic approach: \begin{align*} \sum_{n_1+n_2+\cdots+n_M=N}n_1\binom{N}{n_1,n_2,\cdots,n_M}&=\sum_{n_1=0}^N n_1 \sum_{n_2+n_3+\cdots+n_M=N-n_1}\binom{N}{n_1,n_2,\cdots,n_M}\\ &=\sum_{n_1=0}^N n_1 \sum_{n_2+n_3+\cdots+n_M=N-n_1}\frac{N!}{n_1! n_2!\cdots n_M !}\\ &=\sum_{n_1=0}^N n_1 \sum_{n_2+n_3+\cdots+n_M=N-n_1}\frac{N!}{n_1! n_2!\cdots n_M !}\frac{(N-n_1)!}{(N-n_1)!}\\ &=\sum_{n_1=0}^N n_1 \binom{N}{n_1} \sum_{n_2+n_3+\cdots+n_M=N-n_1}\frac{(N-n_1)!}{n_2!\cdots n_M !}\\ &=\sum_{n_1=0}^N n_1 \binom{N}{n_1}(M-1)^{N-n_1}\\ &=\sum_{n_1=0}^N n_1 \binom{N}{n_1}1^{n_1}(M-1)^{N-n_1}\\ &=N M^{N-1} \end{align*} And, yes, I know, this doesn't use Mathematica. A: Following Carl Woll's comment, correcting $m$ and $n$, and providing a more efficient form: n = 17; m = 9; p = IntegerPartitions[n, {m}, Range[0, n]]; Sum[Total[Permutations[x][[All, 1]] * Multinomial @@ x], {x, p}] n m^(n - 1) 31501343210481297 31501343210481297 Solved, it would seem.
{ "pile_set_name": "StackExchange" }
Q: how to get Category description after product listing How can i get category description after product list in product listing page? A: The category description is already displayed in the category view page. You just need to move elements around. The template you need to modify is this: app/design/frontend/{package}/{theme}/template/catalog/category/view.phtml. take this code: <?php if($_description=$this->getCurrentCategory()->getDescription()): ?> <div class="category-description std"> <?php echo $_helper->categoryAttribute($_category, $_description, 'description') ?> </div> <?php endif; ?> and move it at the bottom of the file. That's it.
{ "pile_set_name": "StackExchange" }
Q: get_post_title is not working on homepage My simple shortcode works on all pages except for the homepage (static) in Wordpress 2016 Theme. All content I can read except for the post title. It comes back empty. I want to display posts on homepage with titles. It all works. However the title is blank. Thanks, //Recent post shortcode single function mfbs_recent_post1x1($atts){ $q = new WP_Query( array( 'orderby' => 'date', 'posts_per_page' => '4') ); $list = '<div class="row mfbs1x1">'; while($q->have_posts()) : $q->the_post(); $title = $q->the_post()->post_title; $list .= '<div class="small-12 medium-12 large-12 columns">'; $list .= $title; $list .= '<a href="' . get_permalink() . '">' ; $list .= get_the_post_thumbnail($the_post->ID , 'medium', array( 'class' => 'alignleft' ) ); $list .= '<br>' . get_the_title() . '</a>' . '<br>' . get_the_excerpt() . '</div>'; endwhile; wp_reset_query(); return $list . '</div>'; } add_shortcode('foodrecentpost1x1', 'mfbs_recent_post1x1'); A: You're using a query inside a query at this point. Because of that you need to define global $post at the top of your functions file so it has something to assign in the_post(). Now that you have a $post object you can replace all your test code with $post->attribute: //Recent post shortcode single function mfbs_recent_post1x1($atts){ global $post; $q = new WP_Query( array( 'orderby' => 'date', 'posts_per_page' => '4') ); $list = '<div class="row mfbs1x1">'; while($q->have_posts()) : $q->the_post(); $title = $post->post_title; $list .= '<div class="small-12 medium-12 large-12 columns">'; $list .= $title; $list .= '<a href="' . get_permalink() . '">' ; $list .= get_the_post_thumbnail($post->ID , 'medium', array( 'class' => 'alignleft' ) ); $list .= '<br>' . get_the_title() . '</a>' . '<br>' . get_the_excerpt() . '</div>'; endwhile; wp_reset_query(); return $list . '</div>'; } add_shortcode('foodrecentpost1x1', 'mfbs_recent_post1x1');
{ "pile_set_name": "StackExchange" }
Q: Calculating a circle's radius from one point and two circles on it's circumference Suppose that there are four points $A, B, C, D$. A circle of radius $r_A$ surrounds point $A$, a circle of radius $r_C$ surrounds point $C$, and a circle of radius $|DB|$ surrounds point $D$. $AB||BC$, $|AB|=|BC|$. Circle $D$ intersects circles $A$ and $C$ exactly once per circle, at different points, in addition to intersecting with point $B$. How to solve $|DB|$ algebraically (preferably without iterating) knowing only the values of $r_A$, $r_C$ and $|AB|$? A: Your constraints (first 2 are law of cosines): $$|DA|^2 = |DB|^2 + |AB|^2 - 2|AB||DB|\cos(x)$$ $$|DC|^2 = |DB|^2 + |BC|^2 - 2|BC||DB|\cos(y)$$ $$x + y = \pi$$ $$|DA| = r_A + |DB|$$ $$|DC| = r_C + |DB|$$ $$|AB| = |BC|$$ Substitute the last 4 into the first 2: $$(r_A + |DB|)^2 = |DB|^2 + |AB|^2 - 2|AB||DB|\cos(x)$$ $$(r_C + |DB|)^2 = |DB|^2 + |AB|^2 - 2|AB||DB|\cos(\pi - x)$$ Now you have 2 equations and 2 variables, x and |DB|. I suggest writing $\cos(\pi - x) = \cos(\pi)\cos(x) + \sin(\pi)\sin(x) = -\cos(x)$. $$(r_A + |DB|)^2 = |DB|^2 + |AB|^2 - 2|AB||DB|\cos(x)$$ $$(r_C + |DB|)^2 = |DB|^2 + |AB|^2 + 2|AB||DB|\cos(x)$$ Then just add and solve the resulting equation. The quadratic terms look like they'll cancel out so it should be straightfoward.
{ "pile_set_name": "StackExchange" }
Q: Extracting nth position from space-separated string in dplyr I have a dataframe that looks something like this: data <- data.frame(label = c('S', 'SH', 'S', 'S', 'SH'), word = c('sip', 'shoe', 'plaster', 'reception', 'reception'), word.segs = c('S IH1 P', 'SH UW1', 'P L AE1 S T AH0', 'R AH0 S EH1 P SH AH0 N', 'R AH0 S EH1 P SH AH0 N'), seg.index = c(1, 1, 4, 3, 6)) 'word.segs' contains a phonetic transcription of the words in the 'word' column, and the value in 'seg.index' refers to the segment of interest - the nth segment in that transcription. What I want to do is to create two new columns containing the two segments after this, i.e. seg.index+1 and seg.index+2. I've tried it in the following loop, which works but it takes absolutely ages (and I have 100k rows, so it's important to have an efficient solution here) for (x in 1:nrow(data)){ data[x, ]$fol.seg = unlist(data$word.segs[x])[data[x, ]$seg.index+1] data[x, ]$fol.seg2 = unlist(data$word.segs[x])[data[x, ]$seg.index+2] } (note that I've also tried only unlisting once, saving this to a separate object and then extracting the two values of interest, but this doesn't appear to be significantly faster) I also tried an alternative in dplyr in the hope that it might be more efficient: data <- data %>% mutate(fol.seg = word.segs %>% strsplit(split = " ") %>% unlist() %>% nth(seg.index+1)) But I get the following error message, and I have no idea why it's not working: Error in mutate_impl(.data, dots) : Evaluation error: length(n) == 1 is not TRUE. Any help would be greatly appreciated! A: This works, just using base R. You might be able to fancy it up with purrr. library(dplyr) try_pull = function(x, i) { if (i > length(x)) NA else x[[i]] } res = data %>% mutate(seg_list = strsplit(word.segs, split = " "), seg1 = Map(f = try_pull, seg_list, seg.index + 1), seg2 = Map(f = try_pull, seg_list, seg.index + 2) ) res # label word word.segs seg.index seg_list seg1 seg2 # 1 S sip S IH1 P 1 S, IH1, P IH1 P # 2 SH shoe SH UW1 1 SH, UW1 UW1 NA # 3 S plaster P L AE1 S T AH0 4 P, L, AE1, S, T, AH0 T AH0 # 4 S reception R AH0 S EH1 P SH AH0 N 3 R, AH0, S, EH1, P, SH, AH0, N EH1 P # 5 SH reception R AH0 S EH1 P SH AH0 N 6 R, AH0, S, EH1, P, SH, AH0, N AH0 N
{ "pile_set_name": "StackExchange" }
Q: Which Java classes are usable when developing native Apps in Android? It's said in the title. which Java Classes can I use when developing Android apps. Are there any exceptions, can I use the lot of the Java Library, like the whole of the standard Edition? A: You can use all classes listed in the Android API for your desired API level (which corresponds to Android releases). The Android API is roughly based on the Java SE API, but it is missing a few parts and has added significant parts of its own API. Knowing the Java SE API can certainly help, but you shouldn't assume that everything in there is available on Android. A: You can almost use all the Java Classes. The only thing you need to be aware of is that you can't use any Graphical and UI classes as Swing and AWT. Else it's pretty much the same.
{ "pile_set_name": "StackExchange" }
Q: string replacement using SED I am trying to replace certain functions using SED. Let say I have some function named, AAAABBBB() and I need to change this into CCCC(nBBBB) %BBBB <- this can be any legnth, but AAAA, CCCC, n are fixed length. How I can do this using SED? or even using other method? Thanks A: Here is a quick one: echo "AAAABBBB()" | sed -e 's/AAAA\(.\+\)()/CCCC(n\1)/' CCCC(nBBBB) echo "AAAAFF()" | sed -e 's/AAAA\(.\+\)()/CCCC(n\1)/' CCCC(nFF) The idea is pretty simple: Match the AAAA string, then capture the B's in a backreference (1 or more of them). Now replace that with a couple of C's and the backref. Same goes for the other letter. You are better off with some concrete examples by the way. Otherwise we might not hit exactly right on the substitution you want.
{ "pile_set_name": "StackExchange" }
Q: Why is my Rebus handler being called multiple times for a single Azure Service Bus message? I'm using Rebus to send a message to an Azure Service Bus queue. For each message, my consumer's handler method seems to get called multiple times. Received. is written to 9 separate log files. Producer: await _bus.Advanced.Routing.Send("some-queue", new SomeMessage()); Consumer: public class SomeMessageHandler : IHandleMessages<SomeMessage> { public async Task Handle(SomeMessage message) { _logger.Information("Received."); await SomeApiCall(); } } Consumer configuration: builder.RegisterRebus((configurer, context) => configurer .Logging(l => l.Serilog()) .Transport(t => t.UseAzureServiceBus("Endpoint=<redcated>;SharedAccessKeyName=<redacted>;SharedAccessKey=<redacted>", "some-queue"))); A: The method was throwing an unhandled exception. Rebus was trying to re-process it since it was erroring out. Adding exception handling allowed the method to finish. Now the handler is only called one time as expected.
{ "pile_set_name": "StackExchange" }
Q: is it ok to retain the delegate? I have stumbled upon a problem in my application where my music player view controller needs to retain the delegate (which is a cloud based storage with songs) to keep the song playlist, until the song from a new folder is selected. So, when the user taps a song in some folder, I assign the delegate to that ViewController so even when it is pushed from the view, it stays in the memory so the music player can play next and previous songs. But when the user selects the song from another folder(ViewController), I set the music player delegate to nil, and assign the delegate to that new ViewController. Is this solution acceptable? Code: MusicPlayerViewController has: @property (nonatomic, strong) id <MusicPlayerViewDelegate> delegate; View Controller in which the songs will be loaded from cloud storage folders has this called when tapped on cell(song): musicPlayerViewController.delegate = nil; musicPlayerViewController.delegate = self; A: There is no fundamental problem with retaining (holding a strong reference to) a delegate. It is unusual, but not unprecedented. NSURLConnection does it. It creates a retain loop that can be very useful if correctly managed. It's just up to you to make sure that the object will release its delegate in a deterministic way so that the retain loop is broken. BUT... the specific case that you're discussing here sounds like you have an MVC problem and that your view controller is doing something it shouldn't be. I assign the delegate to that ViewController so even when it is pushed from the view, it stays in the memory so the music player can play next and previous songs. If you're saying that you cannot play music unless a certain view controller is in memory, then the view controller probably has an incorrect responsibility. The view controller should manage the view. That should be independent of actually playing music. See https://stackoverflow.com/a/5228317/97337 for discussion of how a music-playing system might be broken out in MVC.
{ "pile_set_name": "StackExchange" }
Q: class name as variable in python I remember the following code in C++: myObj = MyClass(); typedef typeof(myObj) NewClass; NewClass newObj = NewClass(); Then myObj and newObj are from kind of MyClass. Now I need to write a function in python and pass myobject to my function, then new call my constructor of myobject. I have many class. Question: How i do it? A: This creates a reference to MyClass: >>> class MyClass(object): ... pass ... >>> myObj = MyClass() >>> NewClass = myObj.__class__ >>> newObj = NewClass() >>> myObj, newObj (<__main__.MyClass object at 0x102740d90>, <__main__.MyClass object at 0x102740d50>) This creates a new class based on myObj's class: >>> myObj = MyClass() >>> NewClass = type("NewClass", (myObj.__class__,), {}) >>> newObj = NewClass() >>> myObj, newObj (<__main__.MyClass object at 0x102740d90>, <__main__.NewClass object at 0x102752610>) >>>
{ "pile_set_name": "StackExchange" }
Q: Why won't PHP print 0 value? I have been making a Fahrenheit to Celsius (and vise versa) calculator. All of it works just great, however when I try to calculate 32 fahrenheit to celsius it's supposed to be 0, but instead displays nothing. I do not understand why it will not echo 0 values. Here is some code: <?php // Celsius and Fahrenheit Converter // Programmed by Clyde Cammarata $error = '<font color="red">Error.</font>'; function tempconvert($temptype, $givenvalue){ if ($temptype == 'fahrenheit') { $celsius = 5/9*($givenvalue-32); echo $celsius; } elseif ($temptype == 'celsius') { $fahrenheit = $givenvalue*9/5+32; echo $fahrenheit; } else { die($error); exit(); } } tempconvert('fahrenheit', '50'); ?> A: looks like $celcius has value 0 (int type) not "0" (string type), so it wont echoed because php read that as false (0 = false, 1 = true). try change your code echo $celcius; to echo $celcius.""; or echo (string) $celcius; it will convert your variable to string
{ "pile_set_name": "StackExchange" }
Q: Calculating the Zeroes of the Riemann-Zeta function Wikipedia states that The Riemann zeta function $\zeta(s)$ is defined for all complex numbers $s \neq 1$. It has zeros at the negative even integers (i.e. at $s = −2, −4, −6, ...)$. These are called the trivial zeros. The Riemann hypothesis is concerned with the non-trivial zeros, and states that: The real part of any non-trivial zero of the Riemann zeta function is $\frac{1}{2}$. What does it mean to say that $\zeta(s)$ has a $\text{trivial}$ zero and a $\text{non-trivial}$ zero. I know that $$\zeta(s) = \sum_{n=1}^{\infty} \frac{1}{n^s}$$ what wikipedia claims it that $\zeta(-2) = \sum_{n=1}^{\infty} n^{2} = 0$ which looks absurd. My question is can somebody show me how to calculate a zero for the $\zeta$ function. A: You are going to need a bit of knowledge about complex analysis before you can really follow the answer, but if you start with a function defined as a series, it is frequently possible to extend that function to a much larger part of the complex plane. For example, if you define $f(x)=1+x+x^2+x^3+...$ then $f$ can be extended to $\mathbb C\setminus \{1\}$ as $g(x)=\frac{1}{1-x}$. Clearly, it is "absurd" to say that $f(2)=-1$, but $g(2)=-1$ makes sense. The Riemann zeta function is initially defined as a series, but it can be "analytically extended" to $\mathbb C\setminus \{1\}$. The details of this really require complex analysis. Calculating the non-trivial zeroes of the Riemann zeta function is a whole entire field of mathematics. A: Copied from Wikipedia: For all $s\in\mathbb{C}\setminus\{1\}$ the integral relation $$\zeta(s) = \frac{2^{s-1}}{s-1}-2^s\!\int_0^{\infty}\!\!\!\frac{\sin(s\arctan t)}{(1+t^2)^\frac{s}{2}(\mathrm{e}^{\pi\,t}+1)}\,\mathrm{d}t,$$ holds true, which may be used for a numerical evaluation of the Zeta-function. http://mo.mathematik.uni-stuttgart.de/kurse/kurs5/seite19.html
{ "pile_set_name": "StackExchange" }
Q: Custom Html Helper not working I am trying to learn MVC3 from Pro ASP.NET MVC3 Framework. But i am stuck at one place where we add custom Html Helper. I did every thing mentioned in the book, but i am not able to add the custom Html helper. Can somebody please help. Thanks List.cshtml @model SportsStore.WebUI.Models.ProductListViewModel @{ ViewBag.Titke = "Product"; } <!DOCTYPE html> <html> <head> <title>List</title> </head> <body> <div> @foreach (var p in Model.Products) { <div class="item"> @p.Name @p.Description <h4>@p.Price.ToString("c")</h4> </div> } <div class="Pager"> @Html.PageLinks(Model.pagingInfo, x => Url.Action("List", new {page = x})) </div> </div> </body> </html> PagingHelper.Cs using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SportsStore.WebUI.Models; using System.Text; namespace SportsStore.WebUI.HtmlHelpers { public static class PagingHelper { public static MvcHtmlString PageLinks(HtmlHelper helper, PagingInfo pagingInfo, Func<int, string> pageUrl) { StringBuilder linkString = new StringBuilder(); for (int i = 1; i <= pagingInfo.TotalPages; i++) { TagBuilder tag = new TagBuilder("a"); tag.MergeAttribute("href", pageUrl(i)); tag.InnerHtml = i.ToString(); if (i == pagingInfo.CurrentPage) { tag.AddCssClass("selected"); } linkString.Append(tag.ToString()); } return MvcHtmlString.Create(linkString.ToString()); } } } Web.Config <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="SportsStore.WebUI.HtmlHelpers" /> </namespaces> </pages> </system.web.webPages.razor> A: You didn't create an extension method. To make an extension method, you need to decorate the first parameter with the this keyword.
{ "pile_set_name": "StackExchange" }
Q: Are all of these correct? I came across this question on grammar but it seems I can fill this with any of the 4 past tenses. Diya _____ ( cook ) for hours yesterday. My answers: Diya cooked for hours yesterday Diya was cooking for hours yesterday Diya had cooked for hours yesterday. Diya had been cooking for hours yesterday A: All four are possible. The difference, as usual for questions of aspect in English, is not in the circumstances described, but in the way the speaker/writer chooses to refer to them and to relate them to other events. In the absence of any particular context, the second is much the most likely. You would only use the third or fourth forms if you were setting the event relative to some later event; and as user178049 says, for hours refers to a long activity, so the continuous "was cooking" is more likely; but if this is the first sentence in a continuing narrative of things that happened after the cooking, the first would be more likely.
{ "pile_set_name": "StackExchange" }
Q: Fastest way to copy sql table Im looking for the fastest way to copy a table and its contents on my sql server just simple copy of the table with the source and destination on the same server/database. Currently with a stored procedure select * into sql statement it takes 6.75 minutes to copy over 4.7 million records. This is too slow. CREATE PROCEDURE [dbo].[CopyTable1] AS BEGIN DECLARE @mainTable VARCHAR(255), @backupTable VARCHAR(255), @sql VARCHAR(255), @qry nvarchar(max); SET NOCOUNT ON; Set @mainTable='Table1' Set @backupTable=@mainTable + '_Previous' IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@backupTable) AND type in (N'U')) BEGIN SET @Sql = 'if exists (select * from sysobjects ' SET @Sql = @Sql + 'where id = object_id(N''[' + @backupTable + ']'') and ' SET @Sql = @Sql + 'OBJECTPROPERTY(id, N''IsUserTable'') = 1) ' + CHAR(13) SET @Sql = @Sql + 'DROP TABLE [' + @backupTable + ']' EXEC (@Sql) END IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@mainTable) AND type in (N'U')) SET @Sql = 'SELECT * INTO dbo.[' + @backupTable + '] FROM dbo.[' + @mainTable + ']' EXEC (@Sql) END A: If you are concerned about speed, it seems you have two alternatives; copying by block or the BCP/Bulk insert method. Block Transfer DECLARE @CurrentRow bigint, @RowCount bigint, @CurrentBlock bigint SET @CurrentRow = 1 SELECT @RowCount = Count(*) FROM oldtable WITH (NOLOCK) WHILE @CurrentRow < @RowCount BEGIN SET @CurrentBlock = @CurrentRow + 1000000 INSERT INTO newtable (FIELDS,GO,HERE) SELECT FIELDS,GO,HERE FROM ( SELECT FIELDS,GO,HERE, ROW_NUMBER() OVER (ORDER BY SomeColumn) AS RowNum FROM oldtable WITH (NOLOCK) ) AS MyDerivedTable WHERE MyDerivedTable.RowNum BETWEEN @startRow AND @endRow SET @CurrentRow = @CurrentBlock + 1 end How to copy a huge table data into another table in SQL Server BCP/Bulk Insert SELECT * INTO NewTable FROM OldTable WHERE 1=2 BULK INSERT NewTable FROM 'c:\temp\OldTable.txt' WITH (DATAFILETYPE = 'native') What is the fastest way to copy data from one table to another http://www.databasejournal.com/features/mssql/article.php/3507171/Transferring-Data-from-One-Table-to-Another.htm A: You seem to want to copy a table that is a heap and has no indexes. That is the easiest case to get right. Just do a insert into Target with (tablock) select * from Source Make sure, that minimal logging for bulk operations is enabled (search for that term). Switch to the simple recovery model. This will take up almost no log space because only allocations are logged with minimal logging. This just scans the source in allocation order and append new bulk-allocated pages to the target. Again, you have asked about the easiest case. Things get more complicated when indexes come into play. Why not insert in batches? It's not necessary. Log space is not an issue. And because the target is not sorted (it is a heap) we don't need sort buffers.
{ "pile_set_name": "StackExchange" }
Q: Remove short overlapping string from list of string I have a list of strings: mylist = ["Hanks", "Tom Hanks","Tom","Tom Can"], I need to remove shorter strings that are substring of another string in the list. For example in the case above, output should be : ["Tom Hanks","Tom Can"]. What I have done in python: mylist = ["Hanks", "Tom Hanks","Tom","Tom Can"] newlst = [] for x in mylist: noexist = True for j in mylist: if x==j:continue noexist = noexist and not(x in j) if (noexist==True): newlst.append(x) print(newlst) The code works fine. How can I make it efficient? A: If order in output does not matter (replace ',' character with a character that doesn't occur in strings of your list): mylist = ["Hanks", "Tom Hanks","Tom","Tom Can"] mylist.sort(key = len) newlst = [] for i,x in enumerate(mylist): if x not in ','.join(mylist[i+1:]): newlst.append(x) list comprehension alternative (less readable): mylist = ["Hanks", "Tom Hanks","Tom","Tom Can"] mylist.sort(key = len) newlst = [x for i,x in enumerate(mylist) if x not in ','.join(mylist[i+1:])] output: ['Tom Can', 'Tom Hanks'] And if you want to keep the order: mylist = ["Hanks", "Tom Hanks","Tom","Tom Can"] mylist_sorted = mylist.copy() mylist_sorted.sort(key = len) newlst = [x for i,x in enumerate(mylist_sorted) if x not in ','.join(mylist_sorted[i+1:])] newlst = [x for x in mylist if x in newlst] output: ['Tom Hanks', 'Tom Can']
{ "pile_set_name": "StackExchange" }
Q: Parse filter list for FileDialog If I have a filter string like this (filter for FileDialog): "Image Files (*.bmp, *.jpg)|*.bmp;*.jpg|All Files (*.*)|*.*" Is there a function in C# that gives me a list of all extensions in this filter? This would be "*.bmp", "*.jpg" and "*.*" A: You can do it with this regular expresion: (?<Name>[^|]*)\|(?<Extension>[^|]*)\|? Here is a sample code: var regex = new Regex(@"(?<Name>[^|]*)\|(?<Extension>[^|]*)\|?"); var matches = regex.Matches(@"Image Files (*.bmp, *.jpg)|*.bmp;*.jpg|All Files (*.*)|*.*"); foreach (Match match in matches) { Debug.Print("Name: '{0}' Extension:'{1}'", match.Groups["Name"].Value, match.Groups["Extension"].Value); }
{ "pile_set_name": "StackExchange" }
Q: Grails 2.3.8 Internationalization coded strings I don't understand why some strings in my messages.properties files won't show in my gsp. More exactly, the show in term of the key name in the file not the value. For example, this string in my messages.properties: gtunes.store.subtitle=Your online music store and storage service! is showing up on the gsp where I have this line of code: <h1><g:message code='gtunes.store.subtitle'/></h1> simply as: gtunes.store.subtitle My code is here. A: I downloaded your app and the reason for the error is because there's no message with this key configured in messages.properties. If you try to render a message for a key that doesn't exist, the key is displayed instead.
{ "pile_set_name": "StackExchange" }
Q: Property Dependency Injection used in Constructor using Unity Ok, I have a dependent property defined in a base class and I'm trying to use it inside of the constructor of its derived class but that does not work, the property appears as null. Unity resolves the dependent property AFTER resolving an instance with container.Resolve(); One alternative I have is to add a IUnityContainer parameter to my MyViewModel class constructor and set the ILogger property my self with something like: public MyViewModel(IUnityContainer container) { Logger = container.Resolve<ILogger>(); } EDIT: Another suggestion by @Wiktor_Zychla is to pass a constructor-injected parameter as: public MyViewModel(ILogger _logger) { Logger = _logger; } This seems to work fine, but I would have to do that for all my derived ViewModels.. But then I'm not using the annotated ILogger dependency in my base class. See my class samples below. The question is: Which alternatives do I have, or what am I doing wrong? Thanks! I have a ViewModel base class like this: public abstract class ViewModelBase { [Dependency] public ILogger Logger { get; set; } .... } Then I have a class deriving that: public class MyViewModel : ViewModelBase { public MyViewModel() { //I want to use my dependent property in constructor, but doesn't Logger.Error("PRINT AN ERROR"); } } And in my application entry point I am registering my ILogger as a singleton and my MyViewModel class: container.RegisterType<ILogger, MyAppLogger>(new ContainerControlledLifetimeManager()); container.RegisterType<MyViewModel>(); A: Unity resolves the dependent property AFTER resolving an instance with container.Resolve(); Which is quite obvious, if you think about it. Just try to do this manually. You won't succeed. To be able to inject a property, there must be an instance, and having an instance, means the constructor has been called. Your problem is caused because you are doing too much in your constructor. From a dependency injection perspective, a constructor should do nothing more than accept its dependencies (check that they are not null), and store them in private fields. Doing anything more than this is an anti-pattern. You shouldn't have any logic in your constructor. Having logic in constructors makes creating the object graph unreliable, while constructing object graphs should be fast and reliable. When you follow this principle, there will not be a problem, since once you run any business logic, your class will be completely instantiated. Since the constructor should do nothing more than set private fields, nothing can go wrong and there can't be any reason to call Logger.Error("PRINT AN ERROR"); as you are doing.
{ "pile_set_name": "StackExchange" }
Q: Accessing package controllers in Laravel 4 I have created a package following the "Creating a Package" instructions in the Laravel 4 documentation. After creating the package I have created a "controllers" folder and a routes file. The new file structure is: /src /Vendor /Package PackageServiceProvider.php /config /controllers /lang /migrations /views routes.php /tests /public I added the routes file to the boot portion of the package service provider: public function boot() { $this->package('vendor/package'); include __DIR__ . '/../../routes.php'; } Then added a basic route to the routes file: Route::get('/package', function() { return "Package route test"; }); Visiting my application at the specified route (app.dev/package) returns the expected: Package route test Then adding a basic controller call to the route (using the default Laravel controller, "HomeController") works: Route::get('/package', 'HomeController@showWelcome'); I then followed this SO answer for setting up the controller for the package. I added the src/controllers folder to the composer classmap, then I dumped the autoloader and checked vendor/composer/autoload_classmap.php and found the class is successfully loaded by composer: <?php // autoload_classmap.php generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'HomeController' => $baseDir . '/src/controllers/HomeController.php', ); Now I added the new package controller to the route using the namespace: Route::get('/package', 'Vendor\Package\Controllers\HomeController@showWelcome'); but this produces an error about not finding the class: ReflectionException: Class Vendor\Package\Controllers\HomeController does not exist I've also tried calling it using the package name: Route::get('/package', 'Package::HomeController@showWelcome'); which produces the same error: ReflectionException: Class Vendor\Package\Controllers\HomeController does not exist No matter what I try the package cannot access its own controller, which composer confirms is loaded (by viewing vendor/package/autoload_classmap.php). Any ideas? I'm not sure if the issue is composer not loading the class, I'm not sure where to start with debugging the problem. I've created another package and repeated the steps here and get the same problem. I can access the package views from both the package and the app, eg: View::make('package::view'); The problem seems to be between composer loading the controller and Laravel being able to access it. A: The mistake was including the controllers path in the route. I had the following: Route::get('/package', 'Vendor\Package\Controllers\HomeController@showWelcome'); The correct usage is: Route::get('/package', 'Vendor\Package\HomeController@showWelcome'); With the namespace included in the controller: namespace Vendor\Package; Controller should extend illuminate: \Illuminate\Routing\Controllers\Controller Still can't use the package name (eg: Package::HomeController@showWelcome), but I can using the namespace. yay. Problem solved. A: You may try edit your Vendor/Package/composer.json and insert the controllers dir to autoload/classmap: .... "autoload": { "classmap": [ "src/migrations", "src/controllers", "src/models" ], "psr-0": { "Package\\Controller": "src/" } } .... After that, open your terminal and from your package root dir do a composer dump-autoload Works for me...
{ "pile_set_name": "StackExchange" }
Q: something wrong with the result of mysql query with joins and select Good day, I am trying to join 3 tables for my inventory report but I am getting weird results out of it. my query SELECT i_inventory.xid, count(x_transaction_details.xitem) AS occurrence, i_inventory.xitem AS itemName, SUM(i_items_group.or_qty) AS `openingQty`, avg(x_transaction_details.cost) AS avg_cost, SUM(x_transaction_details.qty) AS totalNumberSold, SUM(i_items_group.or_qty) - SUM(x_transaction_details.qty) AS totalRemQty FROM x_transaction_details LEFT JOIN i_inventory ON x_transaction_details.xitem = i_inventory.xid LEFT JOIN i_items_group ON i_inventory.xid = i_items_group.xitem WHERE (x_transaction_details.date_at BETWEEN '2015-01-18 03:14:54' AND '2015-10-18 03:14:54') AND i_inventory.xid = 3840 GROUP BY x_transaction_details.xitem ORDER BY occurrence DESC This query gives me this result: See the openingQty column, I then tried to do a simple query to verify the result, here's my query for checking the openingQty with joining only 2 tables i_items_group table (batches are stored) and i_inventory table (item Information are stored). SELECT i_inventory.xid, i_inventory.xitem, SUM(i_items_group.or_qty) AS openingQty, i_items_group.cost FROM i_inventory INNER JOIN i_items_group ON i_inventory.xid = i_items_group.xitem WHERE i_inventory.xid = 3840 AND (i_items_group.date_at BETWEEN '2015-01-18 03:14:54' AND '2015-10-18 03:14:54') my result was: which is the correct data. I also made a query on my x_transaction_details table also to verify if its correct or not. heres my query: select xitem, qty as qtySold from x_transaction_details where xitem = 3840 AND (date_at BETWEEN '2015-01-18 03:14:54' AND '2015-10-18 03:14:54') result: Which would total to: 15-quatitySold. I'm just confused on how did I get 3269 as a result of my query where as the true openingQty should be only 467. I guess the problem was in my query with joins, its messing up with number of transactions then it sums it up (I really dont know though). Can you please help me identify it, and help me come up with the correct query. A: This is a common problem with multiple SUM statements in a single query. Keep in mind how SQL does aggregation: first it generates a set of data that is not aggregated, then it aggregates it. Try your query without the GROUP BY or aggregate functions, and you'll be surprised what you turn up. There aren't enough of the right details in your post for me to determine where the breakdown is, but I can guess. It looks like you have an xitem corresponding to some kind of product, then you have joined that to both transactions and items groups. Suppose a particular xitem matches with 3 transactions and 5 item groups. You'll get 15 records from that join. And when you sum it, any SUM calculations based on fields from the transaction table will be 5x higher than you expect, and any SUM calculations from the item groups table will be 3x higher than you expect. The key symptom here is the aggregate result being a multiple of the correct value, but seemingly different multiples for different rows. There are multiple ways to address this kind of error. Some developers like to calculate one of hte aggregates in a subquery, then do the other aggregate in the main query and group by the already correct result from the subquery. Others like to write in-line queries to do the aggregate right in the expression: SELECT xitem, (SELECT SUM(i_items_group.or_qty) FROM i_items_group WHERE i_inventory.xid = i_items_group.xitem) AS `openingQty` , -- select more fields Find what approach works best for you. But if you want to see the evidence for yourself, run this query with the aggregates gone and you'll see why those SUMs are doing what they are doing: SELECT i_inventory.xid, x_transaction_details.xitem AS occurrence, i_inventory.xitem AS itemName, i_items_group.or_qty, x_transaction_details.cost, x_transaction_details.qty, i_items_group.or_qty - x_transaction_details.qty AS RemainingQty FROM x_transaction_details LEFT JOIN i_inventory ON x_transaction_details.xitem = i_inventory.xid LEFT JOIN i_items_group ON i_inventory.xid = i_items_group.xitem WHERE (x_transaction_details.date_at BETWEEN '2015-01-18 03:14:54' AND '2015-10-18 03:14:54') AND i_inventory.xid = 3840 ORDER BY occurrence DESC
{ "pile_set_name": "StackExchange" }
Q: Why is my large file when extracted is of very less size on google colab? I am using the 'Dogs vs. Cats Redux: Kernels Edition' dataset from kaggle for a deep learning model. import os from getpass import getpass user = getpass('Kaggle Username: ') key = getpass('Kaggle API key: ') if '.kaggle' not in os.listdir('/root'): !mkdir ~/.kaggle !touch /root/.kaggle/kaggle.json !chmod 666 /root/.kaggle/kaggle.json with open('/root/.kaggle/kaggle.json', 'w') as f: f.write('{"username":"%s","key":"%s"}' % (user, key)) !kaggle competitions download -c dogs-vs-cats-redux-kernels-edition I have downloaded it in my colab notebook environment, the total dataset size(test+train) is of approximately greater than 800mbs. ls -sh 112K sample_submission.csv 272M test.zip 544M train.zip However, when I extract the train and test zip, why is the size of the extracted file so less? unzip test.zip && unzip train.zip ls -sh total 816M 112K sample_submission.csv 272M test.zip 544M train.zip 276K test 752K train The unzip happens without the quiet mode so I can see the files are getting extracted one by one Also I can see the images inside the test folder which are completely accessible through the side directory I thought this was some size display bug by the ls command and the files are really extracted, but when running the training code, it throws error related to images not found. I unzipped some files by uploading a small dataset locally and they are working fine, so unzip is working fine too, same is the case with 7z and python unzipping. Any approach towards the problem or alternate solution would be helpful. A: You're looking at the size of the directory instead of the size of its contents. Try checking the size with du instead.
{ "pile_set_name": "StackExchange" }
Q: Changing username and password in MYSQL I tried to change MySQL username and password: mysql> UPDATE mysql.user SET user='myuser', password=PASSWORD('mypassword') WHERE user='root'; Query OK, 0 rows affected (0.00 sec) Rows matched: 0 Changed: 0 Warnings: 0 mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec) but now mysql won't let me in and can't try anything else. :/ A: Try to create new user CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'password'. GRANT ALL PRIVILEGES ON * . * TO 'new_user'@'localhost'; FLUSH PRIVILEGES; To change Password of root user: UPDATE user SET Password=PASSWORD('YOURNEWPASSWORD') WHERE User='root'; FLUSH PRIVILEGES; exit; To change Password for myuser : UPDATE mysql.user SET Password=PASSWORD('YOURNEWPASSWORD') WHERE User='myuser';
{ "pile_set_name": "StackExchange" }
Q: Does having category name in permalinks affect SEO when having a post in multiple categories? If I change the permalink structure to the following in the Permalinks settings page in WordPress: www.example.com/%category%/%postname%/ Then I create a post with the slug my-post and add two categories for that post category1 and category2, will Google see this as duplicate content because if you go to both these links: www.example.com/category1/my-post/ www.example.com/category2/my-post/ They will go to the same post but the URL does not change, isn't this classed as duplicate content? Will Google and other search engines penalise a site that uses this practice? What is the recommend approach to this problem? A: It should not affect it because Wordpress redirects links to post leaving you with only one canonical and working one. Post would be visible in both categories but will have only one correct permalink.
{ "pile_set_name": "StackExchange" }
Q: Page View Counter Counting Up Adding 2 Instead Of 1 This code iv written is working as i like, but for some reason when refreshing the page counter adds 2 instead of 1, the Views column is as an Integer. $updateviews = $db->prepare("UPDATE pages SET views = views + 1 WHERE type = 'home'"); $updateviews->execute(); Hope someone can help, cant seam to find the problem. A: Iv fixed it, im not sure what iv done but just playing with code over time and i checked it again today and now it works.. strange.
{ "pile_set_name": "StackExchange" }
Q: Issue with ArrayList from JSON using Retrofit and populating RecyclerView I’ve been trying to get recycler view working with retrofit. I seem to be pulling in the JSON fine from within getRecipes() method, and my logs are showing me that the some data is there. However, when I call my getRecipes() method from onCreate(), something seems to be going wrong. When I check to see if my recipeList array contains my JSON results within onCreate, it is telling me it is empty. Why is it doing this if my logs within my getRecipes() method are showing me that data is there...? Not sure if it is an issue with my recycler view or what I am doing with retrofit, or something else. Been trying for days to figure out, so any advice would be greatly appreciated. JSON https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json public class ItemListActivity extends AppCompatActivity { private boolean mTwoPane; public static final String LOG_TAG = "myLogs"; public static List<Recipe> recipeList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getRecipes(); setContentView(R.layout.activity_item_list); getRecipes(); //Logging to check that recipeList contains data if(recipeList.isEmpty()){ Log.d(LOG_TAG, "Is empty"); }else { Log.d(LOG_TAG, "Is not empty"); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle(getTitle()); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.item_list); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList); recyclerView.setAdapter(simpleItemRecyclerViewAdapter); if (findViewById(R.id.item_detail_container) != null) { mTwoPane = true; } } public void getRecipes(){ String ROOT_URL = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/"; Retrofit RETROFIT = new Retrofit.Builder() .baseUrl(ROOT_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); RecipeService service = RETROFIT.create(RecipeService.class); Call<List<Recipe>> call = service.getMyJson(); call.enqueue(new Callback<List<Recipe>>() { @Override public void onResponse(Call<List<Recipe>> call, Response<List<Recipe>> response) { Log.d(LOG_TAG, "Got here"); if (!response.isSuccessful()) { Log.d(LOG_TAG, "No Success"); } Log.d(LOG_TAG, "Got here"); recipeList = response.body(); //Logging to check data is there Log.v(LOG_TAG, "LOGS" + recipeList.size()); for (int i = 0; i < recipeList.size(); i++) { String newString = recipeList.get(i).getName(); Ingredients[] ingredients = recipeList.get(i).getIngredients(); for(int j = 0; j < ingredients.length; j++){ Log.d(LOG_TAG, ingredients[j].getIngredient()); } Steps[] steps = recipeList.get(i).getSteps(); for(int k = 0; k < steps.length; k++){ Log.d(LOG_TAG, steps[k].getDescription()); } Log.d(LOG_TAG, newString); } } @Override public void onFailure(Call<List<Recipe>> call, Throwable t) { Log.e("getRecipes throwable: ", t.getMessage()); t.printStackTrace(); } }); } public class SimpleItemRecyclerViewAdapter extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> { private final List<Recipe> mValues; public SimpleItemRecyclerViewAdapter(List<Recipe> items) { mValues = items; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_list_content, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { holder.mItem = mValues.get(position); holder.mContentView.setText(mValues.get(position).getName()); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mTwoPane) { Bundle arguments = new Bundle(); arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getId()); ItemDetailFragment fragment = new ItemDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .replace(R.id.item_detail_container, fragment) .commit(); } else { Context context = v.getContext(); Intent intent = new Intent(context, ItemDetailActivity.class); intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getId()); context.startActivity(intent); } } }); } @Override public int getItemCount() { return mValues.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public View mView; public TextView mContentView; public Recipe mItem; public ViewHolder(View view) { super(view); mView = view; mContentView = (TextView) view.findViewById(R.id.content); } @Override public String toString() { return super.toString() + " '" + mContentView.getText() + "'"; } } } RecipeService public interface RecipeService { @GET("baking.json") Call<List<Recipe>> getMyJson();} Models Recipe public class Recipe{ private Ingredients[] ingredients; private String id; private String servings; private String name; private String image; private Steps[] steps; public Ingredients[] getIngredients () { return ingredients; } public void setIngredients (Ingredients[] ingredients) { this.ingredients = ingredients; } public String getId () { return id; } public void setId (String id) { this.id = id; } public String getServings () { return servings; } public void setServings (String servings) { this.servings = servings; } public String getName () { return name; } public void setName (String name) { this.name = name; } public String getImage () { return image; } public void setImage (String image) { this.image = image; } public Steps[] getSteps () { return steps; } public void setSteps (Steps[] steps) { this.steps = steps; } @Override public String toString() { return "[ingredients = "+ingredients+", id = "+id+", servings = "+servings+", name = "+name+", image = "+image+", steps = "+steps+"]"; }} Ingredients public class Ingredients{ private String measure; private String ingredient; private String quantity; public String getMeasure () { return measure; } public void setMeasure (String measure) { this.measure = measure; } public String getIngredient () { return ingredient; } public void setIngredient (String ingredient) { this.ingredient = ingredient; } public String getQuantity () { return quantity; } public void setQuantity (String quantity) { this.quantity = quantity; } @Override public String toString() { return "[measure = "+measure+", ingredient = "+ingredient+", quantity = "+quantity+"]"; }} Steps public class Steps{ private String id; private String shortDescription; private String description; private String videoURL; private String thumbnailURL; public String getId () { return id; } public void setId (String id) { this.id = id; } public String getShortDescription () { return shortDescription; } public void setShortDescription (String shortDescription) { this.shortDescription = shortDescription; } public String getDescription () { return description; } public void setDescription (String description) { this.description = description; } public String getVideoURL () { return videoURL; } public void setVideoURL (String videoURL) { this.videoURL = videoURL; } public String getThumbnailURL () { return thumbnailURL; } public void setThumbnailURL (String thumbnailURL) { this.thumbnailURL = thumbnailURL; } @Override public String toString() { return "[id = "+id+", shortDescription = "+shortDescription+", description = "+description+", videoURL = "+videoURL+", thumbnailURL = "+thumbnailURL+"]"; }} Logs https://gist.github.com/2triggers/12b6eeb32ed8909ab50bbadd4742d7f7 A: it is because you are sending the recipelist into the adapter before even it is populated , after you are sending the recipelist into the adapter which is empty you are populating your recipelist from getRecipes method, you might be wondering you have declared the getRecipes method before even you are assigning the recipelist to adapter so how come it is empty, yea but the fact is your getRecipes work on background thread so even before your recipelist gets populated your adapter assignment takes place on the main thread so you are basically assigning the empty list, one thing you can do is notify when the adapter when the data changes or when the the recipelist is filled with data that is from within the getRecipe method. when you assign the recipelist = response.body right after this you can notify the adapter or move this two lines SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList); recyclerView.setAdapter(simpleItemRecyclerViewAdapter); right after the recipelist = response.body; in getRecipes method
{ "pile_set_name": "StackExchange" }
Q: Why noise in GAN's are random? I was learning about GAN's and how it can be used for creating images of cat, dog, mouse and bird. This is how I think in supervised learning system we train the features and labels to generate images. cat,dog,mouse, bird = 0,1,2,3 X Y 1 dog.jpg 3 bird.jpg 0 cat.jpg 0 cat1.jpg . . . . train(X,Y) after training for generating a image predict(0) #generates cat image predict(2) #generates mouse image Because GAN is an unsupervised learning system it learns to generate images using adversarial training. What I have seen in others implementation of GANs is that they add a noise as an input to the generator. The noise is generally a continuous number between 0 and 1. Why do they add random number as noise? why cant they simply add some numbers for example cat,dog,mouse, bird = [0,1,2,3]? A: The way you can think of noise is as an embedding which has information about the texture, the style, orientation etc. And the task of the generator is to use this embedding and figure out a way to map these embeddings to Image space. As far as your questions go,if we only use label [0,1,2,3] you are making it a deterministic problem and forcing it to generate only one image. Thats not what we want from the GAN.We want to generate multiple images of the same class.
{ "pile_set_name": "StackExchange" }
Q: Javascript/jQuery pure javascript equivalent of code I'm looking to translate this code into pure javascript so I don't have to use jquery: $('#msg').show(0).delay(5000).hide(0); What would be the javascript equivalent? A: You can use the following code: document.getElementById("msg").style.display = 'block'; setTimeout(function () { document.getElementById("msg").style.display = 'none'; }, 5000); #msg {background: #f90; width: 50px; height: 50px;} <div id="msg"> Hello </div> I have given the CSS for demo purposes to be clear.
{ "pile_set_name": "StackExchange" }
Q: Scoping issue memoising bash function with associative array I have a bash script which uses jq to look up 'dependency' data in some JSON, and take the closure (find dependencies of dependencies of dependencies, etc.). This works fine, but can be very slow, since it may look up the same dependencies over and over, so I'd like to memoise it. I tried using a global associative array to associate arguments with results, but the array doesn't seem to be storing anything. I've extracted the relevant code into the following demo: #!/usr/bin/env bash # Associative arrays must be declared; use 'g' for global declare -Ag MYCACHE function expensive { # Look up $1 in MYCACHE if [ "${MYCACHE[$1]+_}" ] then echo "Using cached version" >> /dev/stderr echo "${MYCACHE[$1]}" return fi # Not found, perform expensive calculation RESULT="foo" echo "Caching result" >> /dev/stderr MYCACHE["$1"]="$RESULT" # Check if the result was cached if [ "${MYCACHE[$1]+_}" ] then echo "Cached" >> /dev/stderr else abort "Didn't cache" fi # Done echo "$RESULT" } function abort { echo "$1" >> /dev/stderr exit 1 } # Run once, make sure result is "foo" [[ "x$(expensive "hello")" = "xfoo" ]] || abort "Failed for hello" # Run again, make sure "Using cached version" is in stderr expensive "hello" 2>&1 > /dev/null | grep "Using cached version" || abort "Didn't use cache" Here are my results: $ ./foo.sh Caching result Cached Didn't use cache The fact we get Cached seems to indicate that I'm storing and looking up values correctly, but they're not preserved across invocations of expensive since we hit the Didn't use cache branch. It looks like a scoping issue to me, maybe caused by the declare. However, declare -A seems to be a requirement for using associative arrays. Here's my bash version: $ bash --version GNU bash, version 4.3.42(1)-release (i686-pc-linux-gnu) Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software; you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. As well as figuring out the behaviour I'm experiencing, I'd also appreciate alternative ways of memoising functions in bash (preferably nothing which touches the filesystem, even if it's RAM-based) A: You have a few issues: declare -g is only meaningful inside a function. Outside, a variable is already global. A global variable is only global to the process in which it is declared. You can't have global variables shared across processes. Running expensive inside a command substitution does so in a separate process, so the cache it creates and populates disappears with that process. Running expensive as the first command of a pipeline also creates a new process; the cache it uses is only visible to that process. You can work around this by making sure expensive is only run in the current shell with expensive "hello" > tmp.txt && read result < tmp.txt [[ $foo = foo ]] || abort ... expensive "hello" 2>&1 > /dev/null < <(grep "Using cached version") || abort "Didn't use cache" Shell scripting, however, is simply not designed for this type of data processing. If caching is important, use a different language with better support for data structures and in-memory handling of data. Shell is optimized for starting new processes and managing input/output files.
{ "pile_set_name": "StackExchange" }
Q: Android ViewFlipper to flip pages on a Listview I have a ListView in Android that I want to split in pages that fit the size of the screen. This is the code for listview xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="1"> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:textFilterEnabled="true" android:layout_height="match_parent" > </ListView> </LinearLayout> I know that in order to use ViewFlipper you need to have as much views (ListViews in ths case) as you need inside 'ViewFlipper /ViewFlipper' Tags. Here's my problem: My list fills from SQL querys and you can filter it, so the list sometimes have 3 pages, sometimes have 10.... So my question is: Is there any way to dynamically generate another ListView to use ViewFlipper or... is there any way to modify the xml dinamically and add Listview tags depending on how many pages I need to show? A: A tricky way is to add only one listView to ViewFlipper. now reload contents of desired page on flips in same listview . this will give you not only provide you showNext() and showPrevious() effects , but also good for memory consumption , because listview itself is very optimized in terms of rendering .
{ "pile_set_name": "StackExchange" }
Q: Using Accessorizer doesn't paste generated code I'm trying to get into Accessorizer, but every time I am trying it, I run into the same problem. I select some code (for example, multiple @property statements), hit cmd-c and move my cursor to the place I want the generated code to be. I now use Accessorizer's menu, select Implementation and my copied properties are pasted in, instead of @synthesize statements. As far as I can see, I followed the setup instructions precisely. I don't like the difficult to use shortcuts, so I would like to use the system menu, at least for now. A: Ah, so you need to invoke the Accessorizer text service by pressing shift-alt-cmd-0 instead of cmd-c. That sends the text to Accessorizer. Only after you've done this, you can use the Action Menu / press shift-ctrl-cmd-0.
{ "pile_set_name": "StackExchange" }