text
stringlengths
64
89.7k
meta
dict
Q: Apache rewrite : how avoid to display url parameter when the url final slash is omitted? In my .htacess of my domain, I must point subdomain to the 1rst GET parameter of the domain. The subdomain represents the language (for example en., fr, etc...). In order to achieve this aim, here the rewrite code in the .htaccess : Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^(.*)\.example\.com$ [NC] RewriteRule ^(.*)$ $1?lang=%1 [NC,L] I create a directory named test. This directory contains just index.html file. So when you type in the url bar of a browser en.example.com/test/, the rewrite code works. But if you type en.example.com/test without the final slash, it redirects to en.example.com/test/?lang=en => it's a problem. So have you an idea to correct that ? Thank you in advance, cordially. A: When specifying xx.example.com/test/, an internal redirect occurs to xx.example.com/test/?lang=xx. The client never sees the ?lang=xx. However, when specifying xx.example.com/test, where test is a directory, mod_dir steps in and rewrites the URL to xx.example.com/test/, but in such a way that the rewrite rule for the ?lang=xx redirect becomes public, having the client see xx.example.com/test/?lang=xx as the URL - which is unwanted. In order to keep the '?lang=' redirect local (hidden from the client) place this in the .htaccess, BEFORE the original rewrite rules: RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^(.+[^/])$ $1/ [R,L] The condition checks whether the requested filename is a directory, and the rule forces a client-side redirect [R], so that a client requesting xx.example.com/test will be redirected to xx.example.com/test/. The key however is the [L], which makes this rule the Last, preventing the following rules from executing. Without this L flag, the entire redirect from xx.example.com/test to xx.example.com/test/?lang=xx becomes public. After the client is forcefully redirected to the proper URL with a terminating /, the rewrite rules doing the internal redirect adding the lang GET parameter are executed as normal. Here's the entire .htaccess: Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^(.+[^/])$ $1/ [R,L] RewriteCond %{HTTP_HOST} ^(.*)\.example\.com$ [NC] RewriteRule ^(.*)$ $1?lang=%1 [NC,L] There is however another way to achieve this without using Apache config and internal redirect, and that is to examine $_SERVER['SERVER_NAME']: <?php list( $lang ) = explode('.', $_REQUEST['SERVER_NAME'] );
{ "pile_set_name": "StackExchange" }
Q: Perl Moose TypeDecorator error. How do I debug? Hey guys. I've recently run into a problem I'd greatly appreciate any insight into. I posted a similar question prior to Christmas over at PerlMonks with some feedback to switch away from MooseX::Declare ([http://www.perlmonks.org/?node_id=877703][1]). I have now switched the code over to vanilla Moose with MooseX::Types and MooseX::Params::Validate. However, the same error is occurring in the same spot. Not surprising since it appears to be MooseX::Types related. I am getting the following error (tried to space this out for readability and bottom of stack truncated): plxc16479> tmp10.pl Argument cannot be 'name' at /nfs/pdx/disks/nehalem.pde.077/perl/lib64/site_perl/MooseX/Types/TypeDecorator.pm line 88 MooseX::Types::TypeDecorator::new('MooseX::Types::TypeDecorator=HASH(0x1620c58)', 'name', 'g1145114N5582201_16161616a2x_FU02xxT_2bxc2e3_6x0xxxp0fx0xxx0x...', 'mask_data', '', 'tags', 0) called at /nfs/pdx/disks/nehalem.pde.077/projects/lib/Program-Plist-Pl/lib/Program/Plist/Pl.pm line 61 Program::Plist::Pl::_create_pattern_obj(undef, 'name', 'g1145114N5582201_16161616a2x_FU02xxT_2bxc2e3_6x0xxxp0fx0xxx0x...', 'mask_data', '', 'tag_data', '') called at /nfs/pdx/disks/nehalem.pde.077/projects/lib/Program-Plist-Pl/lib/Program/Plist/Pl.pm line 77 Program::Plist::Pl::BUILD('Program::Plist::Pl=HASH(0x162d6c0)', 'HASH(0x162d648)') called at generated method (unknown origin) line 101 Program::Plist::Pl::new('Program::Plist::Pl', 'name', 'bist_hfmmin_16161616_list', 'parents', 'HASH(0xccf040)', 'fh', 'GLOB(0xccc928)', 'external_pl_code', 'CODE(0x14910b0)', ...) called at /nfs/pdx/disks/nehalem.pde.077/projects/lib/Program-Roles-PlHandler/lib/Program/Roles/PlHandler.pm line 52 Program::Roles::PlHandler::_create_global_pl_obj(undef, 'name', 'bist_hfmmin_16161616_list', 'parents', 'HASH(0xccf040)', 'fh', 'GLOB(0xccc928)') called at /nfs/pdx/disks/nehalem.pde.077/projects/lib/Program-Plist-Pl/lib/Program/Plist/Pl.pm line 77 Program::Plist::Pl::BUILD('Program::Plist::Pl=HASH(0xccd300)', 'HASH(0xccc628)') called at generated method (unknown origin) line 101 Program::Plist::Pl::new('Program::Plist::Pl', 'name', 'bist_list', 'parents', 'HASH(0xccce80)', 'fh', 'GLOB(0xccc928)', 'external_pl_code', 'CODE(0x14910b0)', ...) called at /nfs/pdx/disks/nehalem.pde.077/projects/lib/Program-Roles-PlHandler/lib/Program/Roles/PlHandler.pm line 52 The problem i seems to be the top call to TypeDecorator::new. The TypeDecorator constructor seems to expect two arguments, the class/self argument and a reference to a TypeDecorator or TypeConstraint object. Instead, it's somehow receiving the arguments from my create pattern object call. I have verified that the arguments coming into the _create_pattern_obj function are correct and that the arguments going into the Pattern->new call are also correct (borne out by the stack traced arguments). The _create_pattern_obj function looks like this: sub _create_pattern_obj { my ($self, $name, $mask_data, $tag_data) = validated_list(\@_, name => {isa => Str}, mask_data => {isa => Str, optional => 1}, tag_data => {isa => Str, optional => 1}); $mask_data = '' if !defined $mask_data; my $tags = defined $tag_data ? map {$_ => 1} split(',', $tag_data) : {}; my $pattern_obj = Program::Plist::Pl::Pattern->new(name => $name, mask_data => $mask_data, tags => $tags); $self->_add_pattern($pattern_obj); } The function is dieing on the Program::Plist::Pl::Pattern->new call, which is the line 61 in file Pl.pm file referenced in the above call stack where the TypeDecorator::new call is claiming to come from. The Pattern class is: package Program::Plist::Pl::Pattern; use 5.012002; our $VERSION = sprintf "2.%03d", q($Revision: 473 $) =~ /: (\d+)/; use Moose; use namespace::autoclean; use MooseX::Types::Moose qw(Str Num Int HashRef); use MooseX::Params::Validate; has 'name' => (isa => Str, is => 'ro', required => 1); has 'tuple' => (isa => Int, is => 'ro'); has 'tid' => (isa => Int, is => 'ro'); has 'weight' => (isa => Num, is => 'ro'); has 'tags' => (isa => HashRef[Str], is => 'ro', default => sub {{}}); has 'mask_data' => (isa => Str, is => 'rw', default => '', writer => '_set_mask_data'); sub has_tag { my ($self, $tag) = (shift, pos_validated_list(\@_, {isa => Str})); exists $self->{tags}->{$tag} ? return 1 : return 0; } sub _add_tag { my ($self, $tag) = (shift, pos_validated_list(\@_, {isa => Str})); $self->{tags}->{$tag} = 1; } sub BUILDARGS { print STDERR 'CALLED '.__PACKAGE__."BUILDARGS\n"; print STDERR 'ARGUMENTS:'.join(',', @_)."\n"; } sub BUILD { my ($self) = @_; print STDERR 'CALLED '.__PACKAGE__."::BUILD\n"; } __PACKAGE__->meta->make_immutable; 1; Somehow, judging from the arguments in the call stack, my arguments to the Pattern->new call are ending up being passed to the TypeDecorator::new call and it's choking on them. I've verified that a good call to this subroutine (from and earlier stack trace) looks like this (note the two arguments): DB<1> T $ = MooseX::Types::TypeDecorator::new('MooseX::Types::TypeDecorator', ref(Moose::Meta::TypeConstraint)) called from file `/nfs/pdx/disks/nehalem.pde.077/perl/lib64/site_perl/MooseX/Types.pm' line 464 The problem is that I can't figure out how to debug what's going on. When stepping through the code, execution passes directly from the Pattern->new call to the TypeDecorator code. This is occurring prior to any of my class code executing. I know Moose is creating the new method for me, but I can't figure out how to debug code I can't look at. I've looked through documentation on Moose, but that's all on how to use it as opposed to what's going on under the hood. I did read through the Class::MOP documentation, but I'm unclear as to exactly where this code is being created and when. While I've learned a fair bit from all my research, none of it has directly help me with my problem :) First off, any ideas as to what's occurring would be appreciated. Second, how do I debug into this issue? All my usual debug tools have failed me! The execution is jumping directly from my new call to the problem code and I can't seem to trace where the TypeDecorator::new arguments are actually being passed from. Lastly, are there any good writeups out there on exactly how Moose does what it does? Or Class::MOP? Edit - Here are my type definitions. I might add this is my first foray into Moose, so if you see anything I'm doing that's odd feel free to point it out. package Program::Types; use 5.012002; use strict; use warnings; our $VERSION = sprintf "2.%03d", q($Revision: 473 $) =~ /: (\d+)/; # predeclare types use MooseX::Types -declare => [qw(NonemptyStr FilePath DirectoryPath FilePathThatExists DirectoryPathThatExists TwoDigNum Pl LocalPl Pattern Program_Env Program_Whichload Program_Tpl Program_Plist Program_Bmfc Program_Tpl_Test Program_Tpl_Flow Program_Tpl_Flow_Item Program_Tpl_Flow_Item_Result Word)]; # import some MooseX builtin types that will be built on use MooseX::Types::Moose qw(Str Int Object); # types base on some objects that I use class_type Pl, {class => 'Program::Plist::Pl'}; class_type LocalPl, {class => 'Program::Plist::LocalPl'}; class_type Pattern, {class => 'Program::Plist::Pl::Pattern'}; class_type Program_Env, {class => 'Program::Env'}; class_type Program_Whichload, {class => 'Program::Whichload'}; class_type Program_Tpl, {class => 'Program::Tpl'}; class_type Program_Tpl_Test, {class => 'Program::Tpl::Test'}; class_type Program_Tpl_Flow, {class => 'Program::Tpl::Flow'}; class_type Program_Tpl_Flow_Item, {class => 'Program::Tpl::Flow::Item'}; class_type Program_Tpl_Flow_Item_Result, {class => 'Program::Tpl::Flow::Item::Result'}; class_type Program_Plist, {class => 'Program::Plist'}; class_type Program_Bmfc, {class => 'Program::Bmfc'}; subtype Word, as Str, where {$_ =~ /^\w*$/}; coerce Word, from Str, via {$_}; subtype NonemptyStr, as Str, where {$_ ne ''}; coerce NonemptyStr, from Str, via {$_}; subtype TwoDigNum, as Int, where {$_ =~ /^\d\d\z/}, message {'TwoDigNum must be made of two digits.'}; coerce TwoDigNum, from Int, via {$_}; subtype FilePath, as Str, where {!($_ =~ /\0/)}, message {'FilePath cannot contain a null character'}; coerce FilePath, from Str, via {$_}; subtype DirectoryPath, as Str, where {!($_ =~ /\0/)}, message {'DirectoryPath cannot contain a null character'}; coerce DirectoryPath, from Str, via {$_}; subtype FilePathThatExists, as Str, where {(!($_ =~ /\0/) and -e $_)}, message {'FilePathThatExists must reference a path to a valid existing file.'. "Path ($_)"}; coerce FilePathThatExists, from Str, via {$_}; coerce FilePathThatExists, from FilePath, via {$_}; subtype DirectoryPathThatExists, as FilePath, where {(!($_ =~ /\0/) and -d $_)}, message {'DirectoryPathThatExists must reference a path to a valid existing '. "directory. Path ($_)"}; coerce DirectoryPathThatExists, from Str, via {$_}; coerce DirectoryPathThatExists, from DirectoryPath, via {$_}; 1; Edit2 -- Removed due to obvious operator error :) Note that I am using BUILDARGS in the Pattern class without returning the argument list. I have removed this in current code with no change to the error. Phaylon, Here's the Program::Plist::Pl class. package Program::Plist::Pl; use 5.012002; our $VERSION = sprintf "2.%03d", q($Revision: 473 $) =~ /: (\d+)/; use Moose; use namespace::autoclean; use Program::Plist::Pl::Pattern; use Program::Types qw(Pl LocalPl TwoDigNum Pattern); use Program::Utils qw(rchomp); use MooseX::Types::Moose qw(HashRef GlobRef Str); use MooseX::Params::Validate; with 'Program::Roles::PlHandler'; has 'name' => (isa => Str, is => 'ro', required => 1); has 'parents' => (isa => HashRef[Pl|LocalPl], is => 'ro', required => 1); has 'children' => (isa => HashRef[Pl|LocalPl], is => 'ro'); has 'prefixes' => (isa => HashRef[TwoDigNum], is => 'ro', default => sub{{}}); has 'patterns' => (isa => HashRef[Pattern], is => 'ro', default => sub{{}}); sub _add_child { my ($self, $obj) = (shift, pos_validated_list(\@_, {isa => Pl|LocalPl})); $self->{children}->{$obj->name} = $obj; } sub _add_pattern { my ($self, $obj) = (shift, pos_validated_list(\@_, {isa => Pattern})); $self->{patterns}->{$obj->name} = $obj; } sub _create_pattern_obj { $DB::single = 1; my ($self, $name, $mask_data, $tag_data) = validated_list(\@_, name => {isa => Str}, mask_data => {isa => Str, optional => 1}, tag_data => {isa => Str, optional => 1}); $mask_data = '' if !defined $mask_data; my $tags = defined $tag_data ? map {$_ => 1} split(',', $tag_data) : {}; $DB::single = 1; my $pattern_obj = Program::Plist::Pl::Pattern->new(name => $name, mask_data => $mask_data, tags => $tags); $self->_add_pattern($pattern_obj); } sub BUILD { my ($self, $fh) = (shift, pos_validated_list([$_[0]->{fh}], {isa => GlobRef})); while (<$fh>) { # skip empty or commented lines rchomp; next if ((/^\s*#/) or (/^\s*$/)); # handle global plist declarations if (my @m = /^\s*GlobalPList\s+(\w+)/) { # creating new object and adding it to our data print STDERR # "SELF($self)\n".join("\n",sort keys # %Program::Plist::Pl::)."\n"; $self->_create_global_pl_obj(name => $m[0], parents => {%{$self->parents}, $self->name => $self}, fh => $fh); } # handle local referenced plist declarations elsif (@m = /^\s*PList\s+(\w+):(\w+)/) { $self->_create_local_pl_obj(file => $m[0], name => $m[1]); } # handling pattern lines elsif (@m = /^\s*Pat\s+(\w+)\s*(\[.*\])?\s*;\s*(#([\w,])#)?\s*$/) { $self->_create_pattern_obj(name => $m[0], mask_data => do {defined $m[1] ? $m[1] : ''}, tag_data => do {defined $m[2] ? $m[2] : ''}); } # handling our patlist closure elsif (/^\s*\}/) { last; } } # need to populate our hash of child plists for (@{$self->data}) { if (($_->isa('Pl')) or ($_->isa('LocalPl'))) { $self->_add_child($_); } } } __PACKAGE__->meta->make_immutable; 1; A: The problem is I believe here. use Program::Types qw(Pl LocalPl TwoDigNum Pattern); You're importing a function named Pattern into your Program::Plist::Pl class. You then call this function (unintentionally) here: my $pattern_obj = Program::Plist::Pl::Pattern->new(name => $name, mask_data => $mask_data, tags => $tags); Specifically Program::Plist::Pl::Pattern resolves to your fully qualified function name rather than to the Class (technically package name) you're expecting. This function returns a TypeObject which you then call new() on. Note: This is exactly what phaylon suggests in the comments above. There really is no way to debug this except to know that you can always call a function with it's fully qualified name, and thus should never have a MooseX::Type and a valid Class name collide. If it were me I'd start writing a very simple test case and add code to replicate the original file until it breaks. I'd probably start with the call to new. Then slowly add back assumptions until I found the one that breaks. Hopefully you add the MooseX::Types call early enough in that process that it triggers the "oh duh obviously that is it" moment.
{ "pile_set_name": "StackExchange" }
Q: "%s ", string not printing space after string In this code snippet here: printf("shell> "); fgets(input, MAX_INPUT_SIZE, stdin); //tokenize input string, put each token into an array char *space; space = strtok(input, " "); tokens[0] = space; int i = 1; while (space != NULL) { space = strtok(NULL, " "); tokens[i] = space; ++i; } //copy tokens after first one into string strcpy((char*)cmdargs, ("%s ",tokens[1])); for (i = 2; tokens[i] != NULL; i++) { strcat((char*)cmdargs, ("%s ", tokens[i])); } printf((char*)cmdargs); With the input: echo hello world and stuff, the program prints: helloworldandstuff It seems to me that the line strcat((char*)cmdargs, ("%s ", tokens[i])); should concatenate the string at tokens[i] with a space following it. Does strcat not work with string formatting? Any other ideas what might be going on? A: strcat does not support formatting strings, it just does concatenation. Moreover, your use of the extra pair of parenthesis cause the C compiler to parse this as a comma operator, and not as arguments passed to the function. That is, strcat((char*)cmdargs, ("%s ", tokens[i])); will result in a call strcat((char*)cmdargs, tokens[i]); as the comma operator invoke side-effect of all expression, but return the last value. If you want to use strcat, you should write: strcat((char*)cmdargs, " "); strcat((char*)cmdargs, tokens[i]); The same thing apply to the strcpy function call too.
{ "pile_set_name": "StackExchange" }
Q: Which format of "May 28, 2013 6:04:38 PM"? I trying parse the String "May 28, 2013 6:04:38 PM" to Date with SimpleDateFormat, but I couldn't do it. Below is what I did: public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a"); try { System.out.println(sdf.parse("May 28, 2013 6:04:38 PM")); } catch (ParseException e) { e.printStackTrace(); } } the error: java.text.ParseException: Unparseable date: "May 28, 2013 6:04:38 PM" at java.text.DateFormat.parse(DateFormat.java:377) at com.test(DateUtil.java:71) A: Try this: DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMMM d, y h:mm:ss a"); String datestr = "May 28, 2013 1:04:38 PM"; LocalDateTime dateTime = LocalDateTime.parse(datestr, dtf); System.out.println(dateTime.format(dtf));
{ "pile_set_name": "StackExchange" }
Q: How to get the element in the control template in Silverlight? I want to get the element in the control template from code behind. In the XAML below I want to get the Border element "btnBorder" and change the color from red to any other color from code behind. <Window x:Class="WpfApplication4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <StackPanel Name ="st" Margin="0,3,0,3" Grid.Row="4" Orientation="Horizontal"> <Button Name="btn" Height="22" Margin="0,0,25,0"> <Button.Template x:Uid="dd"> <ControlTemplate x:Name="tmp" TargetType="Button"> <Border x:Name="btnBorder" Background="Red"> <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" /> </Border> </ControlTemplate> </Button.Template> Test Button </Button> </StackPanel> </Grid> </Window> I have tried various methods like GetTemplateChild("btnBorder") object o = template.FindName("btnBorder", this.btn); but these methods are returning null. Please let me know where I am doing wrong or what is the correct way to access the template child from code behind? A: You can set BorderBrush of your Button and bind it with BorderBrush of Border control in ControlTemplate. So when you will set BorderBrush for your Button from code behind it will reflect to underlying binding and so on your Border control in ControlTemplate. <Page.Resources> <Style x:Key="MyButtonStyle" TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Border x:Name="btnBorder" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"> <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </Page.Resources> This is how you can apply the Style <StackPanel> <Button Style={StaticResource MyButtonStyle} Name="btn1" Content="Test Button 1" BorderBrush="Red"/> <Button Style={StaticResource MyButtonStyle} Name="btn2" Content="Test Button 2" BorderBrush="Green"/> </StackPanel>
{ "pile_set_name": "StackExchange" }
Q: Sharing instantiated objects in requirejs I'm defining a module Foo and I am instantiating it within another module Bar. I have a third module Other which I'd like to provide with the same instance of Foo that Bar created and modified. define('Foo', [], function() { var test = function() { this.foo = 'foo'; }; return test; }); define('Bar', ['Foo'], function(Foo) { Foo = new Foo(); Foo.bar = 'bar'; console.log('From bar', Foo); }); define('Other', ['Foo'], function(Foo) { console.log('From the other', Foo); }); require(['Foo', 'Bar', 'Other'], function(Foo, Bar, Other) { console.log('Bringing it all together'); }); http://jsfiddle.net/radu/Zhyx9/ Without require, I would be doing something like: App = {}; App.Foo = function() { this.foo = 'foo'; } App.Bar = function() { App.Foo = new App.Foo(); App.Foo.bar = 'bar'; console.log('From bar', App.Foo); } App.Other = function() { console.log('From other', App.Foo); } App.Bar(); App.Other(); http://jsfiddle.net/radu/eqxaA/ I know I must be missing something here and since this is one my first forays in requirejs there is probably some sort of misunderstanding mixed in. The example may look contrived but I'm coming across something similar in shoehorning a project into using Backbone and RequireJS. ​ A: What you expose from the module using return is accessible from the argument that represents that module in the requiring module Here's your demo, modified define('Bar', ['Foo'], function(Foo) { Foo = new Foo(); Foo.bar = 'bar'; //return instantiated Foo return Foo; }); require(['Foo', 'Bar', 'Other'], function(Foo, Bar, Other) { //Bar is the instantiated Foo, exposed from Bar console.log(Bar); }); A: I posted this as comment to one of the answers but I was aware that I could share an instance like so: define('Foo', [], function() { var test = function() { this.foo = 'foo'; }; return new test(); }); define('Bar', ['Foo'], function(Foo) { Foo.bar = 'bar'; console.log('From bar', Foo); }); define('Other', ['Foo'], function(Foo) { Foo.other = 'other'; console.log('From the other', Foo); }); require(['Foo', 'Bar', 'Other'], function(Foo, Bar, Other) { console.log('Bringing it all together'); }); http://jsfiddle.net/radu/XEL6S/ However, the reason I didn't do this in the first place was that the Foo module couldn't instantiate itself as it required the DOM to be ready. However, being new to RequireJS, I wasn't aware that this sort of functionality is built in. In other words, to share an instance of a module Foo as I specified above, instantiate in its definition and add the domReady module as specified in the requireJS docs.
{ "pile_set_name": "StackExchange" }
Q: Why system-wide socks proxy doesn't work for Chrome? First of all, I'm not asking how to enable proxy in Chrome. I've already done it with SwitchySharp extension. The question I'm about to ask, is the mechanism under OSX's network preference setting and chrome's mechanism. The phenomenon: I used ssh -D 7001 my_user@my_host to build a local socks server. And I set System Preferences -> network -> current_wifi -> Advanced -> Proxies -> "Select" SOCKS Proxy -> "Input" 127.0.0.1:7001 At this time point, when I use safari to open a website, it use this 7001 socks proxy, but when use chrome, it doesn't. So, when I set that socks proxy parameters in System Preferences, what did OSX do? And how did Chrome bypass this socks proxy setting? A: It isn't that Chrome bypassed it, it "ignores" it (because it might not have implemented reading the values). I did find some docs that show how to manually set Chrome on Mac to use SOCKS: https://www.chromium.org/developers/design-documents/network-stack/socks-proxy (if my memory bank properly translated what I read). I couldn't find any docs from Google that said: Chrome on MacOS will obey SOCKS prefs. Before someone down votes this because it sounds incorrect... Proxy support for apps usually comes down to three things: Support for HTTP proxy (FTP is really HTTP), HTTPS (Connect) and SOCKS of two versions. Each of these is pretty different than the other, but the standard dialog boxes originally designed by Netscape made them look like they were simply operating in parallel. Users assume that a browser that works with one setting in the dialog should work with all the others, that simply isn't true from a feature/support/protocol/code perspective. For MacOS browsers, the browser developer had to decide if they would support the proxy type, and then how would they read the system settings, if they supported the system settings. This is why for a long time Camino (Mozilla browser for MacOS-only supported OS settings, but Firefox (Mozilla browser for all platforms) did not. (As best as I can remember... I was Proxy QA for Netscape/Mozilla back in the day.)
{ "pile_set_name": "StackExchange" }
Q: LIBSVM how to prepare training dataset with images for logo detection? TASK: I have more them 100 thousands images taken from videos (video frames) and I need to classify which images have logos from my list. THE PROBLEM: I created a library of logo images. For the classification task I'm going to use LIBSVM. I need to transform images to the format of an SVM dataset. I've read through materials on the LIBSVM website, FAQ & "A Practical Guide to Support Vector Classication". But I still can't find answer how to prepare data/images for LIBSVM training. I will appreciate any help. A: You will need to vectorize your data, using a feature set of your choosing which can be computed based on images. I will not elaborate on all the details here, as it would take up way too much space and be off-topic for SO. In short, the best way to vectorize depends largely on the shapes you want to detect (e.g. the logos). The Hough transform is used almost all the time, amongst others, so you may want to look into that. Secondly, object detection is generally performed by running a set of classifiers on many pans/zooms/rotations for each single image. In this context you want to be using classifiers with very low run-time complexity. The linear kernel and intersection kernels are commonly used. Intersection kernels are not provided by LIBSVM, but you can compute them for yourself. For complexity reasons, it is probably more interesting to use LIBLINEAR, which explicitly constructs the separating hyperplane and thus predicts at much lower complexity.
{ "pile_set_name": "StackExchange" }
Q: ng-repeat-start with 3 different TR If you want to repeat this structure with 1 TR/1 TD and 1 TR/2 TDs <tr> <td>Nitish</td> </tr> <tr> <td>26</td> <td>Male</td> </tr> you can do this as taken from http://www.nitishkumarsingh.com/blog/advantage-of-ng-repeat-start-and-ng-repeat-end-repeating-over-multiple-elements/ <table> <tbody> <tr ng-repeat-start="l in list"> <td>{{l.name}}</td> </tr> <tr ng-repeat-end> <td>{{l.age}}</td> <td>{{l.gender}}</td> </tr> </tbody> </table> But what about adding one more TR with one more TD so 3 TDs after 1 and 2 TDs ? <tr> <td>Nitish</td> </tr> <tr> <td>26</td> <td>Male</td> </tr> <tr> <td>767 Fifth Avenue</td> <td>New York, NY 10153</td> <td>(212) 336-1440</td> </tr> A: Just put ng-repeat-end at last tr, so that intermediate template between ng-repeat-start & ng-repeat-end will get repeated. <table> <tbody> <tr ng-repeat-start="l in list"> <td>{{l.name}}</td> </tr> <tr> <td>{{l.age}}</td> <td>{{l.gender}}</td> </tr> <tr ng-repeat-end> <td>{{l.addressLine1}}</td> <td>{{l.addressLine2}}</td> <td>{{l.phoneNumber}}</td> </tr> </tbody> </table>
{ "pile_set_name": "StackExchange" }
Q: How to use LIKE clause with IN caluse in Sql Server? I want to use LIKE clause and IN clause together. e.g: Currently my query is - SELECT * FROM [USER_DETAILS] WHERE [NAME] LIKE 'Dev%' OR [NAME] LIKE 'Deb%' OR ...... ...... How can i use IN clause to achieve this? Can someone please help? :) A: Put the parameter values in a table, then use a single JOIN condition e.g. SELECT * FROM [USER_DETAILS] AS U1 INNER JOIN Params AS P1 ON U1.[NAME] LIKE P1.param + '%';
{ "pile_set_name": "StackExchange" }
Q: r: convert data into another format in an experiment I investigated effort in different tasks with two tools. So I got the following results: Task1ToolA Task1ToolB Task2ToolA Task2ToolB P1 3 NA NA 4 P2 NA 4 5 NA P3 2 NA NA 3 P1, P2, P3 are my test persons. My variables are Task1ToolA, Task1ToolB, Task2ToolA, Task2ToolB. I think for evaluation and plotting, I better had the following: EffortTask1 ToolOfTask1 EffortTask2 ToolOfTask2 P1 3 A 4 B P2 4 B 5 A P3 2 A 3 B Each entry in the first table gives rise to two entries in the second table, one for the score and one for the tool. So, how can I convert this? I am a complete beginner to R and ggplot2. Thanks for your answer. A: Personally, I think that you might benefit from having your data in "long format". First we recreate your data frame: d <- read.table(text='Task1ToolA Task1ToolB Task2ToolA Task2ToolB P1 3 NA NA 4 P2 NA 4 5 NA P3 2 NA NA 3', header=TRUE) And now create a new data frame in long format: d_new <- data.frame( # person: repeat each of the row names as many times as there # are columns. person=rep(row.names(d), ncol(d)), # task: extract the task number (see ?sub), from the column names, # and repeat each as many times as there are rows. task=as.numeric(rep(sub('Task(\\d+).*', '\\1', colnames(d)), each=nrow(d))), # tool: similarly, extract the tool number from the column names, # and repeat each as many times as there are rows. tool=rep(sub('.*Tool(.*)', '\\1', colnames(d)), each=nrow(d)), # score: reduce the data.frame of scores to a vector. score=unlist(d) ) Which looks like: d_new ## person task tool score ## Task1ToolA1 P1 1 A 3 ## Task1ToolA2 P2 1 A NA ## Task1ToolA3 P3 1 A 2 ## Task1ToolB1 P1 1 B NA ## Task1ToolB2 P2 1 B 4 ## Task1ToolB3 P3 1 B NA ## Task2ToolA1 P1 2 A NA ## Task2ToolA2 P2 2 A 5 ## Task2ToolA3 P3 2 A NA ## Task2ToolB1 P1 2 B 4 ## Task2ToolB2 P2 2 B NA ## Task2ToolB3 P3 2 B 3 Optionally, you can remove the (now confusing) row names, and filter out the rows with NA scores: d_new <- na.omit(d_new) row.names(d_new) <- NULL d_new ## person task tool score ## 1 P1 1 A 3 ## 2 P3 1 A 2 ## 3 P2 1 B 4 ## 4 P2 2 A 5 ## 5 P1 2 B 4 ## 6 P3 2 B 3
{ "pile_set_name": "StackExchange" }
Q: ¿Por que se detiene mi app en modo release, pero no en modo debug? Estoy utilizando una librería para visualizar un PDF (flutter_pdfview) el cual no hasta ahora no me causaba problemas. Actualmente probé la aplicación para realizar unas actualizaciones, en modo debug funciona todo bien. Ahora genero el apk con flutter build apk, instalo la app en mi teléfono y al entrar a visualizar el PDF la app se cierra. para intentar encontrar el error he intentado ejecutar flutter run --release, esto ocasiona que mi teléfono se reinicie pero después de 3 o 4 intentos se pudo ejecutar y funciona perfectamente Por si acaso, algunas soluciones y lo que dice la documentación mencionan el uso de proguard el cual no uso, o por lo menos no esta en mi archivo build.gradle Gracias al comentario, puede obtener el log en el cual muestra lo siguiente (solo coloco la parte donde muestra el error ya que lo demás no creo que sea relevante). 2020-06-11 10:15:42.105 12785-12838/? D/OpenGLRenderer: eglCreateWindowSurface = 0xcc79bb90, 0xcaf7e008 2020-06-11 10:15:42.107 12785-12852/? D/jniPdfium: Init FPDF library 2020-06-11 10:15:42.108 12785-12785/? D/ViewRootImpl@5b60fda[MainActivity]: MSG_RESIZED_REPORT: frame=Rect(0, 0 - 1080, 1680) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1 2020-06-11 10:15:42.128 4363-9699/? D/WindowManager: finishDrawingWindow: Window{5e42c8c u0 Sys2030:mx.com.publicacioneselfaro.himnia_musica/mx.com.publicacioneselfaro.himnia_musica.MainActivity} mDrawState=DRAW_PENDING 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] JNI DETECTED ERROR IN APPLICATION: java_class == null 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] in call to GetMethodID 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] from com.shockwave.pdfium.a.a com.shockwave.pdfium.PdfiumCore.nativeGetPageSizeByIndex(long, int, int) 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] "AsyncTask #1" prio=5 tid=21 Runnable 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] | group="main" sCount=0 dsCount=0 flags=0 obj=0x12e0b1b0 self=0xe4452a00 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] | sysTid=12852 nice=10 cgrp=default sched=0/0 handle=0xcab09970 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] | state=R schedstat=( 0 0 0 ) utm=4 stm=5 core=3 HZ=100 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] | stack=0xcaa07000-0xcaa09000 stackSize=1038KB 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] | held mutexes= "mutator lock"(shared held) 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] native: #00 pc 002eedcf /system/lib/libart.so (art::DumpNativeStack(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, int, BacktraceMap*, char const*, art::ArtMethod*, void*)+130) 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] native: #01 pc 003844db /system/lib/libart.so (art::Thread::DumpStack(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, bool, BacktraceMap*, bool) const+206) 2020-06-11 10:15:42.376 12785-12852/? A/zygote: java_vm_ext.cc:534] native: #02 pc 00380a57 /system/lib/libart.so (art::Thread::Dump(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, bool, BacktraceMap*, bool) const+34) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] native: #03 pc 0025187f /system/lib/libart.so (art::JavaVMExt::JniAbort(char const*, char const*)+738) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] native: #04 pc 00251c6b /system/lib/libart.so (art::JavaVMExt::JniAbortF(char const*, char const*, ...)+66) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] native: #05 pc 00286c8b /system/lib/libart.so (art::JNI::GetMethodID(_JNIEnv*, _jclass*, char const*, char const*)+994) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] native: #06 pc 000037d7 /data/app/mx.com.publicacioneselfaro.himnia_musica-heck9rZ6EQdvqxG_4m-dkA==/lib/arm/libjniPdfium.so (Java_com_shockwave_pdfium_PdfiumCore_nativeGetPageSizeByIndex+134) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] native: #07 pc 0000046d /data/app/mx.com.publicacioneselfaro.himnia_musica-heck9rZ6EQdvqxG_4m-dkA==/oat/arm/base.odex (Java_com_shockwave_pdfium_PdfiumCore_nativeGetPageSizeByIndex__JII+100) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] at com.shockwave.pdfium.PdfiumCore.nativeGetPageSizeByIndex(Native method) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] at com.shockwave.pdfium.PdfiumCore.b(:251) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] - locked <0x0d28c339> (a java.lang.Object) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] at c.a.a.a.i.b(:93) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] at c.a.a.a.i.<init>(:82) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] at c.a.a.a.c.a(:51) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] at c.a.a.a.c.doInBackground(:25) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] at android.os.AsyncTask$2.call(AsyncTask.java:333) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] at java.util.concurrent.FutureTask.run(FutureTask.java:266) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] at java.lang.Thread.run(Thread.java:764) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: java_vm_ext.cc:534] 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:542] Runtime aborting... 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:542] 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] JNI DETECTED ERROR IN APPLICATION: java_class == null 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] in call to GetMethodID 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] from com.shockwave.pdfium.a.a com.shockwave.pdfium.PdfiumCore.nativeGetPageSizeByIndex(long, int, int) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] "AsyncTask #1" prio=5 tid=21 Runnable 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] | group="main" sCount=0 dsCount=0 flags=0 obj=0x12e0b1b0 self=0xe4452a00 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] | sysTid=12852 nice=10 cgrp=default sched=0/0 handle=0xcab09970 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] | state=R schedstat=( 0 0 0 ) utm=4 stm=5 core=3 HZ=100 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] | stack=0xcaa07000-0xcaa09000 stackSize=1038KB 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] | held mutexes= "mutator lock"(shared held) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] native: #00 pc 002eedcf /system/lib/libart.so (art::DumpNativeStack(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, int, BacktraceMap*, char const*, art::ArtMethod*, void*)+130) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] native: #01 pc 003844db /system/lib/libart.so (art::Thread::DumpStack(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, bool, BacktraceMap*, bool) const+206) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] native: #02 pc 00380a57 /system/lib/libart.so (art::Thread::Dump(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, bool, BacktraceMap*, bool) const+34) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] native: #03 pc 0025187f /system/lib/libart.so (art::JavaVMExt::JniAbort(char const*, char const*)+738) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] native: #04 pc 00251c6b /system/lib/libart.so (art::JavaVMExt::JniAbortF(char const*, char const*, ...)+66) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] native: #05 pc 00286c8b /system/lib/libart.so (art::JNI::GetMethodID(_JNIEnv*, _jclass*, char const*, char const*)+994) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] native: #06 pc 000037d7 /data/app/mx.com.publicacioneselfaro.himnia_musica-heck9rZ6EQdvqxG_4m-dkA==/lib/arm/libjniPdfium.so (Java_com_shockwave_pdfium_PdfiumCore_nativeGetPageSizeByIndex+134) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] native: #07 pc 0000046d /data/app/mx.com.publicacioneselfaro.himnia_musica-heck9rZ6EQdvqxG_4m-dkA==/oat/arm/base.odex (Java_com_shockwave_pdfium_PdfiumCore_nativeGetPageSizeByIndex__JII+100) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] at com.shockwave.pdfium.PdfiumCore.nativeGetPageSizeByIndex(Native method) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] at com.shockwave.pdfium.PdfiumCore.b(:251) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] - locked <0x0d28c339> (a java.lang.Object) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] at c.a.a.a.i.b(:93) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] at c.a.a.a.i.<init>(:82) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] at c.a.a.a.c.a(:51) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] at c.a.a.a.c.doInBackground(:25) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] at android.os.AsyncTask$2.call(AsyncTask.java:333) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] at java.util.concurrent.FutureTask.run(FutureTask.java:266) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] at java.lang.Thread.run(Thread.java:764) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] --------- beginning of crash 2020-06-11 10:15:42.378 12785-12852/? A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 12852 (AsyncTask #1), pid 12785 (o.himnia_musica) 2020-06-11 10:15:42.377 12785-12852/? A/zygote: runtime.cc:550] 2020-06-11 10:15:42.475 12855-12855/? I/crash_dump32: obtaining output fd from tombstoned, type: kDebuggerdTombstone 2020-06-11 10:15:42.477 4120-4120/? I//system/bin/tombstoned: received crash request for pid 12785 2020-06-11 10:15:42.479 12855-12855/? I/crash_dump32: performing dump of process 12785 (target tid = 12852) 2020-06-11 10:15:42.480 12855-12855/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 2020-06-11 10:15:42.480 12855-12855/? A/DEBUG: Build fingerprint: 'samsung/on7xelteub/on7xelte:8.1.0/M1AJQ/G610MUBS7CTA2:user/release-keys' 2020-06-11 10:15:42.480 12855-12855/? A/DEBUG: Revision: '4' 2020-06-11 10:15:42.480 12855-12855/? A/DEBUG: ABI: 'arm' 2020-06-11 10:15:42.480 12855-12855/? A/DEBUG: pid: 12785, tid: 12852, name: AsyncTask #1 >>> mx.com.publicacioneselfaro.himnia_musica <<< 2020-06-11 10:15:42.480 12855-12855/? A/DEBUG: signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr -------- 2020-06-11 10:15:42.485 12855-12855/? A/DEBUG: Abort message: 'java_vm_ext.cc:534] JNI DETECTED ERROR IN APPLICATION: java_class == null' 2020-06-11 10:15:42.485 12855-12855/? A/DEBUG: r0 00000000 r1 00003234 r2 00000006 r3 00000008 2020-06-11 10:15:42.485 12855-12855/? A/DEBUG: r4 000031f1 r5 00003234 r6 cab086ec r7 0000010c 2020-06-11 10:15:42.485 12855-12855/? A/DEBUG: r8 00000000 r9 cab08739 sl 0000000a fp cab08738 2020-06-11 10:15:42.485 12855-12855/? A/DEBUG: ip c939aa20 sp cab086d8 lr f0544e6f pc f053e528 cpsr 200f0030 2020-06-11 10:15:42.489 12855-12855/? A/DEBUG: backtrace: 2020-06-11 10:15:42.489 12855-12855/? A/DEBUG: #00 pc 0001a528 /system/lib/libc.so (abort+63) 2020-06-11 10:15:42.489 12855-12855/? A/DEBUG: #01 pc 00365cd3 /system/lib/libart.so (art::Runtime::Abort(char const*)+402) 2020-06-11 10:15:42.489 12855-12855/? A/DEBUG: #02 pc 004276e7 /system/lib/libart.so (android::base::LogMessage::~LogMessage()+454) 2020-06-11 10:15:42.489 12855-12855/? A/DEBUG: #03 pc 00251a75 /system/lib/libart.so (art::JavaVMExt::JniAbort(char const*, char const*)+1240) 2020-06-11 10:15:42.489 12855-12855/? A/DEBUG: #04 pc 00251c6b /system/lib/libart.so (art::JavaVMExt::JniAbortF(char const*, char const*, ...)+66) 2020-06-11 10:15:42.489 12855-12855/? A/DEBUG: #05 pc 00286c8b /system/lib/libart.so (art::JNI::GetMethodID(_JNIEnv*, _jclass*, char const*, char const*)+994) 2020-06-11 10:15:42.489 12855-12855/? A/DEBUG: #06 pc 000037d7 /data/app/mx.com.publicacioneselfaro.himnia_musica-heck9rZ6EQdvqxG_4m-dkA==/lib/arm/libjniPdfium.so (Java_com_shockwave_pdfium_PdfiumCore_nativeGetPageSizeByIndex+134) 2020-06-11 10:15:42.489 12855-12855/? A/DEBUG: #07 pc 0000f46d /data/app/mx.com.publicacioneselfaro.himnia_musica-heck9rZ6EQdvqxG_4m-dkA==/oat/arm/base.odex (offset 0xf000) 2020-06-11 10:15:42.513 5448-5448/? D/io_stats: !@ 179,0 r 1549150 49420340 w 546257 10574324 d 82329 5077248 f 123355 123290 iot 1416740 1392264 th 51200 0 0 pt 0 inp 0 0 47039.532 2020-06-11 10:15:42.749 2613-8893/? I/display: [PrimaryDisplay] [DYNAMIC_RECOMP] HWC_2_GLES by low FPS(0) 2020-06-11 10:15:42.989 4363-4511/? D/WifiTrafficPoller: TrafficStats TxPkts=393208 RxPkts=1067699 TxBytes=98352287 RxBytes=1311285470 , Foreground uid=10553 pkgName=mx.com.publicacioneselfaro.himnia_musica txBytes=118744 rxBytes=9876941 2020-06-11 10:15:42.991 4790-4991/? D/Tile.WifiTile: handleUpdateState enabled = true 2020-06-11 10:15:43.575 9959-10020/? W/SQLiteConnectionPool: The connection pool for database '+data+user+0+com_microsoft_launcher+databases+AriaStorage_db' has been unable to grant a connection to thread 3332 (Aria-Stats-thread-1) with flags 0x2 for 16126.857 seconds. Connections: 0 active, 1 idle, 0 available. A: El error que mencionas se debe a proguard, está ofuscando las clases incluso del plugin. Sigue este link para configurar proguard : https://flutter-es.io/docs/deployment/android#paso-1---configurar-proguard Crea el archivo /android/app/proguard-rules.pro y añade las reglas listadas a continuación. En el archivo agrega lo siguiente: #Flutter Wrapper -keep class io.flutter.app.** { *; } -keep class io.flutter.plugin.** { *; } -keep class io.flutter.util.** { *; } -keep class io.flutter.view.** { *; } -keep class io.flutter.** { *; } -keep class io.flutter.plugins.** { *; } #Aquí lo que indica el plugin -keep class com.shockwave.** Con eso se debería solucionar el problema
{ "pile_set_name": "StackExchange" }
Q: How does the applicant counter work on LinkedIn? I saw this internship posting on LinkedIn: How does the applicant counter work on LinkedIn? I find it hard to believe that 558 were sent in one day. A: My assumption is that the counter is highly inaccurate. I did hit the "Apply on the company website" button once by accident and surprisingly found the counter was incremented on the LinkedIn page, even though I did not proceed with application. I checked this few times later, every time you hit that button (apparently from unique profile) the counter goes up by one, but I do not take that counter seriously anymore
{ "pile_set_name": "StackExchange" }
Q: Find rows that are not in a set of values (similar to SQL Except) What I'm trying to do is delete several rows of an Excel-Files (with pandas) and then save the File without those rows to .xlsx (with pyexcelerate module). I'm aware that I can remove rows of a data frame by dropping them (I already got that to work). But I have read in several posts that when there are many (in my case > 5000) rows that should be deleted it's much faster to just get the indexes of the "to delete" rows from the data frame and then slice the data frame (just as a SQL Except statement for example would do). Unfortunately I can't get it to work, even though I've tried several methods. Here are my "source posts": Slice Pandas dataframe by labels that are not in a list - Answer from User ASGM How to drop a list of rows from Pandas dataframe? - Answer from User Dennis Golomazov And here is a part of the function, that should delete the rows and save the created file: for index, cell in enumerate(wb_in[header_xlsx]): if str(cell) in delete_set: set_to_delete.append(index) print str(cell) + " deleted from set: " + str(len(set_to_delete)) wb_out = Workbook() data_out = wb_in.loc[set(wb_in.index) - set(set_to_delete)] ws_out = wb_out.new_sheet('Main', data=data_out) wb_out.save(file_path + filename + "_2.xlsx") Here is an example of the data frame: sku product_group name \ 0 ABCDb00610-23.0 ABA1 Anti 1 ABCDb00610-10.0 ABA1 Anti 2 ABCDb00610-1.1 ABA1 Anti 3 ABCDb00609-23.0 ABA1 Anti 4 ABCDb00609-10.0 ABA1 Anti 5 ABCDb00609-1.1 ABA1 Anti 6 ABCDb00608-23.0 ABA1 Anti 7 ABCDb00608-10.0 ABA1 Anti 8 ABCDb00608-3.3 ABA1 Anti 9 ABCDb00608-3.0 ABA1 Anti Delete_set is a set that contains only skus (e.g.: ABCDb00608-3.3 or ABCDb00609-1.1). Btw: I have tried many solution suggestions! Thanks in advance! A: Use pd.Series.isin: df = df[~df.sku.isin(delete_set)] print(df) sku product_group name 0 ABAAb00610-23.0 ABA1 Anti-Involucrin [SY5] 1 ABAAb00610-10.0 ABA1 Anti-Involucrin [SY5] 2 ABAAb00610-1.1 ABA1 Anti-EpCAM [AUA1] 3 ABAAb00609-23.0 ABA1 Anti-EpCAM [AUA1] 4 ABAAb00609-10.0 ABA1 Anti-EpCAM [AUA1] 5 ABAAb00609-1.1 ABA1 Anti-EpCAM [AUA1] 6 ABAAb00608-23.0 ABA1 Anti-EpCAM [AUA1] 7 ABAAb00608-10.0 ABA1 Anti-EpCAM [AUA1] 8 ABAAb00608-3.3 ABA1 Anti-EpCAM [AUA1] 9 ABAAb00608-3.0 ABA1 Anti-EpCAM [AUA1] print(delete_set) ('ABAAb00608-3.3', 'ABAAb00609-1.1') m = ~df.sku.isin(delete_set) print(m) 0 True 1 True 2 True 3 True 4 True 5 False 6 True 7 True 8 False 9 True Name: sku, dtype: bool print(df[m]) sku product_group name 0 ABAAb00610-23.0 ABA1 Anti-Involucrin [SY5] 1 ABAAb00610-10.0 ABA1 Anti-Involucrin [SY5] 2 ABAAb00610-1.1 ABA1 Anti-EpCAM [AUA1] 3 ABAAb00609-23.0 ABA1 Anti-EpCAM [AUA1] 4 ABAAb00609-10.0 ABA1 Anti-EpCAM [AUA1] 6 ABAAb00608-23.0 ABA1 Anti-EpCAM [AUA1] 7 ABAAb00608-10.0 ABA1 Anti-EpCAM [AUA1] 9 ABAAb00608-3.0 ABA1 Anti-EpCAM [AUA1]
{ "pile_set_name": "StackExchange" }
Q: Multivariable calculus - Implicit function theorem we are given the function $F: \mathbb R^3 \to \mathbb R^2$, $F(x,y,z)=\begin{pmatrix} x+yz-z^3-1 \\ x^3-xz+y^3\end{pmatrix}$ Show that around $(1,-1,0)$ we can represent $x$ and $y$ as functions of $z$, and find $\frac{dx}{dz}$ and $\frac{dy}{dz}$ What I did: The differential of $F$ is: $\begin{pmatrix} 1 & z &y-3z^2\\3x^2-z & 3y^2 &-x\end{pmatrix}$, insert $x=1,y=-1,z=0$ to get: $\begin{pmatrix} 1 & 0 &-1 \\3&3&-1\end{pmatrix}$ The matrix of the partial derivatives with respect to x and y is the first 2 columns, and it is invertible, and so the requirements of the implicit function theorem are met. How do i find the differential of $x$ and $y$ with respect to $z$ tho? One would expect that $\frac{dx}{dz} = -\frac{dF}{dz}(\frac{dF}{dx})^{-1}$ but...those are vectors. what is the inverse of a vector? how do you multiply vectors? there's a size mismatch. A: The implicit function theorem: Let $m,n$ be natural numbers, $\Omega$ an open subset of $\mathbb R^{n+m}$, $F\colon \Omega\to \mathbb R^m$ a class $C^1$ function and $(a_1, \ldots ,a_n, b_1, \ldots ,b_m)\in \Omega$ such that $$F(a_1, \ldots ,a_n, b_1, \ldots ,b_m)=0_{\mathbb R^{\large m}}.$$ Writing $F=(f_1, \ldots, f_m)$ where for each $k\in \{1, \ldots m\}$, $f_k\colon \mathbb R^{n+m}\to \mathbb R$ is a class $C^1$ function, assume that the following $m\times m$ matrix is invertible: $$\begin{pmatrix} \dfrac{\partial f_1}{\partial y_1} & \cdots & \dfrac{\partial f_1}{\partial y_m}\\ \vdots & \ddots & \vdots\\ \dfrac{\partial f_m}{\partial y_1} & \cdots& \dfrac{\partial f_m}{\partial y_m}\end{pmatrix}(a_1, \ldots ,a_n, b_1, \ldots ,b_m).$$ In these conditions there exists a neighborhood $V$ of $(a_1, \ldots ,a_n)$, a neighborhood $W$ of $(b_1, \ldots ,b_m)$ and a class $C^1$ function $G\colon V\to W$ such that: $G(a_1, \ldots ,a_n)=(b_1, \ldots ,b_m)$ and $\forall (x_1, \ldots ,x_n)\in V\left(F(x_1, \ldots , x_n, g_1(x_1, \ldots , x_n), \ldots ,g_m(x_1, \ldots , x_n))=0_{\mathbb R^{\large m}}\right)$, where for each $l\in \{1, \ldots , m\}$, $g_l\colon \mathbb R^n \to \mathbb R$ is a class $C^1$ function and $G=(g_1, \ldots ,g_m)$. Furthermore, $J_G=-\left(J_2\right)^{-1}J_1$ where $$J_G \text{ is } \begin{pmatrix}\dfrac {\partial g_1}{\partial x_1} & \cdots & \dfrac {\partial g_1}{\partial x_n}\\ \vdots &\ddots &\vdots\\ \dfrac {\partial g_m}{\partial x_1} & \cdots & \dfrac {\partial g_m}{\partial x_n} \end{pmatrix}_{m\times n}\\ \text{ evaluated at }(x_1, \ldots ,x_n), \\~\\ J_2\text{ is }\begin{pmatrix} \dfrac{\partial f_1}{\partial y_1} & \cdots & \dfrac{\partial f_1}{\partial y_m}\\ \vdots & \ddots & \vdots\\ \dfrac{\partial f_m}{\partial y_1} & \cdots& \dfrac{\partial f_m}{\partial y_m}\end{pmatrix}_{m\times m}\\ \text{ evaluated at }(x_1, \ldots , x_n, g_1(x_1, \ldots , x_n), \ldots ,g_m(x_1, \ldots , x_n)),$$ and $$J_1\text{ is }\begin{pmatrix} \dfrac{\partial f_1}{\partial x_1} & \cdots & \dfrac{\partial f_1}{\partial x_n}\\ \vdots & \ddots & \vdots\\ \dfrac{\partial f_m}{\partial x_1} & \cdots& \dfrac{\partial f_m}{\partial x_n}\end{pmatrix}_{m\times n}\\ \text{ evaluated at }(x_1, \ldots , x_n, g_1(x_1, \ldots , x_n), \ldots ,g_m(x_1, \ldots , x_n)).$$ In this problem we can't apply the IFT as it is, because to use this version of the IFT one writes the last $m$ variables as functions of the first $n$ ones, but looking at the proof one notices that we can just consider permutations of this and this is what happens here. In the notation above one has $n=1, m=2, \Omega =\mathbb R^{n+m}, F\colon \mathbb R^{n+m}\to \mathbb R^m$ given by $F(x,y,z)=(f_1(x,y,z), f_2(x,y,z))$, where $f_1(x,y,z)=x+yz-z^3$ and $f_2(x,y,z)=x^3-xz+y^3$. For all $(x,y,z)\in \mathbb R^3$ it holds that: $\dfrac {\partial f_1}{\partial x}(x,y,z)=1,$ $\dfrac {\partial f_1}{\partial y}(x,y,z)=z,$ $\dfrac {\partial f_2}{\partial x}(x,y,z)=3x^2-z,$ and $\dfrac {\partial f_2}{\partial y}(x,y,z)=3y^2$. Therefore $\begin{pmatrix} \dfrac {\partial f_1}{\partial x}(1,-1, 0) & \dfrac {\partial f_1}{\partial y}(1, -1, 0)\\ \dfrac {\partial f_2}{\partial x}(1, -1, 0) & \dfrac {\partial f_2}{\partial y}(1, -1, 0)\end{pmatrix}=\begin{pmatrix} 1 & 0\\ 3 & 3\end{pmatrix}$ and the matrix $\begin{pmatrix} 1 & 0\\ 3 & 3\end{pmatrix}$ is invertible. So, by the IFT, there exists an interval $V$ around $z=0$ and a neighborhood $W$ around $(x,y)=(1,-1)$ and a class $C^1(V)$ function $G\colon V\to W$ such that $G(0)=(1-1)$ and $\forall z\in V\left(F(g_1(z), g_2(z), z)=0\right)$, where $g_1(z), g_2(z)$ denote the first and second entries, respectively, of $G(z)$, for all $z\in V$. (In analyst terms, $g_1(z)=x(z)$ and $g_2(z)=y(z)$). One also finds $$ \begin{pmatrix} \dfrac {\partial g_1}{\partial z}(z)\\ \dfrac {\partial g_2}{\partial z}(z) \end{pmatrix}=\\ -\begin{pmatrix} \dfrac{\partial f_1}{\partial x}(g_1(z), g_2(z), z) & \dfrac{\partial f_1}{\partial y}(g_1(z), g_2(z), z)\\ \dfrac{\partial f_2}{\partial x}(g_1(z), g_2(z), z) & \dfrac{\partial f_2}{\partial y}(g_1(z), g_2(z), z) \end{pmatrix}^{-1} \begin{pmatrix} \dfrac{\partial f_1}{\partial z}(g_1(z), g_2(z), z)\\ \dfrac{\partial f_2}{\partial z}(g_1(z), g_2(z), z) \end{pmatrix}_. $$ Now you can happily evaluate the RHS at $z=0$.
{ "pile_set_name": "StackExchange" }
Q: "Bottle up the disruptive methods"? But he has so far resisted many binding efforts to create a more conventional order around him, encouraging aides who color outside the lines on television, maintaining walk-in power for each of his senior staff members and starting each morning with a tweetstorm that often upends the news cycle in unexpected ways. Bottle up the disruptive methods and Trump fears he could lose the magic that made him President. I'm not sure what the bold part means, especially the phrase "Bottle up the disruptive methods" but I made two interpretations. Please tell me which one is correct. Bottle up the disruptive methods and Trump fears he could lose the magic that made him President. #1. Keep him (imperative) from using disruptive methods then he will never be able to use the magic which will make him fear. #2 If he (Trump) stop using such methods that he fears, he will never be able to use the magic. Source: Inside Donald Trump's White House Chaos A: In fairy tales and other stories, there are often potions that give the consumer magical powers. They are often in little, clear bottles. The author is using figurative language to say that the disruptive methods are like magical potions. They give the consumer (Trump) magical powers (the power to disrupt). If you bottle them up (= take them away), then he loses his magic. Further, magic has a meaning other than the one associated with spells and powers. magic noun [U] (SPECIAL QUALITY) ​a special, exciting quality that makes something or someone different and better than others: As an actress, she has lost none of her magic, and she still is thrilling to watch. (Cambridge) So lose the magic not only refers to losing his powers, but it also means that he would lose the charm that appealed to his supporters and got him elected as president. Lastly, Trump fears that he could lose those things, or he is afraid that he could lose those things. The interpretation is not that he is afraid of them.
{ "pile_set_name": "StackExchange" }
Q: How to encrypt password in ExpressJS Current I tried to create authentication controller for my app. But I just use plain password. Can u help me a good package to do it. With a tuts then best. Thank you so much. A: This is a good package: https://www.npmjs.com/package/bcrypt You can follow this ebook: https://www.udemy.com/nodejs-master-class/
{ "pile_set_name": "StackExchange" }
Q: How can I access my wordpress form data through REST API The word press website I am creating involves quite a lot of form filling. I've tried using a ninja forms and contact-form-7 and I want to fetch my form submissions through REST API. But ninja forms just doesn't have much documentation for this and contact-form-7 gives me an error: http://localhost/wordpress/wp-json/contact-form-7/v1/contact-forms ERROR { "code": "wpcf7_forbidden", "message": "You are not allowed to access contact forms.", "data": { "status": 403 } } How should I go about this? Is there any way to use REST API for form data on wordpress? If anyone could point me in the right direction I would be so thankful A: Contact Form 7 (<=5.1.4) does not store any submission data in the database. I've tested Contact Form CFDB7 (<=1.2.4.8), Contact Form Entries (<=1.0.8), Flamingo (<=2.1) add-ons for Contact Form 7 and none of those provide Rest API endpoints to collect form submission data ether. Ninja Forms (<=3.4.21) does not expose any Rest API endpoints. You have couple options at this point: Submit a request to CF7 or/and Ninja Forms developers requesting a feature. Look for existing plugin / extension that does this (free or premium). Implement Rest API yourself. It's not very complicated and can be implemented as separate plugin. You will not have to modify CF7/Ninja Forms plugins to make it work. Here is WordPress documentation: https://developer.wordpress.org/rest-api/extending-the-rest-api/
{ "pile_set_name": "StackExchange" }
Q: Finding length of list without using the 'len' function in python In my High school assignment part of it is to make a function that will find the average number in a list of floating points. We can't use len and such so something like sum(numList)/float(len(numList)) isn't an option for me. I've spent an hour researching and racking my brain for a way to find the list length without using the len function, and I've got nothing so I was hoping to be either shown how to do it or to be pointed in the right direction. Help me stack overflow, your my only hope. :) A: Use a loop to add up the values from the list, and count them at the same time: def average(numList): total = 0 count = 0 for num in numList: total += num count += 1 return total / count If you might be passed an empty list, you might want to check for that first and either return a predetermined value (e.g. 0), or raise a more helpful exception than the ZeroDivisionError you'll get if you don't do any checking. If you're using Python 2 and the list might be all integers, you should either put from __future__ import division at the top of the file, or convert one of total or count to a float before doing the division (initializing one of them to 0.0 would also work).
{ "pile_set_name": "StackExchange" }
Q: Binding Silverlight Control to View Model element? Say I have: <TextBlock Text="{Binding MyString}"/> public class AlanViewModel { public string MyString {get; set;} public TextBlock Control { get; set; } //How to bind this to the TextBlock control? } Can I bind the instance of the control to the ViewModel, or must I continue to jump through hoops in the code-behind to couple them together? I know this couples the ViewModel to the View, but it's for a good reason. A: <ContentControl Content="{Binding TextBlock}" />
{ "pile_set_name": "StackExchange" }
Q: Legacy Data Feed, trade off between Standards, Xml and Performance We're working with legacy data feeds and apps that consume them. We want to introduce Xml but the additional performance overhead is hard to justify. How have you addressed this issue? We're working with a number of pre-existing data feeds, often files in a well known directory which are updated every few minutes. One approach to making this legacy data standards compliant is to convert it to Xml and publish the XSD - making it available to all. However this means we're going to serialise/deserialise everything before we can use it, whereas currently apps just read the data. We going from File -> App To File -> Serialize to XML -> ESB/Network -> Deserialize -> App The latter is clearly more structured and re-usable, a 'better' architecture. But the performance hit we're going to take is high. A: Convert to XML only where you must; don't convert for the sake of "standards compliance" or "better architecture". Surely you'd rather be adding more features or otherwise improving your product, right? This is a good moment to reflect on the YAGNI principle.
{ "pile_set_name": "StackExchange" }
Q: CakePHP 2.1.1 foreach In my view I want a HTML table something like this: COUNTRY TOWN france paris This is my query: $foo=$this->country->find('all', array( 'contain' => array( 'Town' => array( 'conditions' => array("Town.country_id = country.id"), 'fields' => array('id','name') ) ) ) ); I want to display to my view like this: line6 <?php foreach ($diponibilite as $f): ?> line7 line8 <tr> line9 <td><?php echo $f['country']['name'];?></td> line10 <td><?php echo $f['town']['name'];?></td> line11 line12 </tr> line13 <?php endforeach; ?> The models 'country' and 'town' are associated: country hasmany town and town belongsto country unfortunately, an error: Notice (8): Undefined index: name [APP\View\index\index.ctp, line 10] Why? A: The problem is that since you have a Country hasmany Town relationship there could be multiple towns in one country (as the output of debug( $f ) shows). To print all of the towns you need another loop: <?php foreach( $diponibilite as $f ): ?> <tr> <td><?php echo $f[ 'country' ][ 'name' ]; ?></td> <td><?php foreach( $f[ 'town' ] as $town ) { echo $town[ 'name' ].' '; } ?></td> </tr> <?php endforeach; ?> Or, if you just want the first one, use $f[ 'town' ][ 0 ][ 'name' ]. Side note: if you have the associations set up properly, you don't need the condition in the find. You can just do $foo = $this->country->find( 'all', array( 'contain' => array( 'Town.id', 'Town.name' ) ) );
{ "pile_set_name": "StackExchange" }
Q: How do I dynamically update labels on a screen when all text fields have values in SwiftUI? I'm working on an app that allows users to type odds for a bet using 2 separate text fields. So for example, let's say the odds the user wants is 3/1. The user will need to enter 3 into one field, and 1 into the other. I have 2 state variables: leftOddsVal rightOddsVal This is how I use them with the CustomTextField: CustomTextfield(text: $leftOddsVal, placeHolder: "Enter text", keyboardType: .numberPad) CustomTextfield(text: $rightOddsVal, placeHolder: "Enter text", keyboardType: .numberPad) CustomTextfield(text: $state, placeHolder: "Enter text", keyboardType: .numberPad) This is the code for the custom textfield: struct CustomTextfield: UIViewRepresentable { @Binding var text : String var placeHolder: String var keyboardType: UIKeyboardType final class Coordinator: NSObject { var textField: CustomTextfield init(_ textField: CustomTextfield) { self.textField = textField } } func makeCoordinator() -> DabbleTextfield.Coordinator { Coordinator(self) } func makeUIView(context: Context) -> UITextField { let textField = UITextField() textField.backgroundColor = .white textField.placeholder = self.placeHolder textField.keyboardType = self.keyboardType return textField } func updateUIView(_ uiView: UITextField, context: Context) { } } What I am trying to do: I want to take the values of each field, and write some logic to work out how much could be won and lost then update some text labels on the screen. Rather than have the user submit the form before they can see what they may win or lose, I would like the win/lose labels to be updated automatically after all fields have values. These are how the labels look: The problem: The textFieldDidEndEditing delegate method needs to know what method to trigger. This means, I need to modify the CustomTextField to trigger a method inside my viewModel that will fire. Then I can trigger the win/lose calculation method. However, I'm starting to feel as this is a lot of work for something so simple. It seems messy. I'm unable to access the text field values directly inside the view. This would be simple if I was using SwiftUI's TextField component. However, I'm using UIKit's UITextField component wrapped in a UIRepresentable struct as you can see in my code above. What I've tried: I have a view model, and I tried to pass that into the CustomtextField. I simply declared my environment variable like this: struct CustomTextfield: UIViewRepresentable { @EnvironmentObject var viewModel: EnvironmentObject<AnyObject> @Binding var text : String var placeHolder: String var keyboardType: UIKeyboardType I used AnyObject so that I can cast whatever model I pass into the CustomTextField as the correct type. I don't want to ever need to manually modify the CustomTextField to cater to each model I may use it with. I now use the CustomTextField like this: CustomTextfield(viewModel: betViewModel as! EnvironmentObject<BetViewModel>, value: $oddsLeftValue, placeHolder: "Enter text", keyboardType: .numberPad) And I store a copy of the TextField in a variable in my ViewModel: func makeUIView(context: Context) -> UITextField { let textField = UITextField() if let fieldValue = textField.text { self.viewModel.textField = fieldValue } But I get the following error: Type 'AnyObject' does not conform to protocol 'ObservableObject' I also tried setting the binded text value to the value of the textField, but this didn't work either. I'm hoping someone can give me some insight into what I'm doing wrong. I feel like I'm going in circles, and the cause of this comes from trying to reuse the UIRepresentable UIKit component. It seems to be limiting me, which results in workarounds that seem to be an overkill for what I'm trying to achieve. All I want to do is allow a user to type in their odds and stake and have the win/lose labels updated dynamically without needing to tap any buttons. All while being able to reuse the CustomTextField. Looking forward to your suggestions. Thanks in advance. A: The below makes your custom text field operable... for updating external bound, hope this was the goal of such long description. Tested with Xcode 11.4 / iOS 13.4 Small TestCustomTextfield at the end was used to check updating label on changes in CustomTextfield. struct CustomTextfield: UIViewRepresentable { @Binding var text : String var placeHolder: String var keyboardType: UIKeyboardType final class Coordinator: NSObject, UITextFieldDelegate { var parent: CustomTextfield init(_ parent: CustomTextfield) { self.parent = parent } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { parent.text = textField.text ?? "" return true } } func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIView(context: Context) -> UITextField { let textField = UITextField() textField.backgroundColor = .white textField.placeholder = self.placeHolder textField.keyboardType = self.keyboardType textField.setContentHuggingPriority(.required, for: .vertical) textField.delegate = context.coordinator return textField } func updateUIView(_ uiField: UITextField, context: Context) { if let text = textField.text as NSString? { parent.text = text.replacingCharacters(in: range, with: string) } else { parent.text = "" } } } struct TestCustomTextfield: View { @State private var value = "" var body: some View { VStack { Text("Label: \(value)") CustomTextfield(text: $value, placeHolder: "Your value", keyboardType: .numberPad) } } }
{ "pile_set_name": "StackExchange" }
Q: Dropbox conflict causing Github issues Ugh. So Dropbox has just caused me a couple of issues thanks to it not syncing when it should have. I don't know whether to merge or rebase or something else. I need some advanced gitfu. I'm the only developer on the project and the conflict appeared because of switching between my desktop and laptop. Nobody else works with this repo... I could literally wipe the remote repo and start again and it would be fine. (I don't really want to lose the history, but it would be fine from a code POV.) Running git push simply says: To github.com:JCW/kicker-ticketing.git ! [rejected] master -> master (non-fast-forward) error: failed to push some refs to '[email protected]:JCW/kicker-ticketing.git' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. git status reveals: On branch master Your branch and 'origin/master' have diverged, and have 6 and 3 different commits each, respectively. (use "git pull" to merge the remote branch into yours) nothing to commit, working tree clean I've deleted all the conflicted files (including the ones in .git/ and manually added all the code changes) -- my local repo is now what should be the remote origin/master. What is the best way, in this particular solo-dev situation, to just push my local repo to become the new remote origin/master? I've read a few guides on rebase vs merge, but still the obvious solution eludes me. Next time I will make sure that Dropbox hasn't crashed before continuing to work. Sigh. A: You say: my local repo is now what should be the remote origin/master If you are sure in that, to reset the remote state from your local state just run git push -f. This is destructive for the remote end, so it is nice if you backup that first. As a solo developer (and in small teams) I prefer to use git pull --rebase to keep the linear history at all times, because it is then easier for me to debug issues like that one.
{ "pile_set_name": "StackExchange" }
Q: Is there a specific linguistic term for the following practice of constructing new words/characters? I have in mind examples such as the Scheingallizismus (lit. appearance of Gallicism) in German which are words/phrases constructed from French origins but are themselves unknown in French speaking countries. For instance, the German word blamage meaning "disgrace" was coined from French blamieren (to embarrass) and the nominal suffix -age, and is even pronounced like French. For non-alphabetic writing systems, I have in mind the Japanese kokuji/wasei kanji (国字/和製漢字) which are characters coined mainly based on logographical rules of Chinese characters (interestingly, while many of these kokuji are only seen in Japanese, a few of them did wind up adopted back into simplified Chinese); for instance, the kanji 凪 meaning "calm" was coined from the radical (i.e. component form) ⺇ and the character 止 meaning "to stop". In such cases, although the constructed words/phrases/characters are mostly unknown in their adopted source languages, native speakers of the adopted languages are often able to recognize some parts of these coined words/characters, but only to a limited extent. My question: is there a linguistic term specifically accounting for the phenomenon described above? I've thought about calques, loanwords, semantic loans, false cognates, neologisms, phono-semantic matchings, and so on; but none of them seems to accurately describe it. I do admit that this is a field that I am relatively ignorant of, and please correct me if I have made any mistakes. Update: After some further research, it seems to me that the concept of pseudo-loan would be an appropriate umbrella term for all above-mentioned instances. There is another rather rare term, allogenism, which essentially describes the same phenomenon. However, I am not certain as to whether these two are accepted as linguistic terms, or rather just convenient designations. A: In German, there is the term Pseudoentlehnung or Scheinentlehnung for such kind of words, abstracting from the alledged original language. I think, you can use this term untranslated in a scholarly publication, I am not aware of an English translation of it. A: I've occasionally seen this term, pseudo-loans, for instance in Louviot, Élise, and Catherine Delesse. 2017. Studies in language variation and change 2: Shifts and turns in the history of English:
{ "pile_set_name": "StackExchange" }
Q: Generic type checking Is there a way to enforce/limit the types that are passed to primitives? (bool, int, string, etc.) Now, I know you can limit the generic type parameter to a type or interface implementation via the where clause. However, this doesn't fit the bill for primitives (AFAIK) because they do not all have a common ground (apart from object before someone says! :P). So, my current thoughts are to just grit my teeth and do a big switch statement and throw an ArgumentException on failure.. EDIT 1: Just to clarify: The code definition should be like: public class MyClass<GenericType> .... And instantiation: MyClass<bool> = new MyClass<bool>(); // Legal MyClass<string> = new MyClass<string>(); // Legal MyClass<DataSet> = new MyClass<DataSet>(); // Illegal MyClass<RobsFunkyHat> = new MyClass<RobsFunkyHat>(); // Illegal (but looks awesome!) EDIT 2 @Jon Limjap - Good point, and something I was already considering.. I'm sure there is a generic method that can be used to determine if the type is of a value or reference type.. This could be useful in instantly removing a lot of the objects I dont want to deal with (but then you need to worry about the structs that are used such as Size ).. Interesting problem no? :) Here it is: where T : struct Taken from MSDN. I'm curious.. Could this be done in .NET 3.x using extension methods? Create an interface, and implement the interface in the extension methods (which would probably be cleaner than a bit fat switch). Plus if you then need to later extend to any lightweight custom types, they can also implement the same interface, with no changes required to the base code. What do you guys think? Sad news is I am working in Framework 2!! :D EDIT 3 This was so simple following on from Jon Limjaps Pointer.. So simple I almost want to cry, but it's great because the code works like a charm! So here is what I did (you'll laugh!): Code added to the generic class bool TypeValid() { // Get the TypeCode from the Primitive Type TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType)); // All of the TypeCode Enumeration refer Primitive Types // with the exception of Object and Empty (Null). // Since I am willing to allow Null Types (at this time) // all we need to check for is Object! switch (code) { case TypeCode.Object: return false; default: return true; } } Then a little utility method to check the type and throw an exception, private void EnforcePrimitiveType() { if (!TypeValid()) throw new InvalidOperationException( "Unable to Instantiate SimpleMetadata based on the Generic Type of '" + typeof(PrimitiveDataType).Name + "' - this Class is Designed to Work with Primitive Data Types Only."); } All that then needs to be done is to call EnforcePrimitiveType() in the classes constructors. Job done! :-) The only one downside, it only throws an exception at runtime (obviously) rather than design time.. But that's no big deal and could be picked up with utilities like FxCop (which we don't use at work). Special thanks to Jon Limjap on this one! A: public class Class1<GenericType> where GenericType : struct { } This one seemed to do the job.. A: Primitives appear to be specified in the TypeCode enumeration: Perhaps there is a way to find out if an object contains the TypeCode enum without having to cast it to an specific object or call GetType() or typeof()? Update It was right under my nose. The code sample there shows this: static void WriteObjectInfo(object testObject) { TypeCode typeCode = Type.GetTypeCode( testObject.GetType() ); switch( typeCode ) { case TypeCode.Boolean: Console.WriteLine("Boolean: {0}", testObject); break; case TypeCode.Double: Console.WriteLine("Double: {0}", testObject); break; default: Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject); break; } } } It's still an ugly switch. But it's a good place to start! A: Pretty much what @Lars already said: //Force T to be a value (primitive) type. public class Class1<T> where T: struct //Force T to be a reference type. public class Class1<T> where T: class //Force T to be a parameterless constructor. public class Class1<T> where T: new() All work in .NET 2, 3 and 3.5.
{ "pile_set_name": "StackExchange" }
Q: With Google Website Optimizer's multivariate testing, can I vary multiple css classes on a single div? I would like to use Google Website Optimizer (GWO)'s multivariate tests to test some different versions of a web page. I can change from version to version just by varying some class tags on a div, i.e. the different versions are of this form: <div id="testing" class="foo1 bar1">content</div> <div id="testing" class="foo1 bar2">content</div> <div id="testing" class="foo2 bar1">content</div> <div id="testing" class="foo2 bar2">content</div> In the ideal, I would be able to use GWO section code in place of each class, and google would just swap in the appropriate tags (foo1 or foo2, bar1 or bar2). However, naively doing this results in horribly malformed code because I would be trying to put <script> tags inside the div's class attribute: <div id="testing" class=" <script>utmx_section("foo-class")</script>foo1</noscript> <script>utmx_section("bar-class")</script>bar1</noscript> "> content </div> And indeed, the browser chokes all over it. My current best approach is just to use a different div for each variable in the test, as follows: <script>utmx_section("foo-class-div")</script> <div class="foo1"> </noscript> <script>utmx_section("bar-class-div")</script> <div class="bar1"> </noscript> content </div> </div> So testing multiple variables requires layer of div-nesting per variable, and it all seems rather awkward. Is there a better approach that I could use in which I just vary the classes on a single div? A: Probably the best way is: <div id="testing">content</div> <script> var testingDiv = document.getElementById('testing'); </script> <script>utmx_section("foo-class-div")</script> <script> testingDiv.setAttribute('class', testingDiv.getAttribute('class') + ' foo1'); </script> </noscript> <script>utmx_section("bar-class-div")</script> <script> testingDiv.setAttribute('class', testingDiv.getAttribute('class') + ' bar1'); </script> </noscript>
{ "pile_set_name": "StackExchange" }
Q: Accessing function arguments from decorator I have a Request handler and a decorator, I would like to work with the self object inside the decorator class MyHandler(webapp.RequestHandler): @myDecorator def get(self): #code Update: Please notice the difference between the first and second self class myDecorator(object): def __init__(self, f): self.f = f def __call__(self): #work with self MyHandler > get ( function ) > self ( argument ) myDecorator > __call__ ( function ) > self ( argument ) the self arguments mentioned above are different. My intention is to access the first self from inside __call__ function, or find a way to do something similar. Hi can I access MyHandlers self argument from get function inside the decorator? Update2: I want to implement a decorator to work with a custom login in google app engine: I have a class ( requestHandler ): class SomeHandler(webapp.RequestHandler): @only_registered_users def get(self): #do stuff here And I want to decorate the get function in order to check out if the user is logged in or not: from util.sessions import Session import logging class only_registered_users(object): def __init__(self, f): self.f = f def __call__(self): def decorated_get(self): logging.debug("request object:", self.request) session = Session() if hasattr(session, 'user_key'): return self.f(self) else: self.request.redirect("/login") return decorated_get I know if a user is logged in if has the property 'user_key' in a session Object. That's the main goal I'm interested in on this specific case Let me know your suggestions / opinions if I'm doing something wrong! Thanks! A: I'm not entirely clear what it is you want, but if you just want to use the decorated function's arguments, then that is exactly what a basic decorator does. So to access say, self.request from a decorator you could do: def log_request(fn): def decorated_get(self): logging.debug("request object:", self.request) return fn(self) return decorated_get class MyHandler(webapp. RequestHandler): @log_request def get(self): self.response.out.write('hello world') If you are trying to access the class the decorated function is attached to, then it's a bit tricker and you'll have to cheat a bit using the inspect module. import inspect def class_printer(fn): cls = inspect.getouterframes(inspect.currentframe())[1][3] def decorated_fn(self, msg): fn(self,cls+" says: "+msg) return decorated_fn class MyClass(): @class_printer def say(self, msg): print msg In the example above we fetch the name of the class from the currentframe (during the execution of the decorator) and then store that in the decorated function. Here we are just prepending the class-name to whatever the msg variable is before passing it on to the original say function, but you can use your imagination to do what ever you like once you have the class name. >>> MyClass().say('hello') MyClass says: hello
{ "pile_set_name": "StackExchange" }
Q: Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found I have a controller that I'd like to be unique per session. According to the spring documentation there are two details to the implementation: 1. Initial web configuration To support the scoping of beans at the request, session, and global session levels (web-scoped beans), some minor initial configuration is required before you define your beans. I've added the following to my web.xml as shown in the documentation: <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> 2. Scoped beans as dependencies If you want to inject (for example) an HTTP request scoped bean into another bean, you must inject an AOP proxy in place of the scoped bean. I've annotated the bean with @Scope providing the proxyMode as shown below: @Controller @Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS) public class ReportBuilder implements Serializable { ... ... } Problem In spite of the above configuration, I get the following exception: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.reportBuilder': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request. Update 1 Below is my component scan. I have the following in web.xml: <context-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>org.example.AppConfig</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> And the following in AppConfig.java: @Configuration @EnableAsync @EnableCaching @ComponentScan("org.example") @ImportResource("classpath:applicationContext.xml") public class AppConfig implements AsyncConfigurer { ... ... } Update 2 I've created a reproducible test case. This is a much smaller project, so there are differences, but the same error happens. There's quite a few files, so I've uploaded it as a tar.gz to megafileupload. A: The problem is not in your Spring annotations but your design pattern. You mix together different scopes and threads: singleton session (or request) thread pool of jobs The singleton is available anywhere, it is ok. However session/request scope is not available outside a thread that is attached to a request. Asynchronous job can run even the request or session doesn't exist anymore, so it is not possible to use a request/session dependent bean. Also there is no way to know, if your are running a job in a separate thread, which thread is the originator request (it means aop:proxy is not helpful in this case). I think your code looks like that you want to make a contract between ReportController, ReportBuilder, UselessTask and ReportPage. Is there a way to use just a simple class (POJO) to store data from UselessTask and read it in ReportController or ReportPage and do not use ReportBuilder anymore? A: I'm answering my own question because it provides a better overview of the cause and possible solutions. I've awarded the bonus to @Martin because he pin pointed the cause. Cause As suggested by @Martin the cause is the use of multiple threads. The request object is not available in these threads, as mentioned in the Spring Guide: DispatcherServlet, RequestContextListener and RequestContextFilter all do exactly the same thing, namely bind the HTTP request object to the Thread that is servicing that request. This makes beans that are request- and session-scoped available further down the call chain. Solution 1 It is possible to make the request object available to other threads, but it places a couple of limitations on the system, which may not be workable in all projects. I got this solution from Accessing request scoped beans in a multi-threaded web application: I managed to get around this issue. I started using SimpleAsyncTaskExecutor instead of WorkManagerTaskExecutor / ThreadPoolExecutorFactoryBean. The benefit is that SimpleAsyncTaskExecutor will never re-use threads. That's only half the solution. The other half of the solution is to use a RequestContextFilter instead of RequestContextListener. RequestContextFilter (as well as DispatcherServlet) has a threadContextInheritable property which basically allows child threads to inherit the parent context. Solution 2 The only other option is to use the session scoped bean inside the request thread. In my case this wasn't possible because: The controller method is annotated with @Async; The controller method starts a batch job which uses threads for parallel job steps. A: If anyone else stuck on same point, following solved my problem. In web.xml <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> In Session component @Component @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) In pom.xml <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> </dependency>
{ "pile_set_name": "StackExchange" }
Q: Can I sell a supplement that references non-SRD Cleric Domains? I am creating a completely unique setting for Dungeons & Dragons 5th Edition, and really pouring my heart and soul into it. Under Wizards of the Coast's OGL (Open Gaming License), I am hoping to sell this setting as a supplement book (probably a downloadable PDF through DriveThruRPG). However, I'm a little bit fuzzy on the differences between the OGL, and the SRD, and what I'm allowed to use vs. what I'm not in the context of a commercial product. Specifically, I was thinking of referencing some non-SRD cleric domains (the only SRD cleric domain, as far as I know, is Life), such as, say, the ones from the Player's Handbook, in the context of locations that are tied to particular Domains. Would that be permissible? I don't know if I'm allowed to use non-SRD domains in a commercial work. I wouldn't be reproducing the actual Domains, in their specific mechanics, just referencing their existence. A: No The SRD is issued under the OGL and the first 2 pages of the SRD are the OGL. If you choose to use the OGL (and you have to for a homebrew setting), you can only use content from the SRD. The only Cleric domain in the SRD is the Life domain so that is the only published one that you can use or make reference to. Similarly, you can only use magic items, monsters etc. that are in the SRD. If you want to use all of the published D&D 5e material, you can use Dungeon Masters Guild but you must have no setting or use the Forgotten Realms, Ravenloft, Eberron or Ravnica settings. This doesn't seem like it would meet your needs. But surely, I can just refer to this stuff? In general, yes. Reference to a copyrighted work does not violate copyright and even copying parts of it for private use (as in your home campaign) or for commentary and education (as on this site) has fair use/dealing protection. However, using WotC copyrighted work to make a derivative work (your campaign world) to sell is not fair use/dealing. You are only allowed to do that in accordance with the terms of the licence issued by the copyright holder, WotC. And they say, you can't refer to anything outside the SRD in your derivative work. It's not that the reference is copyright violation - it's a violation of your contract which means you don't get the benefit of the licence which makes the rest of your derivative work copyright violation.
{ "pile_set_name": "StackExchange" }
Q: Experiencing strange behaviour when trying to make my boss gameObject flicker before a charge? I'm trying to code a behaviour for my boss where it charges at the player but before charging it is supposed to flicker a bit to show intent of charge. Below is how I am achieving this in Update(): if (chargeTimer <= 0) { if (!returnToStart) { StartCoroutine(TankSpriteFlicker()); if (chargeNow) { transform.position = Vector3.MoveTowards(transform.position, chargeTarget, Time.deltaTime * chargeSpeed); // Target reached? If so, start moving back to the original position if (Vector3.Distance(transform.position, chargeTarget) <= Mathf.Epsilon) { returnToStart = true; this.chargeTimer = this.chargeRate; } chargeNow = false; } } else { transform.position = Vector3.MoveTowards(transform.position, tankStartPosition, Time.deltaTime * returnSpeed); // Original position reached? If so, start moving to the target if (Vector3.Distance(transform.position, tankStartPosition) <= Mathf.Epsilon) { returnToStart = false; this.chargeTimer = this.chargeRate; } } } else { this.chargeTimer -= Time.time; } IEnumerator TankSpriteFlicker() { for (int i = 0; i <= 2; i++) { tankSprite.color = Color.red; yield return new WaitForSeconds(0.1f); tankSprite.color = startColor; yield return new WaitForSeconds(0.1f); } chargeNow = true; } chargeTarget is a fixed value of chargeTarget = new Vector3(-2.5f, transform.position.y, transform.position.z); The problem with this is that it charges, but stops midway and then charges again. Also as time passes by the flickering becomes very random and it starts flickering during and after a charge.. Here is the problem in action: https://gfycat.com/latefrigidbullmastiff-rivalsofaether I can't explain any of this behaviour and cant fix it, any help would be appreciated. A: This is not how coroutines work Lets look at just these lines: StartCoroutine(TankSpriteFlicker()); if (chargeNow) { ... } You start a coroutine, that's fine, but your next instruction asks if the coroutine has been completed (as chargeNow is not set to true until the last line of the coroutine). This cannot and will not ever be true at this point in the execution because coroutines are fundamentally "go do this stuff later" and later is not now. You need to move these additional pieces of logic (the stuff that happens "after" the coroutine) to the end of the coroutine.
{ "pile_set_name": "StackExchange" }
Q: Acknowledgement reliability using UDP I have a question about UDP. For context, I'm working on a real-time action game. I've read quite a bit about the differences between UDP and TCP and I feel I understand them quite well, but there's one piece that has never felt correct, and that's reliability, and specifically acknowledgements. I understand that UDP offers no reliability by default (i.e. packets can be dropped or arrive out of order). When some reliability is required, the solution I've seen (which makes sense conceptually) is to use acknowledgements (i.e. the server sends a packet to the client, and when the client receives that message, it sends back an acknowledgement to the server). What happens when the acknowledgement is dropped? In the example above (one server sending a packet to one client), the server handles potential packet loss by re-sending packets every frame until acknowledgements are received for those packets. You could still run into issues of bandwidth or out-of-order messages, but purely from a packet-loss perspective, the server is covered. However, if the client sends an acknowledgement that never arrives, the server would have no choice but to eventually stop sending that message, which could break the game if the information contained in that packet was required. You could take a similar approach to the server (i.e. keep sending acknowledgements until you receive an ack for the ack?), but that approach would have you looping back and forth forever (since you'd need an ack for the ack for the ack and so on). I feel my basic logic is correct here, which leaves me with two options. Send a single acknowledgment packet and hope for the best. Send a handful of acknowledgment packets (maybe 3-4) and hope for the best, assuming that not all of them will be dropped. Is there an answer to this problem? Am I fundamentally misunderstanding something? Is there some guarantee of using UDP I'm not aware of? I feel hesitant to move forward with too much networking code until I feel comfortable that my logic is sound. A: This is a form of the Two Generals Problem, and you're right - no number of retries is enough to perfectly guarantee receipt. In practice in games, there's usually a time horizon beyond which the information doesn't really matter though even if it technically arrives reliably. Like finding out you had a perfect headshot lined up 2 seconds ago - it's too late for the player to use that information now. If your packet loss is so high that you can't routinely get the needed info through inside a tight reaction window, then for a realtime game you might be better off kicking the player and trying to find a better match for them elsewhere, rather than continue trying to send the packet to emulate a reliable connection. Because of this, some game replication systems skip acknowledgement & retries altogether and opt to just spam the newest update as often as they can. If one gets dropped or arrives late, too bad, skip it, pick up the next one and carry on, relying on the prediction & interpolation systems to smooth the gap and minimize hiccups visible to the player. I suddenly want to start calling this "Simba Replication" for how it disregards problems in the past and tries to live in the present moment. ;) A hybrid solution is to race ahead sending the new update AND (since game state updates can often be quite small / compressible) also pack-in the last update, and maybe the one before that... So just in case the client missed them, you don't have to wait a full round trip time to find out and fix it. Most of the time the client already saw this, so there's redundant data this way, but the latency for correcting a missed message is lower. The client's updates can include the index number of the most recent consecutive update they've seen, so you can be minimally conservative with how many old updates you include in the next update packet. You could also implement a two-tier system as another type of hybrid, where short-lived state is replicated in an unreliable rapid-fire manner, and long-term state is synchronized reliably, using TCP or your own reliability implementation with a high retry count. This gets more complex to manage though, because you have two messaging systems to maintain, and the two snapshots can be out of sync with one another, adding a whole new class of edge case. A: The approach TCP uses is that the sender will keep resending the packet until it receives an acknowledgement. The receiver will ignore duplicate packets, but still send acknowledgements for them. The sender will ignore duplicate acknowledgements. If a packet gets lost, the sender resends it, as you already know. If an acknowledgement gets lost, the sender resends the original packet, which causes the receiver to resend the acknowledgement. If an acknowledgement is not received within a certain time (perhaps 60 seconds, or 20 retries) then the player is considered to be disconnected from the game. You must implement some kind of timeout rule, or otherwise a player who unplugs their network cable will tie up resources on your server forever. A: If you want to reinvent TCP, it makes sense to look at TCP first, which deals with the exact problem you describe (part of the solution is to use user defined values for retry attempts and timeouts). Solutions that use 2 channels, a TCP channel (for reliable communication) as well as a UDP (for low latency communication) channel are not uncommon. Some solutions detect when a client is missing some information for too long, and start a resynchronization, which may use UDP or TCP. Another common approach is to design communication such that it doesn't rely on acknowledgements at all, but that's outside the scope of the question.
{ "pile_set_name": "StackExchange" }
Q: Find the remainder of $7^{2002}$ divided by 101. This is what I have so far: Since 101 is a prime and does not divide 7, we can apply Fermat's Little Theorem to see that $$7^{100} \equiv 1 \ (mod \ 101)$$ We can then reduce $7^{2002}$ to $7^{2} (7^{100})^{20} \equiv 7^{2}(1)^{20} \ (mod \ 101)$ which is where I'm stuck at. $7^2=49 \equiv 150 \ (mod \ 101)$. How do I reduce $7^2$ in a way that is constructive towards my solution since $(mod \ 101)$ is such a large modulus to operate in? A: You had the solution and broke it :) At $$7^{2002} \equiv 49\pmod {101} \,,$$ you are done, the remainder must be $49$. Indeed, if you denote the remainder by $r$ then $0 \leq r \leq 100$ and $$ r \equiv 49 \pmod{101} \,.$$ This means that $101|r-49$, and since $-49 \leq r-49 < 52$ you get $r-49=0$.
{ "pile_set_name": "StackExchange" }
Q: Show CMS block only for customers who have not subscribed to a Newsletter I'm looking for a way to show a CMS block only to customers (who are logged in anyways) who have not subscribed for the newsletter. Could someone help me with the code? I know how to implement the CMS block, just not sure how to check whether the customer has subscribed already or not. Thanks a lot, Johannes A: Magento is check a customer email exits or not by below code $status = Mage::getModel('newsletter/subscriber')->subscribe($email); $subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email); if($subscriber->getId()) { if ($status == Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE) { // 'Confirmation request has been sent.'; } else { //Thank you for your subscription; } } else{ //no subcription }
{ "pile_set_name": "StackExchange" }
Q: suitable generics to use in an arraylist I am using an Arraylist to hold heterogeneous data...a mix of String, int and class objects (These objects could be instances of any class I've defined.). I've initialised the ArrayList as ArrayList<Object> = new ArrayList<Object>. But I think I've heard ppl saying that directly referring to the Objects is sth. bad/undesirable? I'm referring to the objects because I can't find any suitable generics to use in my case. Is it ok to use or are there any suitable generics? (I'm relatively new to Java) A: Use different list for each type and keep those lists in a map and you can use the class object as the key so it wont mix up and easy to access. Map<Class<?>,List<?>> map = new HashMap<Class<?>,List<?>>(); map.put(String.class, new ArrayList<String>()); map.put(Integer.class, new ArrayList<Integer>()); map.put(Class.class, new ArrayList<Class<?>>()); EDIT: P.S: You will still get an unchecked warning when you retrieve the list from the map if you want to add new object into the list. public static void main(String[] args) { Map<Class<?>,List<?>> map = new HashMap<Class<?>,List<?>>(); map.put(String.class, new ArrayList<String>()); map.put(Integer.class, new ArrayList<Integer>()); map.put(Class.class, new ArrayList<Class<?>>()); String str = "deneme"; @SuppressWarnings("unchecked") List<String> strList = (List<String>) map.get(String.class); strList.add(str); strList.add("str2"); strList.add("str2"); @SuppressWarnings("unchecked") List<Class<?>> classList = (List<Class<?>>) map.get(Class.class); classList.add(String.class); classList.add(Integer.class); classList.add(Double.class); for(String currentStr:strList){ System.out.println(currentStr); } }
{ "pile_set_name": "StackExchange" }
Q: Real basic question about Sharepoint users I cannot seem to get how this is done. I've read a bit about using AD, so I assume that Sharepoint can be set up to authenticate against AD? Besides AD, is it possible to manually enter users and groups in Sharepoint to be used for authentication purposes? Is it possible to use the two together? A: Yes, you can use both AD users and groups to authenticate and authorize users inside of SharePoint.
{ "pile_set_name": "StackExchange" }
Q: How to find a real $3\times3$ matrix that has no cubic root How does one find a real $3\times3$ matrix that does not have a cubic root? If given a matrix without a cubic root, how can one prove that it does not have a cube root? A: Let $A=\begin{bmatrix}0&1&0\\0&0&0\\0&0&0\end{bmatrix},\;$ and let $B$ be a matrix with $B^3=A$. If $\lambda$ is an eigenvalue of $B$, then $\lambda^3$ is an eigenvalue of $A$, so $\lambda^3=0$ and therefore $\lambda=0$. Then $B=P^{-1}JP$ where $J=\begin{bmatrix}0&1&0\\0&0&0\\0&0&0\end{bmatrix}, \;J=\begin{bmatrix}0&0&0\\0&0&1\\0&0&0\end{bmatrix},\;J=\begin{bmatrix}0&1&0\\0&0&1\\0&0&0\end{bmatrix}$, or $J=\begin{bmatrix}0&0&0\\0&0&0\\0&0&0\end{bmatrix}$. Then $A=B^3=P^{-1}J^{3}P=P^{-1}0P=0$, which gives a contradiction; so $A$ doesn't have a cube root. A: Let $A$ be a nilpotent matrix of order $3$. For example, $$ A = \begin{pmatrix}0 & 1 & 0 \\ 0 & 0 &1 \\ 0 & 0 & 0\end{pmatrix} $$ That is, $A \ne 0$, $A^{2} \ne 0$, $A^{3}=0$. Suppose $A=B^{3}$. Then $B^{9}=0$, which means that the minimal polynomial for $B$ is a power of $\lambda$. However, $B^{6} \ne 0$, which is impossible because of the Cayley Hamilton Theorem. $A$ also has no square root.
{ "pile_set_name": "StackExchange" }
Q: Where does the word 青年 come from? I know the word 少年 means boy or lad, and it is composed by the kanjis for few (少) and year (年), so it makes sense for me to associate boy with few years. In the other hand, 青年 means young man (usually refering to young adults as far as I know), but this word is made of the kanjis of blue (青) and year (年), so I don't see the same logic as in 少年. So, that's what I want to know, what's the reason for using these kanji to refer to young men. Maybe blue years have a meaning in Japanese? Or is it that my attempt at translation is too literal? A: Interesting question. Apparently to understand why 青 is used in 青年 we have to go look at 青春{せいしゅん}. The origin of this word is closely related to the Chinese concepts of Yin/Yang and Wuxing (the five elements). Basically you have the five elements: 「木・火・土・金・水」each of them connected with a cardinal point, color, time, and god. In particular the wood (木) is related to east (東), to 青 ("blue" as you said but notice that another meaning for it is young/immature. More on the color later), spring (春), and 青竜 (the blue dragon, an auspicious mystical creature said to rule over the eastern heavens). Among these 青 is the color of spring and hence 青春 became a synonym of spring. Now from here the connection is straightforward since 青春 is itself a pseudonym for the early years in one's life. The precise reference of this part is here: 春の異称「青春」が、年の若い時代をさすようになったのは、夢や希望に満ち溢れていることから、人生の春にたとえられたものである。 Therefore, connecting the dots, most likely 青 in 青年 comes from 青春 and the meaning related above. You can find the full quote above from the entry for 青春 in an etymology dictionary here. For convenience I'll copy it here too: 青春は、陰陽五行説に由来する。 陰陽五行説には、「木・火・土・金・水」の五行があり、各々に対応する「方位」「色」「時」「神」がある。 五行の「木」は、「東」「青」「春」「青竜」に対応し、春の色は「青」であることから、「春」の異称が「青春」となった。 「朱夏」「白秋」「玄冬」も、陰陽五行説に対応する色に基づいた季節の異称である。 春の異称「青春」が、年の若い時代をさすようになったのは、夢や希望に満ち溢れていることから、人生の春にたとえられたものである。 季節の異称の中で「青春」のみが人生の時期を表しているのは、「青二才」や「青臭い」のように、「青」に「未熟」の意味が含まれていることも影響していると思われる。 Here is the definition of 青年: 青春期の男女。10代後半から20代の、特に男子をいうことが多い。若さを強調する場合には30代にもいう。わかもの。わこうど。「青年実業家」 A note on the color 青 As pointed out in a comment, let me give some more info about the actual color of that 青 represents. Let's start off by saying that the translation "blue" is an over simplification. Of course according to wikipedia, that's the most natural translation one would give (as it is listed as one of the three primary colors). Also, its RGB code is #0067C0 which corresponds to blue indeed. However, in general it is used in every day life to refer to a wider spectrum. One interesting example is for sure the color of traffic lights. What is called 青 in Japanese is what any westerner (I guess) would call green (reference pic below). Now, actually I believe that some Japanese people as well might argue that the traffic light color is actually "green", but the point of this example is just to stress the ambiguity of 青 and show that (especially in daily life) it might represent a wide spectrum of colors rather than a single specific one. As I also mentioned above, it is considered the color of spring, hence would be not surprising if green comes into play as well. In this case, it is interesting to notice the association that the color green has in English with youth and inexperience. See here for example.
{ "pile_set_name": "StackExchange" }
Q: Adobe Air vertical scroll for rich text I have a rich text component with large amount of text. How to add vertical scrollbar to it? I tried: <mx:Canvas width="100%" height="100%" verticalScrollBar="vsb"> <s:RichText id="text" width="100%" height="100%" maxDisplayedLines="-1"/> </mx:Canvas> <s:VScrollBar id="vsb" height="100%"/> But it get error: Initializer for 'verticalScrollBar': values of type mx.controls.scrollClasses.ScrollBar cannot be represented in text. A: Reading the docs on RichText, I see this: For performance reasons, it does not support scrolling, selection, editing, clickable hyperlinks, or images loaded from URLs. If you need those capabilities, please see the RichEditableText class. So, going with a RichEditableText (and setting its editable property to false, this works for me with FlashBuilder 4.5. Note: I set the Scroller height to 200 and added lots of text to force a scrollbar to appear) <mx:Canvas width="100%" height="100%"> <s:Scroller width="100%" height="200"> <s:RichEditableText percentWidth="100" percentHeight="100" editable="false"> <!-- add lots of text here to introduce a scrollbar --> </s:RichEditableText> </s:Scroller> </mx:Canvas>
{ "pile_set_name": "StackExchange" }
Q: Test controller action that makes an external API call I have an API controller with an action function. This function makes an external call for another API to get some data. this external call is made by simply creating a client with a URL. I want to create a test using WebApplicationFactory to test this action function. I would like to know how to configure this external call. To say if the server calls this URL return this response. May be it should be somewhere in overriding ConfigureWebHost to tell the server that if you call this URL (The external API url) return this response. Here is the controller action I want to test. namespace MyAppAPI.Controllers { public class MyController : ControllerBase { [HttpPost("MyAction")] public async Task MyAction([FromBody] int inputParam) { var externalApiURL = "http://www.external.com?param=inputParam"; var client = new HttpClient(); var externalResponse = await client.GetAsync(externalApiURL); //more work with the externalResponse } } } Here is the Test class I want to use public class MyAppAPITests : IClassFixture<WebApplicationFactory<MyAppAPI.Startup>> { private readonly WebApplicationFactory<MyAppAPI.Startup> _factory; public MyAppAPITests(WebApplicationFactory<MyAppAPI.Startup> factory) { _factory = factory; } [Fact] public async Task Test_MyActionReturnsExpectedResponse() { //Arrange Code //Act //Here I would like to have something like this or a similar fashion _factory.ConfigureReponseForURL("http://www.external.com?param=inputParam", response => { response.Response = "ExpectedResponse"; }); //Assert Code } } The code in Test_MyActionReturnsExpectedResponse does not exist anywhere, it is just what I would like to have either by inheriting WebApplicationFactory or by configuring it. I would like to know how that can be achieved. i.e. configuring a response when an API controller makes an external call. Thank you for your help. A: The issue is that you have a hidden dependency, namely HttpClient. Because you're newing this up in your action, it's impossible to mock. Instead, you should be injecting this dependency into your controller. With ASP.NET Core 2.1+ that's possible with HttpClient thanks to IHttpClientFactory. However, out of the box, you cannot inject HttpClient directly into a controller, because controllers are not registered in the service collection. While you can change that, the recommended approach is to instead create a "service" class. This is actually better anyways as it abstract the knowledge of interacting with this API out of your controller entirely. Long and short, you should do something like: public class ExternalApiService { private readonly HttpClient _httpClient; public ExternalApiService(HttpClient httpClient) { _httpClient = httpClient; } public Task<ExternalReponseType> GetExternalResponseAsync(int inputParam) => _httpClient.GetAsync($"/endpoint?param={inputParam}"); } Then, register this in ConfigureServices: services.AddHttpClient<ExternalApiService>(c => { c.BaseAddress = new Uri("http://www.external.com"); }); And finally, inject it into your controller: public class MyController : ControllerBase { private readonly ExternalApiService _externalApi; public MyController(ExternalApiService externalApi) { _externalApi = externalApi; } [HttpPost("MyAction")] public async Task MyAction([FromBody] int inputParam) { var externalResponse = await _externalApi.GetExternalResponseAsync(inputParam); //more work with the externalResponse } } Now, the logic for working with this API is abstracted from your controller and you have a dependency you can easily mock. Since you're wanting to do integration testing, you'll need to sub in a different service implementation when testing. For that, I'd actually do a little further abstraction. First, create an interface for the ExternalApiService and make the service implement that. Then, in your test project you can create an alternate implementation that bypasses HttpClient entirely and just returns pre-made responses. Then, while not strictly necessary, I'd create an IServiceCollection extension to abstract the AddHttpClient call, allowing you to reuse this logic without repeating yourself: public static class IServiceCollectionExtensions { public static IServiceCollection AddExternalApiService<TImplementation>(this IServiceCollection services, string baseAddress) where TImplementation : class, IExternalApiService { services.AddHttpClient<IExternalApiService, TImplementation>(c => { c.BaseAddress = new Uri(baseAddress) }); return services; } } Which you would then use like: services.AddExternalApiService<ExternalApiService>("http://www.external.com"); The base address could (and probably should) be provided via config, for an extra layer of abstraction/testability. Finally, you should be use a TestStartup with WebApplicationFactory. It makes it far easier to switch out services and other implementations without rewriting all your ConfigureServices logic in Startup, which of course adds variables to your test: e.g. is it not working because I forgot to register something the same way as in my real Startup? Simply add some virtual methods to your Startup class and then use these for things like adding your databases, and here, adding your service: public class Startup { ... public void ConfigureServices(IServiceCollection services) { ... AddExternalApiService(services); } protected virtual void AddExternalApiService(IServiceCollection services) { services.AddExternalApiService<ExternalApiService>("http://www.external.com"); } } Then, in your test project, you can derive from Startup and override this and similar methods: public class TestStartup : MyAppAPI.Startup { protected override void AddExternalApiService(IServiceCollection services) { // sub in your test `IExternalApiService` implementation services.AddExternalApiService<TestExternalApiService>("http://www.external.com"); } } Finally, when getting your test client: var client = _factory.WithWebHostBuilder(b => b.UseStartup<TestStartup>()).CreateClient(); The actual WebApplicationFactory still uses MyAppAPI.Startup, since that generic type param corresponds to the app entry point, not actually what Startup class is being used.
{ "pile_set_name": "StackExchange" }
Q: Exponential to base 10 I came up with this UDF, there must be a better way? If the number is <0.00001 then use base 10 notation instead of e-. Input range is 0-1. report.Rmd ```{r temp} udf_expTo10 <- function(x){ x <- as.character(x) if(grepl("e-",x)){ x <- round(as.numeric(unlist(strsplit(x,"e-"))),1) x <- paste0(x[1]," x 10^-",x[2],"^")}else{ x <- round(as.numeric(x),4)} return(as.character(x)) } ``` pvalue = `r udf_expTo10(0.000000123)` pvalue = `r udf_expTo10(0.00123)` pvalue = `r udf_expTo10(1)` pvlaue = `r udf_expTo10("-1.222123e-15")` report.docx A: This has been done in knitr long time ago, you can simply write $`r -1.222123e-15`$ or $`r 0.000000123`$. I'm not sure why you were trying to reinvent the wheel, but I'm open to suggestions to improve knitr:::format_sci_one.
{ "pile_set_name": "StackExchange" }
Q: setText() from not layout xml is it possible to do a setText() from one class to another, let me explain, for example class A have the layout A.xml and class B have B.xml. Is possible to setText() to a TextView in B.xml from class A? I tryed doing this: setContentView(R.layout.activity_match_finder); hold = (TextView) findViewById(R.id.hold); hold.setText(""); But it didn't work. A: You can send text via intent from one class to another and then set it as the textview like so: class a: String word = "hello"; Intent send= new Intent(a.this,b.class); send.putExtra("TAG", word); a.this.startActivity(send); then in class b String getVal; getVal = getIntent().getExtras().getString("TAG"); textview.setText(getVal); obviously the intent in class a needs to be sent using some sort of button click depending on what your design wants.
{ "pile_set_name": "StackExchange" }
Q: How to get the Previous formula field value in Crystal Report? I am creating a crystal report containing the FORMULA fields like Openbalance,debitamount,creditamount and closing balance in details section grouped by its type.. In this, the Previous day Closing balance will be the next day's Opening balance. Please help me out to get the Previous day Closing Balance which will be in the Open balance field. Thanks in advance. A: @Shiva. Thank you so much for your idea. Its working great. But small change is needed for my requirement. I need the opening balance for each record.So I just created inter groups(i.e. first grouped the records by its name and inside,it was grouped by its serial no.,so that i can get values for each record) Then as you said but without using the counter part. In the footer section(grouped by Serial No), create a formula field: Shared Numbervar a; a:=//the value you want to pass In the header section(grouped by Serial No),create a formula field: Shared NumberVar b; Shared NumberVar a; b:=a; Finally,In the details section formula field, Shared Numbervar b; b
{ "pile_set_name": "StackExchange" }
Q: Make a pause during infinite CSS3 animation I try to make an animation that run every 3 seconds without JavaScript. My animation's duration is 1 second. I'm only able to wait 3seconds the first occurence then it's a loop of 1s animation. My code so far: https://jsfiddle.net/belut/aojp8ozn/32/ .face.back { -webkit-animation: BackRotate 1s linear infinite; -webkit-animation-delay: 3s; animation: BackRotate 1s linear infinite; animation-delay: 3s; } .face.front { -webkit-animation: Rotate 1s linear infinite; -webkit-animation-delay: 3s; animation: Rotate 1s linear infinite; animation-delay: 3s; } @-webkit-keyframes Rotate { from {-webkit-transform:rotateY(0deg);} to {-webkit-transform:rotateY(360deg);} } @-webkit-keyframes BackRotate { from {-webkit-transform:rotateY(180deg);} to {-webkit-transform:rotateY(540deg);} } @keyframes Rotate { from {-webkit-transform:rotateY(0deg);} to {-webkit-transform:rotateY(360deg);} } @keyframes BackRotate { from {-webkit-transform:rotateY(0deg);} to {-webkit-transform:rotateY(360deg);} } I know how to do it with javascript: https://jsfiddle.net/belut/fk3f47jL/1/ I tried this answer without success: Cycling CSS3 animation with a pause period? Can you help me please? EDIT Thanks great answers i'm also able to make this scenario: wait 2s, run 1s flip, wait 2s, run 1s back_flip, wait 2s. #f1_container { position: relative; margin: 10px auto; width: 90px; height: 90px; z-index: 1; } #f1_container { perspective: 1000; } #f1_card { width: 100%; height: 100%; } img { width: 90px; height: 90px; } .face { position: absolute; width: 100%; height: 100%; backface-visibility: hidden; } .face.back { display: block; transform: rotateY(180deg); } .face.back { -webkit-animation: BackRotate 5s linear infinite; } .face.front { -webkit-animation: Rotate 5s linear infinite; } @-webkit-keyframes Rotate { 0%,40% {-webkit-transform:rotateY(0deg);} 50%,90% {-webkit-transform:rotateY(180deg);} 100% {-webkit-transform:rotateY(360deg);} } @-webkit-keyframes BackRotate { 0%,40% {-webkit-transform:rotateY(180deg);} 50%,90% {-webkit-transform:rotateY(360deg);} 100% {-webkit-transform:rotateY(540deg);} } A: It seems like the only way to achieve this is to extend the animation so that it lasts 4s instead of 1s. Then you could delay the animation by animating from 75% to 100% (rather than 0% to 100%). In doing so, there is essentially an artificial delay in the animation itself. You just have to do the math to figure out how long this delay is in correlation with the total length of the animation itself. Updated Example .face.back { display: block; transform: rotateY(180deg); } .face.back { -webkit-animation: BackRotate 4s linear infinite; animation: BackRotate 4s linear infinite; } .face.front { -webkit-animation: Rotate 4s linear infinite; animation: Rotate 4s linear infinite; } @-webkit-keyframes Rotate { 75% {-webkit-transform:rotateY(0deg);} 100% {-webkit-transform:rotateY(360deg);} } @-webkit-keyframes BackRotate { 75% {-webkit-transform:rotateY(180deg);} 100% {-webkit-transform:rotateY(540deg);} } @keyframes Rotate { 75% {-webkit-transform:rotateY(0deg);} 100% {-webkit-transform:rotateY(360deg);} } @keyframes BackRotate { 75% {-webkit-transform:rotateY(180deg);} 100% {-webkit-transform:rotateY(540deg);} } A: I am not sure exactly when it was released, and it's not the most cross-browser approach (does not cover older browsers like I.E. 9) but you could use the animationPlayState style prop. Theres some documentation on this found here if you want to check it out. animationPlayState=false webkitAnimationPlayState=false function pause() { var animationElement = document.getElementById('animatedItem'); animationElement.style.animationPlayState='paused'; animationElement.style.webkitAnimationPlayState='paused'; } As you can see this put's the items animation into a "paused"state, to put it back where it left the animation off at, you can set it to the "running" state that this prop accepts. Here is a quick example I found when browsing Google.
{ "pile_set_name": "StackExchange" }
Q: Динамически создаваемый объект и обращение к методу Добрый день, начал изучать java совсем недавно, появился вопрос. В php мы можем вызвать метод таким образом: $name = 'productController'; $action = 'run'; $controller = new $name; $controller->$action(); Пробовал сделать что-то подобное, не получается. Возможен подобный вызов в java или тут всё строго и такой свободы не ждать? :) A: Если я правильно понял, вы хотите динамически, вызывать методы или создать объекты основываясь на названии. В java для этих целей есть несколько интрументов reflection, method handlers. Написал небольшой пример: import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Method; public class Solution { public static void main(String[] args) throws Throwable { String methodName = "greeter"; reflectionInvoker(methodName, Solution.class); methodHandlerInvoker(methodName,Solution.class); } private static void reflectionInvoker(String methodName, Class<?> clazz) throws Exception { Method method = clazz.getMethod(methodName); method.invoke(null); } private static void methodHandlerInvoker(String methodName,Class<?>clazz) throws Throwable { MethodHandle methodHandle= MethodHandles.lookup().findStatic(clazz,methodName, MethodType.methodType(void.class)); methodHandle.invoke(); } public static void greeter() { System.out.println("hello world"); } } A: Можно попробовать способ под названием рефлексия (Reflection) Reflection в Java используется для просмотра информации о классах, интерфейсах, методах, полях, конструкторах, аннотациях во время выполнения java программ. При этом знать названия исследуемых элементов заранее не обязательно. Все классы для работы с reflection расположены в пакете java.lang.reflect. С помощью рефлексии можно Получить информацию о модификаторах класса, полях, методах, константах, конструкторах и суперклассах. Вызвать метод объекта по имени. Выяснить, какие методы принадлежат реализуемому интерфейсу/интерфейсам. Создать экземпляр класса, причем имя класса неизвестно до момента выполнения программы. Получить и установить значение поля объекта по имени. Узнать/определить класс объекта прочее Пример: MyClass obj = new MyClass(); // <--- это класс, который будем просматривать Class c = obj.getClass(); // Получение объекта типа Class Method[] methods = c.getDeclaredMethods(); // возвращаем все методы класса не зависимо от типа доступа for (Method method : methods) { System.out.println("Имя: " + method.getName()); System.out.println("Возвращаемый тип: " + method.getReturnType().getName()); Class[] paramTypes = method.getParameterTypes(); // берем параметры метода System.out.print("Типы параметров: "); for (Class paramType : paramTypes) { System.out.print(" " + paramType.getName()); } System.out.println(); System.out.println("------------------------"); } // Пример получения конкретного метода по имени Method method1 = с.getMethod("simple"); // Вызвать метод с помощью invoke - передать туда только объект String simple = (String)method1.invoke(c); Если мы не знаем имя класса на момент компиляции, но знаем во время выполнения приложения, то можно использовать метод forName(), чтобы получить объект Class. Class obj = Class.forName("com.test.classes.MyClass"); Также вместо MyClass obj = new MyClass(); // <--- это класс, который будем просматривать Class c = obj.getClass(); // Получение объекта типа Class Можно писать: Class obj = MyClass.class; Т.е. не нужно создавать экземпляр класса (который может вызвать конструктор и провернуть неизвестные манипуляции), а мы уже знаем в момент компиляции какого типа он будет.
{ "pile_set_name": "StackExchange" }
Q: diagonalizable matrix such that sum of every column is the same number Let A be a square matrix which is diagonalizable over field $\mathbb{F}$ and the sum of the entries of any column is the same number $a\in\mathbb{F}$. Show that $a$ is eigenvalue of the matrix A. My try: Let A be the arbitrary matrix $\displaystyle \left(\begin{matrix} a_{11}&a_{12}&\cdots&a_{1(n-1)}&a_{1n} \\ a_{21}&a_{22}&\cdots&a_{2(n-1)}&a_{2n} \\ \vdots&\vdots & \ddots&\vdots&\vdots \\a_{(n-1)1}&a_{(n-1)2}&\cdots&a_{(n-1)(n-1)}&a_{(n-1)n} \\ a_{n1}&a_{n2}&\cdots&a_{n(n-1)}&a_{nn}\end{matrix}\right)$. Now $\displaystyle p_A(x)=\det(xI-A)=\det\left(\begin{matrix} x-a_{11}&-a_{12}&\cdots&-a_{1(n-1)}&-a_{1n} \\ -a_{21}&x-a_{22}&\cdots&-a_{2(n-1)}&-a_{2n} \\ \vdots&\vdots & \ddots&\vdots&\vdots \\-a_{(n-1)1}&-a_{(n-1)2}&\cdots&x-a_{(n-1)(n-1)}&-a_{(n-1)n} \\ -a_{n1}&-a_{n2}&\cdots&-a_{n(n-1)}&-a_{nn}\end{matrix}\right)$. Multiply row and add it to other row doesn't change the value of the determinant, hance we can add any row $2\le j\le n$ to the first row and get $$p_A(x)=\det\left(\begin{matrix} x-\sum_{i=1}^na_{i1}&x-\sum_{i=1}^na_{i2}&\cdots&x-\sum_{i=1}^na_{i(n-1)}&x-\sum_{i=1}^na_{in} \\ -a_{21}&x-a_{22}&\cdots&-a_{2(n-1)}&-a_{2n} \\ \vdots&\vdots & \ddots&\vdots&\vdots \\-a_{(n-1)1}&-a_{(n-1)2}&\cdots&x-a_{(n-1)(n-1)}&-a_{(n-1)n} \\ -a_{n1}&-a_{n2}&\cdots&-a_{n(n-1)}&-a_{nn}\end{matrix}\right)$$ But we know that $\displaystyle \forall 1 \le k \le n: \ \sum_{i=1}^n a_{ik}=a$, hence $$p_A(x)=\det\left(\begin{matrix} x-a&x-a&\cdots&x-a&x-a \\ -a_{21}&x-a_{22}&\cdots&-a_{2(n-1)}&-a_{2n} \\ \vdots&\vdots & \ddots&\vdots&\vdots \\-a_{(n-1)1}&-a_{(n-1)2}&\cdots&x-a_{(n-1)(n-1)}&-a_{(n-1)n} \\ -a_{n1}&-a_{n2}&\cdots&-a_{n(n-1)}&-a_{nn}\end{matrix}\right)= \\ =(x-a)\cdot\det\left(\begin{matrix} 1&1&\cdots&1&1 \\ -a_{21}&x-a_{22}&\cdots&-a_{2(n-1)}&-a_{2n} \\ \vdots&\vdots & \ddots&\vdots&\vdots \\-a_{(n-1)1}&-a_{(n-1)2}&\cdots&x-a_{(n-1)(n-1)}&-a_{(n-1)n} \\ -a_{n1}&-a_{n2}&\cdots&-a_{n(n-1)}&-a_{nn}\end{matrix}\right)$$ thus $a$ is an eigenvalue of the matrix A. I didn't use the fact that A is diagonalizable and don't know why it is needed. Any help/hint will be appreciated, thank you! A: $A$ and $A^T$ have the same eigenvalues. Take $X=\left( \begin{matrix} 1\\ 1\\ ...\\ 1 \end{matrix} \right)$ $A^T X=aX$, $a$ being the sum of each column of $A$, thus the sum of each row of $A^T$. Then $a$ is eigenvalue of $A^T$, and of $A$. A: i will avoid the use of the fact that $A$ and $A^T$ have the same eigenvalue therby avoiding any appeal to determinants explicitly. bus we do use the fact the one sided invertiblilty implies the other. that is $AB = I$ iff $BA = I.$ if the sum of every column is $a,$ then $A$ has left eigenvector corresponding to $a.$ that is there is $u = (1,1,\cdots, 1)^T \neq 0$ such that $u^TA = au^T.$ therefore $A - aI$ is not invertible which in turn implies that $a$ is an eigenvalue of $A$ and has a (right)eigenvector $x \neq 0$ such that $Ax = ax$ A: There is nothing wrong with the proof although you probably use a gun to kill the fly. Indeed, you don't need $A$ to be diagonalizable. We can construct a matrix $A$ with this property, which is not diagonalizable, easily. Consider $$ A=\left[\begin{array}{rrr}0&-1&-1\\1&1&0\\0&1&2\end{array}\right]. $$ The column sums are all equal to $1$, which is the only eigenvalue of $A$ with the algebraic multiplicity $3$. However, $A$ is not diagonalizable.
{ "pile_set_name": "StackExchange" }
Q: Error encountered compiling kernel 2.6.35-25.44 I downloaded the linux-source-2.6.35 package and tried to compile it using the command "fakeroot make-kpkg --append-to-version=.dbg kernel_image kernel_source kernel_headers --initrd" after "make menuconfig". The image .deb file is produced and installs fine, but an error stops the build process while trying to make the source package: scripts/Makefile.clean:17: /home/ade/linux-source-2.6.35/debian/linux-source-2.6.35.10.dbg/usr/src/linux-source-2.6.35.10.dbg/crypto/Makefile: No such file or directory make[1]: *** No rule to make target `/home/ade/linux-source-2.6.35/debian/linux-source-2.6.35.10.dbg/usr/src/linux-source-2.6.35.10.dbg/crypto/Makefile'. Stop. make: *** [_clean_crypto] Error 2 Sure enough, the folder linux-source-2.6.35/debian/linux-source-2.6.35.10.dbg/usr/src/linux-source-2.6.35.10.dbg/crypto does not exist (although all of the other kernel source folders appear to be there). I haven't even been able to determine where the folder is supposed to be copied over, or what's supposed to invoke clean. Am I doing something wrong here? It should be noted that I am running 10.04. A: One of the kernel package scripts wasn't working right, so it was trying to copy crypto.master and failing. Below is a patch I made to fix it, although the source package still doesn't include the debian and debian.master folders outside the tar archive like the official Ubuntu kernel source packages. --- /usr/share/kernel-package/ruleset/targets/source.mk 2009-08-21 09:47:53.000000000 -0400 +++ /usr/share/kernel-package/ruleset/targets/source.mkmod 2011-02-28 14:42:22.000000000 -0500 @@ -64,12 +64,10 @@ debian/stamp/install/$(s_package): #### ###################################################################### ifneq ($(strip $(int_follow_symlinks_in_src)),) - -tar cfh - $$(echo * | sed -e 's/ debian//g' -e 's/\.deb//g' ) | \ - (cd $(SRCDIR); umask 000; tar xpsf -) + -(umask 000; find . -mindepth 1 -maxdepth 1 -not -name '*.deb' -not -name 'debian*' -exec cp -Lr {} $(SRCDIR) \;; ) (cd $(SRCDIR)/include; rm -rf asm ; ) else - -tar cf - $$(echo * | sed -e 's/ debian//g' -e 's/\.deb//g' ) | \ - (cd $(SRCDIR); umask 000; tar xspf -) + -(umask 000; find . -mindepth 1 -maxdepth 1 -not -name '*.deb' -not -name 'debian*' -exec cp -r {} $(SRCDIR) \;; ) (cd $(SRCDIR)/include; rm -f asm ; ) endif $(install_file) debian/changelog $(SRCDIR)/Debian.src.changelog
{ "pile_set_name": "StackExchange" }
Q: Why don't Jedi spaceships have hyperdrive motors while Sith spaceships do? Jedi single-person spaceships don't have hyperdrive motors (as far as I know), but dock with a ring that has a hyperdrive motor. As shown in the first few seconds of this movie clip. Darth Maul's spaceship can jump to hyperspace without a separate component. Count Dooku's sailship doesn't need a separate hyperdrive motor because it can jump too. Why would Jedi not use a spaceship with a hyperdrive motor built into it? Just seems vulnerable to have to dock and undock with a hyperdrive unit. And if the hyperdrive unit gets stolen or blasted, well, somebody is stranded on an isolated planet. Edit: I prefer a G-canon answer with citations, but will settle for a lower canon. A: Per the Star Wars Databank, Jedi Starfighters are designed to be as nimble as possible. That includes not having bulky hyperdrive systems. These wedge-shaped one-man starfighters were built for the Jedi Order. The Delta-7’s designers worked with the Jedi to create a starfighter for pilots with Force-aided reflexes, stripping down the fighters’ systems and making their controls as responsive as possible. With skilled pilots such as Anakin Skywalker and Saesee Tiin at the controls, Delta-7s were lightning-quick in combat, darting in for attack runs and then skipping nimbly away from retaliatory fire. DELTA-7 JEDI STARFIGHTER - StarWars.com The Star Wars: Revenge of the Sith Incredible Cross-Sections factbook also mentions that many Jedi ships are simply too small to safely contain a hyperdrive The original Star Wars Databank article on hyperdrive rings also mentions power limitations and the need for Jedi fighters to operate independently of larger ships (and presumably covertly) which necessitates the need for a detachable hyperdrive system. Small space-faring vessels generally do not have the power plant yields or necessary spaceframe to support supralight engines. Snubfighters equipped with hyperdrives are rare and expensive, and small craft tend to rely on larger carrier ships for extended voyages into the depths of space. For the Jedi starfighter, which often operates independently, its operational range needed to support the scope of the individual missions undertaken by the Jedi order.
{ "pile_set_name": "StackExchange" }
Q: rails 3 temporary user input to use for comparison I'm not sure how to even research this question so maybe some awesome rails developer can point me in the right direction. I have a model that's holding a question and correct answer. On the show view, I want the user to enter their answer into an input field and upon pressing submit, their answer is compared to the one held in the model. I don't need to save their answer. Thoughts? A: You could use a non ActiveRecord model for that. Something like this: class UserAnswer # note that this class doesn't inherit from ActiveRecord::Base attr_accessor :question_id, :answer def initialize(params) @question_id = params[:question_id] @answer = params[:answer] end def correct? q = QuestionAnswerModel.find(self.question_id) q.answer == self.answer end end Then in your controller you can do something like this: user_answer = UserAnswer.new(params) # params contains :question_id and :answer user_answer.correct? # returns true or false
{ "pile_set_name": "StackExchange" }
Q: select from table with parameters from another table first table meter_values |id | somedata | date(YY-MM-DD)| status | |-----+-----------+---------------+--------| |1 | tets | 20180628 | 6 | |2 | setd | 20180627 | 6 | |3 | ewrw5 | 20180701 | 6 | |4 | 6werww | 20180730 | 6 | |5 | werqwe | 20180803 | 6 | |6 | wrwerw | 20171130 | 6 | second table period | year | begin | end | |--------+----------+----------| | 201807 | 20180626 | 20180704 | | 201808 | 20180730 | 20180803 | | 201801 | 20171228 | 20180104 | | 201712 | 20171129 | 20171205 | i need get count(meter_values) where meter_values.status=6 and group by year and date from table period.begin and period.endexample: | year | begin | end | count(meter_values) | |--------+----------+----------+---------------------| | 201807 | 20180626 | 20180704 | 3 | | 201808 | 20180730 | 20180803 | 2 | | 201801 | 20171228 | 20180104 | 0 | | 201712 | 20171129 | 20171205 | 1 | i try this query select * from period, (select count(meter_values.id) from meter_values, period where meter_values.date>=period.begin and meter_values.date<=period.end and meter_values.status=6 and period.begin is not null and period.end is not null) as mv where period.begin is not null and period.end is not null; but i get count of all records | year | begin | end | count(meter_values) | |--------+----------+----------+---------------------| | 201807 | 20180626 | 20180704 | 6 | | 201808 | 20180730 | 20180803 | 6 | | 201801 | 20171228 | 20180104 | 6 | | 201712 | 20171129 | 20171205 | 6 | A: you could use a inner join and a count select a.year, a.begin, a.end, count(*) from meter_values b inner join period a on b.date between a.begin and a.end and b.status = 6 group by a.year, a.begin, a.end
{ "pile_set_name": "StackExchange" }
Q: how to remove whitespace from explode how will i eliminate the white space when the value is empty? i used this codes i also try to trim it but it does not work how should i do this ? thank you in advance. Here is the picture $imeitransferserial = explode(',', $imeitransfer); $imeiserial = explode(',', $imei); foreach($imeiserial as $is){ $imeicode = trim($is); if (in_array($is,$imeitransferserial)) { $select = 'selected="selected" '; } else { $select = ""; } echo "<option ".$select."value='$imeicode'>".$imeicode."</option>"; } A: A combination of array_map and array_filter, or possibly just array_filter, will do the trick. array_map with trim will remove extra whitespaces: $imeitransferserial = array_map('trim',$imeitransferserial ); array_filter will remove empty elements from the array: $imeitransferserial = array_filter($imeitransferserial); If you can have a value of 0 in the array, you will want to use strlen as a callback for array_filter: $imeitransferserial = array_filter($imeitransferserial, 'strlen'); By default, array_filter will remove anything that evaluates to 0.
{ "pile_set_name": "StackExchange" }
Q: chainer StandardUpdater iterator Parameters in the chainer doc, it shows in https://docs.chainer.org/en/stable/reference/core/generated/chainer.training.StandardUpdater.html#chainer.training.StandardUpdater Parameters: iterator – Dataset iterator for the training dataset. It can also be a dictionary that maps strings to iterators. If this is just an iterator, then the iterator is registered by the name 'main'. but actually in the chainer's code, i hava found def update_core(self): batch = self._iterators['main'].next() it means that it only use the iterator dict by the name 'main'? A: Yes, as default StandardUpdater only uses 'main' iterator. I think the functionality of multiple iterator can be useful only when you are defining your own Updater class which is subclass of StandardUpdater. For example: import chainer from chainer import training class MyUpdater(training.updaters.StandardUpdater): # override `update_core` def update_core(self): # You can use several iterators here! batch0 = self.get_iterator('0').next() batch1 = self.get_iterator('1').next() # do what ever you want with `batch0` and `batch1` etc. ... ... train_iter0 = chainer.iterators.SerialIterator(train0, args.batchsize) train_iter1 = chainer.iterators.SerialIterator(train1, args.batchsize) # You can pass several iterators in dict format to your own Updater class. updater = MyUpdater( {'0': train_iter0, '1': train_iter1}, optimizer, device=args.gpu) Note that I have not tested that above code works or not. For other reference, DCGAN example code shows another example of overriding update_core to defining your own update scheme (but it is also not using multiple iterator). https://github.com/chainer/chainer/blob/master/examples/dcgan/updater.py#L30
{ "pile_set_name": "StackExchange" }
Q: Time Invariance of an integrator I have the following input output equation that I have been told is not time invariant; however, I am not sure why this is the case. $$y(t)=\int_{-5}^5x(\tau)\space{}d\tau$$ I am not sure how this would vary with time considering $t$ doesn't appear in the integral. Thanks. Edit: I was given the following explanation: $$x_a(t)=x(t-a)$$ $$y_a(t)=\int_{-5}^5x(\tau)\space{}d\tau=\int_{-5}^5x(\tau-a)\space{}d\tau$$ $$=\int_{-5-a}^{5-a}x(\tau)\space{}d\tau$$ $$y(t-a)=\int_{-5}^5x(\tau)\space{}d\tau \space{}\text{(Note: t is not a factor)}$$ $$y(t-a)\neq{}y_a(t)$$ So not time invariant Which I am having trouble understanding. A: This is a tricky question. The output of the integrator is indeed a constant value, independent of $t$. This, however, does not necessarily imply time invariance. Note that the output of the system is the integral of the input signal over the interval $[-5, 5]$. Let's denote the output of the system with input $x(t)$ as $y_0(t)=y_0, t\in\mathbb{R}$. Now, if the input is shifted by $a$ before application to the filter, the integration will still be performed over the interval $[-5, 5]$, however, on the shifted version, $x(t-a)$, of the original input. The output of the system will again be a constant value, say, $y_a(t)=y_a, t \in \mathbb{R}$, that is, in general, different from $y_0$. Therefore, it holds $y_a(t)=y_a\neq y_0 = y_0(t)=y_0(t-\alpha)$, which means that the time invariance property does not hold.
{ "pile_set_name": "StackExchange" }
Q: Do we need cache for an array? Since we're developing a web-based project using django. we cache the db operation to make a better performance. But I'm wondering whether we need cache the array. the code sample like this: ABigArray = { "1" : { "name" : "xx", "gender" "xxx", ... }, "2" : { ... }, ... } class Items: def __init__(self): self.data = ABigArray def get_item_by_id(self, id): item = cache.get("item" + str(id)) # get the cached item if possible if item: return item else: item = self.data.get(str(id)) cache.set("item" + str(id), item) return item So I'm wondering whether we really need such cache, since IMO the array( ABigArray ) will be loaded in memory when trying to get one item. So we don't need use cache in such condition, right? Or I'm wrong? Please correct me if I'm wrong. Thanks. A: You've cut out a bit too much information, but it looks like the "array" (actually a dictionary) is always the same - there's a single instance that is created when the module is first imported, and will be used by every Items object. So there's absolutely nothing to be gained by caching it - in fact you will lose by doing so, as you will introduce an unnecessary round trip to get the data from the cache.
{ "pile_set_name": "StackExchange" }
Q: read violation while accessing to a vector which is for an object this is a c++ question. I'm working on an OpenGL project. wrote a simple OBJ loader. I have a class called Mesh. By getting an object pointer called monkey Mesh* monkey; and calling function: load_obj("Monkey.obj", monkey); I want to read from file and put it in monkey vertices. but when running it gives me unhandled exception:read violation when want to pushback to vector at: mesh->vertices.push_back(v); I tested a local vector dummy but it successfully pushedback. I don't know why it can't push to the object pointers vector? here is the mesh header include[...] using namespace std; class Mesh { private: GLuint vbo_vertices, vbo_normals, ibo_elements; public: vector <glm::vec4> vertices; vector <glm::vec3> normals; vector <GLushort> elements; glm::mat4 object2world; Mesh() : vertices(1), normals(1), elements(3), object2world(glm::mat4(1)) {} ~Mesh(void){} ; void Mesh::draw(void) ; }; and this is the obj-loader.cpp relative part void load_obj(const char* filename, Mesh* mesh) { ifstream in(filename, ios::in); if (!in) { cerr << "Cannot open " << filename << endl; exit(1); } vector<int> nb_seen; vector<glm::vec4> dummy; string line; while (getline(in, line)) { if (line.substr(0,2) == "v ") { istringstream s(line.substr(2)); glm::vec4 v; s >> v.x; s >> v.y; s >> v.z; v.w = 1.0; dummy.push_back(v); mesh->vertices.push_back(v); } any help would be appreciated! your confused friend! A: From the code fragments you have posted, it appears that you haven't actually allocated the mesh object. Declaring the pointer like this: Mesh* monkey; doesn't initialise the pointer or allocate any memory, so its value is undefined. That's why the loading code is crashing. Because the mesh pointer is invalid, and pointing to some garbage memory. It should be something more like: Mesh* monkey = new Mesh(); Then at least you will have a valid pointer which you can then legitimately refer to in the loader code.
{ "pile_set_name": "StackExchange" }
Q: Imacro copy feature I need any other possible way for getting long description. Still i am using Clipboard text for getting my data because my description field is too long which can not be taken through column reference {{!Col1}. Is there any way to get text from any other source except csv and clipboard. Thanks in advance. FORM=ID:reply_mebc_form ATTR=ID:body-msgForm CONTENT={{!CLIPBOARD}} 'its copying text from clipboard A: Yes. There is an option to read the whole file. But for that you have to use javascript scripting and some additional features. If you don't know how to use JS then you can close this question.
{ "pile_set_name": "StackExchange" }
Q: Pygame window freezes when it opens I'm learning how to use pygame, and I'm just trying to open up a window for the game I'm creating. The program compiles fine, and I tried drawing a circle to see if that would change anything but in both scenarios I still just get a blank window that freezes. My computer has plenty of storage space and only 2 applications open, and yet this is the only application that is freezing. import pygame pygame.init() window = pygame.display.set_mode((500, 500)) I have to force quit Python because it stops responding. I have Python version 3.7.4 and Pygame version 1.9.6. Any advice? A: A minimal, typical PyGame application needs a game loop has to handle the events, by either pygame.event.pump() or pygame.event.get(). has to update the Surface whuch represents the display respectively window, by either pygame.display.flip() or pygame.display.update(). See also Python Pygame Introduction Simple example, which draws a red circle in the center of the window: import pygame pygame.init() window = pygame.display.set_mode((500, 500)) # main application loop run = True while run: # event loop for event in pygame.event.get(): if event.type == pygame.QUIT: run = False # clear the display window.fill(0) # draw the scene pygame.draw.circle(window, (255, 0, 0), (250, 250), 100) # update the display pygame.display.flip()
{ "pile_set_name": "StackExchange" }
Q: Can I hint the optimizer by giving the range of an integer? I am using an int type to store a value. By the semantics of the program, the value always varies in a very small range (0 - 36), and int (not a char) is used only because of the CPU efficiency. It seems like many special arithmetical optimizations can be performed on such a small range of integers. Many function calls on those integers might be optimized into a small set of "magical" operations, and some functions may even be optimized into table look-ups. So, is it possible to tell the compiler that this int is always in that small range, and is it possible for the compiler to do those optimizations? A: Yes, it is possible. For example, for gcc you can use __builtin_unreachable to tell the compiler about impossible conditions, like so: if (value < 0 || value > 36) __builtin_unreachable(); We can wrap the condition above in a macro: #define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0) And use it like so: assume(x >= 0 && x <= 10); As you can see, gcc performs optimizations based on this information: #define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0) int func(int x){ assume(x >=0 && x <= 10); if (x > 11){ return 2; } else{ return 17; } } Produces: func(int): mov eax, 17 ret One downside, however, that if your code ever breaks such assumptions, you get undefined behavior. It doesn't notify you when this happens, even in debug builds. To debug/test/catch bugs with assumptions more easily, you can use a hybrid assume/assert macro (credits to @David Z), like this one: #if defined(NDEBUG) #define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0) #else #include <cassert> #define assume(cond) assert(cond) #endif In debug builds (with NDEBUG not defined), it works like an ordinary assert, printing error message and abort'ing program, and in release builds it makes use of an assumption, producing optimized code. Note, however, that it is not a substitute for regular assert - cond remains in release builds, so you should not do something like assume(VeryExpensiveComputation()). A: There is standard support for this. What you should do is to include stdint.h (cstdint) and then use the type uint_fast8_t. This tells the compiler that you are only using numbers between 0 - 255, but that it is free to use a larger type if that gives faster code. Similarly, the compiler can assume that the variable will never have a value above 255 and then do optimizations accordingly. A: The current answer is good for the case when you know for sure what the range is, but if you still want correct behavior when the value is out of the expected range, then it won't work. For that case, I found this technique can work: if (x == c) // assume c is a constant { foo(x); } else { foo(x); } The idea is a code-data tradeoff: you're moving 1 bit of data (whether x == c) into control logic. This hints to the optimizer that x is in fact a known constant c, encouraging it to inline and optimize the first invocation of foo separately from the rest, possibly quite heavily. Make sure to actually factor the code into a single subroutine foo, though -- don't duplicate the code. Example: For this technique to work you need to be a little lucky -- there are cases where the compiler decides not to evaluate things statically, and they're kind of arbitrary. But when it works, it works well: #include <math.h> #include <stdio.h> unsigned foo(unsigned x) { return x * (x + 1); } unsigned bar(unsigned x) { return foo(x + 1) + foo(2 * x); } int main() { unsigned x; scanf("%u", &x); unsigned r; if (x == 1) { r = bar(bar(x)); } else if (x == 0) { r = bar(bar(x)); } else { r = bar(x + 1); } printf("%#x\n", r); } Just use -O3 and notice the pre-evaluated constants 0x20 and 0x30e in the assembler output.
{ "pile_set_name": "StackExchange" }
Q: GCP Instance startup script error Trying to add a startup script following the sample here: https://cloud.google.com/compute/docs/startupscript The instance is created with no problems but the script does not execute. Console shows the following output: Jul 28 15:54:39 testclient-pbx startup-script: INFO Starting startup scripts. Jul 28 15:54:39 testclient-pbx startup-script: INFO Found startup-script in metadata. Jul 28 15:54:39 hostname startup-script: INFO startup-script: /bin/bash: /startup-aVpN6i/tmpVVdFyB: /bin/bash^M: bad interpreter: No such file or directory Jul 28 15:54:39 hostname startup-script: INFO startup-script: Return code 126. Jul 28 15:54:39 hostname startup-script: INFO Finished running startup scripts. I'm actually trying to run more complex script but was receiving same error. Using debian-cloud/debian-9 image. A: I'm using VScode on Win platform and as you can see above the message hinted file was not found. I had to change CRLF in VScode to LF "Unix" style and script now runs correctly! In VScode just click the CRLF bottom right and change to LF.
{ "pile_set_name": "StackExchange" }
Q: append query in VBA (run-time error 3067) I'm pulling seven values from unbound text boxes on a form into variables. Five of the variables are string type, two are double. I'm then using sql to append the data to a table using a where statement and a global variable which contains a foreign key I used from another table, since I was unsure how to use openargs with browseto... Option Compare Database Private Sub Form_Load() Dim rowN, rowR, mat, crew, perCom As String Dim budEst, curBud As Double End Sub Private Sub btnCapSubmit_Click() rowN = Me.CAP_ROW_N rowR = Me.CAP_ROW_R mat = Me.CAP_MAT crew = Me.CAP_CREW perCom = Me.CAP_PER budEst = Me.CAP_BUD_EST curBud = Me.CAP_BUD_CUR Dim appendIt As String appendIt = "INSERT INTO CAPITAL " & _ "([CAPITAL].[CAP_ROW_N], CAPITAL.[CAP_ROW_R], [CAPITAL].[CAP_MAT], [CAPITAL].[CAP_CREW], [CAPITAL].[CAP_PER], [CAPITAL].[CAP_BUD_EST], [CAPITAL].[CAP_BUD_CUR]) " & _ "VALUES ('" & rowN & "','" & rowR & "','" & mat & "','" & crew & "','" & perCom & "','" & budEst & "','" & curBud & "') WHERE [PRO_ID] = '" & gblFind & "';" Debug.Print appendIt DoCmd.RunSQL appendIt DoCmd.BrowseTo acBrowseToForm, "frmSearchEdit", "NavForm.NavigationSubform", , , acFormEdit End Sub Access complains with error #3067, "Query input must contain at least one table or query." I have no idea what I'm doing. I tried using debug.print but didn't see anything right off the bat. Then again I've been working on this database all day, so I could be overlooking something really easy. P.S. I also tried replacing the variables with Me.CAP_ROW_N (textbox names), but no dice. A: It's unclear what you are trying to do here, but an INSERT INTO ... VALUES () statement does not take a WHERE clause. Error 3067 is "Query input must contain at least one table or query." You are likely seeing this error because you have included a WHERE clause but you are not selecting existing values from a table. Try this instead: appendIt = "INSERT INTO CAPITAL " & _ "([CAPITAL].[CAP_ROW_N], CAPITAL.[CAP_ROW_R], [CAPITAL].[CAP_MAT], [CAPITAL].[CAP_CREW], [CAPITAL].[CAP_PER], [CAPITAL].[CAP_BUD_EST], [CAPITAL].[CAP_BUD_CUR]) " & _ "VALUES ('" & rowN & "','" & rowR & "','" & mat & "','" & crew & "','" & perCom & "','" & budEst & "','" & curBud & "');" There are several other issues here as well. I will just list them and let you Google for more guidance: You should use the .Execute DAO method instead of DoCmd.RunSQL because it allows for better error handling, especially when used with the dbFailOnError option. You will eventually run into trouble using single-quotes on unescaped inputs. For example, WHERE LastName = 'O'Malley' You appear to be treating all seven values as text by wrapping them in quotes, even though you said two of your values were numeric (double). Numeric values do not get quotes. A: Do not qualify the field names with the table name in your field list. A WHERE clause doesn't belong in an INSERT ... VALUES statement; get rid of that. This is a smaller-scale example of the pattern I think you want: appendIt = "INSERT INTO CAPITAL " & _ "([CAP_ROW_N], [CAP_ROW_R]) " & _ "VALUES ('" & rowN & "','" & rowR & "');" However, I suggest you tackle this with a parameter query. appendIt = "INSERT INTO CAPITAL " & _ "(CAP_ROW_N, CAP_ROW_R) " & _ "VALUES (pCAP_ROW_N, pCAP_ROW_R);" Dim db As DAO.Database Dim qdf As DAO.QueryDef Set db = CurrentDb Set qdf = db.CreateQueryDef(vbNullString, appendIt) qdf.Parameters("pCAP_ROW_N") = Me.CAP_ROW_N.Value qdf.Parameters("pCAP_ROW_R") = Me.CAP_ROW_R.Value qdf.Execute dbFailOnError Note I used the text box values for the parameter values directly --- instead of declaring variables to hold the text box values. Also notice one of the benefits of parameter queries is you needn't bother with delimiters for the values: quotes for text; or # for dates.
{ "pile_set_name": "StackExchange" }
Q: Disk encryption vs encrypted file container Is there any difference between disk encryption and encrypted file container in terms of security? Which one is better? A: It depends on what you need to secure, and who should have access to it. In some circumstances, implementing both is reasonable. Full disk encryption (FDE) is generally more secure if only one method can be chosen. If the entire volume is encrypted, an attacker cannot modify files. Without FDE, they could install a rootkit or a keylogger to steal the password for your encrypted container. Along those lines, an attacker will have no access to forensic artifacts in the environment, including such useful resources as: the pagefile, recently-used files lists, Windows registry, user authentication data, full/partial copies of files in slack space, and public/shared folders. FDE has some limitations and operability concerns. Either the system must support automatic unlocking, or the users must have credentials which can unlock the boot volume. In addition, if the encryption header is corrupted, the entire volume will become inaccessible, and the computer will be unusable until it is reimaged. (Note that most FDE solutions store multiple copies of the header to reduce this risk.) An encrypted container may support multiple unique users who are capable of unlocking it, e.g., Bitlocker-protected VHDX files. Each user must be enrolled by providing a password, token, certificate, and/or PIN. Access can be revoked by removing their key protector on the fly, which offers greater convenience and flexibility. Note that some container formats use a single keyfile, and each user merely protects their copy of the keyfile---in these cases, the container would need to be re-keyed or recreated to revoke access. If this concerns only your own personal data, this might not matter to you. Both methods have several software options, and administrators can usually configure emergency recovery methods, as long as this is planned prior to encryption. Recovery agents are typically assigned smart cards, key fobs, or certificates which they can use to unlock managed devices. In an enterprise scenario, user enrollment and recovery planning are often as important as data protection. In both cases, encrypted data cannot be compressed or deduplicated. These space-saving technologies will not work once the data is encrypted. While you can compress/dedupe data before encryption, you will usually see a significant reduction in deduplication savings. Since containers only encrypt files chosen by the user, they are more efficient with regard to disk utilization in the enterprise. There is no technical limitation which prohibits you from using an encrypted container on an encrypted disk. In a high-security or high-stakes environment, using both types of encryption may be necessary.
{ "pile_set_name": "StackExchange" }
Q: move folder contents recursive into nested folder I don't expected that this will be a problem. Because I thought the coreutils support these things and then, that a dirty combination of cp ls and rm would be enough. However, this was not the case and I would be really much appreciated if you now explain me why my approuch is failing and further, how I should do this in a proper way. Code function CheckoutFolder { local dir=$1 mkdir "$dir/.CheckoutFolderTmp" ( cd "$dir" \ && cp -R $(ls -Q -A "$dir" --ignore=".CheckoutFolderTmp") "$dir/.CheckoutFolderTmp" \ && rm -Rf $(ls -Q -A "$dir" --ignore=".CheckoutFolderTmp") ) mv "$dir/.CheckoutFolderTmp" "$dir/src" mkdir -p "$dir/"{build,log} } Sample output ++ CheckoutFolder /home/tobias/Develop/src/thelegacy/RCMeta ++ local dir=/home/tobias/Develop/src/thelegacy/RCMeta ++ mkdir /home/tobias/Develop/src/thelegacy/RCMeta/.CheckoutFolderTmp ++ cd /home/tobias/Develop/src/thelegacy/RCMeta +++ ls -Q -A /home/tobias/Develop/src/thelegacy/RCMeta --ignore=.CheckoutFolderTmp ++ cp -R '"build"' '"buildmythli.sh"' '"CMakeLists.txt"' '".directory"' '".libbuildmythli.sh"' '"log"' '"RCMeta"' '"RCMetaTest"' '"src"' /home/tobias/Develop/src/thelegacy/RC cp: cannot stat `"build"': No such file or directory cp: cannot stat `"buildmythli.sh"': No such file or directory cp: cannot stat `"CMakeLists.txt"': No such file or directory cp: cannot stat `".directory"': No such file or directory cp: cannot stat `".libbuildmythli.sh"': No such file or directory cp: cannot stat `"log"': No such file or directory cp: cannot stat `"RCMeta"': No such file or directory cp: cannot stat `"RCMetaTest"': No such file or directory cp: cannot stat `"src"': No such file or directory ++ mv /home/tobias/Develop/src/thelegacy/RCMeta/.CheckoutFolderTmp /home/tobias/Develop/src/thelegacy/RCMeta/src ++ mkdir -p /home/tobias/Develop/src/thelegacy/RCMeta/build /home/tobias/Develop/src/thelegacy/RCMeta/log ++ return 0 Mythli A: As Les says, ls -Q is putting quotation-marks around the filenames, and those quotation-marks are getting passed in the arguments to cp and rm. (The use of quotation-marks to quote and delimit arguments is an aspect of the Bash command-line, when you actually type in a command; it doesn't work when you're passing the output of one command into another.) In general, parsing the output of ls is not generally a good idea. Here is an alternative approach: function CheckoutFolder() ( cd "$1" mkdir .CheckoutFolderTmp find -mindepth 1 -maxdepth 1 -not -name .CheckoutFolderTmp \ -exec mv {} .CheckoutFolderTmp/{} \; mv .CheckoutFolderTmp src mkdir build log ) (Note that I surrounded the function body with parentheses (...) rather than curly-brackets {...}. This causes the whole function to be run in a subshell.)
{ "pile_set_name": "StackExchange" }
Q: Finding closest larger resolution with nearest aspect ratio in an array of resolutions I have an array: $resolutions = array( '480x640', '480x800', '640x480', '640x960', '800x1280', '2048x1536' ); I want to retrieve closest larger value with the nearest aspect ratio (same orientation). So, in case of $needle = '768x1280' - 800x1280. And, in case of $needle = '320x240' - 640x480. While the closest here is 480x640 it shouldn't be matched, because its aspect ratio differs too much. So on, and so forth. Purpose: I have a set of images with resolutions as specified in $resolutions. Those images are going to be used for smartphone wallpapers. With JavaScript, I am sending over a request with screen.width and screen.height to determine $needle. On the server side, I am going to fetch the closest larger value of the given resolution, scale it down to fit the whole screen while preserving aspect ratio, and if something overlaps the dimensions, crop it to perfectly fit the screen. Problem: While everything is pretty simple with scaling and cropping, I cannot think of a way to find out the closest larger value, to load the reference image. Hints: In case it helps, $resolutions and $needle can be in a different format, ie.: array('width' => x, 'height' => y). Tries: I tried to experiment with levenshtein distance: http://codepad.viper-7.com/e8JGOw Apparently, it worked only for 768x1280 and resulted 800x1280. For 320x240 it resulted in 480x640 but that does not fit this time. A: Try this echo getClosestRes('500x960'); echo '<br /> try too large to match: '.getClosestRes('50000x960'); function getClosestRes($res){ $screens = array( 'landscape'=>array( '640x480', '1200x800' ), 'portrait'=>array( '480x640', '480x800', '640x960', '800x1280', '1536x2048' ) ); list($x,$y)=explode('x',$res); $use=($x>$y?'landscape':'portrait'); // if exact match exists return original if (array_search($res, $screens[$use])) return $res; foreach ($screens[$use] as $screen){ $s=explode('x',$screen); if ($s[0]>=$x && $s[1]>=$y) return $screen; } // just return largest if it gets this far. return $screen; // last one set to $screen is largest }
{ "pile_set_name": "StackExchange" }
Q: Express app.get not executing middleware function I have an app.get call in my express.js app like this: app.get('/blog', (query, res) => res.send('Hello Blog!')); What I'm expecting to happen is that, every time someone goes to example.com/blog, function query is run, followed by res, which is just "Hello Blog!". Further down the file, I have function query: function query(req, res, next) { console.log('test'); res.send('ploop!'); next(); } What I'm expecting here is to get something logged into my terminal window, followed by 'ploop!' getting logged to the window, and then next() should continue on with the original request. The /blog request goes through as expected, but console.log('test'); and res.send('ploop!); don't appear to execute. I realize console.log must not be the best way to troubleshoot/debug this situation in Node/Express. Ultimately, I'm trying to produce some kind of obvious output from function query that will let me know that it's working (or not working). A: Are you declaring app.use(query) after you initialize your express server?
{ "pile_set_name": "StackExchange" }
Q: Ancient Civilization in non-Egyption Africa? I am looking for ancient civilizations in central and south of Africa. Were there any ancient cities, such as Timbuktu, Benin, or Zimbabwe for which there are scientific tools or other artifacts giving evidence of early civilization? A: What's ancient for you? There are old paintings in South Africa The Kingdom of Kush isn't in central/south of Africa, so I think it does not count. There is Great Zimbabwe (11th century) The Mali Empire existed from 1230–c. 1600. This cultural heritage is actually a victim of war in Mali. Wikipedia list some more Pre-Colonial African States in the article History of Africa
{ "pile_set_name": "StackExchange" }
Q: How do I install a keyboard layout? I have a keyboard layout file that I want to install on 17.10, but I fail to make it work. How is it supposed to be done? So far I have tried Guessing how to do it based on existing files in /usr/share/X11/xkb/symbols/ and the appearance of /usr/share/X11/xkb/rules/evdev.xml Guessing what a "variant" is, how to add it, what fields need to be updated, where the contents of this symbols file should be placed Guessing that placing it with a unique name directly in /symbols/ means I have to add it as a <layout> in evdev.xml. Still no idea whether that is true, nor which field -- if any -- is supposed to correspond to the file name Guessing that placing it inside an existing file in /symbols/ means I have to add it as a "variant". No idea whether that is true It would help if there was some way to avoid the guessing. I don't need a crash-course in the architecture, just a non-ambiguous way to make the keyboard layout 1. show up in the keyboard layout settings dialog, and 2. produce the correct input. So far the farthest I've come is #1 -- but don't ask me how, because I don't know which part did it. Update Exactly this has been done The contents of the symbols file that I linked to is in /usr/share/X11/xkb/symbols/svorak-a5 The following block has been inserted into /usr/share/X11/xkb/rules/evdev.xml right before the pre-existing element sequence <layout> <configItem> <name>se: <layout> <configItem> <name>svorak-a5</name> <shortDescription>sva5</shortDescription> <description>Svorak A5</description> <languageList> <iso639Id>swe</iso639Id> </languageList> </configItem> </layout> /var/lib/xkb contains no .xkms. A: First you should give the layout variant a name; see /usr/share/X11/xkb/symbols/se for examples. Then add it to /usr/share/X11/xkb/symbols/se and add a corresponding entry to /usr/share/X11/xkb/rules/evdev.xml. Edit: I tested the steps in the "update" section of your question, and it worked fine for me after having rebooted. The layout is shown in a submenu of Swedish (Sweden). For testing subsequent changes, rebooting isn't necessary, but this command should suffice: systemctl restart keyboard-setup Edit II: I have a theory (untested) on why the layout isn't working as robustly as you would wish. Try to change the two first lines in svorak-a5: partial alphanumeric_keys xkb_symbols "svorak" { to default partial alphanumeric_keys xkb_symbols "basic" {
{ "pile_set_name": "StackExchange" }
Q: Paypal API falls over when pointing to my certificate file I am trying to DoCapture some payments using the Paypal API and I am getting a Fatal Exception on the line of code where I set the CertificateFile property to the location of my certificate file. The relevant code is below: using com.paypal.sdk.profiles; using com.paypal.sdk.services; using com.paypal.sdk.util; IAPIProfile profile = ProfileFactory.createSignatureAPIProfile(); profile.CertificateFile = @"~\MyTestCertificate.txt"; Drilling down into the Exceptions details doesn't give me much more information, it more or less just confirms that a Fatal Exception has indeed been thrown. Leaving out the tilde and backslash like so throws the same error: profile.CertificateFile = @"MyTestCertificate.txt"; I thought that maybe I needed the contents of the file, instead of the location so I tried the following but got the same error: profile.CertificateFile = new StreamReader(@"MyTestCertificate.txt").ReadToEnd().ToString(); It seems that whatever you set the CertificateFile property to, you get a fatal exception. A couple of questions: Where can I find documentation on the IAPIProfile class in the Paypal API, in particular documentation for the CertificateFile property If I am not supposed to put the path to my certificate file in this location, what am I supposed to do? Just to confirm, MyTestCertificate.txt is added to my solution and Copy to Output Directory is set to Copy Always. The exception text is as follows: {"Exception of type 'com.paypal.sdk.exceptions.FatalException' was thrown."} The StackTrace looks like this: at com.paypal.sdk.profiles.SignatureAPIProfile.set_CertificateFile(String value) at MyProject_Payment_Processing.Paypal.DoCaptureCode(String authorization_id, String amount) in C:\Users\JMK\documents\visual studio 2010\Projects\MyProject Payment Processing\MyProject Payment Processing\Paypal.cs:line 16 at MyProject_Payment_Processing.Program.Main(String[] args) in C:\Users\JMK\documents\visual studio 2010\Projects\MyProject Payment Processing\MyProject Payment Processing\Program.cs:line 15 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() The Paypal API uses Log4Net which logs the error as so: 20 Jul 2012 12:39:11 FATAL [FatalException] com.paypal.sdk.exceptions.FatalException: Exception of type 'com.paypal.sdk.exceptions.FatalException' was thrown. Thanks A: It turns out aydiv was right, I had to use WinHttpCertCfg to register the certificate. Martin was also right in that I was using the signature profile, as opposed to the certificate profile. The first thing I had to do was use OpenSSL to encrypt my certificate, using the following command. I had to enter a password here, which I used later. This created an encrypted certificate file named paypal_cert.p12: openssl pkcs12 -export -in MyTestCertificate.txt -inkey MyTestCertificate.txt -out paypal_cert.p12 I then installed WinHttpCertCfg and used the following command to register my certificate, substituting PFXPassword for the password I entered earlier: winhttpcertcfg -i PFXFile -c LOCAL_MACHINE\My -a JMK -p PFXPassword Also, I was using the NVP DLL files before, I instead need to use the SOAP dll's from here. This meant that I had to replace NVPCallerServices in my code with Callerservices, along with a few other things. My final code for performing a Paypal DoCapture in C# .Net is below, hopefully this will help somebody who comes across this problem in the future! class Paypal { public string DoCaptureCode(string authorization_id, string amount) { CallerServices caller = new CallerServices(); IAPIProfile profile = ProfileFactory.createSSLAPIProfile(); profile.APIUsername = "JMK"; profile.APIPassword = "FooBar"; profile.CertificateFile = @"~\MyTestCertificate.txt"; profile.Environment = "sandbox"; caller.APIProfile = profile; DoCaptureRequestType pp_request = new DoCaptureRequestType(); pp_request.Version = "51.0"; pp_request.AuthorizationID = authorization_id; pp_request.Amount = new BasicAmountType(); pp_request.Amount.Value = amount; pp_request.Amount.currencyID = CurrencyCodeType.GBP; pp_request.CompleteType = CompleteCodeType.Complete; DoCaptureResponseType pp_response = new DoCaptureResponseType(); pp_response = (DoCaptureResponseType)caller.Call("DoCapture", pp_request); return pp_response.Ack.ToString(); } }
{ "pile_set_name": "StackExchange" }
Q: C# stackoverflow exception I had a stack overflow exception and i was able to use windbg to get a log of everything, however the log is very greek to me, and i'm not sure what i'm looking for. Any help is appreciated. FAULTING_IP: +1d42faf00b2df58 02dbb89f e9e3000000 jmp 02dbb987 EXCEPTION_RECORD: ffffffff -- (.exr 0xffffffffffffffff) ExceptionAddress: 791a2c0c (clr!EECodeManager::EnumGcRefs+0x0000001b) ExceptionCode: c00000fd (Stack overflow) ExceptionFlags: 00000000 NumberParameters: 2 Parameter[0]: 00000001 Parameter[1]: 02dd2edc PROCESS_NAME: crawler.exe ERROR_CODE: (NTSTATUS) 0xc00000fd - A new guard page for the stack cannot be created. EXCEPTION_CODE: (NTSTATUS) 0xc00000fd - A new guard page for the stack cannot be created. EXCEPTION_PARAMETER1: 00000001 EXCEPTION_PARAMETER2: 02dd2edc RECURRING_STACK: From frames 0x19 to 0x19 MOD_LIST: <ANALYSIS/> NTGLOBALFLAG: 0 APPLICATION_VERIFIER_FLAGS: 0 MANAGED_STACK: !dumpstack -EE No export dumpstack found ADDITIONAL_DEBUG_TEXT: Followup set based on attribute [Is_ChosenCrashFollowupThread] from Frame:[0] on thread:[PSEUDO_THREAD] LAST_CONTROL_TRANSFER: from 791a2fad to 791a2c0c FAULTING_THREAD: ffffffff DEFAULT_BUCKET_ID: NOSOS PRIMARY_PROBLEM_CLASS: NOSOS BUGCHECK_STR: APPLICATION_FAULT_NOSOS_STACK_OVERFLOW_STACKIMMUNE STACK_TEXT: 00000000 00000000 crawler.exe+0x0 SYMBOL_NAME: crawler.exe FOLLOWUP_NAME: MachineOwner MODULE_NAME: crawler IMAGE_NAME: crawler.exe DEBUG_FLR_IMAGE_TIMESTAMP: 4e5a416f STACK_COMMAND: ** Pseudo Context ** ; kb FAILURE_BUCKET_ID: NOSOS_c00000fd_crawler.exe!Unknown BUCKET_ID: APPLICATION_FAULT_NOSOS_STACK_OVERFLOW_STACKIMMUNE_crawler.exe FOLLOWUP_IP: *** WARNING: Unable to verify checksum for crawler.exe *** ERROR: Module load completed but symbols could not be loaded for crawler.exe crawler+0 00400000 4d dec ebp WATSON_STAGEONE_URL: http://watson.microsoft.com/StageOne/crawler_exe/1_0_0_0/4e5a416f/clr_dll/4_0_30319_1/4ba1d9ef/c00000fd/00062c0c.htm?Retriage=1 Followup: MachineOwner --------- 0:005> .exr 0xffffffffffffffff ExceptionAddress: 791a2c0c (clr!EECodeManager::EnumGcRefs+0x0000001b) ExceptionCode: c00000fd (Stack overflow) ExceptionFlags: 00000000 NumberParameters: 2 Parameter[0]: 00000001 Parameter[1]: 02dd2edc A: Load SOS (.loadby sos clr or .loadby sos mscorwks if you're not on .NET 4) and use the !pe command to display the exception. If you don't have the exception object, use !threads to list the threads and any exceptions they may have. A: Work out what the process was doing at the time, and look for either: Deliberately recursive methods which might have recursed beyond where they were meant to Accidentally recursive properties like this: private readonly string foo; public string Foo { get { return Foo; } } // Should have been return foo; Ideally, you should have unit tests which can help to pin this down - they're normally pretty good at finding such problems. The unit test running may still crash (StackOverflowException can't be caught) but it should help to isolate it. I would personally have a few goes at reproducing the problem in conventional ways before going for advanced debugging techniques.
{ "pile_set_name": "StackExchange" }
Q: Re-arrange columns after Unpivot ORACLE If i start off with: SELECT * FROM unpivot_test; ID CUSTOMER_ID PRODUCT_CODE_A PRODUCT_CODE_B PRODUCT_CODE_C PRODUCT_CODE_D ---------- ----------- -------------- -------------- -------------- -------------- 1 101 10 20 30 2 102 40 50 3 103 60 70 80 90 4 104 100 and when i Unpivot i get the values SELECT * FROM unpivot_test UNPIVOT (quantity FOR product_code IN (product_code_a AS 'A', product_code_b AS 'B', product_code_c AS 'C', product_code_d AS 'D')); ID CUSTOMER_ID P QUANTITY ---------- ----------- --- ---------- 1 101 A 10 1 101 B 20 1 101 C 30 2 102 A 40 2 102 C 50 3 103 A 60 3 103 B 70 3 103 C 80 3 103 D 90 4 104 A 100 What if i want to make it so that quantity column shows BEFORE the P column, how would i go about doing this, i basically want ID CUSTOMER_ID QUANTITY P ---------- ----------- ----------- ---------- 1 101 10 A 1 101 20 B ..... oracle version is 11g A: SELECT ID, CUSTOMER_ID, QUANTITY, P FROM (SELECT * FROM unpivot_test UNPIVOT (quantity FOR product_code IN (product_code_a AS 'A', product_code_b AS 'B', product_code_c AS 'C', product_code_d AS 'D')));
{ "pile_set_name": "StackExchange" }
Q: C# Socket BeginReceive / EndReceive capturing multiple messages Problem: When I do something like this: for (int i = 0; i < 100; i++) { SendMessage( sometSocket, i.ToString()); Thread.Sleep(250); // works with this, doesn't work without } With or without the sleep the server logs sending of separate messages. However without the sleep the client ends up receiving multiple messages in single OnDataReceived so the client will receive messages like: 0, 1, 2, 34, 5, 678, 9 .... Server sending Code: private void SendMessage(Socket socket, string message) { logger.Info("SendMessage: Preparing to send message:" + message); byte[] byteData = Encoding.ASCII.GetBytes(message); if (socket == null) return; if (!socket.Connected) return; logger.Info("SendMessage: Sending message to non " + "null and connected socket with ip:" + socket.RemoteEndPoint); // Record this message so unit testing can very this works. socket.Send(byteData); } Client receiving code: private void OnDataReceived(IAsyncResult asyn) { logger.Info("OnDataReceived: Data received."); try { SocketPacket theSockId = (SocketPacket)asyn.AsyncState; int iRx = theSockId.Socket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(theSockId.DataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); logger.Info("OnDataReceived: Received message:" + szData); InvokeMessageReceived(new SocketMessageEventArgs(szData)); WaitForData(); // ..... Socket Packet: public class SocketPacket { private Socket _socket; private readonly int _clientNumber; private byte[] _dataBuffer = new byte[1024]; .... My hunch is it's something to do with the buffer size or its just the between the OnDataReceived and EndReceive we're getting multiple messages. Update: It turns out when I put a Thread.Sleep at the start of OnDataReceived it gets every message. Is the only solution to this wrapping my message in a prefix of length and an string to signify the end? A: This is expected behaviour. A TCP socket represents a linear stream of bytes, not a sequence of well-delimited “packets”. You must not assume that the data you receive is chunked the same way it was when it was sent. Notice that this has two consequences: Two messages may get merged into a single callback call. (You noticed this one.) A single message may get split up (at any point) into two separate callback calls. Your code must be written to handle both of these cases, otherwise it has a bug.
{ "pile_set_name": "StackExchange" }
Q: Select only specific fields with Linq (EF core) I have a DbContext where I would like to run a query to return only specific columns, to avoid fetching all the data. The problem is that I would like to specify the column names with a set of strings, and I would like to obtain an IQueryable of the original type, i.e. without constructing an anonymous type. Here is an example: // Install-Package Microsoft.AspNetCore.All // Install-Package Microsoft.EntityFrameworkCore using Microsoft.EntityFrameworkCore; using System; using System.Linq; public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public class TestContext : DbContext { public virtual DbSet<Person> Persons { get; set; } public TestContext(DbContextOptions<TestContext> options) : base(options) { } } class Program { static void Main(string[] args) { var builder = new DbContextOptionsBuilder<TestContext>(); builder.UseInMemoryDatabase(Guid.NewGuid().ToString()); var context = new TestContext(builder.Options); context.Persons.Add(new Person { FirstName = "John", LastName = "Doe" }); context.SaveChanges(); // How can I express this selecting columns with a set of strings? IQueryable<Person> query = from p in context.Persons select new Person { FirstName = p.FirstName }; } } I would like to have something like this method: static IQueryable<Person> GetPersons(TestContext context, params string[] fieldsToSelect) { // ... } Is there a way I can do this? A: Since you are projecting (selecting) the members of the type T to the same type T, the required Expression<Func<T, T>> can relatively easy be created with Expression class methods like this: public static partial class QueryableExtensions { public static IQueryable<T> SelectMembers<T>(this IQueryable<T> source, params string[] memberNames) { var parameter = Expression.Parameter(typeof(T), "e"); var bindings = memberNames .Select(name => Expression.PropertyOrField(parameter, name)) .Select(member => Expression.Bind(member.Member, member)); var body = Expression.MemberInit(Expression.New(typeof(T)), bindings); var selector = Expression.Lambda<Func<T, T>>(body, parameter); return source.Select(selector); } } Expression.MemberInit is the expression equivalent of the new T { Member1 = x.Member1, Member2 = x.Member2, ... } C# construct. The sample usage would be: return context.Set<Person>().SelectMembers(fieldsToSelect);
{ "pile_set_name": "StackExchange" }
Q: Best way to import version-specific python modules Which method makes the most sense for importing a module in python that is version specific? My use case is that I'm writing code that will be deployed into a python 2.3 environment and in a few months be upgraded to python 2.5. This: if sys.version_info[:2] >= (2, 5): from string import Template else: from our.compat.string import Template or this try: from string import Template except ImportError: from our.compat.string import Template I know that either case is equally correct and works correctly but which one is preferable? A: Always the second way - you never know what different Python installations will have installed. Template is a specific case where it matters less, but when you test for the capability instead of the versioning you're always more robust. That's how I make Testoob support Python 2.2 - 2.6: I try to import a module in different ways until it works. It's also relevant to 3rd-party libraries. Here's an extreme case - supporting different options for ElementTree to appear: try: import elementtree.ElementTree as ET except ImportError: try: import cElementTree as ET except ImportError: try: import lxml.etree as ET except ImportError: import xml.etree.ElementTree as ET # Python 2.5 and up
{ "pile_set_name": "StackExchange" }
Q: Visual Studio doesn't show full array when when dynamically creating array of pointers My code: #include "pch.h" #include <iostream> using namespace std; int main() { char** pptr = new char*[5]; for (int i = 0; i < 5; i++) pptr[i] = new char[5]; } What I want to happen is that pptr now points to the beginning of an array of 5 pointers that each point to the beginning of an array of 5 characters. I put a breakpoint at the end of the main function and added pptr to watch, and it only stores one pointer. Why does this happen and how do I do it correctly? A: This is the default knowledge of your pointer type in Visual Studio. You indicate in the code that char** pptr is a pointer, but it cannot know how big. To fix this, you can add a watch on pptr[0], and then you can specify that it has a "size" of 5 by changing it to pptr[0],5. Also, if the size is variable you can do "ptr[0],[size]" where size is an expression that evaluates to the number of elements to show.
{ "pile_set_name": "StackExchange" }
Q: Get security error when saving canvas object into an image Well not exactly. If I just draw (ex lines,rect...) and try to export the canvas as an image. It works fine. If I however use the canvas.drawImage(...) function which places an image on the canvas. Then try to export it as an image, I get the following security error: [16:05:05.326] uncaught exception: [Exception... "Security error" code: "1000" nsresult: "0x805303e8 (NS_ERROR_DOM_SECURITY_ERR)" location: "http://127.0.0.1:8020/Blackboard/Models/BlackboardCanvas.js Line: 82"] I was assuming that the canvas.drawImage would take the raw pixel from the image and paste it onto the canvas, but I guess I was wrong. What can I do? A: The behavior you describe is per the specification. Excerpted: All canvas elements must start with their origin-clean set to true. The flag must be set to false if any of the following actions occur: The element's 2D context's drawImage() method is called with an HTMLImageElement or an HTMLVideoElement whose origin is not the same as that of the Document object that owns the canvas element. [...] Whenever the toDataURL() method of a canvas element whose origin-clean flag is set to false is called, the method must throw a SecurityError exception. The only way to circumvent this is to use a server-side technology to fetch the remote image for you and re-serve it from your same domain.
{ "pile_set_name": "StackExchange" }
Q: Breaking down an audio player into an MVC structure Imagine an audio player that does 3 main things: Manipulates and creates data (progress length, time conversion, volume calculation etc) Listens to user interactions / inputs and triggers manipulation of data or visibility of gui components Displays and updates gui components on screen. Where in the MVC would you put which of the above? I was thinking: - First is part of the model - Second the controller - Third the view However, im not entirely sure which is why im asking. A: Data manipulation and creation should be handled by the model. The view would be the actual GUI, with all the controls such as play/pause/volume etc. Each control would have events associated with it, such as play_click, pause_click, volume_up etc. The presenter would have event handlers for these view events. Whenever an event occurs, the associated handler would execute, causing changes in the model and/or view as required. For example, if the model contains a volume property, and the view raises a volume_up event, the onVolume_up event handler in the presenter will execute, causing the volume property of the model to increment, and also update the view accordingly. Note that the presenter does not depend on the view. So tomorrow you can change your entire GUI, and you wouldn't have to touch the presenter or the model. You can set up all of this manually yourself, or use a framework like Knockoutjs.
{ "pile_set_name": "StackExchange" }
Q: IEEE tran one column, two column elements in the same page possible? I'm using IEEEtran.cls for a journal paper and I'm unable to make a one column abstract using the inbuilt commands in IEEEtran: \onecolumn, \twocolumn. Switching between the two flushes the page and starts a new one. \nopagebreak doesn't work. Tried putting samepage tags. Didn't help either. I'm compiling using Xelatex. Any way to make one column and two column in the same page? A: A minimal working example: \documentclass{IEEEtran} \usepackage{microtype} \usepackage{lipsum} \title{The title} \author{You} \begin{document} \twocolumn[ \begin{@twocolumnfalse} \maketitle \end{@twocolumnfalse} \begin{abstract} ~{\lipsum[1]\lipsum[1]} \end{abstract} \bigskip] \section{Introduction} \lipsum[1-7] \end{document} Note: For some reason \lipsum[1] inside the abstract environment must be enclosed with brackets and must be at least one character before (it can be be ~, but no a normal space), but nothing of this is needed for real text.
{ "pile_set_name": "StackExchange" }
Q: Suppose that for all $t <1$ there are points $x_t$ and $y_t$ such that $d(x_t,y_t) = t$. Let $(X,d)$ be a compact metric space. Suppose that for all $t <1$ there are points $x_t$ and $y_t$ such that $d(x_t,y_t) = t$. Prove that there exists points $x$ and $y$ such that $d(x,y) = 1$. I have attempted to use the fact that since $A= \{(x_t,y_t) : d(xt,yt)=t\}$ is infinite then $A$ has a limit point since $X$ is compact and then the limit point would be this set $\{(x,y) : d(x,y) =1\}$... but i dont even know if im looking at this in the right way. A: Hint: Why does the function $X\times X\to \mathbb R$, $(x,y)\mapsto \left|1-d(x,y)\right|$ assume its minimum?
{ "pile_set_name": "StackExchange" }
Q: How to create a new array position an element at first position based on a condition? I have an array called data, I need to create a new array, where element matching variable toBeFirst is the first one. Please note I cannot touch the original array data const toBeFirst = 'b' const data = [{name: 'a'},{name: 'b'},{name: 'e'}, {name: 'x'}] // final result const data = [{name: 'b'},{name: 'a'},{name: 'e'}, {name: 'x'} any idea how to do it using latest js? can be done using reduce? A: Just append the elements, and prepend if its that special element: const result = data.reduce((arr, el) => el.name === toBeFirst ? [el].concat(arr) : arr.concat([el]), []); But mutating the array is probably eaiser: data.unshift(data.splice(data.findIndex(el => el.name === toBeFirst), 1)[0]);
{ "pile_set_name": "StackExchange" }
Q: MySQL REPLACE statement incorrect? "A new statement was found, but no delimiter" I'm trying to replace substrings in the fields of a table, but phpMyAdmin says "A new statement was found, but no delimiter between it and the previous one' (near REPLACE)" I've digged through the documentation, but found no hint on what I could do. Also, a web search doesn't yield helpful results... My statement: update phpbb_users SET user_avatar = REPLACE(user_avatar, 'http://', '//') WHERE user_avatar LIKE ('http://%'); I get a similar error message when trying it with update phpbb_posts SET post_text = REPLACE(post_text, 'http&#58;//', '//') WHERE post_text LIKE ('http&#58;//'); A: This appears to have been a bug with that (outdated) phpMyAdmin version; it's fixed at least in the current 4.5.5.1, possibly earlier but I didn't test extensively to find when exactly.
{ "pile_set_name": "StackExchange" }
Q: Is there a published campaign where a missing artifact or a relic is creating trouble by its absence? I already wrote months ago a question about linking Lost Mine of Phandelver to another published module. By then, I hadn't yet bought the starter set and hadn't even GM'd. I now have GM'd through the first chapter of the starter set campaign, and I really love it. I'm now sure that I'd like to buy other modules to follow on after LMOP. In the previously linked question, Storm King's Thunder was the most cited module, and it seems pretty interesting. It was the first module I was thinking about to buy after the starter set campaign is over. But now that I have started to play with some friends, one came with an interesting background : His character is a monk (a woman, can't find the word for it) that before joining the group for their quest in LMOP, was guarding a temple where a powerful artifact lied, the kind that could create war over it. His character can't speak about this artifact, as it could create trouble. I really like this background (found on aidedd.fr, a french site with a lot of translated data from the basic rules), and I'd like to use it as a plot hook for a module to string after LMOP. So, I was wondering if there is a published module where there's a missing artifact/relic which is creating trouble by its absence. The artifact doesn't need to be found by characters at the beginning of the module, it can even be held by the BBG. I would handwave something to link it, like if the BBG have to get it, then he may steal it in the temple or something alike. I'd like only published modules. If there's a module with a missing, important item, even if it's less powerful than an artifact, it's worth mentioning it too. A: There are several...though they are not 'Artifacts' in the sense of being an Artifact-tier magic item, but they are unique items of significant power and importance that are causing problems and the fact that the 'wrong people' have them is central to the story, and having them be an item that used to be secured and has now been stolen is a pretty easy adjustment to make. As requested in a comment, I'm also including the locations where these campaigns take place. Naturally, spoilers abound. Proceed with caution. Tyranny of Dragons The Tyranny of Dragons modules (Hoard of the Dragon Queen and Rise of Tiamat) revolve around the use of 'Dragon Masks' that give their wearer influence over chromatic dragons, and someone seeking to unite all 5 of the masks to summon the evil dragon-god Tiamat into the world. The Monastery could have been guarding one of them. This campaign ranges all up and down the Sword Coast from Neverwinter to south of Baldur's Gate--it technically starts in Greenest, a town just south of Baldur's Gate, but relocating that town would not be too difficult. Waterdeep: Dragon Heist The Stone of Golorr is a magical item central to this adventure that is used to obscure secrets, and also contains knowledge of a vast array of things probably-better-left-unknown. It's also evil and sentient. It was acquired by Open Lord Dagult Neverember for his own purposes--but could easily have been held by the Monastery beforehand This campaign takes place entirely within the city of Waterdeep. Princes of the Apocalypse This adventure features 4 Magical Weapons of significant power and danger--each capable of creating Weapons of Mass Destruction when used in the right place and the right way, and each also usable as a key to free their respective Lord of Elemental Evil (note: any one of them being freed is a world-ending catastrophe). Note: these weapons are also corruptive in nature, drawing out negative qualities in those who wield them. Again, one or more of these weapons could easily have been held by the Monastery. This campaign is geographically the closest to the events of LMOP, taking place in the Dessarin Valley, which is just south of Triboar--only a few days' travel from Phandalin A: Yes, there is one in a published module In Tomb of Annihilation (ToA), there is The Ring of Winter That item is carried by an NPC and other NPC's are searching for it. (FWIW, I think it will dovetail into SKT nicely - but that's personal opinion). It has potential world-wide implication if certain parties get their hands on it. It is "missing" in the sense that two groups of NPCs want it, and another NPC (who is nearly impossible to find except by random encounter) has it in their possession. It is a very powerful item to the extent that in Adventurer's League, during public play, that item will be confiscated/removed from a player who ends up with it on their character sheet if they end up with it during play. We have a Q&A on that here. Caution: there are spoilers. The trouble with it being absent. For one thing, it is mentioned in the Storm King's Thunder adventure as being absent in the introduction. Its absence informs a piece of the back story for a key faction in the adventure: the Frost Giants. In the introduction, the motivations for the Frost Giant Jarl (king) is shows that recovery of the Ring of Winter is one of his prime objectives. He wants that artifact to bring back a kind of Ice Age in the North. His problem is that the means he has used to track it down - using a drop of blood from the last person known to have it - has created a red herring. His agents are tracking down relatives of the person who has it, not the person themselves. In other words, based on the lore up to the time of SKT, the Jarl will never find it. ToA was published after the SKT adventure, which changes the lore(continuity) and thus the chances of the artifact being found, as well as the means by which it may be found. Our ToA group ran into a two powerful groups of NPCs (well, more powerful than our party by quite a bit as it turned out) who were looking for that item specifically. We had to use our wits to get out of those encounters without a TPK: the power imbalance was that bad. The trouble in a larger scale is that a group of dangerous and powerful NPCs is running amok in a part of the world that they don't normally visit. The mission that led to us encountering them was that their presence had severely disrupted trade on the eastern coast of Chult. (Among other things) I am leery of saying more given the spoilerish nature of the reveal.
{ "pile_set_name": "StackExchange" }
Q: Creating temporary JMS jms topic in Spring I'm trying to refactor some legacy code to use Spring to handle the jms connections to a mainframe service. I need to connect create a temporary topic for the mainframe service reply and set that as the message.setJMSReplyTo(replyTo); in the message before I send the message. Can anyone provide examples of this? I have not found anything in the documentation that allows you to get to the low level jms objects such as the session or TopicConnection in order to create a temporary topic. A: If you need low-level access to the JMS API using JmsTemplate, then you need to use one of JmsTemplate's execute(...) methods. The simplest of these is execute(SessionCallBack), where the SessionCallback provides you with the JMS Session object. With that, you can call createTemporaryQueue() or createTemporaryTopic(). You can probably use one of the other execute() methods do some of the initial work for you, though, such as this one.
{ "pile_set_name": "StackExchange" }
Q: How to get a vector of different vectors in C++ I'd like to have a C++ representation of a table like the following: 0 1 2 = = = 1 1.0 a 2 2.0 b 3 3.0 c The types of the columns have to be chosen from int, double or string at runtime. What is the best way to express it in C++? Addendum: my real problem: I want a columnar representation of a database table which can have arbitrary SQL types (I'll settle for int, double and string). A: edit: to create an object of dynamic type at runtime, google "factory pattern". You need the first vector to contain a consistent type, so you probably (in C++) want to have a base class and derive from it. I'm not sure if the std::vector class has an untyped base (it might). So, you either create a wrapper class around the concept of a vector (yuck), you create a vector of variant types (yuck), or you create a some kind of variant vector (yuck). I'd probably choose the latter because its the simplest method that still has type safe vectors within it. typedef union VectorOfThings { std::vector<int> i; std::vector<double> d; std::vector<string> s; }; struct TypedVectorOfThings { enum Type { ints, doubles, strings }; Type type; VectorOfThings myVector; }; std::vector<TypedVectorOfThings > myVectorOfVectors; and season to taste. But oh dear gods it's horrible. Is this a run time representation of a user defined database table or something?
{ "pile_set_name": "StackExchange" }
Q: how to parse column data to arrays? I have a file as follows: 1 99 2 33 3 90 4 25 5 89 I want to parse 1,2,3,4,5 into list x and 99, 33, 90, 25, 89 into list y, how can I do it? The part I dont' understand is that I just can readline but don't know how to parse in to two lists, I guess maybe there's a more elegant way to to it except spliting by space and add words[0] to x and word[1] to y A: with open('number-file') as f: x,y = zip(*(map(int, line.split()) for line in f)) will get you what you want. with open('number-file') as f: opens a file for reading (and closes it once the code is done). You can then simply iterate over it. (line.split() for line in f) is a generator expression that yields two strings for each line. For each line, map(int, line.split()) converts these strings into integers. The result until now looks like [[1, 99], [2, 33], [3, 90], [4, 25], [5, 89]] With zip, we can join the n-th elements of the sublists in the result lists x and y. Technically, x and y are tuples(immutable) instead of lists(can be extended and changed) now. In most cases, tuples should work as well, but if you really need lists, simply add x,y = list(x), list(y)
{ "pile_set_name": "StackExchange" }
Q: Python - Is sendto()'s return value useless? In my recent project, I need to use the UDP protocol to transmit data. If I send data by using size = s.sendto(data, (<addr>, <port>)), will the UDP protocol ensure that the data is packed into one UDP packet? If so, will size == len(data) always be True? Is there anything that I misunderstood? More precisely, will 'sendto()' split my data into several smaller chunks and then pack each chunk into UDP packet to transimit? A: Finally, I got the answer from "UNIX Network Programming", Chapter 2.11 Buffer Sizes and Limitations, Section UDP Output. This time, we show the socket send buffer as a dashed box because it doesn't really exist. A UDP socket has a send buffer size (which we can change with the SO_SNDBUF socket option, Section 7.5), but this is simply an upper limit on the maximum-sized UDP datagram that can be written to the socket. If an application writes a datagram larger than the socket send buffer size, EMSGSIZE is returned.
{ "pile_set_name": "StackExchange" }
Q: List option in the select tag from json file What I want to do is: As you can see from the ajaxTest.html, there is a <select id="sel1"> tag. I want the option value becomes Test1 Test2 Test3. which can be retrieved from the json file..how can I do that? ajaxTest.html <!DOCTYPE html> <html> <head> <script src="js/jquery-1.7.1.min.js"></script> <script src="js/jquery-ui.js"></script> </head> <body> <p>Username:</p> <div id="uname"></div> <p>Password:</p> <div id="pword"></div> <p>Account Information</p> <div id="accnum1"></div> <div id="regdate1"></div> <div id="lastUpd1"></div> <p>Select acc type:</p><select id="sel1"></select> <script> $.ajax({ type:"GET", datatype:"json", async:true, url:'ref/list.json', success:function(data){ alert("Welcome "+data.password+data.loginid); console.log(data.password); $('#uname').html(data.loginid); $('#pword').html(data.password); } }); $.ajax({ type:"GET", datatype:"json", async:true, url:'ref/accinfo.json', success:function(data){ console.log(data.accnum); $('#accnum1').html(data.accnum); $('#regdate1').html(data.regdate); $('#lastUpd1').html(data.lastUpd); } }); </script> </body> </html> list.json { "loginid":"nurwafiqa", "password":"welcome123", "acclist":[ { "acctype":"Test1", "name":"Wafiqa" }, { "acctype":"Test2", "name":"Wafiqa" }, { "acctype":"Test3", "name":"Wafiqa" } ] } A: //...your code success:function(data){ //loop thru the acclist array for (var i=0;i<data.acclist.length;i++) { //not sure what values you want in the option, here's a start var $option=$('<option />'); $option.attr('value',data.acclist[i].acctype); $option.text(data.acclist[i].acctype); $('#sel1').append($option); } }
{ "pile_set_name": "StackExchange" }
Q: Improper integral convergence example with absolute value $$ \int_{a}^{+\infty}|f(x)|dx < +\infty \Longrightarrow \int_{a}^{+\infty}f(x)dx \in \mathbb{R}$$ Show that the opposite ( $\Longleftarrow$ ) is not true. Is there a "simple" function as counter-example? I discovered $$f(x) = \frac{sin(x)}{x}$$ is a good example from 1 to $+\infty$, but how can I show it? I'm in a calculus course, and I don't know convergence/divergence theorems for integrals. I also thought about a piecewise function that should have a certain positive "area" and a certain negative "area", so that when you integrate it you have a convergent integral (positive "areas" cancel negative "areas") but you have a divergent integral using $|f(x)|$ A: Note that for any integer $N>1$ $$\begin{align} \int_1^{N\pi}\left|\frac{\sin(x)}{x}\right|\,dx&\ge \int_\pi^{N\pi}\left|\frac{\sin(x)}{x}\right|\,dx\\\\ &=\sum_{k=1}^{N-1} \int_{k\pi}^{(k+1)\pi}\left|\frac{\sin(x)}{x}\right|\,dx\\\\ &\ge \sum_{k=1}^{N-1} \frac{1}{(k+1)\pi}\int_{k\pi}^{(k+1)\pi}|\sin(x)|\,dx\\\\ &=\frac2\pi\sum_{k=2}^{N}\frac1k \end{align}$$ Inasmuch as the harmonic series diverges, we see that the integral of interest does likewise.
{ "pile_set_name": "StackExchange" }
Q: Installing VMWare ESXi 4 on a workstation computer gives vmfs3 failure I need to run VMWare ESXi on a normal PC for creating two virtual machines (one Linux and one Windows). I suposed that will be easy as install vmware-server on Linux or something but I've found that it isn't. When I boot the CD with the latest ISO avaible here I always get the same error: Vmkctl.HostCtlException: Unable to load module /usr/lib/vmware/vmkmod/vmfs3: Failure I have been looking for internet and some people said that it was a NIC problem so I figured out that was my motherboard Atheros 1Gbit problem and tried customizing the ESXi with http://www.vm-help.com/esx40i/customize_oem_tgz.php but... nothing. So I don't know what more to do. The specs of the computer are the next: ASUS P8H67-V B3 Revision Interl Core i7-2600, 3.40GHz 8GB DDR3 RAM (2x4 DIMM) 2 x 1TB HDD, with hardware RAID1 I've tried with RAID1 and SATA of and using as IDE and nothing. Thank you in advance! A: ESXi is indeed very different from VMWare Server and most importantly has an extremely limited hardware compatibility list - because it's designed for modern servers, not any old PC. Basically if your hardware's not down on the list, it's not going to work.
{ "pile_set_name": "StackExchange" }
Q: How to get Category Id of current product? I have get the current product category id on product details page. I have used some method like : $_product = Mage::getModel('catalog/product')->load(prodId); $ids = $_product->getCategoryId(); $cat = Mage::getModel('catalog/product')->setId($ids); but its not work as i want. $products = Mage::getResourceModel('reports/product_collection') ->addAttributeToSelect('*') ->setStoreId($storeId) ->addStoreFilter($storeId) ->addViewsCount() ->addCategoryFilter($cat) ->setPageSize($productCount); but its return some times this error Fatal error: Call to a member function getId() on a non-object in /var/www/html/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php on line 719 A: Because 1 product can stored in multi categories, so when call $categoryIds = $_product->getCategoryIds(); it will a array. foreach($categoryIds as $id) { $cat = Mage::getModel('catalog/category')->load($id); } A: You can use below code: $categoryIds = $_product->getCategoryIds(); if(count($categoryIds) ){ $firstCategoryId = $categoryIds[0]; $_category = Mage::getModel('catalog/category')->load($firstCategoryId); echo $_category->getName(); echo $_category->getId(); } A: Try this: //This will get the info of current product. $product = Mage::registry('current_product'); $prodID = $product->getId(); $_product = Mage::getModel('catalog/product')->load($prodID); $categoryIds = $_product->getCategoryIds(); foreach($categoryIds as $categoryIds1) { $_category = Mage::getModel('catalog/category')->load($categoryIds1); //get all category ID in the current product. echo $category_id = $_category->getId(); //get all the Category Name of the Current Product. echo $category_name = $_category->getName(); }
{ "pile_set_name": "StackExchange" }
Q: UITableViewCell With UIWebView Dynamic Height I have a table view with cells that have a webView in them, I want the height of the cell to match the height of the webView. This is the code I use: func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("newsCell") as! NewsTableViewCell cell.webView.loadHTMLString("test<br>test<br>test<br>test<br>test<br>test", baseURL: nil) cell.webView.delegate = self var webFrame = cell.webView.frame var cellFrame = cell.frame cell.frame = CGRectMake(cellFrame.origin.x, cellFrame.origin.y, cellFrame.width, webFrame.height + 20) cell.backgroundColor = UIColor.redColor() return cell } func webViewDidFinishLoad(webView: UIWebView) { println("finished loading") var frame = webView.frame frame.size.height = 1 webView.frame = frame var fittingSize = webView.sizeThatFits(CGSizeZero) frame.size = fittingSize webView.frame = frame var height: CGFloat = frame.height println(height) webView.frame = CGRectMake(frame.origin.x, frame.origin.x, frame.size.width, frame.size.height) newsTable.beginUpdates() newsTable.endUpdates() } And this is the result: https://postimg.cc/image/8qew1lqjj/ The webView is the correct height but the cell isn't, How can I fix this problem? A: TableView will resize cells itself, you just need implement tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat delegate method. Yes, you don't know the height of WebView initially, but you can calculate it and then ask TableView to reload cell. Something like this: class TableViewController: UITableViewController, UIWebViewDelegate { var content : [String] = ["test1<br>test1<br>test1<br>test1<br>test1<br>test1", "test22<br>test22<br>test22<br>test22<br>test22<br>test22"] var contentHeights : [CGFloat] = [0.0, 0.0] // ... override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("newsCell", forIndexPath: indexPath) as! NewsTableViewCell let htmlString = content[indexPath.row] let htmlHeight = contentHeights[indexPath.row] cell.webView.tag = indexPath.row cell.webView.delegate = self cell.webView.loadHTMLString(htmlString, baseURL: nil) cell.webView.frame = CGRectMake(0, 0, cell.frame.size.width, htmlHeight) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return contentHeights[indexPath.row] } func webViewDidFinishLoad(webView: UIWebView) { if (contentHeights[webView.tag] != 0.0) { // we already know height, no need to reload cell return } contentHeights[webView.tag] = webView.scrollView.contentSize.height tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: webView.tag, inSection: 0)], withRowAnimation: .Automatic) } // ... } A: Swift 4 ifau's Answer modified for Swift 4, using UITableView instead of UITableViewController. In storyboard, take a UITableView. Add 1 prototype cell to it. Keep the reuseIdentifier of the cell to "cell". Drag a webView into the cell and set leading, trailing, top and bottom constraints to 0. Set the cell class to TableViewCell TableViewCell.swift Connect webView outlet to storyboard: import UIKit class TableViewCell: UITableViewCell { @IBOutlet weak var webView: UIWebView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } ViewController.swift Connect the tableView outlet to the storyboard: import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate { @IBOutlet weak var tableView: UITableView! var content : [String] = ["test1<br>test1<br>test1", "test22<br>test22<br>test22<br>test22<br>test22<br>test22"] var contentHeights : [CGFloat] = [0.0, 0.0] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.dataSource = self tableView.delegate = self } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return content.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let cell : TableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell let htmlString = content[indexPath.row] let htmlHeight = contentHeights[indexPath.row] cell.webView.tag = indexPath.row cell.webView.delegate = self cell.webView.loadHTMLString(htmlString, baseURL: nil) cell.webView.frame = CGRect(x: 0, y: 0, width: cell.frame.size.width, height: htmlHeight) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if contentHeights[indexPath.row] != 0 { return contentHeights[indexPath.row] } } public func webViewDidFinishLoad(_ webView: UIWebView){ if (contentHeights[webView.tag] != 0.0) { // we already know height, no need to reload cell return } contentHeights[webView.tag] = webView.scrollView.contentSize.height tableView.reloadRows(at: [IndexPath(row: webView.tag, section: 0)], with: .automatic) } } A: It's work for me, easy Way to load Html String on WebView with dynamic. First take textView in TableViewCell with scroll disable and then take WebView, Apply Zero constraint on all 4 Side with ContentView. Now give same height constraint to both textview and WebView.Now give same text to both view as shown below code. For Clean UI Hide textView From XIB or storyBoard. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "tableviewcell") as! tableviewcell let theString : String = "</p><img src='https://pbs.twimg.com/profile_images/655066410087940096/QSUlrrlm.png' width=100 height=100 /><h2>Subheader</h2>" let theAttributedString = try! NSAttributedString(data: theString.data(using: String.Encoding.utf8, allowLossyConversion: false)!,options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) cell.textview.attributedText = theAttributedString cell.webview.loadHTMLString(theString, baseURL: nil) return cell }
{ "pile_set_name": "StackExchange" }
Q: What is the Powershell equivalent for bash $*? In other words how can I get the command line of the script itself? So, I know about $PSBoundParameters, but it is not the same. I just want to get the string containing the passed in parameters as is. How do I do it? A: $MyInvocation.Line Read about_Automatic_Variables: $MyInvocation Contains an information about the current command, such as the name, parameters, parameter values, and information about how the command was started, called, or "invoked," such as the name of the script that called the current command. $MyInvocation is populated only for scripts, function, and script blocks.
{ "pile_set_name": "StackExchange" }
Q: No more than one module in position I was just wondering if there was some PHP that I could add to my template index.php that would ensure only one module is loaded in a particular position. I know there are other options available such as Advanced Module Manager but for this particular site it would be great if I could add some php directly to the page. Basically if there are 2 modules being loaded into one position then I just want the first module to load. Thanks. A: I have to agree with Lodder's comment... This is not making a real sense and it probably will create confusion. But for the sake of answering to your question and to help you find a way to achieve something like this, you could try the approach below: <?php jimport( 'joomla.application.module.helper' ); $modules = JModuleHelper::getModules( 'yourposition' ); $attribs = array('style' => 'xhtml'); echo JModuleHelper::renderModule($modules[0], $attribs); ?> The getModules($position) function will load an array with all the modules in your position, ordered by module id. Then, with the renderModule($module,$attributes) function, you output the module. But since you have an array, you need to tell which module you will render, by specifying the index of the array's element. But because there will still be a dynamic way of creating/editing/changing modules settings, I am not that sure how you could ensure what module will be rendered at the end, in the case that other users will be managing the website. So, if you would explain a little bit more what are you trying to achieve and why, we could propose you the right solution.
{ "pile_set_name": "StackExchange" }
Q: checking database and validate form with angular I can use ajax to check infomation in database with jquery but I dont know do same with angularjs . I use $http({ type : "post", dataType : "JSON", url : "register.php", data : data, success : function(result) { .... } php code $errors = array( 'error' => 0 ); $username = $_POST['username'] $password = $_POST['password'] $email =$_POST['email'] $fullname = $_POST['fullname'] $sql = "SELECT * " . "FROM USERS " . "WHERE username='".$username."' " . "OR email='".$email."'"; if (mysqli_num_rows($result) > 0) { $row = mysqli_fetch_assoc($result); if ($row['username'] == $username){ $errors['username'] = 'Tên đăng nhập đã tồn tại'; } if ($row['email'] == $email){ $errors['email'] = 'Email đã tồn tại'; } } if (count($errors) > 1){ $errors['error'] = 1; die (json_encode($errors)); }else{ //insert database } $result = mysqli_query($conn, $sql); but I dont know do next step . I want check in database if have user name show message error else show succes .Pls help me A: Using success is deprecated but you're on the right path. Here's how you would do it now: $http({ type : "post", url : "register.php", data : data }).then(function(response){ // If data is returned, do stuff with it here console.log('Yay, my data was POSTed', response.data); }, function(response){ console.log('Aww, it failed.'); }); It would be easier to help you further, if you add a bit more information on what you're actually trying to achieve. For instance what is returned by this "register.php" endpoint, and what you intent to do after this.
{ "pile_set_name": "StackExchange" }
Q: Adding a boolean type field to a table using SQL I'm trying to add a boolean field to a table using SQL however I'm not getting anywhere. The query I am using to try and add the field is: ALTER TABLE TEST ADD "NewField" BOOLEAN When running this it will display the error Invalid use of keyword. I'm trying to add this field to a paradox database. Any help would be appreciated. A: There is no Boolean in SQL - use a bit column instead.
{ "pile_set_name": "StackExchange" }
Q: Rails 4 raises ArgumentError (wrong number of arguments (2 for 1)): when updating through AJAX POST I want to update the status of the notifications to read whenever I want the user clicks on the notification dropdown of the app. Here is the controller code: class Api::V1::NotificationsController < ApiController before_action :authenticate_user! def index @notifications = Notification.where(user_id: current_user.id).order(created_at: :desc) render_success @notifications end def create Notification.update_all({status: "read"}, {user_id: current_user.id}) end end and the jQuery code that should trigger the create method for the controller: $('.notifications-menu').on('shown.bs.dropdown', function () { console.log('Opened notifications'); $.post('/api/v1/notifications'); }) Unfortunately, it returns this error: Started POST "/api/v1/notifications" for ::1 at 2017-09-19 16:27:53 +0800 Processing by Api::V1::NotificationsController#create as */* User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 13]] Completed 500 Internal Server Error in 6ms (ActiveRecord: 0.6ms) ArgumentError (wrong number of arguments (2 for 1)): app/controllers/api/v1/notifications_controller.rb:11:in `create' A: Change your create method to this: def create Notification.update_all(status: "read", user_id: current_user.id) end
{ "pile_set_name": "StackExchange" }
Q: Need help creating a working HTML form that calculates ROI I'm trying to create an HTML form that has the user type in expected gain and cost into the input box, click calculate, and the form should calculate and display the net profit and ROI. So far the form lets me input expected gain and cost, but the calculate button doesn't display the net profit and ROI in the appropriate boxes. This is what I have so far (only relevant portions included): // Declare variables var projectName; // Gets user input for project name var expectedCost; // Gets user input for cost of project var expectedGain; // Gets user input for expected gain var netProfit; var returnOnInvestment; function calcNetProfit() { netProfit = expectedGain - expectedCost; // Calculate net profit } function calcReturnOnInvestment() { returnOnInvestment = netProfit / expectedCost * 100; // Calculate Return on Investment } <form> <label>Project Name</label> <input> <br><br> <label>Cost</label> <input> <br><br> <label>Gain</label> <input> <br><br> <label>Net Profit</label> <input> <br><br> <label>ROI as percentage</label> <input> <br><br> <input type="button" name="calculate" value="Calculate" onclick="calcNetProfit(); calcReturnOnInvestment();"/><br /> </form> A: You are missing the steps on how to get the values for the gain, costs, and net profit. Read on JavaScript DOM. Here's the answer in a nutshell. function calcNetProfit() { var expectedGain = document.getElementById('gain').value; var expectedCost = document.getElementById('cost').value; var netProfit = expectedGain - expectedCost; document.getElementById('netprofit').value = netProfit; return netProfit; } function calcReturnOnInvestment() { var expectedCost = document.getElementById('cost').value; var netProfit = calcNetProfit(); var roi = netProfit / expectedCost * 100; // Calculate Return on Investment document.getElementById('roi').value = roi; } <html> <form> <label>Project Name</label> <input> <br><br> <label>Cost</label> <input id="cost"> <br><br> <label>Gain</label> <input id="gain"> <br><br> <label>Net Profit</label> <input id="netprofit"> <br><br> <label>ROI as percentage</label> <input id="roi"> <br><br> <input type="button" name="calculate" value="Calculate" onclick="calcNetProfit(); calcReturnOnInvestment();" /><br /> </form> </html>
{ "pile_set_name": "StackExchange" }
Q: -bash: firebase: command not found I need to host website to google firebase hosting. I looked almost everywhere but steel have the problem. I have installed npm install --global firebase also npm install -g firebase-tools but when I want to use firebase command it says : "command not found" firebase-tools "-bash: firebase: command not found" Firebase Hosting set up issue https://github.com/firebase/firebase-tools/issues/46 this posts didn't helped this is after sudo npm install --global firebase-tools A: alias firebase="`npm config get prefix`/bin/firebase"
{ "pile_set_name": "StackExchange" }
Q: How to maintain data binding between multiple Frames and multiple corresponding objects? I'm working on a UWP application that is essentially a control panel for several of the same objects - let's call them Plate objects. Functionally, a user needs to be able to create & remove Plate objects with specific properties, and all of the currently available Plate objects are shown on the Main Page, with their corresponding unique properties as well as controls to modify them. They way I've implemented this is to create a Grid on the Main Page, and for each available Plate, add a Frame into a grid column, and each Frame navigates to a custom PlateView page to show what's basically a horizontal list of PlateView columns. My problem is that I want to be able to two-way bind data for each control/property from each Plate to its corresponding PlateView. Right now I store the List of all Plates as a public variable in App.cs, as I need to be able to get and modify this master list from multiple parts of the application through its complete lifecycle. The way I understood the data binding description in the UWP documentation, either my Plate object can implement INotifyPropertyChanged or I can create a separate PlateViewModel class that implements it. With Plate implementing it, the PlateView will set its ViewModel to the correct index of Plate in the List (this.ViewModel = App.plateList[1]), but I assume that makes a copy...? So if I modify a variable in PlateView, it won't actually change the Plate object in App.cs. With a new PlateViewModel class, I don't understand how I wouldn't have the same problem, but inside the PlateViewModel class. For example, MS's documentation shows: public class RecordingViewModel { private Recording defaultRecording = new Recording(); public Recording DefaultRecording { get { return this.defaultRecording; } } } Even if I set an internal Plate object inside PlateViewModel, don't I have to call a variable from the XAML {x:bind ...} syntax? So I'd have to make a copy of every variable from the correct Plate into PlateViewModel, and they wouldn't necessarily link to the original Plate object in App.cs? Thanks! A: To simply answer your question without getting into a whole discussion about MVVM, having the additional ViewModel property to bind to does not create a new instance of the List. What I would do is create a View Model property that presents your model with a getter and setter (in this case the App.cs property is your model): ViewModel: public List<Plate> MyPlates { get { return ((App)Application.Current).MyGlobalListofPlates; } set { ((App)Application.Current).MyGlobalListofPlates = value; OnPropertyChanged("MyPlates"); } } That code makes it obvious that it's not a new object being made and it gives you some control over what changes to the data are allowed. Another option is to assign the property in the constructor. This does not create a new object either. It is a reference to the original and any changes you make to it will be reflected everywhere. public List<Plate> MyPlates { get; set; } public MyViewModel() //Constructor { MyPlates = ((App)Application.Current).MyGlobalListofPlates; } This second code block has problems because there's no INotify (which might not matter if it's 2-way binding? Not sure...). Anyway I'm just showing you that assigning the object to another object just creates a reference. You definitely want to read on up on value types versus reference types in C#. Almost any time you do "ThisObject = ThatObject" in C# you're just creating a pointer to the same object in memory.
{ "pile_set_name": "StackExchange" }
Q: generate file name list for a given folder There is a list of document saved in a folder, I need to save the file name along with its path in a plain text file, such as /document/file1.txt /document/file2.txt ... My question is how to iterate through a file folder and extract the path information for each file. Thanks. A: you can try something like this. import os output_file = open(filename, 'w') for root, dirs, files in os.walk(".", topdown=False): for name in files: f = print(os.path.join(root, name)) output_file.write(f) for name in dirs: print(os.path.join(root, name)) output_file.close() you can also use listdir() method file = open(filename, 'w') for f in os.listdir(dirName): f = os.path.join(dirName, f) file.write(f) file.close()
{ "pile_set_name": "StackExchange" }
Q: Subsonic Renames a Table Named "Media" to "Medium" I have a table in my SQL2005 DB named MultiMedia - after DAL generation with SubSonic v2.2, the classes that are generated are named "MultiMedium". The table was originally named Media and this resulted in classes named Medium as well - easy enough to change the name of my table at this point in the project, but wondering if anyone else has run into this and from the team's perspective, is this a known issue? What other naming problems might I run into as changing table names will not remain inconsequential for long. Thanks! A: I get one of these about once every 6 months :) - they're hysterical :). Yes - we do change Octopus to Octopi ... our inflector is pretty rad. Anyway - you can set fixPluralClassNames to false on your provider - it will change this: https://web.archive.org/web/20090524072848/http://subsonicproject.com/configuration/config-options/
{ "pile_set_name": "StackExchange" }
Q: How to convert ascii number to uint64 in C? I'm using Mini Ini to read data from .ini files on an embedded system. It supports reading in long integers or strings. Some of the numbers I have are too large to fit in a long, so I am reading them in as a string. However, I need to then convert them to a uint64_t. I attempted to convert it to a float using atof and casting that to a uint64_t, which crashed and burned, presumably because casting changes how the program views the bits without changing the bits themselves. char string_in[100]; //ret = ini_gets(section,key,"default_value",string_in,100,inifile); //To simplify, use string_in = "5100200300"; uint64_t value = (uint64_t)atof(string_in); I would appreciate help on how to convert a string to a uint64. EDIT: Conclusion The atoll function converts ascii to long long, which serves the purpose I needed. However, for the sake of completeness, I implemented the function provided in the accepted answer and that provided the exact answer to my question. A: You could write your own conversion function: uint64_t convert(const char *text) { uint64_t number=0; for(; *text; text++) { char digit=*text-'0'; number=(number*10)+digit; } return number; }
{ "pile_set_name": "StackExchange" }