text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Colour the padding of a View
Say i have View A, which covers the whole screen
I then do
a.setPadding(90, 0, 90, 0)
So its now 90px down and 90 left
How can i colour these 90 pixels, say, red?
If i use .setBackgroundColour(int colour) it will, obviously, colour the whole View
So what should i do?
If this isn't possible, is it possible to have a View which is just red, 90 pixels wide, and covers that padded area? But still allows touch events to go through to the padded area
I need to do all this programatically
A:
You can create a custom View that draws the color in the padding area. Here I am extending View, but you can extend something else if you desire.
package sample.package.name;
public class ColoredPaddingView extends View {
Rect rect = new Rect();
// Constructors omitted. Override them all and call the super constructor
@Override
public void onDraw(Canvas canvas) {
int l = getPaddingLeft();
int t = getPaddingTop();
int r = getWidth() - getPaddingRight();
int b = getHeight() - getPaddingBottom();
rect.set(l, t, r, b);
canvas.save();
canvas.clipRect(rect, Region.Op.DIFFERENCE);
canvas.drawColor(Color.RED); // or some other color
canvas.restore;
super.onDraw(canvas);
}
}
In your layout XML, you would use the fully qualified class name of the view (including the package) like so:
<sample.package.name.ColoredPaddingView
android:layout_width="..."
android:layout_height="..."
... />
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I precompile jade.php templates?
I've fallen in love with Jade, and can't bear to se any more, but now I have a WordPress theme to design..
So.. I use Codekit, and it handles jade just fine - can I somehow get it to use jade.php instead of the node module? (I couldn't find any packages which mentioned php when i searched npm find jade | grep php)
Could this be accomplished with a grunt watch task?
I'd prefer not to install jade.php in the theme and have it run there.
Also, I'm aware that I can escape the php..
#sidebar1.sidebar.fourcol.last.clearfix(role="complementary")
| <?php if ( is_active_sidebar( 'sidebar1' ) ) : ?>
| <?php dynamic_sidebar( 'sidebar1' ); ?>
| <?php else : ?>
// This content shows up if there are no widgets defined in the backend.
.alert.alert-help
p <?php _e( 'Please activate some Widgets.', 'bonestheme' ); ?>
| <?php endif; ?>
But I'd love to use jade conditionals.. is that greedy?
A:
https://github.com/ajschlosser/wordpress-jade-template is great for regular wordpress. I'm more of a bootstrap person so I prefer the Bootstrap verison at https://github.com/ajschlosser/wordpress-jade-bootstrap-template which also relies on Sass for some reason (even though Bootstrap is Less oriented) so I forked it and made it more Less biased. https://github.com/Xedecimal/wordpress-jade-bootstrap-template in case you don't want to do it yourself, pretty easy though.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Makefile Syntax unclear
This is my first Makefile, and I am can't figure out some of the syntax used. The questions are marked below.
$(BUILD_DIR)/%.o: %.c $(BUILD_DIR)
$(CC) -c $(CFLAGS) -Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@
What is the usage of "$(BUILD_DIR)" in the dependency?
What is the meaning of "$(BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@" in the role?
A:
As with most computer languages the syntax of make cannot be clear if you don't know it. If you are using GNU make the GNU make manual is your friend. In the following explanations I will assume that BUILD_DIR = build and that one of the source files is bar/foo.c.
$(BUILD_DIR) in the list of prerequisites (dependencies) tells make that the build directory (in which object files are supposed to go) must exist before the recipe is executed; logical. There must be another rule somewhere to create the directory if it does not exist yet. Something like:
$(BUILD_DIR):
mkdir -p $@
But unless you forgot to copy an important character, this dependency is terribly sub-optimal. As the last modification time of a directory changes each time its content changes (files or sub-directories added or removed), it will force the re-compilation of all source files every time the directory changes, which is not what you want. A better dependency would be order-only:
$(BUILD_DIR)/%.o: %.c | $(BUILD_DIR)
that tells make to consider only the existence of $(BUILD_DIR), not its last modification time, when deciding to re-build or not.
$(BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@ is just a combination of make automatic variables and functions.
$< and $@ expand as the first prerequisite (bar/foo.c) and the target (build/bar/foo.o) respectively.
$(<:.c=.lst) replaces .c by .lst in $<: bar/foo.lst.
$(notdir $(<:.c=.lst)) removes the directory part: foo.lst.
All in all, for a bar/foo.c source file, and with BUILD_DIR = build, the pattern rule would be equivalent to:
build/bar/foo.o: bar/foo.c | build
$(CC) -c $(CFLAGS) -Wa,-a,-ad,-alms=build/foo.lst bar/foo.c -o build/bar/foo.o
Note that there are two different situations to consider:
All your source files are in the same directory as the Makefile (no bar/foo.c, just foo.c). Then you can simplify your recipe:
$(CC) -c $(CFLAGS) -Wa,-a,-ad,-alms=$(BUILD_DIR)/$(<:.c=.lst) $< -o $@
because the $(notdir...) is useless.
Your source files can be in sub-directories (bar/foo.c). Then you need the $(notdir...) in your recipe. But be warned that if you have two source files with the same base name (bar/foo.c and baz/foo.c) you will have a name conflict for $(BUILD_DIR)/foo.lst and your Makefile will not work as expected. Moreover, the order-only prerequisite of the rule should be equivalent to build/bar (or build/baz), not just build. And there should be a rule to create it if needed. If it is your case I suggest to change your pattern rule for:
$(BUILD_DIR)/%.o: %.c
mkdir -p $(dir $@)
$(CC) -c $(CFLAGS) -Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@
There are other solutions (secondary expansion...) but there are a bit too complicated for this already too long answer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Failing to set up (my own) prebuilt Rails app on OSX
After completing the Rails Tutorial I wanted to extend it into a personal app so I created another directory and moved/copied all the files from tutorialFolder to appFolder.
However I'm encountering some problems when I try to setup the gems again.
bundle install returns:
An error occurred while installing pg (0.17.1), and Bundler cannot continue.
Make sure that `gem install pg -v '0.17.1'` succeeds before bundling.
So I try gem install pg -v '0.17.1 (or bundle update) and get:
You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.
Searching StackOverflow I discover Installing gem or updating RubyGems fails with permissions error
Which explains that /Library/Ruby/Gems/2.0.0
That is the version of Ruby installed by Apple, for their own use. While it's OK to make minor modifications to that if you know what you're doing, because you are not sure about the permissions problem, I'd say it's not a good idea to continue along that track.
To avoid the above I try brew install ruby succesfully but get stuck on bundle install
I can't retrace where, but I also attempted to remove the Gemfile.lock but that didn't do anything.
Additional info: ruby -v >>> ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin14]
rails -v >>> bin/spring:10:in 'read': No such file or directory - /Gemfile.lock (Errno::ENOENT)
bundle install --path vendor/bundle >>> An error occurred while installing pg (0.17.1), and Bundler cannot continue.
Thanks,
Edit* I tried starting from scratch with rails new app however got this:
Bundle complete! 12 Gemfile dependencies, 54 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.
run bundle exec spring binstub --all
/Library/Ruby/Gems/2.0.0/gems/bundler- 1.10.5/lib/bundler/spec_set.rb:92:in `block in materialize': Could not find i18n-0.7.0 in any of the sources (Bundler::GemNotFound)
from /Library/Ruby/Gems/2.0.0/gems/bundler- 1.10.5/lib/bundler/spec_set.rb:85:in `map!'
from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/spec_set.rb:85:in `materialize'
from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/definition.rb:140:in `specs'
from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/definition.rb:185:in `specs_for'
from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/definition.rb:174:in `requested_specs'
from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/environment.rb:18:in `requested_specs'
from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/runtime.rb:13:in `setup'
from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler.rb:127:in `setup'
from /Library/Ruby/Gems/2.0.0/gems/bundler-1.10.5/lib/bundler/setup.rb:18:in `<top (required)>'
from /usr/local/Cellar/ruby/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /usr/local/Cellar/ruby/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
The above block was fixed with rvm gemset empty and then I was able to setup a VANILLA rails app, still can't sync with end of tutorial
A:
From this section of the rails tutorial I had added the following code:
group :production do
gem 'pg', '0.17.1'
gem 'rails_12factor', '0.0.2'
end
Which is explained with
Note also the addition of the rails_12factor gem, which is used by Heroku to serve static assets such as images and stylesheets. The resulting Gemfile appears as in Listing 1.14.
To prepare the system for deployment to production, we run bundle
install with a special flag to prevent the local installation of any
production gems (which in this case consists of pg and
rails_12factor):
bundle install --without production
And everything works.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WP8 loading listbox locations on map
I'm new to wp8 application development I would like to know how to load the map locations with listbox places.. I have no idea on it so please help me to know how to do it.. thanks in advance..
I have a listbox with the places loaded with its latitude and longitude and a MAP button a side.. when I click the MAP button I should display the listbox places into the map.. so please anyone help me to do this...
This is a code to just add map to the page.. (code behind)
private void Map_Click(object sender, RoutedEventArgs e)
{
Map MyMap = new Map();
MyMap.Height = 392;
MyMap.Width = 412;
MyMap.Center = new System.Device.Location.GeoCoordinate(-25.235,133.611);
MyMap.ZoomLevel = 2;
MyMap.LandmarksEnabled = true;
MyMap.PedestrianFeaturesEnabled = true;
MyMap.ColorMode = MapColorMode.Dark;
srch.Children.Add(MyMap);
}
A:
Well I don't know how your listbox looks like so I just created a empty Pushpin for each location.
Following Method loops through every row in your ListBox and calls the method to draw the pushpin
private void ReadListBox()
{
foreach (var location in YourListBox)
{
DrawLocationToMap(new GeoCoordinate(latitudeInListBox, longitudeInListBox));
}
}
Following method creates the location pushpin and adds it to your map
private void DrawLocationToMap(GeoCoordinate currGeo)
{
Pushpin locationPushPin = new Pushpin();
locationPushPin.Background = new SolidColorBrush(Colors.Black);
MapOverlay locationPushPinOverlay = new MapOverlay();
locationPushPinOverlay.Content = locationPushPin;
locationPushPinOverlay.PositionOrigin = new Point(0.5, 0.5);
locationPushPinOverlay.GeoCoordinate = new GeoCoordinate(currGeo.Latitude, currGeo.Longitude);
MapLayer locationLayer = new MapLayer();
locationLayer.Add(locationPushPinOverlay);
MyMap.Layers.Add(locationLayer);
}
You'll need the WPToolkit to use PushPins.
To install the toolkit you'll need NuGet. How to install: http://docs.nuget.org/docs/start-here/installing-nuget
After NuGet is installed, open the console
and enter
Install-Package WPtoolkit
Finally just add the namespace into your xaml
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I can only show $|X_{n}-X||Y_{n}-Y|\xrightarrow{P} 0$ for $0<\delta<1$
Say $X_{n}\xrightarrow{P} X$ and $Y_{n}\xrightarrow{P} Y$ (*)
I want to show that:
$|X_{n}-X||Y_{n}-Y|\xrightarrow{P} 0$
My ideas:
Let $0<\delta\leq1$
$P( |X_{n}-X||Y_{n}-Y| \geq \delta )\leq P(|X_{n}-X|\geq\delta)+P(|Y_{n}-Y|\geq\delta)\xrightarrow{n\to \infty}0$
But I do not have any sensible ideas on how to show that this is the case for $\delta > 0$
Let me perhaps explain the background of the question:
I want to show under condition (*) that
$X_{n}Y_{n}\xrightarrow{P}XY$ and as a hint, I am given that
$X_{n}Y_{n}-XY=(X_{n}-X)(Y_{n}-Y)+X(Y_{n}-Y)+Y(X_{n}-X)$
So in order to show convergence in probability, I need to show it for $\delta > 0$ and not $0<\delta \leq 1$, correct?
A:
If $P\{Z_n >\delta \} \to 0$ for $\delta \in (0,1)$ then, for $\delta \geq 1$ we have $P\{Z_n >\delta \} \leq P\{Z_n >\frac 1 2 \} \to 0$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to convert dynamic JSON reponse with Java Gson library
I have an API that can return JSON arrays or objects. Example JSON object
{
"id": 1,
"name": "name"
}
JSON array:
[
{
"id": 1,
"name": "name"
},
{
"id": 1,
"name": "name"
}
]
When mapping a JSON object response to a POJO I use:
MyEntity myEntity = new Gson().fromJson(jsonString, MyEntity.class);
When mapping a JSON array response to an array of POJOs I use:
MyEntity[] myEntity = new GSON().fromJson(jsonString, MyEntity[].class);
How can I convert those two responses to the appropriate types dynamically?
NOTE: I can't modify the server response, this is a public API.
Thank you!
EDIT:
I am trying to implement a method that does this automatically but I am missing something. The method
public <T> T convertResponseToEntity(Class<T> classOfT)
{
JsonElement jsonElement = this.gson.fromJson(getResponseAsString(), JsonElement.class);
if (jsonElement.isJsonArray()) {
Type listType = new TypeToken<T>(){}.getType();
return this.gson.fromJson(getResponseAsString(), listType);
}
return this.gson.fromJson(getResponseAsString(), (Type) classOfT);
}
It returns a list of LinkedTreeMaps. How can I modify the code to return the same content as Object[]?
A:
How can I convert those 2 responses dynamically to the appropriate type?
It depends on how to interpret the "appropriate type" here because it would lead to instanceof or visitor pattern to get the appropriate type once you try to handle the parsed-from-JSON object every time you need it. If you can't change the API, you can smooth the way you use it. One of possible options here is handling such response as if everything is a list. Even a single object can be handled as a list with one element only (and many libraries work with sequences/lists only having that fact: Stream API in Java, LINQ in .NET, jQuery in JavaScript, etc).
Suppose you have the following MyEntity class to handle the elements obtained from the API you need:
// For the testing purposes, package-visible final fields are perfect
// Gson can deal with final fields too
final class MyEntity {
final int id = Integer.valueOf(0); // not letting javac to inline 0 since it's primitive
final String name = null;
@Override
public String toString() {
return id + "=>" + name;
}
}
Next, let's create a type adapter that will always align "true" lists and single objects as if it were a list:
final class AlwaysListTypeAdapter<T>
extends TypeAdapter<List<T>> {
private final TypeAdapter<T> elementTypeAdapter;
private AlwaysListTypeAdapter(final TypeAdapter<T> elementTypeAdapter) {
this.elementTypeAdapter = elementTypeAdapter;
}
static <T> TypeAdapter<List<T>> getAlwaysListTypeAdapter(final TypeAdapter<T> elementTypeAdapter) {
return new AlwaysListTypeAdapter<>(elementTypeAdapter);
}
@Override
@SuppressWarnings("resource")
public void write(final JsonWriter out, final List<T> list)
throws IOException {
if ( list == null ) {
out.nullValue();
} else {
switch ( list.size() ) {
case 0:
out.beginArray();
out.endArray();
break;
case 1:
elementTypeAdapter.write(out, list.iterator().next());
break;
default:
out.beginArray();
for ( final T element : list ) {
elementTypeAdapter.write(out, element);
}
out.endArray();
break;
}
}
}
@Override
public List<T> read(final JsonReader in)
throws IOException {
final JsonToken token = in.peek();
switch ( token ) {
case BEGIN_ARRAY:
final List<T> list = new ArrayList<>();
in.beginArray();
while ( in.peek() != END_ARRAY ) {
list.add(elementTypeAdapter.read(in));
}
in.endArray();
return unmodifiableList(list);
case BEGIN_OBJECT:
return singletonList(elementTypeAdapter.read(in));
case NULL:
return null;
case END_ARRAY:
case END_OBJECT:
case NAME:
case STRING:
case NUMBER:
case BOOLEAN:
case END_DOCUMENT:
throw new MalformedJsonException("Unexpected token: " + token);
default:
// A guard case: what if Gson would add another token someday?
throw new AssertionError("Must never happen: " + token);
}
}
}
Gson TypeAdapter are designed to work in streaming fashion thus they are cheap from the efficiency perspective, but not that easy in implementation. The write() method above is implemented just for the sake of not putting throw new UnsupportedOperationException(); there (I'm assuming you only read that API, but don't know if that API might consume "either element or a list" modification requests). Now it's necessary to create a type adapter factory to let Gson pick up the right type adapter for every particular type:
final class AlwaysListTypeAdapterFactory
implements TypeAdapterFactory {
private static final TypeAdapterFactory alwaysListTypeAdapterFactory = new AlwaysListTypeAdapterFactory();
private AlwaysListTypeAdapterFactory() {
}
static TypeAdapterFactory getAlwaysListTypeAdapterFactory() {
return alwaysListTypeAdapterFactory;
}
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken)
throws IllegalArgumentException {
if ( List.class.isAssignableFrom(typeToken.getRawType()) ) {
final Type elementType = getElementType(typeToken);
// Class<T> instances can be compared with ==
final TypeAdapter<?> elementTypeAdapter = elementType == MyEntity.class ? gson.getAdapter(MyEntity.class) : null;
// Found supported element type adapter?
if ( elementTypeAdapter != null ) {
@SuppressWarnings("unchecked")
final TypeAdapter<T> castTypeAdapter = (TypeAdapter<T>) getAlwaysListTypeAdapter(elementTypeAdapter);
return castTypeAdapter;
}
}
// Not a type that can be handled? Let Gson pick a more appropriate one itself
return null;
}
// Attempt to detect the list element type
private static Type getElementType(final TypeToken<?> typeToken) {
final Type listType = typeToken.getType();
return listType instanceof ParameterizedType
? ((ParameterizedType) listType).getActualTypeArguments()[0]
: Object.class;
}
}
And how it's used after all:
private static final Type responseItemListType = new TypeToken<List<MyEntity>>() {
}.getType();
private static final Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(getAlwaysListTypeAdapterFactory())
.create();
public static void main(final String... args) {
test("");
test("{\"id\":1,\"name\":\"name\"}");
test("[{\"id\":1,\"name\":\"name\"},{\"id\":1,\"name\":\"name\"}]");
test("[]");
}
private static void test(final String incomingJson) {
final List<MyEntity> list = gson.fromJson(incomingJson, responseItemListType);
System.out.print("LIST=");
System.out.println(list);
System.out.print("JSON=");
gson.toJson(list, responseItemListType, System.out); // no need to create an intermediate string, let it just stream
System.out.println();
System.out.println("-----------------------------------");
}
The output:
LIST=null
JSON=null
-----------------------------------
LIST=[1=>name]
JSON={"id":1,"name":"name"}
-----------------------------------
LIST=[1=>name, 1=>name]
JSON=[{"id":1,"name":"name"},{"id":1,"name":"name"}]
-----------------------------------
LIST=[]
JSON=[]
-----------------------------------
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to authorize with oauth 2.0 from appscript to Google APIs?
I'm playing around with AppScript and try to get an oAuth 2.0 access token.
Any sample out there how to get this working in AppScript?
A:
I am working on a cleaner tutorialized version of this, but here is a simple Gist that should give you some sample code on how things would work -
https://gist.github.com/4079885
It still lacks logout, error handling and the refresh_token capability, but at least you should be able to log in and call a oAuth 2 protected Google API (in this case its a profile API).
You can see it in action here -
https://script.google.com/macros/s/AKfycby3gHf7vlIsfOOa9C27z9kVE79DybcuJHtEnNZqT5G8LumszQG3/exec
The key is to use oAuth 2 Web Server flow. Take a look at getAndStoreAccessToken function in the gist to get the key details.
I hope to have this published in the next few weeks but hopefully this will help in the mean time.
UPDATE - adding in info on redirect_uri
The client secret is tied to specific redirect URIs that the authorization code is returned to.
You need to set that at - https://code.google.com/apis/console/
The highlighted URI needs to match the published URI (ends in /exec). You get the published URI from the script editor under Publish -> Deploy as web app. Make sure you are saving new versions and publishing the new versions when you make changes (the published URI stays the same).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I enable vectorization only for one part of the code?
Is there a way to enable vectorization only for some part of the code, like a pragma directive? Basically having as if the -ftree-vectorize is enabled only while compiling some part of the code? Pragma simd for example is not available with gcc...
The reason is that from benchmarking we saw that with -O3 (which enables vectorization) the timings were worse than with -O2. But there are some part of the code for which we would like the compiler to try vectorizing loops.
One solution I could use would be to restrict the compiler directive to one file.
A:
Yes, this is possible. You can either disable it for the whole module or individual functions. You can't however do this for particular loops.
For individual functions use
__attribute__((optimize("no-tree-vectorize"))).
For whole modules -O3 automatic enables -ftree-vectorize. I'm not sure how to disable it once it's enabled but you can use -O2 instead. If you want to use all of -O3 except -ftree-vectorize then do this
gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts
gcc -c -Q -O2 --help=optimizers > /tmp/O2-opts
diff /tmp/O2-opts /tmp/O3-opts | grep enabled
And then include all the options except for -ftree-vectorize.
Edit: I don't see -fno-tree-vectorize in the man pages but it works anyway so you can do -O3 -fno-tree-vectorize.
Edit: The OP actually wants to enable vectorization for particular functions or whole modules. In that case for individual functions __attribute__((optimize("tree-vectorize"))) can be used and for whole modules -O2 -ftree-vectorize.
Edit (from Antonio): In theory there is a pragma directive to enable tree-vectorizing all functions that follow
#pragma GCC optimize("tree-vectorize")
But it seems not to work with my g++ compiler, maybe because of the bug mentioned here:
How to enable optimization in G++ with #pragma. On the other hand, the function attribute works.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is benefit of this constructor definition
I was just going through random pages on Cprogramming.com and noticed the Constructors and Destructors tutorial/example page. They have used the following method of defining a constructor:
class String
{
private:
char *str;
int size;
public:
String() : str(NULL), size(0) { } // <- This statement
String(int size) : str(NULL), size(size) { // <- And this one
str = new char[size];
}
}
I've been using the good old fashioned definition of constructors with the magic this pointer:
String() {
this->str = NULL;
this->size = 0;
}
String(int size) {
this->size = size;
this->str = new char[size];
}
Is there any added benefit in the first declaration beside the obvious smaller code (less number of lines)?
PS: It has been quite a few years since I last did write something in C++.
A:
Those are constructor initialization lists, and for fundamental types there is no difference with respect to the form you are used to, which is based on assignment rather than initialization.
However, for user-defined types there might be a difference in terms of performance (and semantics perhaps) between:
default-constructing an object and then assigning a value to it, and
directly initializing it with that value.
Also, you do not have a choice for those types that are not default-constructible other than using a member initialization list to initialize them, and you do not have a choice for const and reference members either, that must be initialized immediately.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AxWindowsMediaPlayer control location/size
I have a AxWindowsMediaPlayer control on my WinForm.
Everything works so far. But I can't resize or move the control.
I initialize the control like this:
mediaPlayer = new AxWMPLib.AxWindowsMediaPlayer();
mediaPlayer.CreateControl();
mediaPlayer.enableContextMenu = false;
((System.ComponentModel.ISupportInitialize)(mediaPlayer)).BeginInit();
mediaPlayer.Name = "wmPlayer";
mediaPlayer.Enabled = true;
mediaPlayer.Dock = System.Windows.Forms.DockStyle.Fill;
mediaPlayer.Size = this.Size;
this.Controls.Add(mediaPlayer);
((System.ComponentModel.ISupportInitialize)(mediaPlayer)).EndInit();
mediaPlayer.uiMode = "none";
mediaPlayer.URL = fileName;
mediaPlayer.settings.setMode("loop", true);
mediaPlayer.Ctlcontrols.play();
But the size ist always the same. How can I set the Size or the Bounds of this Controls?
Thanks for help
A:
It is better do this in designer, rather than code.
In your code, you set the size of the player control as large as the form.
//occupies all the form's available space
mediaPlayer.Dock = System.Windows.Forms.DockStyle.Fill;
//again, the player is the same size as form
mediaPlayer.Size = this.Size;
In order to set the bound of the player control within the form, you can set the its AnchorStyle- anchoring the control to the edges of the form- and set the control's Location and Size properties.
mediaPlayer.Location = new Point(50, 50);
mediaPlayer.Size = new Size(this.ClientSize.Width - 100, this.ClientSize.Height - 100);
mediaPlayer.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Want to disable image popup dragging on a page using highslide?
I want to off the image dragging all over the page. I just want the image to be zoomed in.how to do that?
A:
You can add this to your highslide.config.js file, or put it in script tags in the head of your page (after highslide-full.js has been loaded):
hs.Expander.prototype.onDrag = function() {
return false;
}
To get rid of the "move" cursor, delete these from highslide.css:
.highslide-move, .highslide-move * {
cursor: move;
}
.highslide-header .highslide-move a {
cursor: move;
}
If you're using any of the wrapper-class names like .draggable-header or .titlebar, you'll need to make further CSS revisions, eliminating the "cursor: move;" attribute wherever you find it in the CSS file.
You'll probably also want to get rid of the "move" icon in the controlbar, but without being able to see your page, I don't know what kind of controlbar you're using, or if you're using one at all.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I want to list all countries in my dropdownlist, where can i get that web service?
I want to list all the countries in my dropdown list. where can i get all the names?
from service right? How to do this?
A:
Get the ISO 3166 country list; this is the world's official country list complete with official names and country codes. You can even get it in XML format and regular updates are available.
A:
Web Service?
Do you really consider calling Web Service each time just to get a static list of countries? This list is pretty static and does not change even each year.
I would suggest to go and copy the list from any web site that has it.
After that you could store it in your Database or somewhere else or even fix code it ( given that you are using it only on one place ).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
check if there exists a[i] = 2*a[j] in an unsorted array a?
Given a unsorted sequence of a[1,...,n] of integers, give an O(nlogn) runtime algorithm to check there are two indices i and j such that a[i] =2*a[j]. The algorithm should return i=0 and j=2 on input 4,12,8,10 and false on input 4,3,1,11.
I think we have to sort the array anyways which is O(nlogn). I'm not sure what to do after that.
A:
Note: that can be done on O(n)1 on average, using a hash table.
set <- new hash set
for each x in array:
set.add(2*x)
for each x in array:
if set.contains(x):
return true
return false
Proof:
=>
If there are 2 elements a[i] and a[j] such that a[i] = 2 * a[j], then when iterating first time, we inserted 2*a[j] to the set when we read a[j]. On the second iteration, we find that a[i] == 2* a[j] is in set, and return true.
<=
If the algorithm returned true, then it found a[i] such that a[i] is already in the set in second iteration. So, during first itetation - we inserted a[i]. That only can be done if there is a second element a[j] such that a[i] == 2 * a[j], and we inserted a[i] when reading a[j].
Note:
In order to return the indices of the elemets, one can simply use a hash-map instead of a set, and for each i store 2*a[i] as key and i as value.
Example:
Input = [4,12,8,10]
first insert for each x - 2x to the hash table, and the index. You will get:
hashTable = {(8,0),(24,1),(16,2),(20,3)}
Now, on secod iteration you check for each element if it is in the table:
arr[0]: 4 is not in the table
arr[1]: 12 is not in the table
arr[2]: 8 is in the table - return the current index [2] and the value of 8 in the map, which is 0.
so, final output is 2,0 - as expected.
(1) Complexity notice:
In here, O(n) assumes O(1) hash function. This is not always true. If we do assume O(1) hash function, we can also assume sorting with radix-sort is O(n), and using a post-processing of O(n) [similar to the one suggested by @SteveJessop in his answer], we can also achieve O(n) with sorting-based algorithm.
A:
Sort the array (O(n log n), or O(n) if you're willing to stretch a point about arrays of fixed-size integers)
Initialise two pointers ("fast" and "slow") at the start of the array (O(1))
Repeatedly:
increment "fast" until you find an even value >= twice the value at "slow"
if the value at "fast" is exactly twice the value at "slow", return true
increment "slow" until you find a value >= half the value at fast
if the value at "slow" is exactly half the value at "fast", return true
if one of the attempts to increment goes past the end, return false
Since each of fast and slow can be incremented at most n times total before reaching the end of the array, the "repeatedly" part is O(n).
A:
You're right that the first step is sorting the array.
Once the array is sorted, you can find out whether a given element is inside the array in O(log n) time. So if for every of the n elements, you check for the inclusion of another element in O(log n) time, you end up with a runtime of O(n log n).
Does that help you?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Vertical NSLevelIndicator OSX
I wonder if there is a way of creating/modifying a NSLevelIndicator object so it can be positioned vertically, i.e. display discrete levels from bottom up, not from left to right, so it can be also used as element of interface-building library in Xcode?
There are lots of examples of such level displays in Apple and non-Apple OSX applications, and quite a few reasons why such an object should exist, yet how to create such an object for some reason (from what I can see in developer forums) seems either not worth asking or a "best kept secret".
Is there a template code which can be modified to into an object of such properties?
I haven't even faintest idea if such an object should really be written from scratch? Mission impossible?
Thanks in advance!
A:
Try using
[NSView setFrameRotation:90];
it's sketchy but easier than a custom view
Edit: Alternatively try
[levelView setFrameCenterRotation:90];
SetFrameRotation:90 rotated it around the bottom left axis for me so it ended up being clipped. This one rotates it around the centre so you should be able to see it. I just made a quick swift playground showcasing it: http://cl.ly/WsL8/Vertical%20LevelIndicatorView.playground.zip
Edit again: If you're still stuck, I made a sample project with a vertical level indicator in objective-c: http://cl.ly/WrdH/levelindicator.zip
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как присвоить null календарю в asp.net c#
Есть проблема с присвоением календарю значения null. Пишет что null присвоить ему нельзя, пытаюсь конвертировать календарь или как нибудь привести к стрингу, тоже не получается.
Вот как я пытаюсь:
cldDateReservCancel.SelectedDate.ToString() = null
Подскажите пожалуйста как это можно сделать?
A:
SelectedDate имеет тип DateTime и поэтому null ему присвоить невозможно. при попытке
cldDateReservCancel.SelectedDate.ToString() = null
вы пытаетесь присвоить null не свойству календаря, а некой анонимной переменной которую вернула функция ToString(), такое присвоение, кстати, тоже невозможно, поэтому так тоже не получится.
Вашу задачу надо решать как то иначе, в зависимости от того что это за задача. Воспользоваться сторонним компонентом, например. Или если вам нужно обозначить, например, что дата выбрана не была, можно воспользоваться какой либо датой, которая, заведомо, не может быть выбрана пользователем (например DataTime.MinData, если это дата поступления сотрудника на работу) и потом проверять на равенство этой дате.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I have to print some values from the nested arrays i tried with foreach syntax but somehow i'm not doing it right
I have to print some values from the nested arrays i tried with foreach syntax but somehow i'm not doing it right .
So this is the code :
<?php
echo "<strong><h1>EXERCISES</h1></strong>";
/*THree friends (John Doe , Jane Foo , and Elvis Peanutbutter )
are playing the 6/49 lottery and each selects 6 numbers on their
lottery tickets. */
/* 1. Define a nested a array to hold their first
name; last name and the ticket with 6 numbers.*/
$friends = array();
$friends[1] = array('first_name'=>'John', 'last_name'=>'Doe', 'ticket' => array(1,3,21,4,54,32));
$friends[2] = array('first_name'=>'Jane', 'last_name'=>'Foo','ticket' => array(31,13,12,14,45,43));
$friends[3] = array('first_name'=>'Elvis', 'last_name'=>'Peanutbutter','ticket' => array(33,11,12,24,44,54));
/* 2. Elvis selects a 7th number , add it to his
ticket*/
$friends[3]['ticket'][6] = 5 ;
/* 3. Jane cancels her ticket, so remove her
numbers array completly*/
unset($friends[2]['ticket']) ;
/* 4. For each friend, display their first name and
the number of numbers they have on the ticket*/
foreach ( $friends as $friend ) {
echo $friend['first_name'] . ' has ';
if ( isset( $friend['ticket'] ) ) {
echo count($friend['ticket']);
}
else {
'NO';
}
echo ' tickets<br>';
}
?>
Now that error don't show up but the nr of the tickets don't show up either .
A:
The foreach should do it, but you have to remember that each item delivered by the foreach, is in fact an array also.
<?php
echo "<strong><h1>EXERCISES</h1></strong>";
/*THree friends (John Doe , Jane Foo , and Elvis Peanutbutter )
are playing the 6/49 lottery and each selects 6 numbers on their
lottery tickets. */
/* 1. Define a nested a array to hold their first
name; last name and the ticket with 6 numbers.*/
$friends = array();
$friends[1] = array('first_name'=>'John', 'last_name'=>'Doe', 'ticket' => array(1,3,21,4,54,32));
$friends[2] = array('first_name'=>'Jane', 'last_name'=>'Foo','ticket' => array(31,13,12,14,45,43));
$friends[3] = array('first_name'=>'Elvis', 'last_name'=>'Peanutbutter','ticket' => array(33,11,12,24,44,54));
/* 2. Elvis selects a 7th number , add it to his
ticket*/
$friends[3]['ticket'][6] = 5 ;
/* 3. Jane cancels her ticket, so remove her
numbers array completly*/
unset($friends[2]['ticket']) ;
/* 4. For each friend, display their first name and
the number of numbers they have on the ticket*/
foreach ( $friends as $friend ) {
echo $friend['first_name'] . ' has ';
if ( isset( $friend['ticket'] ) ) {
echo count($friend['ticket']);
} else {
echo 'NO';
}
echo ' tickets<br>';
}
Produces the output
John has 6 tickets
Jane has NO tickets
Elvis has 7 tickets
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using computed min/max image values to set min/max visualization parameters in GEE
I would like to use the calculated min/max values of an image region to set the min/max visualization parameters of that image. I can retrieve the actual numbers, but can't use them as variables in the visualization parameters block. I keep getting the error:
Shaded: Layer error: Can't encode object: abs() Computes the
absolute value of the input. Args: this:input (Number): The
input value.
Here's the code I'm using:
var fc = ee.FeatureCollection('TIGER/2018/States')
.filter(ee.Filter.and(ee.Filter.eq('NAME', 'Utah')));
var DEM = ee.Image('USGS/NED').clip(fc);
var Terrain = ee.Terrain.products(DEM).select('slope');
print(Terrain);
var visPct = Terrain.reduceRegion({reducer: ee.Reducer.percentile([5,95]).setOutputs(['min','max']),
geometry: fc,
scale: 10,
bestEffort: true
});
var Min = visPct.getNumber('slope_min');
var Max = visPct.getNumber('slope_max');
print(Min,Max);
var vizParams = {
min: Min,
max: Max,
palette: ['blue','green','Yellow','red']
};
Map.centerObject(fc);
Map.addLayer(Terrain, vizParams, 'Shaded');
The only thing that I can figure out is that GEE is trying to display the image before the min/max values are calculated.
A:
The Map.addLayer() visualization parameters are expected to be client-side JS objects, but you are providing server-side EE objects (ee.Number). Use the .evaluate() function to convert server-side objects to client-side objects.
Here, I've included the computed min and max values in an ee.Dictionary object and applied the .evaluate() function to it. A client-side dictionary object (dict) is made available within the scope of the anonymous function, where the min and max values can then be referenced and set as visualization parameters for displaying the image to the Map.
Code Editor script
var fc = ee.FeatureCollection('TIGER/2018/States')
.filter(ee.Filter.eq('NAME', 'Utah'));
var DEM = ee.Image('USGS/NED').clip(fc);
var Terrain = ee.Terrain.products(DEM).select('slope');
print(Terrain);
var visPct = Terrain.reduceRegion({
reducer: ee.Reducer.percentile([5,95]).setOutputs(['min','max']),
geometry: fc,
scale: 10,
bestEffort: true
});
// #########################################################
// ### ▼ EDITED ▼ ###
// #########################################################
var minMax = ee.Dictionary({
minVal: visPct.getNumber('slope_min'),
maxVal: visPct.getNumber('slope_max')
});
print(minMax);
minMax.evaluate(function(dict) {
var vizParams = {
min: dict.minVal,
max: dict.maxVal,
palette: ['blue','green','Yellow','red']
};
Map.centerObject(fc);
Map.addLayer(Terrain, vizParams, 'Shaded');
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
return value in localStorage as an Int in js?
I understand that localStorage only stores strings, but lets say the string is '43', would there be a way of printing this as an int?
I tried parseInt() but I keep getting NaN..
A:
You should probably use isNaN() function to determine whether a value is an illegal number (Not-a-Number). If it is a number, you can pass it into parseInt(). Please let me know if you have other issues.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CakePHP 2.0.4: Using the "Number" Helper in Controllers
I know it's against MVC methodologies to use helpers in controllers, but there are some cases where it's useful. For example, consider this snippet of controller code from one of my CakePHP 1.3.13 projects that handles an image upload:
elseif ($_FILES['data']['error']['ModelName']['field_name'] === UPLOAD_ERR_INI_SIZE) {
App::import('Helper', 'Number');
$Number = new NumberHelper();
$this->Session->setFlash("The image you uploaded was not saved because it appeared to be larger than {$Number->toReadableSize($max_filesize_in_bytes)}.");
}
I'm working on a CakePHP 2.0.4 project now and I used the same code, except I replaced App::import('Helper', 'Number'); with App::uses('NumberHelper', 'View/Helper'); and I got this error message:
Warning (4096): Argument 1 passed to Helper::__construct() must be an instance of View, none given, called in /Path/To/My/Website/app/Controller/MyController.php
Any ideas?
A:
you shouldnt use helpers in controllers. I proposed quite some time ago that there should be library classes for this. hopefully this will be integrated in 2.1
until then you should be using
$Number = new NumberHelper(new View(null));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Join csv files and sort to look like result from SQL query
I have mysql database, and i run sql query on that database with joins and where clause, lets say query will look like
SELECT a.value1,
a.value2,
b.value3,
c.value4
FROM table1 a
LEFT JOIN table2 b ON a.some_value=b.some_value
LEFT JOIN table3 c ON a.some_value=c.some_value
WHERE a.some_value = 'some_text';
and i run query 1000times to get average time needed for this query on database with 4.5milions records.
But, i need help if it is possible
because i don't have idea is it possible and if it is possible, how to do, and where to start for next steps.
That steps are: i want to export in CSV files
table1, table2 and table3 (and that is ok, i know to export tables in csv file), after that, in PHP i want to load each csv file, and to get almost exact result as this SQL query give.
Also i want to run this query 1.000 times and to get average time. I want to do these to make comparison between running query on tables and sorting from csv files.
A:
If you really have to put yourself through this pain, at least it's a fairly simple query.
Something like
$a = fopen('a.csv', 'r');
$b = fopen('b.csv', 'r');
$c = fopen('c.csv', 'r');
$output = fopen('php://output', 'w');
while (($dataA = fgetcsv($a, 1024, ",")) !== false) {
if ($dataA[0] == 'some_text') {
$bCount = 0;
rewind($b);
while (($dataB = fgetcsv($b, 1024, ",")) !== false) {
if ($dataB[0] == $dataA[3]) {
$bCount = 0;
$cCount = 0;
rewind($c);
while (($dataC = fgetcsv($c, 1024, ",")) !== false) {
if ($dataC[0] == $dataA[4]) {
fputcsv($output, [$dataA[1], $dataA[2], $dataB[1], $dataC[1]]);
++$cCount;
}
}
if ($cCount == 0) {
fputcsv($output, [$dataA[1], $dataA[2], $dataB[1], null]);
}
++$bCount;
}
}
if ($bCount == 0) {
$cCount = 0;
rewind($c);
while (($dataC = fgetcsv($c, 1024, ",")) !== false) {
if ($dataC[0] == $dataA[4]) {
fputcsv($output, [$dataA[1], $dataA[2], null, $dataC[1]]);
++$cCount;
}
}
if ($cCount == 0) {
fputcsv($output, [$dataA[1], $dataA[2], null, null]);
}
}
}
}
would be pretty close to what you want.
Modify your row IDs to suit your query. If you want to "name" your cells in each row to make the code more "readable", then that's an overhead, and this will take long enough to run anyway
EDIT
Logically, it loops through file a, testing each row in turn to see if it matches your where criteria, ignoring any row that doesn't match and moving on to the next. If it does find a match, then it does a lookup against file b, looping through until it finds any match (the if test there). If it does find a match against b, it then loops against c. If an match is found against c (an if test again), then it displays the result (writing the value from your select as a comma separated list from all 3 files). If no match is found in c, then it displays the values from a and b with a null instead of any value from c. If no matching value is found in b, then it loops against c looking for a match, and displays any matches from a and c with a null for the select value from b. If no matching values re found in either b or c, then it displays the a values with nulls for the b and c cells. The rewinds for b and c loops ensure that the loops will always check from the beginning of the file.
There's no easy way to search a csv other than iterating through the entire file. You could loop through each file a single time caching results against an index to make subsequent loops easier if you had unlimited memory, but PHP isn't the right language for memory-intensive tasks.
Of course, if had unlimited memory and could load the entirety of each file into 3 arrays, then you could use a query tool like LINQ to handle the query
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to accelerate quartz 2d
I have the scene stored in array as collection of shapes that is represented by sequence of points. I'm drawing this scene with CGContextMoveToPoint, CGContextAddLineToPoint, CGContextSetFillColorWithColor and CGContextFillPath functions. The problem is that i need to redraw scene on timer event with short interval (0.01 sec) and the scene redrawing is very slow. Is there a way to accelerate this stuff? Or only OpenGLES can help me?
A:
Quartz 2D (Core Graphics) graphics are not accelerated on the iPhone. Path fills are likely CPU bound as well. If you want hardware acceleration, you'll have to convert your scene to OpenGL ES (triangle strips and textures). Even using OpenGL ES, you will have to optimize your graphics fairly well to get a 60 Hz frame rate (0.017 sec).
One other possibility is to pre-render your shapes into CALayers, and just animate the layers (scale, rotate, overlay, hide, etc.) CALayer animation is also hardware assisted.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does ownership based sharing rule also shares records of users' subordinates?
Sales Manager A has subordinates A1, A2.
Sales Manager B has subordinates B1, B2.
Using ownership based sharing rule, records owned by A are shard with B. Does it also share records owned by A1 and A2?
A:
I can presume that, Sales Manager A and Sales Manager B are in different roles in Role Hierarchy.
Through Ownership based Sharing rule, using Roles and Internal Subordinates, Sales Manager and his subordinates records can be shared to Sales Manager B.
Now, if you are not talking about role based sharing and asking about user based sharing then, question is how you going to share records, either by public groups, queues?
If Sales Manager A and his subordinates are in same public group or queues then all the records owned by them can be shared to Sales Manager B (assuming it is in different group or queues).
By sharing rule, Salesforce doesn't allow individual user and his subordinates (which is identified by Manager field in User record) records to be shared other than that way.
Refer Record-Level Access: Under the Hood for more understanding about this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Button of UIAlertController changes its color on click. How to solve? - Swift
I have a UIAlertController with the tintColor orange but everytime I click on the Button it changes its color to blue (I guess the native color). How do i solve it?
let orange: UIColor = UIColor(red: 232.0/255, green: 121.0/255, blue: 23.0/255, alpha: 1.0)
let alert = UIAlertController(title: "Welcome!", message: "", preferredStyle: UIAlertControllerStyle.Alert)
alert.view.tintColor = orange
alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
A:
this is the Bug in iOS 9.0, see apple Community bug reports, may be it fixed on iOS 9.1
for additional reference see this link
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does the tag "status-declined" explanation in the faq make any sense?
It says in the faq:
Why was my feature/bug declined or closed without explanation?
Meta Stack Overflow has been around for a while, and as a result, many issues have been considered in the past. If your feature request has been marked as status-bydesign or status-declined without a comment, it is likely because there is another question that approaches the same topic and a conclusion has been reached. Perhaps you could try searching for your idea with different search terms, hopefully that will find the original discussion.
This should never happen. If a feature request is closed for either of these reasons, there should be an explanation.
Now, if it is closed because it was discussed before, it should be closed as duplicate, and tagged status-* additionally.
I think the current version doesn't convey any useful information and is at best misleading. So it should be changed not only in wording but also in meaning or removed altogether.
A:
My only thought here is that the FAQ is there for a reason:
To prevent the mods here from having to provide explanations for every single request (and every possible variation) that comes in. Instead of repeating themselves, they add the tag and move on.
The FAQ is meant to explain some of the more popular actions taken here, so you don't have to ask why. The obligation is on you to locate the prior discussion. I'm sure they have enough to do.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to send image byte to Lambda through Boto3?
Is it possible to send image byte through Lambda using Boto3? The byte will be sent to Lambda function which will then forward the image to Rekognition. I've tried this but it didn't work:
with open(image_name) as image_source:
image_bytes = image_source.read()
context = base64.b64encode(b'{"custom":{ \
"image_name":"'+imagename+'", \
"image_bytes" : "'+image_bytes+'"}}').decode('utf-8')
response = lambda_fn.invoke(
ClientContext=context,
FunctionName='recognize-face-in-image'
)
And this is the Lambda function code:
import boto3
import base64
import json
def lambda_handler(event, context):
print("Lambda triggered...")
rek = boto3.client('rekognition')
context_dict = context.client_context.custom
image_bytes = context_dict["image_bytes"]
rekresp = rek.detect_faces(Image={'Bytes': image_bytes},Attributes=['ALL'])
if not rekresp['FaceDetails']:
print "No face"
else:
print "Got face"
When I run it, this is the Lambda function error shown in Cloudwatch:
An error occurred (ValidationException) when calling the DetectFaces
operation: 1 validation error detected: Value
'java.nio.HeapByteBuffer[pos=0 lim=0 cap=0]' at 'image.bytes' failed
to satisfy constraint: Member must have length greater than or equal
to 1: ClientError Traceback (most recent call last): File
"/var/task/lambda_function.py", line 17, in lambda_handler rekresp =
rek.detect_faces(Image={'Bytes': image_bytes},Attributes=['ALL']) File
"/var/runtime/botocore/client.py", line 314, in _api_call return
self._make_api_call(operation_name, kwargs) File
"/var/runtime/botocore/client.py", line 612, in _make_api_call raise
error_class(parsed_response, operation_name) ClientError: An error
occurred (ValidationException) when calling the DetectFaces operation:
1 validation error detected: Value 'java.nio.HeapByteBuffer[pos=0
lim=0 cap=0]' at 'image.bytes' failed to satisfy constraint: Member
must have length greater than or equal to 1
A:
ClientContext isn't the right way to send bulk data to Lambda function. Instead, Payload should be used.
Additionally, the image is going to be binary data, which needs to be opened in rb mode and can't be carried in JSON.
import base64
import json
import boto3
with open(image_name, 'rb') as image_source:
image_bytes = image_source.read()
response = boto3.client('lambda').invoke(
FunctionName='recognize-face-in-image',
Payload=json.dumps({
'image_name': image_name,
'image_bytes': base64.b85encode(image_bytes).decode('utf-8'),
}),
)
And the Lambda function should look something like this:
import base64
def handler(event, context):
image_bytes = base64.b85decode(event['image_bytes'])
...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
pygame not reaching K_a input or any input from input in my class
I'm making a class that allows users to make text boxes for pygame games. I'm able to reach the mousebuttondown command but it doesn't reach that keyboard input statement. Given below is my whole code along with that part that is giving me an issue. I also need a way to take the input for every letter.
not printing reached
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect(id, mousepos):
if event.type == pygame.K_a:
print("reached")
self.dict_text[id] = []
self.dict_text[id].append("a")
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("didn't")
else:
pass
whole code - ignore update
import pygame
pygame.font.init()
class textBox:
def __init__(self, surface, id, color, width, height, x, y, antialias, maxtextlen):
self.surface = surface
self.id = id
self.color = color
self.width = width
self.height = height
self.x = x
self.y = y
self.antialias = antialias
self.maxtextlen = maxtextlen
self.text_list = []
self.text_list_keys = []
self.currentId = 0
self.click_check = False
self.font = pygame.font.SysFont('comicsans', 20)
self.dict_all = {}
pygame.draw.rect(self.surface, (self.color), (self.x, self.y, self.width, self.height))
# for i in self.text_list_keys:
# if self.id not in i:
# self.text_list_keys.append(self.id)
# self.text_list.append(tuple(self.id))
# else:
# self.nothing()
self.dict_all[self.id] = tuple((self.x, self.y, self.width, self.height))
self.dict_text = {}
def update(self, events, mousepos):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN and ((self.x + self.width) > mousepos[0] > self.x) \
and ((self.y + self.height) > mousepos[1] > self.y):
print("reached: " + mousepos)
self.click_check = True
else:
self.click_check = False
if self.click_check:
print("1")
if event.type == pygame.KEYDOWN:
print("@")
if event.key == pygame.K_a:
print("reached")
new_t = ""
for j in range(len(self.text_list)):
t = (self.text_list[j][0]).index(self.getId(self.currentId))
new_t = t
self.text_list[new_t].append("a")
self.surface.blit(self.font.render(f'{self.text_list[new_t]}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("this")
else:
pass
def rect(self, text_id, mousepos):
x, y, width, height = self.dict_all[text_id]
if ((x + width) > mousepos[0] > x) and ((y + height) > mousepos[1] > y):
print("yes")
return True
else:
return False
def getId(self, text_id):
self.currentId = text_id
def nothing(self):
return False
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect(id, mousepos):
if event.type == pygame.K_a:
print("reached")
self.dict_text[id] = []
self.dict_text[id].append("a")
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("didn't")
else:
pass
test.py
import pygame
from pygame_textbox import textBox
pygame.init()
win_width = 500
win_height = 500
screen = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("test")
run = True
while run:
mouse = pygame.mouse.get_pressed()
screen.fill((0, 0, 0))
events = pygame.event.get()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
a = textBox(screen, 1, (255, 255, 255), 100, 30, 100, 100, True, 20)
# a.getId(1)
a.rect(1, mouse)
mouse_pos = pygame.mouse.get_pos()
a.main(events, mouse_pos, 1)
pygame.display.update()
edited main
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect(id, mousepos):
if event.type == pygame.KEYDOWN:
# keys = pygame.key.get_pressed()
# if keys[pygame.K_a]:
if event.type == pygame.K_a:
print("reached")
self.dict_text[id] = []
self.dict_text[id].append("a")
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("didn't")
else:
pass
Updated files
import pygame
pygame.font.init()
class textBox:
def __init__(self, surface, id, color, width, height, x, y, antialias, maxtextlen):
self.surface = surface
self.id = id
self.color = color
self.width = width
self.height = height
self.x = x
self.y = y
self.antialias = antialias
self.maxtextlen = maxtextlen
self.text_list = []
self.text_list_keys = []
self.currentId = 0
self.click_check = False
self.font = pygame.font.SysFont('comicsans', 20)
self.dict_all = {}
self.pressed = False
self.dict_text = {}
self.dict_text[id] = []
# pygame.draw.rect(self.surface, (self.color), (self.x, self.y, self.width, self.height))
# for i in self.text_list_keys:
# if self.id not in i:
# self.text_list_keys.append(self.id)
# self.text_list.append(tuple(self.id))
# else:
# self.nothing()
self.dict_all[self.id] = tuple((self.x, self.y, self.width, self.height))
self.dict_text = {}
def draw(self):
pygame.draw.rect(self.surface, (self.color), (self.x, self.y, self.width, self.height))
# def update(self, events, mousepos):
# for event in events:
# if event.type == pygame.QUIT:
# exit()
# if event.type == pygame.MOUSEBUTTONDOWN and ((self.x + self.width) > mousepos[0] > self.x) \
# and ((self.y + self.height) > mousepos[1] > self.y):
# print("reached: ", mousepos)
# self.click_check = True
# else:
# self.click_check = False
#
# if self.click_check:
# print("1")
# if event.type == pygame.KEYDOWN:
# print("@")
# if event.key == pygame.K_a:
# print("reached")
# new_t = ""
# for j in range(len(self.text_list)):
# t = (self.text_list[j][0]).index(self.getId(self.currentId))
# new_t = t
# self.text_list[new_t].append("a")
# self.surface.blit(self.font.render(f'{self.text_list[new_t]}', self.antialias, (0, 0, 0)),
# (self.x, self.y))
#
# else:
# print("this")
#
# else:
# pass
def rect(self, text_id, mousepos):
x, y, width, height = self.dict_all[text_id]
if ((x + width) > mousepos[0] > x) and ((y + height) > mousepos[1] > y):
print("yes")
return True
else:
return False
def getId(self, text_id):
self.currentId = text_id
def nothing(self):
return False
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
self.pressed = False
if self.rect(id, mousepos):
self.pressed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
if self.pressed:
print("reached")
self.dict_text[id].append("a")
self.surface.blit(
self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("didn't")
else:
pass
test.py
import pygame
from pygame_textbox import textBox
pygame.init()
win_width = 500
win_height = 500
screen = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("test")
run = True
a = textBox(screen, 1, (255, 255, 255), 100, 30, 100, 100, True, 20)
while run:
mouse = pygame.mouse.get_pressed()
screen.fill((0, 0, 0))
events = pygame.event.get()
a.draw()
a.getId(1)
a.rect(1, mouse)
mouse_pos = pygame.mouse.get_pos()
a.main(events, mouse_pos, 1)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
pygame.display.update()
A:
The button is stored in the key attribute of the event, rather than the type attribute:
(see pygame.event)
if event.type == pygame.K_a:
if event.key == pygame.K_a:
Any way, that won't solve your issue, because the MOUSEBUTTONDOWN event doesn't evaluate and key state and even has no key attribute. Only the KEYDOWN and KEYUP events provide a key.
You have to use pygame.key.get_pressed() to evaluate if an additional key is hold down when the mouse button is pressed:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect(id, mousepos):
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
print("reached")
# [...]
If you want to detect when the mouse is on the button and a is pressed, then you've to use the KEYDOWN event:
if event.type == pygame.KEYDOWN:
if self.rect(id, mousepos):
if event.key == pygame.K_a:
print("reached")
# [...]
If you want to detect if the button was pressed by the mouse and later you want to detect if a is pressed, then you have to store the state if the button is pressed:
class textBox:
def __init__(self, surface, id, color, width, height, x, y, antialias, maxtextlen):
# [...]
self.pressed = False
def draw(self):
pygame.draw.rect(self.surface, (self.color), (self.x, self.y, self.width, self.height))
for id in self.dict_text:
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)), (self.x, self.y))
# [...]
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
self.pressed = False
if self.rect(id, mousepos):
self.pressed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
if self.pressed:
print("reached")
self.dict_text[id] = []
self.dict_text[id].append("a")
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("didn't")
Of course you've to instance the button (a) before the main application loop:
a = textBox(screen, 1, (255, 255, 255), 100, 30, 100, 100, True, 20)
run = True
while run:
# [...]
a.draw()
a.rect(1, mouse)
# [...]
Complete code:
import pygame
pygame.font.init()
class textBox:
def __init__(self, surface, id, color, width, height, x, y, antialias, maxtextlen):
self.surface = surface
self.id = id
self.color = color
self.width = width
self.height = height
self.x = x
self.y = y
self.antialias = antialias
self.maxtextlen = maxtextlen
self.text_list = []
self.text_list_keys = []
self.currentId = 0
self.click_check = False
self.font = pygame.font.SysFont('comicsans', 20)
self.dict_all = {}
# for i in self.text_list_keys:
# if self.id not in i:
# self.text_list_keys.append(self.id)
# self.text_list.append(tuple(self.id))
# else:
# self.nothing()
self.dict_all[self.id] = tuple((self.x, self.y, self.width, self.height))
self.dict_text = {}
self.pressed = False
def draw(self):
pygame.draw.rect(self.surface, (self.color), (self.x, self.y, self.width, self.height))
for id in self.dict_text:
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)), (self.x, self.y))
def update(self, events, mousepos):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN and ((self.x + self.width) > mousepos[0] > self.x) \
and ((self.y + self.height) > mousepos[1] > self.y):
print("reached: " + mousepos)
self.click_check = True
else:
self.click_check = False
if self.click_check:
print("1")
if event.type == pygame.KEYDOWN:
print("@")
if event.key == pygame.K_a:
print("reached")
new_t = ""
for j in range(len(self.text_list)):
t = (self.text_list[j][0]).index(self.getId(self.currentId))
new_t = t
self.text_list[new_t].append("a")
self.surface.blit(self.font.render(f'{self.text_list[new_t]}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("this")
else:
pass
def rect(self, text_id, mousepos):
x, y, width, height = self.dict_all[text_id]
if ((x + width) > mousepos[0] > x) and ((y + height) > mousepos[1] > y):
print("yes")
return True
else:
return False
def getId(self, text_id):
self.currentId = text_id
def nothing(self):
return False
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
self.pressed = False
if self.rect(id, mousepos):
self.pressed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
if self.pressed:
print("reached")
self.dict_text[id] = []
self.dict_text[id].append("a")
else:
print("didn't")
pygame.init()
win_width = 500
win_height = 500
screen = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("test")
a = textBox(screen, 1, (255, 255, 255), 100, 30, 100, 100, True, 20)
run = True
while run:
mouse = pygame.mouse.get_pressed()
screen.fill((0, 0, 0))
events = pygame.event.get()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
# a.getId(1)
a.draw()
a.rect(1, mouse)
mouse_pos = pygame.mouse.get_pos()
a.main(events, mouse_pos, 1)
pygame.display.update()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Favorite question/Star button. What is it for?
I've looked through the FAQ and about page and i can't seem to find any mention of the favorite/star button... Whats it for?
Thanks!
A:
It is for you to star your favourite questions so you can find them easily at a later date.
If you go to your profile you will see favourites in between badges and bounties
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to do not redirect specific file on nginx?
I just set to redirect when visitors visit my website from http to https using below code.
server {
listen 80;
ssl off;
server_name seoartgallery.com www.seoartgallery.com ja.seoartgallery.com www.ja.seoartgallery.com;
root /var/www/seoart;
location =/example.txt {
# do stuff
}
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name seoartgallery.com ja.seoartgallery.com www.seoartgallery.com www.ja.seoartgallery.com;
root /var/www/seoart;
index index.php;
ssl_certificate /etc/letsencrypt/live/seoartgallery.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/seoartgallery.com/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/seoartgallery.com/chain.pem;
ssl_dhparam /etc/letsencrypt/live/seoartgallery.com/seoartgallery.com.dhparam;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4;
# Enable HSTS. This forces SSL on clients that respect it, most
# modern browsers. The includeSubDomains flag is optional.
add_header Strict-Transport-Security "max-age=31536000";
# Set caches, protocols, and accepted ciphers. This config will
# merit an A+ SSL Labs score.
ssl_session_cache shared:SSL:20m;
ssl_session_timeout 10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
error_log /var/log/nginx/seoart.error.log warn;
location / {
try_files $uri $uri/ /index.php?$args;
}
# Allow Lets Encrypt Domain Validation Program
location ^~ /.well-known/acme-challenge/ {
allow all;
}
# Add a slash at the end of request */wp-admin
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
# Deny files starting with a . (dot)
location ~ /\. {
deny all;
}
location ~ /.well-known {
allow all;
}
# Add Rocket-Nginx configuration (of course !!)
include common/yoast.conf;
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
but i want to set only 1 file did not redirect to https.
example ) http://example.com/example.txt
but i don't know how do i that
Please let me know how to i solve that
Thank you
A:
Something like the below should work:
server {
listen 80;
server_name example.com;
location = /example.txt {
# do stuff
}
location / {
return 301 https://$host$request_uri;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
calling resource menu into other activity
Please help me how can i call a menu resource in other activity .
Here is code of main activity
public class ControlMenu extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, ShowSettings.class);
startActivity(intent);
break;
case R.id.services: Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG).show();
break;
case R.id.another:
}
return true;
}
here is menu resource
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/Quit"
android:title="Quit"
android:icon="@drawable/icon" />
<item android:id="@+id/settings"
android:title="Settings"
android:icon="@drawable/icon" />
<item android:id="@+id/services"
android:title="Services"
android:icon="@drawable/icon" />
</menu>
i can call it in the other activity by writing the main activity code but for that i have rewrite the case statements as well so guide me how can i solve it out .
A:
You should be able to add the menu code to a common Activity subclass, then make all your other Activity classes extend that common class instead of just Activity. For a simple menu this should work just fine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CSS: Div resizing depending on original size
I have time blocks whose size is calculated programmatically.
The objective is:
-If the content is bigger than its container, when you hover over the element it expands to show all of it.
-If the content is smaller than its container, nothing happens.
Here is a fiddle.
Note:
-Red means it is how it currently is.
-Green is my objective.
I'm using Angular, so a javascript solution would be accepted.
Fiddle HTML:
.current {
width: 200px;
background-color: red;
margin-right: 10px;
float: left;
overflow: hidden;
}
.current:hover {
height: auto !important;
}
.supposed {
width: 200px;
background-color: lightgreen;
margin-right: 10px;
float: left;
overflow: hidden;
}
.supposed.small:hover {
height: auto !important;
}
.small {
height: 50px;
}
.big {
height: 100px;
}
.content {
height: 75px;
background-color: rgba(0,0,0,0.5);
}
<body>
<div class="current small">
<div class=" content">
</div>
</div>
<div class="current big">
<div class="content">
</div>
</div>
<div class="supposed small">
<div class="content">
</div>
</div>
<div class="supposed big">
<div class="content">
</div>
</div>
</body>
A:
CSS:
.content {
height: 100%;
}
.current:hover {
height: auto !important;
}
.content:hover {
min-height: inherit;
}
HTML with Angular:
<div class="current" ng-style="{height: calculateHeight()+'em',min-height: calculateHeight()+'em',}">
</div>
The setting of the content height to 100% ensures that hovering over .current equals to hovering over .content.
The setting of "height: calculateHeight()+'em'" gives the desired effect of making .current bigger if .content should bigger than .current.
The setting of "min-height: inherit" ensures that .content is allways at least as big as it was before.
@elveti: thanks for the inspiration with max-height.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Writing to websocket with BLWebSocketsServer
Not sure how many of you are familiar with BLWebsocketsServer. Available at: https://github.com/benlodotcom/BLWebSocketsServer.
It's an Objective-C wrapper for LibWebSocket (Written in C). It basically only provides functionality to callback based on what is received from the client.
I'm trying to send data asynchronously to the open web sockets without using the callback that's already written in to the wrapper (as it won't be in response to anything). I presume this has to be written into the wrapper, but I have no idea how!
A:
I added the support for asynchronous messages (push) in the last version of BLWebSocketsServer. Here is what you need to do to push a message to all your connected clients:
//Start the server
[[BLWebSocketsServer sharedInstance] startListeningOnPort:9000 withProtocolName:@"my-protocol-name" andCompletionBlock:^(NSError *error) {
if (!error) {
NSLog(@"Server started");
}
else {
NSLog(@"%@", error);
}
}];
//Push a message to every connected clients
[[BLWebSocketsServer sharedInstance] pushToAll:[@"pushed message" dataUsingEncoding:NSUTF8StringEncoding]];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Spark DataFrame UDF Partitioning Columns
I want to transform a column. The new column should only contain a partition of the original column. I defined the following udf:
def extract (index : Integer) = udf((v: Seq[Double]) => v.grouped(16).toSeq(index))
To use it in a loop later with
myDF = myDF.withColumn("measurement_"+i,extract(i)($"vector"))
The original vector column was created with:
var vectors :Seq[Seq[Double]] = myVectors
vectors.toDF("vector")
But in the end I get the following error:
Failed to execute user defined function(anonfun$user$sparkapp$MyClass$$extract$2$1: (array<double>) => array<double>)
Have I defined the udf incorrectly?
A:
I can reproduce the error when I try to extract the elements that don't exist, i.e. give an index that is larger than the sequence length:
val myDF = Seq(Seq(1.0, 2.0 ,3, 4.0), Seq(4.0,3,2,1)).toDF("vector")
myDF: org.apache.spark.sql.DataFrame = [vector: array<double>]
def extract (index : Integer) = udf((v: Seq[Double]) => v.grouped(2).toSeq(index))
// extract: (index: Integer)org.apache.spark.sql.expressions.UserDefinedFunction
val i = 2
myDF.withColumn("measurement_"+i,extract(i)($"vector")).show
Gives this error:
org.apache.spark.SparkException: Failed to execute user defined function($anonfun$extract$1: (array<double>) => array<double>)
Most likely you have the same problem while doing toSeq(index), try use toSeq.lift(index) which returns None if the index is out of bound:
def extract (index : Integer) = udf((v: Seq[Double]) => v.grouped(2).toSeq.lift(index))
extract: (index: Integer)org.apache.spark.sql.expressions.UserDefinedFunction
Normal index:
val i = 1
myDF.withColumn("measurement_"+i,extract(i)($"vector")).show
+--------------------+-------------+
| vector|measurement_1|
+--------------------+-------------+
|[1.0, 2.0, 3.0, 4.0]| [3.0, 4.0]|
|[4.0, 3.0, 2.0, 1.0]| [2.0, 1.0]|
+--------------------+-------------+
Index out of bound:
val i = 2
myDF.withColumn("measurement_"+i,extract(i)($"vector")).show
+--------------------+-------------+
| vector|measurement_2|
+--------------------+-------------+
|[1.0, 2.0, 3.0, 4.0]| null|
|[4.0, 3.0, 2.0, 1.0]| null|
+--------------------+-------------+
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Insert formula into cell with VBA: Object-defined error
I'm trying to use this in my VBA code:
ActiveSheet.Range("A1:A1:).Formula = "='Sheet1'!A1" & Chr(34) & Chr(47) & Chr(34) & "'Sheet1'!A2"
This gives me Error: 1004, Object-defined error.
I'd like to see in the cell formula that:
='Sheet1'!A1"/"'Sheet1'!A2
And if the value of the A1 cell is 10 and the A2 value is 20, the cell value should look like that: 10/20
What can be the problem?
A:
First of all you have a colon instead of a speech mark within Range. You could try something like:
ActiveSheet.Range("A1").Value = Sheet("Sheet1").Range("A1").Value & "/" & Sheet("Sheet1").Range("A2").Value
I'd also recommend not using ActiveSheet as much as possible and also referring to the workbook in references. If you want to refer to the workbook that contains the VBA code you can use ThisWorkbook.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Passing state from child to parent in React; child has separate state
I have three components, from outermost to innermost: App => Welcome => SearchBar. There's a state defined in App and SearchBar, but what I want is to get the user-inputted data in SearchBar and display that in a "Results" page. As such, I'm trying to update the state in SearchBar and have that simultaneously update the state in App, so that I can pass that data on to another component that's a child of App (e.g. Results). I have the following code, but it's only updating the state in SearchBar and not that in App.
(I've looked at some examples where the child (in this case SearchBar) doesn't have its own state, but in this case I think it's necessary since I'm tracking user input. I may be wrong though.)
// App.js
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { value: "" };
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
this.setState({
value: event.target.value
});
}
render() {
return (
<Router>
<div className="AppContainer">
<Route
exact
path="/"
render={props => <SearchBar handleSubmit={this.handleSubmit} />}
/>
...
// Welcome.js
export default class Welcome extends React.Component {
render() {
return (
<div>
<SearchBar handleSubmit={this.props.handleSubmit} />
</div>
...
// SearchBar.js
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = { value: "" };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
event.preventDefault();
this.setState({ value: event.target.value });
}
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<input
type="text"
placeholder="Search..."
onChange={this.handleChange}
value={this.state.value}
/>
<input type="submit" />
</form>
);
}
}
Then again, I'm quite new to React so this might not be a pattern that you're supposed to use. In any case, I would appreciate advice on how to best solve this.
A:
Since you've already defined a handleSubmit() event-handler in App.js and passed it all the way down to your SearchBar.js component. You can extrapolate the data you need by giving the input tag in your SearchBar a name prop.
class Searchbar extends React.Component {
state = {
value: ""
};
handleOnChange = e => {
this.setState({
value: e.target.value
});
};
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<input
onChange={this.handleOnChange}
value={this.state.value}
name="search"
/>
</form>
);
}
}
Then in App.js handleSubmit handler, target that name prop to get the value in the input.
handleSubmit = e => {
e.preventDefault();
this.setState({
value: e.target.search.value
})
};
This will likely have the least amount of re-renders.
Edit:
Yes we can totally display a new component upon submitting the form. We just need the help of a second state-value like displayResults or displayComponent then by using a simple if-check, we'll just toggle what components to show.
See working example: Code Demo
|
{
"pile_set_name": "StackExchange"
}
|
Q:
hide my apps picture from gallery (exect use .nomedia)
I use this method to convert my bitmap file and then put these images uri in data base. but I want this folder "my_app" dose not show in gallery. what do I do?!
any solution exept use no media?!
public File bitmapConvertToFile(Bitmap bitmap){
FileOutputStream fileOutputStream = null;
File bitmapFile = null;
try {
File file = new File(Environment.getExternalStorageDirectory()+"/my_app/");
if (!file.exists()){
file.mkdir();
}
bitmapFile = new File(Environment.getExternalStorageDirectory()+"/my_app/"+"today_picture.jpg");
fileOutputStream = new FileOutputStream(bitmapFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
MediaScannerConnection.scanFile(this, new String[]{bitmapFile.getAbsolutePath()}, null, new MediaScannerConnection.MediaScannerConnectionClient() {
@Override
public void onMediaScannerConnected() {
}
@Override
public void onScanCompleted(String path, Uri uri) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(CropImage.this,"saved", Toast.LENGTH_LONG).show();
}
});
}
});
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (fileOutputStream != null){
try {
fileOutputStream.flush();
fileOutputStream.close();
}
catch (Exception e){
}
}
}
return bitmapFile;
}
A:
Instead of using
File file = new File(Environment.getExternalStorageDirectory()+"/my_app/");
use
File file = new File(getFilesDir()+"/my_app/");
What this does is it saves your file inside the app so that it cannot be accessed by any other app except yours.
Hence your bimap file will be
bitmapFile = new File(getFilesDir()+"/my_app/"+"today_picture.jpg");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a Listener that will return when the phone GPS enters a certain longitude or latitude area
Does the Android SDK have a Listener that will return when the phone GPS enters a certain longitude or latitude area?
A:
Yes. There is a function called addProximityAlert
Document says:
It sets a proximity alert for the location given by the position (latitude,
longitude) and the given radius.
When the device detects that it has entered or exited the area surrounding the
location, the given PendingIntent will be used to create an Intent to be fired.
The fired Intent will have a boolean extra added with key
KEY_PROXIMITY_ENTERING. If the value is true, the device is entering the
proximity region; if false, it is exiting.
Due to the approximate nature of position estimation, if the device passes
through the given area briefly, it is possible that no Intent will be fired.
Similarly, an Intent could be fired if the device passes very close to the
given area but does not actually enter it.
After the number of milliseconds given by the expiration parameter, the location
manager will delete this proximity alert and no longer monitor it. A value of -1
indicates that there should be no expiration time.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I have a traditional src/main/scala directory in a Play Application?
I wish to move some of my normal SBT Scala code across to my Play Application. So my first thought was I'll just create a src directory and put it there, but it seems not working.
What is the right way to put normal Scala code into the Scala Play Application?
A:
Adding
unmanagedSourceDirectories in Compile += baseDirectory.value / "src" / "main" / "scala"
in your build.sbt should do the trick.
A:
Currently it should be done in the following way:
disablePlugins(PlayLayoutPlugin)
PlayKeys.playMonitoredFiles ++= (sourceDirectories in (Compile, TwirlKeys.compileTemplates)).value
Described here: https://www.playframework.com/documentation/2.6.x/Anatomy#Default-SBT-layout
|
{
"pile_set_name": "StackExchange"
}
|
Q:
java.lang.NoClassDefFoundError: Could not initialize class org.aspectj.weaver.reflect.ReflectionWorld
So I used Spring to developed a webapp on my local machine, and it works perfectly fine locally. Then I tried to deploy it, and I uploaded the .war file to my site.
I got the NoClassDefFoundError, here's the stack-trace
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'commonController' defined in file [/usr/local/shared/tomcat/kenendz/webapps/zzz/WEB-INF/classes/zzz/web/CommonController.class]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.aspectj.weaver.reflect.ReflectionWorld
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:664)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:630)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:678)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:549)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:490)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at sun.reflect.GeneratedMethodAccessor62.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:274)
at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:271)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAsPrivileged(Subject.java:536)
at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:306)
at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:166)
at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:120)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1260)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1185)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:857)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.aspectj.weaver.reflect.ReflectionWorld
at org.aspectj.weaver.tools.PointcutParser.setClassLoader(PointcutParser.java:219)
at org.aspectj.weaver.tools.PointcutParser.<init>(PointcutParser.java:205)
at org.aspectj.weaver.tools.PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution(PointcutParser.java:167)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.initializePointcutParser(AspectJExpressionPointcut.java:216)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:201)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.checkReadyToMatch(AspectJExpressionPointcut.java:193)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.getClassFilter(AspectJExpressionPointcut.java:170)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:208)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:262)
at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:294)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:118)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:88)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:69)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:330)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:293)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
... 42 more
I do have aspectjweaver.jar and aspectjrt.jar in my classpath, and the webapp works on my local system.
UPDATE
I just find out that there's permission issues during deploying this webapp
INFO: Caught AccessControlException when accessing system property [spring.liveBeansView.mbeanDomain]; its value will be returned [null]. Reason: access denied ("java.util.PropertyPermission" "spring.liveBeansView.mbeanDomain" "read")
Aug 23, 2015 11:39:57 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system environment variable [spring.liveBeansView.mbeanDomain]; its value will be returned [null]. Reason: access denied ("java.lang.RuntimePermission" "getenv.spring.liveBeansView.mbeanDomain")
Aug 23, 2015 11:39:57 AM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 1382 ms
Aug 23, 2015 11:39:57 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'servlet': initialization started
Aug 23, 2015 11:39:57 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system property [spring.profiles.active]; its value will be returned [null]. Reason: access denied ("java.util.PropertyPermission" "spring.profiles.active" "read")
Aug 23, 2015 11:39:57 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system environment variable [spring.profiles.active]; its value will be returned [null]. Reason: access denied ("java.lang.RuntimePermission" "getenv.spring.profiles.active")
Aug 23, 2015 11:39:57 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system property [spring.profiles.default]; its value will be returned [null]. Reason: access denied ("java.util.PropertyPermission" "spring.profiles.default" "read")
Aug 23, 2015 11:39:57 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system environment variable [spring.profiles.default]; its value will be returned [null]. Reason: access denied ("java.lang.RuntimePermission" "getenv.spring.profiles.default")
Aug 23, 2015 11:39:57 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system property [spring.profiles.default]; its value will be returned [null]. Reason: access denied ("java.util.PropertyPermission" "spring.profiles.default" "read")
Aug 23, 2015 11:39:57 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system environment variable [spring.profiles.default]; its value will be returned [null]. Reason: access denied ("java.lang.RuntimePermission" "getenv.spring.profiles.default")
A:
I thought this was the problem with request, but Evil Toad's question leads me to check whether the webapp is deployed successfully. And it turns out it's the problem with the security
Here is the catalina log produced by tomcat
INFO: Caught AccessControlException when accessing system property [spring.profiles.active]; its value will be returned [null]. Reason: access denied ("java.util.PropertyPermission" "spring.profiles.active" "read")
Aug 23, 2015 11:29:59 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system environment variable [spring.profiles.active]; its value will be returned [null]. Reason: access denied ("java.lang.RuntimePermission" "getenv.spring.profiles.active")
Aug 23, 2015 11:29:59 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system property [spring.profiles.default]; its value will be returned [null]. Reason: access denied ("java.util.PropertyPermission" "spring.profiles.default" "read")
Aug 23, 2015 11:29:59 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system environment variable [spring.profiles.default]; its value will be returned [null]. Reason: access denied ("java.lang.RuntimePermission" "getenv.spring.profiles.default")
Aug 23, 2015 11:29:59 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system property [spring.profiles.default]; its value will be returned [null]. Reason: access denied ("java.util.PropertyPermission" "spring.profiles.default" "read")
Aug 23, 2015 11:29:59 AM org.springframework.web.context.support.StandardServletEnvironment getSystemAttribute
INFO: Caught AccessControlException when accessing system environment variable [spring.profiles.default]; its value will be returned [null]. Reason: access denied ("java.lang.RuntimePermission" "getenv.spring.profiles.default")
So I modified catalina.policy
added the following lines
grant codeBase "file:${catalina.base}/webapps/webAppName/-" {
permission java.security.AllPermission;
};
webAppName should be replaced with the webapp's name
Finally the webapp is deployed successfully, and it works!!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VCFloatingButtonAction error
I am getting these two error in my project after importing VCFloatingActionButton
1.
Undefined symbols for architecture x86_64:
"OBJC_CLASS$_VCFloatingActionButton", referenced from:
objc-class-ref in CreateServiceWizardViewController.o
ld: symbol(s) not found for architecture x86_64
2.
clang: error: linker command failed with exit code 1 (use -v to see invocation)
If anyone has used this component intheir project, kindly guide me on how to use this component.
A:
Assuming you have used Cocoa pods for VCFloatingButtonAction for intregation, Cocoapods makes a .xcworkspace file after the intregation is complete. If you open you project by normal .xcodeproj file, xcode will not find the framework and give you linker crash.
Open the project with .xcworkspace and not not .xcodeproj file and everything would be fine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JavaScript Prototype function Issue
I have built a Constructor and added 3 functions to its prototype.
When I try to call a function from the prototype i get this error
TypeError: undefined is not a function (evaluating 'fireOne.addLogs(8)')
Please can someone tell me what I am doing wrong. I cannot figure it out.
Thanks in advance
function SignalFire(ID, startingLogs){
this.fireID = ID;
this.logsLeft = startingLogs;
}
var fireOne = new SignalFire(1, 20);
var fireTwo = new SignalFire(2, 18);
var fireThree = new SignalFire(3, 24);
SignalFire.prototype = {
addLogs: function(numLogs){
this.logsLeft += numLogs;
},
lightFire: function(){
alert("Whoooooosh!");
},
smokeSignal: function(message) {
if (this.logsLeft < this.message.length / 10){
alert("Not enough fuel to send " +
"the current message!");
}
else {
this.lightFire();
var x = this.message.length;
for(var i = 0; i < x; i++){
alert("(((" + this.message[i] + ")))");
if (i % 10 === 0 && i !== 0){
this.logsLeft--;
}
}
}
}
};
fireOne.addLogs(8);
A:
Problem is order of your code. You add things after it is created. If you add the prototype before you create the fires it will work.
function SignalFire(ID, startingLogs){
this.fireID = ID;
this.logsLeft = startingLogs;
}
SignalFire.prototype = {
addLogs: function(numLogs){
this.logsLeft += numLogs;
console.log(this.logsLeft);
}
};
var fireOne = new SignalFire(1, 20);
fireOne.addLogs(8);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Random double between min and max
double get_random(double min, double max) {
/* Returns a random double between min and max */
return min * ((double) rand() / (double) RAND_MAX) - max;
}
That's my function to generate random doubles between a min and a max. However, when I call get_random(-1.0, 1.0);, I get values between -2.0 and -1.0.
Any idea of what I'm doing wrong and how I can fix it?
A:
Shouldn't the formula be
(max - min) * ( (double)rand() / (double)RAND_MAX ) + min
(double)rand() / (double)RAND_MAX returns a random number between 0 and 1
(max - min) * ( (double)rand() / (double)RAND_MAX ) returns a random number between 0 and max - min.
the whole expression will return a random number between 0 + min and min + (max-min) - i.e. min and max.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Wildcard in jquery autocomplete field name
I need a wildcard for digits that come after my #TagEntry in this jquery selector. I tried the code below and a number of other variations but it does not work. I want it to accept #TagEntry1, #TagEntry2, all the way up to #TagEntry999.
//jQuery Auto Complete
jQuery(document).ready(function($){
$("[#TagEntry*]").autocomplete({source:'FavoriteTagList.php', minLength:1});
});
A:
Use $('[id^="TagEntry"]').
jsFiddle: https://jsfiddle.net/00hwj2az/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create a trusted ssl handshake with server using Java
I need help creating a trusted connection with a web service using Axis2 and org.jsslutils.sslcontext.X509SSLContextFactory. I have a generated client cert from the web service's admin console (client.p12). I also have grabbed the server's public cert by going to the endpoint uri and exporting it to a file using the browser (pubserver.cer). I converted the client.p12 to a jks using keytool (mywsks.jks). I also imported pubserver.cer into the keystore. I'm very new to ssl. Do I need to import these certs into .../jre/lib/security/cacert or cacerts or trusted.libraries or can I just reference mywsks.jks? How do I set up my code for the server to trust me using X509SSLContextFactory? It appears to need a keyStore and a trustStore which I'm deriving from this example:
X509SSLContextFactory sslContextFactory = new X509SSLContextFactory(
keyStore, keyStorePassword, trustStore);
I'm currently using this to create the keyStore and trustStore:
KeyStore keyStore = KeyStore.getInstance("JKS");
String keyStoreFile = "mywsks.jks";
InputStream keyInput = new FileInputStream(keyStoreFile);
String keyStorePassword = "thepassword";
keyStore.load(keyInput, keyStorePassword.toCharArray());
keyInput.close();
String trustStoreFile = "/path/to/cacert";
KeyStore trustStore = KeyStore.getInstance("JKS");
keyInput = new FileInputStream(trustStoreFile);
String trustStorePassword = "thepassword";
trustStore.load(keyInput, trustStorePassword.toCharArray());
keyInput.close();
I'm getting the following error:
org.apache.axis2.AxisFault: sun.security.validator.ValidatorException: No trusted certificate found
A:
Add your client certificate that is used for authenticate into web service into a keyStore(client.p12).
Add the server's public key(pubserver.cer) into your trustStore. It can be /jre/lib/security/cacert
Could you post what issue you are facing ? Because according to me, it is a confusing and a big topic to discuss..
This example will help you implementing this..
http://code.google.com/p/jsslutils/wiki/ApacheHttpClientUsage
And finally you could make an URL connection..
|
{
"pile_set_name": "StackExchange"
}
|
Q:
According to Catholicism do any of the Ten Commandments directly relate to tax evasion?
Evasion of tax eg. Income Tax is a punishable offence under the civil laws in many countries. But many Christians seldom get the feeling of having sinned if they have evaded tax.
I wish to know if any of the Ten Commandments directly relates to evasion of civil tax.
What do the teachings of Catholic Church tell its faithful about tax evasion?
A:
As a personal note, I find it interesting that God specifically listed taxes as a reason Israel should not desire a king.
Samuel's Warning Against Kings
10 So Samuel told all the words of the Lord to the people who were
asking for a king from him. 11 He said, “These will be the ways of the
king who will reign over you: he will take your sons and appoint them
to his chariots and to be his horsemen and to run before his chariots.
12 And he will appoint for himself commanders of thousands and
commanders of fifties, and some to plow his ground and to reap his
harvest, and to make his implements of war and the equipment of his
chariots. 13 He will take your daughters to be perfumers and cooks and
bakers. 14 He will take the best of your fields and vineyards and
olive orchards and give them to his servants. 15 He will take the
tenth of your grain and of your vineyards and give it to his officers
and to his servants. 16 He will take your male servants and female
servants and the best of your young men[a] and your donkeys, and put
them to his work. 17 He will take the tenth of your flocks, and you
shall be his slaves. 18 And in that day you will cry out because of
your king, whom you have chosen for yourselves, but the Lord will not
answer you in that day.” (1 Samuel 8: 10-18)
But since your question was specifically about Catholicism you must go to the Catechism, which is the source material for Catholic teachings.
Catechism 2409
The following are also morally illicit: speculation in which one contrives to manipulate the price of goods artificially in order to gain an advantage to the detriment of others; corruption in which one influences the judgment of those who must make decisions according to law; appropriation and use for private purposes of the common goods of an enterprise; work poorly done; tax evasion; forgery of checks and invoices; excessive expenses and waste. Willfully damaging private or public property is contrary to the moral law and requires reparation.
That is according to the official Vatican web site.
A:
The Catholic Church, which does generally claim to follow the Bible, should follow the commands in the New Testament that specifically relate to tax evasion. Examples that weren't explicitly previously mentioned would be Romans 13:1-7 and Matthew 21:15-22.
Romans 13:1-7
1 Let everyone be subject to the governing authorities, for there is no authority except that which God has established. The authorities that exist have been established by God. 2 Consequently, whoever rebels against the authority is rebelling against what God has instituted, and those who do so will bring judgment on themselves. 3 For rulers hold no terror for those who do right, but for those who do wrong. Do you want to be free from fear of the one in authority? Then do what is right and you will be commended. 4 For the one in authority is God’s servant for your good. But if you do wrong, be afraid, for rulers do not bear the sword for no reason. They are God’s servants, agents of wrath to bring punishment on the wrongdoer. 5 Therefore, it is necessary to submit to the authorities, not only because of possible punishment but also as a matter of conscience.
6 This is also why you pay taxes, for the authorities are God’s servants, who give their full time to governing. 7 Give to everyone what you owe them: If you owe taxes, pay taxes; if revenue, then revenue; if respect, then respect; if honor, then honor.
And Matthew 21:15-22
Matthew 21:15-22
15 Then the Pharisees went out and laid plans to trap him in his words. 16 They sent their disciples to him along with the Herodians. “Teacher,” they said, “we know that you are a man of integrity and that you teach the way of God in ?accordance with the truth. You aren’t swayed by others, because you pay no attention to who they are. 17 Tell us then, what is your opinion? Is it right to pay the imperial tax[a] to Caesar or not?”
18 But Jesus, knowing their evil intent, said, “You hypocrites, why are you trying to trap me? 19 Show me the coin used for paying the tax.” They brought him a denarius, 20 and he asked them, “Whose image is this? And whose inscription?”
21 “Caesar’s,” they replied.
Then he said to them, “So give back to Caesar what is Caesar’s, and to God what is God’s.”
22 When they heard this, they were amazed. So they left him and went away.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to declare record containing events which use record as parameter
I'm trying to figure out how to declare both a record and a number of object events which use each other. The problem is no matter which way I declare them, I have an "undeclared identifier".
So with the code below, can I get them to use each other? The events will be used in an object, and the record will be passed and used into the object's constructor.
TMyEvent = procedure(Sender: TObject; var Rec: TMyRecord) of object;
TMyRecord = record
OnMyEvent: TMyEvent;
end;
Is this possible? It needs to work in all versions of Delphi 7 and up.
A:
If you're using a more recent Delphi version, you can declare types within records. Here is how you can reference the record from your event:
type
TMyRecord = record
public type
TMyEvent = procedure (Sender: TObject; var Rec: TMyRecord) of object;
public
OnMyEvent: TMyEvent;
end;
A:
Unfortunately forward declarations are only allowed for classes but not records, so the only way I know of is to use pointers:
PMyRecord = ^TMyRecord;
TMyEvent = procedure(Sender: TObject; Rec: PMyRecord) of object;
TMyRecord = record
OnMyEvent: TMyEvent;
end;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ECG Bash selection tool
I made the following bash script for extracting a group of ECG signals from ECG files. I would like to know if there is any mistakes and/or weaknesses. I have experienced difficulties in integrating bash parameters to it as a function because of AWK part.
I think it would be better not to use so much different separate tools because of such problems, but not sure how to replace, for instance, the AWK part by something more stable together with bash.
Each ECG file contains two columns where the first column is the original signal and the second column is the improved ECG signal.
The database is AAMI MIT-BIH Arrhythmia. The script must be stable and must be valid, so I have not used wildcard characters there. The users give IDs which they want. They give also which ECG signal they want (1 or 2).
Now, the type of ECG signal has to be manually corrected because I cannot integrate $ecg in awk one-liner.
Logic of the script:
Get a list of wanted ECG columns into ECGs; there is a repetition of the ID 118 because repetition should be allowed and duplicate IDs should not removed
Greate and/or empty temporary files; keep iteration individual ECG in /tmp/test.csv and the combination result in result.csv
Loop through ECGs to have them in result.csv
Add a header to the beginning of the file by ids
getEcgs.bash
#!/bin/bash
ids=(101 118 201 103 118)
dir="/home/masi/Documents/CSV/"
#Ecgs=()
index=0
ecg=2 # ecg=1 ecg; ecg=2 improved ecg # change AWK line $2/$1 to corresponding number manually for change; buggy AWK with bash params
#printf '%s\n' "${#ids[@]}"
#printf '%s\n' "${ids[0]}"
#printf '%s\n' "${ids[1]}"
for id in "${ids[@]}";
do
input=$(echo "${dir}P${id}C1.csv")
# take second column of the file here
file=$(awk -F "\"*,\"*" '{print $2}' $input) # http://stackoverflow.com/a/19602188/54964 # http://stackoverflow.com/a/19075707/54964
# printf '%s\n' "${id}"
# printf '%s\n' "$index"
Ecgs[${index}]="${file}"
index=$index+1
done
#declare -A "${Ecgs[@]}"
#printf '%s\n' "${Ecgs[@]}" # http://stackoverflow.com/a/15692004/54964
#printf '%s\n' "${#Ecgs[@]}"
filenameTmp=/tmp/test.csv
filenameTarget=/tmp/result.csv
:> "$filenameTmp" # https://unix.stackexchange.com/a/320142/16920
:> "$filenameTarget"
# Put array items columnwise into .csv file
let N="${#Ecgs[@]}"-1 # https://unix.stackexchange.com/a/149832/16920
for index in `seq 0 "${N}"`;
do
printf '%s\n' "${Ecgs[${index}]}" > "${filenameTmp}"
if [[ "${index}" -eq 0 ]]; then
cat "${filenameTmp}" > "${filenameTarget}"
fi
# cat "${filenameTmp}"
# paste <(cat /tmp/result.csv) <(cat /tmp/test.csv) > /tmp/result.csv
if [[ "${index}" > 0 ]]; then
paste -d "," "${filenameTarget}" "${filenameTmp}" | column -s $'\t' -tn > "${filenameTarget}" # https://unix.stackexchange.com/a/16465/16920
fi
done
header=$(printf ",%s" ${ids[@]}) # http://stackoverflow.com/a/2317171/54964
header=${header:1} # to remove the first comma caused by printf
sed -i "1s/^/${header}\n/" "${filenameTarget}"
Input data examples /home/masi/Documents/CSV/P100C1.csv, P101C1.csv, P118C1.csv and P201C1.csv:
masi@masi:~/Documents/CSV$ head -n +5 P101C1.csv
-0.56,1.61
-0.575,0.67
-0.56,0.695
-0.545,0.38
-0.52,0.43
masi@masi:~/Documents/CSV$ head -n +5 P100C1.csv
-0.295,-0.465
-0.295,-0.44
-0.295,-0.435
-0.31,-0.425
-0.315,-0.41
masi@masi:~/Documents/CSV$ head -n +5 P118C1.csv
-0.69,-1.84
-0.67,-0.71
-0.67,-0.49
-0.69,-0.26
-0.74,0.07
masi@masi:~/Documents/CSV$ head -n +5 P201C1.csv
-0.21,-0.245
-0.205,-0.22
-0.225,-0.2
-0.22,-0.2
-0.21,-0.195
Temporary file content in /tmp/test.csv for a single iteration
-1.84
-0.71
-0.49
-0.26
Output /tmp/result.csv with headers where you see repetition of ID 118 occurs as expected:
101,118,201,103,118
1.61,-1.84,-0.245,-0.405,-1.84
0.67,-0.71,-0.22,-0.32,-0.71
0.695,-0.49,-0.2,-0.32,-0.49
Discussions about some parts of the script:
Using AWK with Bash parameters here; AWK is not critical for the script but causes difficulties in handling Bash parameters; so it can be replaced such that the script could be made a function.
# https://unix.stackexchange.com/a/320857/16920
# not working in this application
#paste -d"," ${input[@]} | awk -F, -v OFS=, '{print $2, $4, $6}' > /tmp/testShort.csv
OS: Debian 8.5
Bash: 4.30
A:
Shell scripts that do complex line-oriented text processing using Awk and other tools are usually better done using Awk alone. Not only would the script be more efficient, it would be more coherent, and have fewer quoting issues. Consider the following script, which I'll call ecg:
#!/usr/bin/gawk -f
# https://www.gnu.org/software/gawk/manual/html_node/Join-Function.html
@include "join.awk"
BEGIN {
FS = "\"*,\"*";
last_row = 0;
}
BEGINFILE {
rows[0][ARGIND] = gensub(".*P([0-9]*)C.*", "\\1", "g", FILENAME);
}
{
rows[FNR][ARGIND] = $col;
if (FNR > last_row) { last_row = FNR; }
}
END {
for (r = 0; r <= last_row; r++) {
print join(rows[r], 1, ARGC - 1, ",");
}
}
Observe what happens when you run it:
$ ./ecg -v col=2 P{101,118,201,118}C1.csv
101,118,201,118
1.61,-1.84,-0.245,-1.84
0.67,-0.71,-0.22,-0.71
0.695,-0.49,-0.2,-0.49
0.38,-0.26,-0.2,-0.26
0.43,0.07,-0.195,0.07
Note that $col extracts the column specified by the parameter col.
Since you are using GNU/Linux, I have taken advantage of some features specific to GNU Awk in the script above:
Multidimensional arrays. Traditional Awk only has one-dimensional arrays which can be indexed using tuples to simulate extra dimensions.
The BEGINFILE special pattern and the ARGIND special variable.
The gensub() function to extract the ID from the filename.
The join() function.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Spring: Do I need @EnableAspectJAutoProxy with Compile time weaving?
I've looked around the internet and found a few suggestions, and also tried different configurations, but I'm totally unsure if it works correctly.
pom.xml (full pom.xml: http://pastebin.com/5Y2qksTH ):
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<versionRange>[1.0,)</versionRange>
<goals>
<goal>test-compile</goal>
<goal>compile</goal>
</goals>
</pluginExecutionFilter>
<action>
<execute>
<runOnConfiguration>true</runOnConfiguration>
<runOnIncremental>true</runOnIncremental>
</execute>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.5</version>
<configuration>
<Xlint>warning</Xlint>
<complianceLevel>1.7</complianceLevel>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
I've added
<execute>
<runOnConfiguration>true</runOnConfiguration>
<runOnIncremental>true</runOnIncremental>
</execute>
because before it seemed like I always had to do Project -> Clean in Eclipse and afterwards Tomcat -> Clean. Else it always executed my cached method. Now it seems to work automatically.
CacheableConfig.java:
@EnableCaching(mode = AdviceMode.ASPECTJ)
public class CacheableConfig implements CachingConfigurer {
@Override
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("testCache");
}
@Override
public KeyGenerator keyGenerator() {
return new SimpleKeyGenerator();
}
}
AppConfig.java:
@EnableAspectJAutoProxy
public class AppConfig {}
Without @EnableAspectJAutoProxy it didn't work at all.
MyTestServiceImpl.java:
@Service
public class MyTestServiceImpl implements MyTestService {
@Scheduled(initialDelay=10000, fixedDelay=30000)
public void a() {
long time = System.currentTimeMillis();
System.out.println("START");
System.out.println("returned: " + b(0));
System.out.println("returned: " + b(1));
System.out.println("returned: " + b(0));
System.out.println("returned: " + b(1));
System.out.println("returned: " + b(2));
System.out.println("END: " + (System.currentTimeMillis() - time));
}
@Cacheable("testCache")
public int b(int i) {
System.out.println("INSIDE CACHED METHOD");
i++;
try {
Thread.sleep(2000);
} catch(InterruptedException ex) {}
return i;
}
}
Note: I just use @Scheduled in order to automatically invoke the method multiple times.
Output:
START
2014-03-01 15:53:25,796 DEBUG o.s.c.annotation.AnnotationCacheOperationSource: 109 - Adding cacheable method 'b' with attribute: [CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless='']
2014-03-01 15:53:25,797 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 0 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
INSIDE CACHED METHOD
returned: 1
2014-03-01 15:53:27,798 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 1 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
INSIDE CACHED METHOD
returned: 2
2014-03-01 15:53:29,799 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 0 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
2014-03-01 15:53:29,799 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 0 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
returned: 1
2014-03-01 15:53:29,799 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 1 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
2014-03-01 15:53:29,799 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 1 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
returned: 2
2014-03-01 15:53:29,799 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 2 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
INSIDE CACHED METHOD
returned: 3
END: 6018
START
2014-03-01 15:54:01,801 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 0 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
2014-03-01 15:54:01,801 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 0 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
returned: 1
2014-03-01 15:54:01,801 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 1 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
2014-03-01 15:54:01,801 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 1 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
returned: 2
2014-03-01 15:54:01,801 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 0 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
2014-03-01 15:54:01,802 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 0 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
returned: 1
2014-03-01 15:54:01,802 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 1 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
2014-03-01 15:54:01,802 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 1 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
returned: 2
2014-03-01 15:54:01,802 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 2 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
2014-03-01 15:54:01,802 TRACE o.s.cache.aspectj.AnnotationCacheAspect: 318 - Computed cache key 2 for operation CacheableOperation[public int MyTestServiceImpl.b(int)] caches=[testCache] | key='' | condition='' | unless=''
returned: 3
END: 1
This basically looks okay:
First call of a() takes 6 seconds, because b() gets called effectively 3 times.
Second call of a() takes 1ms, because everything comes from cache.
Return values are okay.
Questions:
Why are those TRACE logs Computed cache key x for operation ... there always two times? Looks to me like the computation method gets called twice?!
Is the configuration okay? Because I'm not really sure if this will always work as expected, especially because I had to use Project -> Clean and Tomcat -> Clean sometimes. (else it just ignored the @Cacheable annotation and simple called the method)
Thank you!
A:
First of all your current setup will never work with @EnableAspectJAutoProxy. Spring AOP uses proxies to apply aspects. Your @Scheduled calls the method internally and as such will never pass through the proxy and you will never have caching.
Next to that you use compile time weaving so you shouldn't use @EnableAspectJAutoProxy as the aspects are already weaved in. If that isn't working you have a problem in the setup of your pom together with your Eclipse.
Trying to get Eclipse and Maven working together is (or can be) a daunting task. Regarding AspectJ and Maven see aspectj-maven-plugin not covered by lifecycle in Kepler and this blog might also be helpful.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to select objects without UV maps
I am using Blender 2.80. I exported selected meshes to Substance Painter and got a warning that some objects has no UV maps.
Is there any quick way to see what objects have missing UV maps?
A:
I don't think there is a build in way, but you can run this script to select meshes with no UN layers:
import bpy
for obj in (o for o in bpy.data.objects if o.type == 'MESH'):
obj.select_set( len(obj.data.uv_layers) == 0 )
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Applying angular2 form directives to custom input form elements
I want to create a custom InputCustom component and use it to create model-driven forms.
My custom component just wraps an input field and uses Bootstrap material design for look'n'feel.
@Component({
selector:'inputCustom',
template:`
<div class="form-group label-floating is-empty">
<label class="control-label" for="input">Type here</label>
<input class="form-control" id="input" type="text">
<p class="help-block">Some help text</p>
<span class="material-input"></span>
</div>
`})
class InputCustom{....}
In Angular2 when you create a model-driven form
<form [ngFormModel]="formRef">
<input type ="email" ngControl="email">
</form>
all Controls present on form elements are registered into a ControlGroup. By using the formRef you can track field values inside controllers.
@Component({...})
class FormController{
formRef: ControlGroup;
constructor(...){
this.form.valueChanges.subscribe(data => console.log('changes', data));
}
}
Now, I want people to use my component like this
<form [ngFormModel]="formRef">
<inputCustom type ="email" ngControl="email">
</form>
Q1: Do I need write my own custom ngControl directive?
Q2: How to propagate ngControl to the inner <input> element wrapped by <inputCustom>?
Q3: How should I register my Control inside the surrounding forms ControlGroup?
A:
I see two ways to implement that:
Provide your control as parameter of your custom component:
@Component({
selector: 'inputCustom',
template: `
<input [ngFormControl]="control"/>
`
export class FormFieldComponent {
(...)
@Input()
control: Control;
}
This way your input will automatically takes part of the form defined in the parent component.
Implement an ngModel-compliant component. It's a bit longer to implement (you need to implement and register a ControlValueAccessor within a custom directive) but this way you will be able to use directly the ngFormControl and ngModel directly on your custom component.
<inputCustom type ="email" [ngFormControl]="email">
See this question for more details: Angular 2 custom form input
I think that this article could interest you:
Implementing Angular2 forms – Beyond basics (part 2) - http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error building Repository in a seprate project(library) within the same solution
So, I was following this Link
to learn and implement Repository pattern in my solution which consisted of a single project.
But my senior told me this is not the way we usually use and the repository is referenced from a different way(not withing the project). Using a class library, adding it to the solution and then referencing it.
When I tried doing it that way I am getting error.
Error Image
I had shifted my repository interface, class and UnitOfwork class to the library class within the same solution(As a different project)
I have even tried adding references to assembly using nuget
as shown in this question
Link
A:
And where is Your dbContext?
Check namespace of StudentsDemoEntities, and check if repository project referenced project with context.
Then add using statment for dbContext.
Edit
Your repository can't "see" dbContext.
Move Your context to repository project and this error will be resolved.
Remember about namespace!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mixing http and https in RestKit
I have an RestKit-enabled app which makes HTTP GET calls and should make HTTPS POST calls, to protect user data that otherwise would get sent unencrypted. As far as I know, it's possible to set the RestKit framework to either use unencrypted HTTP or SSL-encrypted HTTPS for the entire app by simply setting the base URL to the desired url.
In my case I need to have both. How can I switch between HTTP and HTTPS in RestKit? Is this even possible?
A:
You'll need to use two instances of the RKObjectManager - one for the HTTP GET calls and one for the HTTPS POST calls. Keep in mind to call each manager with the given name and not using [RKObjectManager sharedManager] any more because it's set to the first initialized RKObjectManager.
As an alternative you can set the Base URL of the given RKObjectManager before each GET/POST call.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
My program won't print my results
I recently wrote a brute force program to turn the octal data from permissions in Unix into the human readable form (e.g. 755 -> rwxr-xr-x) However whenever I run my program called myperm I don't get a result (e.g. ./myperm 755 -> nothing) and I'm not quite sure why can anyone help with this
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[])
{
if (argv[1] == "777")
{
printf("rwxrwxrwx");
}
else if (argv[1] == "755")
{
printf("rwxr-xr-x");
}
else if (argv[1] == "750")
{
printf("rwxr-x---");
}
else if (argv[1] == "700")
{
printf("rwxr-x---");
}
else if (argv[1] == "666")
{
printf("rw-rw-rw");
}
else if (argv[1] == "664")
{
printf("rw-rw-r--");
}
else if (argv[1] == "640")
{
printf("rw-r-----");
}
else if (argv[1] == "600")
{
printf("rw-------");
}
else if (argv[1] == "400")
{
printf("r--------");
}
return (0);
}
A:
Comparing strings in C doesn't work like this, you have to use strcmp
Instead of doing if (argv[1] == "XXX"), you should do if (strcmp(argv[1], "XXX") == 0)
Read on here
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Command line software to batch convert TIFF to indexable PDF
I need a utility to batch convert TIFF files to indexable PDF's. The software needs to run on linux and must work from the command line. The software does not need to be open source. I've tried the conversion using tesseract and hocr2pdf however they produce PDF's with garbled text (Note: the text is only garbled if you "select all" text in the PDF). I've found other utilities but they only run under Windows or don't work from the command line. Thanks in advance.
A:
After trying several tools (including Abbyy) I decided on: Vividata. They have decent pricing, run under Linux, and don't have a page per year limit.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add an Index to a list that resets depending on Id group
Given an object such as:
public class Test
{
public int Id { get; set;}
public int Field1 { get; set; }
public int Field2 { get; set; }
}
Which is populated like this:
List<Test> list = new List<Test>();
list.Add( new Test { Id = 1, field1 = 1});
list.Add( new Test { Id = 1, field1 = 2});
list.Add( new Test { Id = 2, field1 = 3});
list.Add( new Test { Id = 2, field1 = 4});
I can create an index column and iterate through the list:
var indexList = list.Select((t, i) => new {t, index = i}).ToList();
foreach (var t in indexList)
{
Console.WriteLine("ID: " + t.t.Id + " ---- Index:" + t.index);
}
And I get results like this:
ID: 1 ---- Index:0
ID: 1 ---- Index:1
ID: 2 ---- Index:2
ID: 2 ---- Index:3
What I really want to do is reset the index for each Id group so that I get output like this:
ID: 1 ---- Index:0
ID: 1 ---- Index:1
ID: 2 ---- Index:0
ID: 2 ---- Index:1
I've tried playing with GroupBy without much luck.
Can someone point me in the right direction please?
Thanks
A:
How about:
var indexList = list
.GroupBy(item => item.Id)
.SelectMany(grp => grp
.Select((item, index) => new { index = index, t = item }))
.ToList();
Example: http://ideone.com/nSTa8A
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как получить данные из SQlite по id?
Есть база данных SQLITE. Элементы базы данных выводятся в ListView.
Моя задача: в onItemClick перейти в другой активити, где выводятся все данные нажатого элемента ListView. Для этого передаю в новый активити через intent.putextra ID элемента.
Подскажите, как получить данные из базы данных с помощью ID?
package com.example.maxim.sqlite;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class Kontakt extends AppCompatActivity {
long DIFFICULTY_EASY;
TextView konname;
TextView konphone;
long userId;
SQLiteDatabase db;
String name;
int phone;
DatabaseHelper sqlHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kontakt);
//получаем строку и формируем имя ресурса
userId = getIntent().getLongExtra("id", DIFFICULTY_EASY);
Log.d("my","лог "+userId);
konname=(TextView)findViewById(R.id.konname);
konphone=(TextView)findViewById(R.id.konphone);
sqlHelper = new DatabaseHelper(getApplicationContext());
db = sqlHelper.getReadableDatabase();
String selection = "_id = ?";
String[] selectionArgs = new String[] {String.valueOf(userId)};
Cursor c = db.query("kontakts", null, selection, selectionArgs, null, null, null);
if(c.moveToFirst()){
name = c.getString(c.getColumnIndexOrThrow ("COLUMN_NAME"));
phone = c.getInt(c.getColumnIndexOrThrow ("COLUMN_PHONE"));
}
Log.d("my","лог "+name+phone);
}
}
A:
Можно использовать метод query или rawQuery. Ниже пример с использованием метода query.
Для этого сформируем параметры для него: название таблицы, а не имя БД как у вас в коде, массив столбцов для выгрузки, если нужны все то передаем null, условие по которому будет производится выборка, без ключевого слова WHERE, и, так как мы хотим избежать инъекций, параметры для условия отдельным массивом. Остальные параметры устанавливаем null, так как нам не важна сортировка, упорядочивание и т.д. Итого получается такой код:
String selection = "_id = ?";
String[] selectionArgs = new String[] {String.valueOf(id)};
Cursor c = db.query("TABLE_NAME", null, selection, selectionArgs, null, null, null);
if(c.moveToFirst()){
// достаем данные из курсора
}
Кстати хочу обратить внимание на то, что не надо делать два последовательных вызова методов moveToFirst() и moveToNext(), т.к. в этом случае будет пропущен первый элемент. Достаточно одного из них в зависимости от того, чего вы хотите - достать первый элемент, или пройтись по всему курсору.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Windows XP, Bluetooth, & accepting files
I've got a cell phone and hooked it up to my laptop running Windows XP. I can send files from my laptop to my phone and from my phone to my laptop just fine, but only one at a time. Questions:
How can I transfer more than 1 file at a time from Windows to my cell phone? I'm using whatever bluetooth client came with XP (SP 3)
How can I make XP accept files from my cell phone without having to click on "receive file" first? How can I receive more than one file at a time?
Because going on a trip (which I'm doing frequently at the moment) and transferring 30+ pictures one by one is a huge pain in the rear end.
A:
I got a laptop through work now that runs Windows 7. It works under Windows 7 just fine with the same bluetooth adapter. Problem solved.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Port blocking on iPhone 6
I am unable to get email to connect to my IMAP server using an iPhone 6+ with iOS 8.3.
The telco (Telstra Australia) loves telling me that they do not block ports.
Either the telco is blocking ports or the phone is blocking ports.
Can a hotspot connected computer route port 993 requests through the phone without blocking within the phone?
I have no trouble routing port 80, 443 requests through the phone as a modem, and also direct from Safari, however any other ports through Safari on the phone, or a hotspot connected computer fail to connect.
Is there a firewall on the iPhone that needs to be configured to allow additional ports through, and if so, how would it be configured.
If the phone is connected via wifi it has no issue connecting to any of the ports it needs to, it is only an issue when connecting over 3G/4G networks.
UPDATE This situation miraculously resolved itself. It seems the telco provider must have been blocking it, as it suddenly started working after months of not working without upgrading iOS, phone, or email systems. Because of this I can only presume the telco changed something.
A:
No, there is no default firewall on iOS so you don't need to configure anything to access port 993. If connectivity is working fine via wifi but not a cellular connection, everything points to your cellular provider blocking port 993.
Are you able to access your email from your phone via a 3G/4G connection? Or is it only a computer tethered to your phone that's not working?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Simple Username and Password logon Python 3
I wrote a simple login program using a user name and password. I am just learning the basics of Python so I thought this was an easy project to try.
The program runs just fine but I would like to know how an experienced programmer would improve it, purely for learning and understanding more.
usernames = ['jo'] ### open from file with open etc..
pwds = ['jo'] ### open from file with open etc..
adpwd = 'jobloggs'
attempts = 3
def username():
global attempts
if attempts == 0:
admin = input('Access locked, Enter admin password: ')
if admin == adpwd:
attempts = 3
elif admin != adpwd:
username()
x = input('User: ')
if x not in usernames and attempts <= 3:
print('User not recognised')
attempts -= 1
username()
elif x in usernames:
print('Hello', x)
pas = input('Password: ')
if pas in pwds:
run()
else:
print('Incorrect password')
username()
def run():
pass
username()
A:
About the reading of passwords, I didn't know you were using a database. I thought you had a file in which you store the passwords. You can store them as a json object, in which the keys are the usernames and the values are the passwords.
{
"jo": "jopwd"
}
You can then read the password table from disk using:
import json
with open('password_table.json', 'r') as f:
passwords = json.load(f)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to integral $\int_{\sqrt{a}}^{\infty}{ e^{-t^2+\beta t} \sin(\beta t)}~\mathrm{d}t$?
I would like to plot the following integral but it gives undefined. Please kindly help me about solving the following integral to plot :
$$
I(t)=\int_{\sqrt{a}}^{\infty}{ e^{-t^2+\beta t} \sin(\beta t)}~\mathrm{d}t
$$
where $a>0$, $\beta>0$.
Thanks!
A:
Possible solution:
Start by completing the square in the exponential part:
$$-t^2 + \beta t = -\left(t - \frac{\beta}{2}\right)^2 + \frac{\beta^2}{4}$$
So you have for the moment:
$$I(t) = \int_{\sqrt{\alpha}}^{+\infty} e^{-\left(t - \frac{\beta}{2}\right)^2 + \frac{\beta}{4}} \sin(\beta t)\ \text{d}t$$
Now operate the shift
$$t - \frac{\beta}{2} = y$$
so that $\text{d}y = \text{d}t$ and check the extrema of the integral. Taking out the exponential that does not depends upon $t$ and for the moment you got:
$$I(t) = e^{\frac{\beta^2}{4}}\ \int_{\sqrt{\alpha} - \frac{\beta}{2}}^{+\infty} e^{-y^2}\sin\left(\beta y - \frac{\beta^2}{2}\right)\ \text{d}y$$
At this point for the integration in $\text{d}y$ just use the exponential Sine form:
$$\sin\left(\beta y - \frac{\beta^2}{2}\right) \equiv \frac{e^{i\left(\beta y - \frac{\beta^2}{2}\right)} - e^{i\left(\beta y - \frac{\beta^2}{2}\right)}}{2i}$$
You obtain then:
$$I(t) = e^{\frac{\beta^2}{4}}\int_{\sqrt{\alpha}-\frac{\beta}{2}}^{+\infty} e^{-y^2}\left(\dfrac{e^{i\beta y - i\frac{\beta^2}{2}} - e^{-i\beta y + i\frac{\beta^2}{2}}}{2i}\right) \text{d} y$$
Now just take off to the integral those exponential in $\beta$ without any dependence upon $y$ and re-arrange the remaining terms. You will obtain:
(Split the two integrals)
$$I(t) = \dfrac{1}{2i}e^{\frac{\beta^2}{4}}e^{-i\frac{\beta^2}{2}}\int_{\sqrt{\alpha}-\frac{\beta}{2}}^{+\infty} e^{-y(y - i\beta)}\text{d} y - \dfrac{1}{2i}e^{\frac{\beta^2}{4}}e^{i\frac{\beta^2}{2}}\int_{\sqrt{\alpha}-\frac{\beta}{2}}^{+\infty} e^{-y(y + i\beta)}\text{d}y $$
To calculate them, we have another time to use the trick of the square completing: In the first integral we have:
$$-y^2 + i\beta y \equiv -\left(y - \frac{i\beta}{2}\right)^2 - \frac{\beta^2}{4}$$
and in the second one we have:
$$-y^2 - i\beta y \equiv -\left(y + \frac{i\beta}{2}\right)^2 - \frac{\beta^2}{4}$$
Use them, substitute and take out the independent part of the exponential and you will get:
$$I(t) = \dfrac{1}{2i}e^{\frac{\beta^2}{4}}e^{-\frac{\beta^2}{4}}\left[e^{-\frac{i\beta^2}{2}}\int_{\sqrt{\alpha}-\frac{\beta}{2}}^{+\infty}e^{-\left(y - \frac{i\beta}{2}\right)^2}\text{d}y - e^{\frac{i\beta^2}{2}}\int_{\sqrt{\alpha}-\frac{\beta}{2}}^{+\infty}e^{-\left(y + \frac{i\beta}{2}\right)^2}\text{d}y \right]$$
Now, if you are familiar with Special Functions you may know this fundamental special integral function:
$$\int_{a}^{+\infty} e^{-(x\pm b)^2}\text{d}x = \frac{\sqrt{\pi}}{2}\text{Erfc}[a \pm b]$$
Using this relation and you will easily integrate the two terms above, obtaining in the end:
$$
\boxed{I(t) = \dfrac{1}{2i}\left[e^{-\frac{i\beta^2}{2}} \dfrac{\sqrt{\pi}}{2}\text{Erfc}\left(\sqrt{\alpha} - \dfrac{\beta}{2} + i\dfrac{\beta}{2}\right) - e^{\frac{i\beta^2}{2}} \dfrac{\sqrt{\pi}}{2}\text{Erfc}\left(\sqrt{\alpha} - \dfrac{\beta}{2} - i\dfrac{\beta}{2}\right)\right]}
$$
Honestly, this result is clearly correct, modulo some signs errors or constants missed. Check the whole procedure please, because it is the way to come to the result, but in the very last passages there could be some missing constants.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to compress a few files to zip in Qt?
I need to zip a few files in Qt. I am trying Quazip. But the zip file contains files with 0kb size. Something goes wrong. Can somebody help me out here!
The code for zipping is given here:
QString testZip = location + "/tempTheme/test.zip";
QuaZip zip(testZip);
zip.setFileNameCodec("IBM866");
if(!zip.open(QuaZip::mdCreate)) {
qWarning("testCreate(): zip.open(): %d", zip.getZipError());
}
zip.setComment("Test comment");
QFileInfoList files=QDir(location + "/tempTheme/").entryInfoList();
QFile inFile;
QuaZipFile outFile(&zip);
char c;
foreach(QFileInfo file, files) {
if(!file.isFile()||file.fileName()=="test.zip") continue;
inFile.setFileName(file.fileName());
if(!inFile.open(QIODevice::ReadOnly)) {
qWarning("testCreate(): inFile.open(): %s", inFile.errorString().toLocal8Bit().constData());
}
if(!outFile.open(QIODevice::WriteOnly, QuaZipNewInfo(inFile.fileName(), inFile.fileName()))) {
qWarning("testCreate(): outFile.open(): %d", outFile.getZipError());
}
while(inFile.getChar(&c)&&outFile.putChar(c));
if(outFile.getZipError()!=UNZ_OK) {
qWarning("testCreate(): outFile.putChar(): %d", outFile.getZipError());
}
outFile.close();
if(outFile.getZipError()!=UNZ_OK) {
qWarning("testCreate(): outFile.close(): %d", outFile.getZipError());
}
inFile.close();
}
zip.close();
if(zip.getZipError()!=0) {
qWarning("testCreate(): zip.close(): %d", zip.getZipError());
QMessageBox msgInfo;
msgInfo.information(this, "blah", "done");
}
A:
If this project is just a toy, character-at-a-time is probably fine, but I can't imagine adding one million characters one-at-a-time to a zip file manager would be very efficient. And a one megabyte file looks mighty small these days. So hunt around the QuaZip API for mechanisms to either add files directly to the zip, or at least large buffers of data at a time. (Qt's buffering saves system calls but one million function calls working on one character vs 128 function calls working with 8k buffers is going to be noticeable in most programs.)
A:
I got the answer, I need to make changes as following,
QString testZip = location + "/test.zip";
QuaZip zip(testZip);
zip.setFileNameCodec("IBM866");
if(!zip.open(QuaZip::mdCreate)) {
qWarning("testCreate(): zip.open(): %d", zip.getZipError());
}
//zip.setComment("Test comment");
QFileInfoList files=QDir(location + "/tempTheme/").entryInfoList();
QFile inFile;
QFile inFileTmp;
QuaZipFile outFile(&zip);
char c;
foreach(QFileInfo file, files) {
if(!file.isFile()) continue;
inFileTmp.setFileName(file.fileName());
inFile.setFileName(file.filePath());
if(!inFile.open(QIODevice::ReadOnly)) {
qWarning("testCreate(): inFile.open(): %s", inFile.errorString().toLocal8Bit().constData());
}
if(!outFile.open(QIODevice::WriteOnly, QuaZipNewInfo(inFileTmp.fileName(), inFile.fileName()))) {
qWarning("testCreate(): outFile.open(): %d", outFile.getZipError());
}
while(inFile.getChar(&c)&&outFile.putChar(c));
if(outFile.getZipError()!=UNZ_OK) {
qWarning("testCreate(): outFile.putChar(): %d", outFile.getZipError());
}
outFile.close();
if(outFile.getZipError()!=UNZ_OK) {
qWarning("testCreate(): outFile.close(): %d", outFile.getZipError());
}
inFile.close();
}
zip.close();
if(zip.getZipError()!=0) {
qWarning("testCreate(): zip.close(): %d", zip.getZipError());
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java tiled based rendering, possible to move the already painted?
So if I don't clear my painting area it will just paint over there I paint and leave the other parts there I haven't painted as the old was. So can I take what's already is painted and move it to the left for example. So I can fit an new set of tiles on the right without needing to repaint all of it?
Or am I getting at this at the wrong angle?
A:
You can do what you're describing but there's no point to it that I can think of. Rendering part of the screen after some offset will yield no real improvement.
I'll assume you're trying to do this for faster rendering.
Most games do 2 things for faster tiled rendering.
Clipping. Don't render what's offscreen. Don't render what's underneath other opaque tiles if you're rendering 2.5D.
Rendering sections of your map to bigger images, then render these bigger images instead of each tile image individually.
The second is more difficult, and has limitations. For example, you'd need to rerender the larger images if your tile content changes. This would probably get you the most improvement.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Correct vertex normals on a heightmapped geodesic sphere
Have generated a geodesic sphere, and am using perlin noise to generate hills etc. Will be looking into using the tessalation shader to divide further. However, I'm using normal mapping, and to do this I am generating tangents and bitangents in the following code:
//Calulate the tangents
deltaPos1 = v1 - v0;
deltaPos2 = v2 - v0;
deltaUV1 = t1 - t0;
deltaUV2 = t2 - t0;
float r = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x);
tangent = (deltaPos1 * deltaUV2.y - deltaPos2 * deltaUV1.y) * r;
bitangent = (deltaPos2 * deltaUV1.x - deltaPos1 * deltaUV2.x) * r;
Before I was using height mapping, the normals on a sphere are simple.
normal = normalize(point-origin);
But obviously this is very different once you involve a height map. I'm currently crossing the tangent and bitangent in the shader to figure out the normal, but this is produces some weird results
mat3 normalMat = transpose(inverse(mat3(transform)));
//vec3 T = normalize(vec3(transform*tangent));
vec3 T = normalize(vec3(normalMat * tangent.xyz));
vec3 B = normalize(vec3(normalMat * bitangent.xyz));
vec3 N = normalize(cross(T, B));
//old normal line here
//vec3 N = normalize(vec3(normalMat * vec4(normal, 0.0).xyz));
TBN = mat3(T, B, N);
outputVertex.TBN = TBN;
However this produces results looking like this:
What is it I'm doing wrong?
Thanks
Edit-
Have reverted back to not doing any height mapping. This is simply the earth projected onto a geodesic sphere, with a specular and normal map. You can see I'm getting weird lighting across all of the triangles, especially where the angle of the light is steeper (so naturally the tile would be darker). I should note that I'm not indexing the triangles at all at the moment, I've read somewhere that my tangents and bitangents should be averages of all the similar points, not quite understanding what this would achieve or how to do that. Is that something I need to be looking into?
I have also reverted to using the original normals normalize(point-origin) for this example too, meaning my TBN matrix calcs look like
mat3 normalMat = transpose(inverse(mat3(transform)));
vec3 T = normalize(vec3(transform * tangent));
vec3 B = normalize(vec3(transform * bitangent));
vec3 N = normalize(vec3(normalMat * vec4(normal, 0.0).xyz));
TBN = mat3(T, B, N);
outputVertex.TBN = TBN;
The cube is just my "player", I use it just to help with lighting etc and seeing where the camera is. Also note that removing the normal mapping completely and just using the input normals fixes the lighting.
Thanks guys.
A:
The (second) problem was indeed fixed by indexing out all my points, and averaging the results of the tangents and bitangents. This led to the fixing of the first problem, which was indirectly caused by the bad tangents and bitangents.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rserve - Multiple instances on one server?
Is it possible to run multiple instances of Rserve on one server at the same time?
For example 10 instances meaning 10 separate R workspaces listening on different ports via Rserve on the same machine?
A:
In the same document specified by @Oleksandr, it clearly states on page 5-6, that in Windows, there is an alternative solution:
Don't run 1 Rserve process, but start multiple Rserve processes, each on a different port (which can be easily specified in the rserve command). Each Rserve process has its own environement.
Connect 1 thread of your application with 1 unique Rserve connection: Then you can exploit parallellism from within your application.
So the answer to your question is: Yes, you can.
I've tested this with a C# application, and it works.
You can use libraries like this: https://github.com/kent37/RserveCLI2
EDIT August 4 2015:
We are now effectively using this in a (windows) production application, namely calling the R code from a C# codebase do to the statistical analysis. We use RServe and RServeCLI for connecting and communication between the 2 codebases. To implement this in a structured manner, we used this pattern for pooled resources. Hope this helps.
A:
Answer is yes, if it is Unix/Linux.
Answer is no, if it is Windows.
More can be found here http://www.ci.tuwien.ac.at/Conferences/DSC-2003/Proceedings/Urbanek.pdf, page 2 says it explicitly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What populates this array list?
My array list somehow becomes populated.
Look at this code:
final ListView list = getListView();
boolean threadNeeded = true;
//settings
list.setItemsCanFocus(false);
Bundle extras = getIntent().getExtras();
allFriends = getIntent().getParcelableExtra("shibby.whisper.allFriends");
selectedFriends = getIntent().getParcelableExtra("shibby.whisper.selectedFriends");
System.out.println("JUST ENTERED ACTIVITY : "+selectedFriends.getPositions());
if(extras !=null) {
maxPlayers = extras.getInt("max_players");
}
if(allFriends != null){
if(!allFriends.getIds().isEmpty()){
threadNeeded = false;
}
}
if(selectedFriends == null){
System.out.println("selectedFriends is null before callback from ListActivity");
selectedFriends = new PlayerList();
}
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FacebookFriendsAdapter a = (FacebookFriendsAdapter) list.getAdapter();
//select item
boolean isSelected = a.toggleSelected(new Integer(position));
//if reached maximum players and have selected a new user
if(((maxPlayers+1 == a.getMaxPlayersCounter() && maxPlayers != 0) && isSelected)
|| (maxPlayers == 0 && a.getMaxPlayersCounter() == maxAvailablePlayers+1)){
Log.e("addfriends","Max Players Reached");
a.toggleSelected(new Integer(position));
final Dialog dialog = new Dialog(FacebookFriendsListActivity.this, R.style.CustomDialogTheme );
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.maxplayers);
dialog.setCancelable(true);
// set the custom dialog components - text, image and button
Button dialogButton = (Button) dialog.findViewById(R.id.max_players_dismiss_btn);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
});
m_friends = new ArrayList<Player>();
this.m_adapter = new FacebookFriendsAdapter(this, R.layout.facebbok_friends_item, m_friends);
//set the selected friends on the adapter to remember earlier picks
if(selectedFriends != null){
oldPositions = selectedFriends.getPositions();
m_adapter.setSelectedIds(selectedFriends.getPositions());
m_adapter.setMaxPlayersCounter(selectedFriends.getIds().size());
System.out.println("Max player selected Is : "+maxPlayers+" And Selected Players Counter Is :" +m_adapter.getMaxPlayersCounter());
}
When the activity starts, the selectedFriends.getPosition() returns empty.
When I click a button I do this action:
if(oldPositions != null){
System.out.println("This is old positions : " + oldPositions);
}
Which is populated (by the new position), but I don't see why. Am I referencing something I shouldn't? Do I override the data in memory?
EDIT : This happens after I select some friends from the ListView. toggleSelected() adds or removes item from an inner ArrayList.
A:
I think your mistake is assuming that this line makes a copy of whatever getPositions return:
oldPositions = selectedFriends.getPositions();
Actually it only makes a copy of the reference - it doesn't make a shallow copy of the entire list.
You probably want something like this (I'm just guessing the type):
oldPositions = new ArrayList<Position>(selectedFriends.getPositions());
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Run 2 seperate IIS sites, with seperate SSL certificates on same server
I am trying to setup 2 completely separate IIS sites on a single server (single IP address) that will both use different DNS entries but the same port (443) to access the site over SSL. For example,
Site 1: www.application.subdomain.domain1.uk
Site 2: www.application.subdomain.domain2.uk
We already have certificates for each of the above sites and I can't seem to get this to work.
I am running Server 2008 with IIS7 and but the host header property is greyed out in IIS so I can't add this in.
Is this possible to achieve? I might be missing something very simple here but just can't see it.
A:
To my knowlege not possible due to security constraints - you need two ip addresses. IIS tries to fowward the request to the proper sub-instance BEFORE decoding it, and it can thus not evaluate the host header via https.
So, for SSL you need multiple ip addresses.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Bokeh: linking a line plot and a scatter plot
I have a line plot and a scatter plot that are conceptually linked by sample IDs, i.e. each dot on the 2D scatter plot corresponds to a line on the line plot.
While I have done linked plotting before using scatter plots, I have not seen examples of this for the situation above - where I select dots and thus selectively view lines.
Is it possible to link dots on a scatter plot to a line on a line plot? If so, is there an example implementation available online?
Searching the web for bokeh link line and scatter plot yields no examples online, as of 14 August 2018.
A:
As things turn out, I was able to make this happen by using HoloViews rather than Bokeh. The relevant example for making this work comes from the Selection1d tap stream.
http://holoviews.org/reference/streams/bokeh/Selection1D_tap.html#selection1d-tap
I will do an annotated version of the example below.
First, we begin with imports. (Note: all of this assumes work is being done in the Jupyter notebook.)
import numpy as np
import holoviews as hv
from holoviews.streams import Selection1D
from scipy import stats
hv.extension('bokeh')
First off, we set some styling options for the charts. In my experience, I usually build the chart before styling it, though.
%%opts Scatter [color_index=2 tools=['tap', 'hover'] width=600] {+framewise} (marker='triangle' cmap='Set1' size=10)
%%opts Overlay [toolbar='above' legend_position='right'] Curve (line_color='black') {+framewise}
This function below generates data.
def gen_samples(N, corr=0.8):
xx = np.array([-0.51, 51.2])
yy = np.array([0.33, 51.6])
means = [xx.mean(), yy.mean()]
stds = [xx.std() / 3, yy.std() / 3]
covs = [[stds[0]**2 , stds[0]*stds[1]*corr],
[stds[0]*stds[1]*corr, stds[1]**2]]
return np.random.multivariate_normal(means, covs, N)
data = [('Week %d' % (i%10), np.random.rand(), chr(65+np.random.randint(5)), i) for i in range(100)]
sample_data = hv.NdOverlay({i: hv.Points(gen_samples(np.random.randint(1000, 5000), r2))
for _, r2, _, i in data})
The real magic begins here. First off, we set up a scatterplot using the hv.Scatter object.
points = hv.Scatter(data, ['Date', 'r2'], ['block', 'id']).redim.range(r2=(0., 1))
Then, we create a Selection1D stream. It pulls in points from the points object.
stream = Selection1D(source=points)
We then create a function to display the regression plot on the right. There's an empty plot that is the "default", and then there's a callback that hv.DynamicMap calls on.
empty = (hv.Points(np.random.rand(0, 2)) * hv.Curve(np.random.rand(0, 2))).relabel('No selection')
def regression(index):
if not index:
return empty
scatter = sample_data[index[0]]
xs, ys = scatter['x'], scatter['y']
slope, intercep, rval, pval, std = stats.linregress(xs, ys)
xs = np.linspace(*scatter.range(0)+(2,))
reg = slope*xs+intercep
return (scatter * hv.Curve((xs, reg))).relabel('r2: %.3f' % slope)
Now, we create the DynamicMap which dynamically loads the regression curve data.
reg = hv.DynamicMap(regression, kdims=[], streams=[stream])
# Ignoring annotation for average - it is not relevant here.
average = hv.Curve(points, 'Date', 'r2').aggregate(function=np.mean)
Finally, we display the plots.
points * average + reg
The most important thing I learned from building this is that the indices for the points have to be lined up with the indices for the regression curves.
I hope this helps others building awesome viz using HoloViews!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"Закон сохранения энергии". Нужны ли кавычки?
Фраза такая: "В фильме это называют "закон сохранения энергии". Я написал "закон..." в кавычках. Но, с другой стороны, данный закон, точнее, его формулировка в кавычки не берется. Так вот, нужны ли они тут?
A:
В такой формулировке, возможно, кавычки и нужны, ибо здесь предполагается или допускается использование как своего рода имени собственного. Но тогда и писать "Закон" стоит с заглавной.
В нормальной же, не акцентированной фразе было бы, имхо, "В фильме это называют законом сохранения энергии" - тут уж ни о каких кавычках речи не идет.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reserving space with fseek safe?
If you can guarantee that there is data to be written after seeking, is it safe to use fseek to reserve bytes at the beginning of a file? For example:
// reserve space
fseek(f, 4096, SEEK_SET);
// ...
// write some data after the reserved space
fwrite(buf, 1, bufsize, f);
// go back to the reserved space (to update it)
rewind(f);
// ...
I noticed it works on Windows, but what about other platforms? Are there any gotchas to look out for?
A:
Yes, this works fine. As long as you've opened the file in w or w+ mode, rather than a or a+, you can seek to any point in the file and write there, and it will write at that point in the file. Other parts of the file will be left unchanged; if they were never written, they'll contain zero bytes.
So if you do the following on a file that was just opened in w mode (which truncates the file first):
fseek(f, 10, SEEK_SET);
fwrite("abc", 1, 3, f);
rewind(f);
fwrite("1234567890", 1, 10, f);
the contents of the file will be:
1234567890abc
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP Sessions, issue with printing session information
I've written a bit of code to upload a file to a server. When the file is successful I made my code go to another web page. On this web page I want to print the file properties which were gained from the previous page so I am using Sessions in PHP.
//Starts up a new PHP session
session_start();
$_SESSION['file']=$_FILES["file"];
$_SESSION['name']=$_FILES['name'];
$_SESSION['type']=$_FILES['type'];
$_SESSION['size']=$_FILES['size'];
$_SESSION['tmp_name']=$_FILES['tmp_name'];
That is my session on page1. Then, when the file is successful, I send the user to page2.
header( 'Location: page2' ) ;
Now, on page2, I have this right at the top of my .php page:
<?php
//Starting session
session_start();
?>
Then, further down for me to be able to print each variable out I've got:
<?php
Print_r ($_SESSION['file']);
?>
I get all my information all jumbled into a long sentence when this is done. I want to have control over the information and print it nice and neatly. What am I doing wrong? I've researched into loads of different ways of doing this and nothing has helped so far.
Tried that, also tried just printing SESSION, also tried echoing each one seperately with the words [Array] being printed only.
Thanks in advance!
A:
Use two dimensional array like below
$_SESSION['upload1']['file']=$_FILES["file"];
$_SESSION['upload1']['name']=$_FILES['name'];
$_SESSION['upload1']['type']=$_FILES['type'];
$_SESSION['upload1']['size']=$_FILES['size'];
$_SESSION['upload1']['tmp_name']=$_FILES['tmp_name'];
on file2.php
<?php
print "<pre>";
print_r($_SESSION['upload1']);
print "</pre>";
?>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reference request: proof that if $L \in DCFL$, then $L \Sigma^* \in DCFL$
So, it's fairly easy to prove that if $L \in DCFL$, then $L \Sigma^* \in DCFL$. Basically, you take the DPDA accepting $L$. You remove all transitions on final states, and then for each $a \in \Sigma$ and each final state $q$, you add a transition looping from $q$ to $q$ on $a$.
I'm using this in a paper, and I'd love to not have to actually prove this construction is valid. It's easy, but it's about a half-page long. Since DPDAs have been studied almost exhaustively, I was wondering, does anybody know of a paper that proves this property?
A:
One of the early works on DCFL is Seymour Ginsburg, Sheila Greibach: Deterministic context free languages, Information and Control, Volume 9, Issue 6, December 1966, Pages 620–648, doi:10.1016/S0019-9958(66)80019-0
The paper has various closure properties, for instance closure under complement (mind that my old Hopcroft and Ullman book states ".. was observed independently by various people") and closure under quotient with regular languages.
Closure of DCFL under concatenation with regular languages is the result you need, which is Theorem 3.3 from the paper.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Simultaneous resolutions and deformations of simple singularities
Let $X\to \Delta$ be a flat family of complex surfaces with at most a finite number of singularities of simple type, where $\Delta$ is a complex domain in $\mathbb C$.
Here simple type means rational double point.
By a result of Tyurina, it is know that such deformations admit locally simultaneous resolutions after passing to a sufficiently high ramified cover of the base.
Conversely if $Y\to\Delta$ is a smooth family of complex surfaces and the central fiber $Y_0$ is the minimal resolution $Y_0\to X_0$ of a complex surface with a finite number of simple singularities, can we say that $Y\to \Delta$ must be (locally) a simultaneous resolution of some flat deformation of $X_0$ ?
I guess this boils down to ask whether it is possible to contract the exceptional curves of $Y_0$ within the family $Y\to\Delta$...
A:
If I understand your question, the answer is no.
You can consider any surface $X_0$ which does not admit a global smoothing. Let $Y_0\to X_0$ be the minimal resolution and consider a family $Y\to \Delta$ such that the general fiber does not admit any curve with negative self-intersection.
A:
I think that the paper Burns-Wahl "Local contributions... " gives some of the examples you are looking for.
(sorry I just wanted to add a comment above, but I am not sure how to do it).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTML5 web app bypass browser permissions for local caching in ALL MAJOR browsers (Safari/Firefox/Opera/Chrome/IE)?
I have been playing around with the HTML5 offline application cache,
running boundary tests to study browser behaviour in edge cases, specifically to find out about the cache quota.
So what I did is to generate and serve an offline app manifest and add 300 5MB JPEG files to the cache.
public ActionResult Manifest()
{
var cacheResources = new List<string>();
var n = 300;
for (var i = 0; i < n; i++)
cacheResources.Add("Content/" + Url.Content("collage.jpeg?" + i));
var manifestResult = new ManifestResult("1")
{
NetworkResources = new string[] { "*" },
CacheResources = cacheResources
};
return manifestResult;
}
In the beginning, I adding 1000 JPEG files to the cache, Chrome threw an error:
it failed to commit the new cache to the storage due to quota exceeded.
I managed to get the right number by slowly reducing the number of images i uploaded,
I could add 300 JPEG files to the cache without crashing it
Investigating chrome://appcache-internals/, I was shocked to see that for
one single web application, there is a huge cache of 2.3GB!!
It's really odd to find that the website I visited is downloading
so much data in the background, and as a user it can get quite
disturbing. Chrome, the (17.0.963.83), desktop browser of choice at that moment
didnt warn me or ask my permission that the site wanted to download and cache
so much data on my local storage! It's quite outrageous.
Because of the aforementioned behaviour about the browser-wide
quota being exceeded, sites stop committing data to the application cache.
Is there a way for the browser to keep track of all these in a more organized
manner? Currently, the 'first browsed, first reserved' is quite annoying. My experience
to resolve this case is to use the applicationCache API to
listen for quota errors, and inform the user to browse to
chrome://appcache-internals/ and remove other caches over
the new one.
A:
Have a look at this whitepaper for more information on how Chrome deals with local storage: https://developers.google.com/chrome/whitepapers/storage
Temporary storage is limited to 20% of the total pool per app, and the total pool is limited to 50% of the available disk space so Chrome can never fill a disk. As you add more files to your local disk, Chrome will shrink the total allocated to the temporary storage pool accordingly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
displaying an image in ASP.NET
How to an image which is retrieved from MYSQL database.
To display a text in textbox we use textbox.TEXT --> We use .TEXT to display text
Likewise how to display an Image retrieved from MYSQL database??
Image1.[___] = dr[0].[_____];
What to be filled in the above blanks??...
I used blob to store image.
A:
Add a Generic Handler to your Web Forms application and in the ProcessRequest method, you need to query the database for the relevant file/binary data. You would pick the right image via a querystring, usually. The following code shows how you can query the database and return the binary data:
using (DbConnection conn = new DbConnection(connect))
{
if (context.Request.QueryString["id"] != null)
{
DbCommand cmd = new DbCommand(qry, conn);
cmd.Parameters.AddWithValue("", context.Request.QueryString["id"]);
conn.Open();
using (DbDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
context.Response.AddHeader("content-disposition", "attachment; filename=" + rdr["FileName"]);
context.Response.ContentType = rdr["MimeType"].ToString();
context.Response.BinaryWrite((byte[])rdr["Blob"]);
}
}
}
}
You need to change the DbConnection, DbCommand and DbDataReader to the type that your provider likes (Odbc or MySql) and then point the ImageUrl property of your Image control to the HttpHandler:
Image1.ImageUrl = "MyHandler.ashx?id=" + whatever the image id is.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to improve auc of a classifier?
I have a data set with binary imbalanced class problem. Only 12% of the records belong to positive class. The auc of the original dataset for many classifiers were around 0.6 or less. So I applied minority class oversampling techniques and majority class under sampling techniques and re evaluated. But the classifer auc is not improving more than 0.63. Why is this? How can I fix this? I even checked if there are duplicate records with opposite classes, but none.
Following is the output
a b <-- classified as
4179 1502 | a = no
469 373 | b = yes
Correct..69.78384179058715
Incorrect % = 30.216158209412846
AUC = 0.6360277685212323
A:
Based on your confusion matrix, there does still seem to be a problem to be fixed as your errors are not symmetric. The first thing to do is look at your learning curves to be sure you aren't over fitting. Over sampling has a strong possibility to over fit with many machine learning algorithms. Depending on the ML algorithm, over sampling can teach the method "class b looks exactly like this but class a can be lots of things". Imaging as an extreme example, a Radial Basis Function SVM classifier with over sampled data. That function could make gamma really, really high making it so that the features of your new data point have to be practically identical to be classified correctly. Still, since there is over sampling and the same data may be in both your training and your test set for validation, the machine could still get perfect accuracy in validation, even though it won't generalize at all.
One possible alternative (depending on your classification technique) is to use class weights instead using sampling techniques. Adding a greater penalty to misclassifying your under represented class can reduce bias without "over training" on the under-represented class samples.
Another option could be leaving the samples alone changing your optimization metric to something not strongly effected by class bias like AUC or the Kappa statistic.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
file download permission denied to read the file
I am using php readfile function to ignore giving full direct url of the file on server. However it displays error only instead of downloading the file, stating failed to open stream: No such file or directory in However the file is in the specified directory.
The file I am trying to download is uploaded by user (i.e. httpd process i think, which will be owner). However the following code says unable to open the file -
$full_path = $row['full_path'];
$file_name = $row['file_path'];
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Type: application/pdf');
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"".$file_name."\"");
readfile($full_path);
Default permissions set for the directory as 755 and the file which I am downloading also shows permissions as 755. i am unable to understand whats the issue here.
EDIT: Server is hostgator.
EDIT: header("Location: $full_path") works fine, so I don't think its related to path.
EDIT: $full_path looks like - uploads/abc.pdf while $file_path looks like abc.pdf
File structure:
--root
downloader.php
---uploads
abc.pdf
A:
Seeing that my comments to the OP did solve this one...
Me:
"what does var_dump(); reveal? make sure there's no whitespace introduced anywhere also. I'm kind of baffled at this point. Fred -ii-"
OP:
"WTF, there was a whitespace at the end in the string. I am really sorry for this, I never checked for that. Thanks to all of you guys... – codeomnitrix"
Me:
trim() would have fixed that in a jiffy
Consult: http://php.net/manual/en/function.trim.php
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Big O of this code
I am doing the exercise of Skiena's book on algorithms and I am stuck in this question:
I need to calculate the big O of the following algorithm:
function mystery()
r=0
for i=1 to n-1 do
for j=i+1 to n do
for k=1 to j do
r=r+1
Here, the big O of the outermost loop will be O(n-1) and the middle loop will be O(n!). Please tell me if I am wrong here.
I am not able to calculate the big O of the innermost loop.
Can anyone please help me with this?
A:
Here's a more rigorous way to approach solving this problem:
Define the run-time of the algorithm to be f(n) since n is our only input. The outer loop tells us this
f(n) = Sum(g(i,n), 1, n-1)
where Sum(expression, min, max) is the sum of expression from i = min to i = max. Notice that, the expression in this case is an evaluation of g(i, n) with a fixed i (the summation index) and n (the input to f(n)). And we can peel another layer and defineg(i, n):
g(i, n) = Sum(h(j), i+1, n), where i < n
which is the sum of h(j) where j ranges of i+1 to n. Finally we can just define
h(j) = Sum(O(1), 1, j)
since we've assumed that r = r+1 takes time O(1).
Notice at this point that we haven't done any hand-waving, saying stuff like "oh you can just multiply the loops together. The 'innermost operation' is the only one that counts." That statement isn't even true for all algorithms. Here's an example:
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Solve_An_NP_Complete_Problem(n);
for (k = 0; k < n; k++)
{
count++;
}
}
}
The above algorithm isn't O(n^3)... it's not even polynomial.
Anyways, now that I've established the superiority of a rigorous evaluation (:D) we need to work our way upwards so we can figure out what the upper bound is for f(n). First, it's easy to see that h(j) is O(j) (just use the definition of Big-Oh). From that we can now rewrite g(i, n) as:
g(i, n) = Sum(O(j), i+1, n)
=> g(i, n) = O(i+1) + O(i+2) + ... O(n-1) + O(n)
=> g(i, n) = O(n^2 - i^2 - 2i - 1) (because we can sum Big-Oh functions
in this way using lemmas based on
the definition of Big-Oh)
=> g(i, n) = O(n^2) (because g(i, n) is only defined for i < n. Also, note
that before this step we had a Theta bound, which is
stronger!)
And so we can rewrite f(n) as:
f(n) = Sum(O(n^2), 1, n-1)
=> f(n) = (n-1)*O(n^2)
=> f(n) = O(n^3)
You might consider proving the lower bound to show that f(n) = Theta(n^3). The trick there is note simplifying g(i, n) = O(n^2) but keeping the tight bound when computing f(n). It requires some ugly algebra, but I'm pretty sure (i.e. I haven't actually done it) that you will be able to prove f(n) = Omega(n^3) as well (or just Theta(n^3) directly if you're really meticulous).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Group by based on a value of a column
i have the following DataFrame:
it contains user_ids, tweets, and the classification of the tweet as negative and positive.
i want to create a new dataframe that has the following columns:
user_id
count of negative tweets by that user_id
count of positive tweets by that user_id
Thanks
A:
Try this:
df.groupby(['user_id','classification'])['user_id'].count()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Where does PHP Output go on MAMP
I'm running a MAMP server and printing data with the echo command in PHP to debug my scripts. I'm looking for where the log that contains this output would be located. It doesn't appear to be in the Apache access log or the PHP error log, so I'm not sure where else to look. Thanks!
A:
As others pointed out, echo goes to the browser. MAMP outputs PHP errors to /Applications/MAMP/logs/php_error.log. The function you're looking for is error_log('message').
If we don't set the message_type or the destination, the
message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to.
Here's a helper function I use.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compare two large dataframes using pyspark
I am currently working on a data migration assignment, trying to compare two dataframes from two different databases using pyspark to find out the differences between two dataframes and record the results in a csv file as part of data validation. I am trying for a performance efficient solution since there are two reasons.i.e. large dataframes and table keys are unknown
#Approach 1 - Not sure about the performance and it is case-sensitive
df1.subtract(df2)
#Approach 2 - Creating row hash for each row in dataframe
piperdd=df1.rdd.map(lambda x: hash(x))
r=row("h_cd")
df1_new=piperdd.map(r).toDF()
The problem which I am facing in approach 2 is final dataframe(df1_new) is retrieving only hash column(h_cd) but I need all the columns of dataframe1(df1) with hash code column(h_cd) since I need to report the row difference in a csv file.Please help
A:
Have a try with dataframes, it should be more concise.
df1 = spark.createDataFrame([(a, a*2, a+3) for a in range(10)], "A B C".split(' '))
#df1.show()
from pyspark.sql.functions import hash
df1.withColumn('hash_value', hash('A','B', 'C')).show()
+---+---+---+-----------+
| A| B| C| hash_value|
+---+---+---+-----------+
| 0| 0| 3| 1074520899|
| 1| 2| 4|-2073566230|
| 2| 4| 5| 2060637564|
| 3| 6| 6|-1286214988|
| 4| 8| 7|-1485932991|
| 5| 10| 8| 2099126539|
| 6| 12| 9| -558961891|
| 7| 14| 10| 1692668950|
| 8| 16| 11| 708810699|
| 9| 18| 12| -11251958|
+---+---+---+-----------+
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to efficiently make the function pointer in the java class?
While coding in Java programming, I have a question as below.
Below is c++ code. As you know, variable Alpha in the SomParam class is function pointer. When the user set the function address to the Alpha in the constructor, then the variable Alpha executes the current functions.
double lin_alpha(double alpha_0, int t, Subscript rlen, double) {
return alpha_0 * (1.0 - (double) t / rlen);
}
double inv_alpha(double alpha_0, int t, Subscript rlen, double C) {
//double C = rlen / INV_ALPHA_CONST;
return alpha_0 * C / (C + t);
}
#define LIN_ALPHA 1
#define INV_ALPHA 2
class SomParam{
public:
typedef double Alpha(double, int, int, double);
protected:
Alpha *_alpha;
int _xdim;
int _ydim;
public:
SomParam(int AlphaType,int xdim, int ydim) {
if (AlphaType == LIN_ALPHA) _alpha = lin_alpha;
else _alpha = lin_alpha;
_xdim = xdim;
_ydim = ydim;
}
My question is that I want to know how to convert the above codes into Java version. Since Java has no pointer concept, I had a hard time converting it into Java version. I've known that interface might be able to replace the function pointer in Java but I couldn't apply it to my code.
How to convert the above one into java version?
Ps. I hope that you should not using the lambda expression since I am using the Java 7.
A:
I would suggest creating a strategy pattern enum implementing the two functions and passing that directly into your constructor:
public enum AlphaType {
LIN_ALPHA {
@Override
public double compute(double alpha_0, int t, Subscript rlen, double C) {
// FIXME t / rlen isn't valid in Java
return alpha_0 * (1.0 - (double) t / rlen);
}
},
INV_ALPHA {
@Override
public double compute(double alpha_0, int t, Subscript rlen, double C) {
//double C = rlen / INV_ALPHA_CONST;
return alpha_0 * C / (C + t);
}
};
public abstract double compute(double alpha_0, int t, Subscript rlen, double C);
}
A:
The best way to do this is with Java 8 lambda expressions. But since you want to avoid those, here is a rough translation of your C++ code into Java 7.
I've used a static inner interface to represent the type of the function pointers, and instances of anonymous implementations of this interface to represent the functions themselves. In my opinion, this is better than using an enum, because it doesn't imply any relationship between the various functions, other than that they have the same signature.
I've set this all up with constants, and shown how to select which of the constant values is appropriate to store in the object that you're instantiating. I've taken a few liberties with data types and so on.
public class AlphaAdjuster {
private static interface AlphaCalculator {
double calculate(double alpha0, int t, int rlen, double c);
}
public static final int LIN_ALPHA = 1;
public static final int INV_ALPHA = 2;
private static final AlphaCalculator LIN_ALPHA_CALCULATOR = new AlphaCalculator(){
@Override
public double calculate(double alpha0, int t, int rlen, double c) {
return alpha0 * (1.0 - (double) t / rlen);
}};
private static final AlphaCalculator INV_ALPHA_CALCULATOR = new AlphaCalculator(){
@Override
public double calculate(double alpha0, int t, int rlen, double c) {
return alpha0 * c / (c + t);
}};
private AlphaCalculator calculator;
private int xDim;
private int yDim;
public AlphaAdjuster(int alphaType, int xDim, int yDim) {
if (alphaType == LIN_ALPHA) {
calculator = LIN_ALPHA_CALCULATOR;
} else {
calculator = INV_ALPHA_CALCULATOR;
}
this.xDim = xDim;
this.yDim = yDim;
}
public double calculate(double alpha0, int t, int rlen, double c) {
return calculator.calculate(alpha0, t, rlen, c);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How is $ds/d\theta =R_0/\cos^2\Psi$ derived?
I have a textbook on general relativity that states the following:
The general straight line is:
$r\cos( \theta - a ) = R_0$
where $a$ and $R_0$ are arbitrary constants. This equation, and $ds^2 = dr^2 + r^2d\theta^2$, give $ds/d\theta =R_0/\cos^2\Psi$ where $\Psi=\theta-a$.
However, I can't figure out the steps to derive that result.
A:
We have $$r=\frac{R_0}{\cos(\theta-a)} \implies dr = \frac{R_0}{\cos^2(\theta-a)}\cdot\sin(\theta-a)d\theta \implies \frac{dr^2}{d\theta^2}=\frac{R_0^2\sin^2(\theta-a)}{\cos^4(\theta-a)}$$
Now,
$$\frac{ds^2}{d\theta^2} = \frac{dr^2}{d\theta^2}+r^2=\frac{R_0^2\sin^2(\theta-a)}{\cos^4(\theta-a)}+\frac{R_0^2}{\cos^2(\theta-a)}=\frac{R_0^2}{\cos^4\psi}\left(\sin^2\psi+\cos^2\psi\right)=\frac{R_0^2}{\cos^4\psi}$$
$$\frac{ds}{d\theta}=\frac{R_0}{\cos^2\psi}$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
TSQL Passing MultiValued Reporting Services Parameter into Dynamic SQL
Duplicate of: TSQL varchar string manipulation
I'm building a dynamic SQL statement out of parameters from a reporting services report. Reporting services passes MutiValue Parameters in a basic CSV format. For example a list of states may be represented as follows: AL,CA,NY,TN,VA
In a SQL statement this is OK:
WHERE customerState In (@StateList)
However, the dynamic variant isn't OK:
SET @WhereClause1 = @WhereClause1 + 'AND customerState IN (' + @StateList + ') '
This is because it translates to (invalid SQL):
AND customerState IN (AL,CA,NY,TN,VA)
To process it needs something like this:
AND customerState IN ('AL','CA','NY','TN','VA')
Is there some cool expression I can use to insert the single quotes into my dynamic SQL?
A:
This takes care of the middle:
SET @StateList = REPLACE(@StateList, ',', ''',''')
Then quote the edges:
SET @WhereClause1 = @WhereClause1 + 'AND customerState IN (''' + @StateList + ''') '
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VT-X not turned on, HAXM error, Android Studio
I just installed the android studio on my laptop, and while running my program on the virtual device, it gives me an HAXM error and ask to turn on VT-x.
I know that i am not the first person ask this question but I didn't found a solution. I have a intel i7 cpu with windows 10 64bit.
1. I checked BIOS and "INTEL virtualization technology" is ENABLED.
2. in "ANDROID SDK MANAGER" the HAXM installer option is CHECKED.
I am a beginner in android, please need your help.
A:
How did you install HAXM driver? If you just installed it via Android SDK Manager then you still need to locate this driver in Android SDK directory and install it from there. It should be in directory like sdk\extras\intel\Hardware_Accelerated_Execution_Manager - install it by running its package from the directory.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Refresh div without reload the page with jquery
I have a page in php and I need to refresh only a div of this page
<body>
.... page code here ....
?><div id="chattext">
<div id="list"><ul><?php
echo "ttt ".time();
... code php ...
</body>
In head tag I hage this code
<script>
$(document).ready(function()
{
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#chattext').hide();
//$('#loading').show();
},
complete: function() {
//$('#loading').hide();
$('#chattext').show();
},
success: function() {
//$('#loading').hide();
$('#chattext').show();
}
});
var url='index.php';
var refreshId = setInterval(function()
{
$('#chattext').load(url + '#list');
}, 3000);
});
The problem is that che the first time reload all page inside the block and only from the second time reload correctly only the div.... Why??? how can I resolve the problem???
A:
In the code where you load the page fragment
$('#chattext').load(url + '#list');
It needs to have a space between the url and the fragment identifier
$('#chattext').load(url + ' #list');
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Load infile statement throws error
I have a table where i am trying to insert data from a text file but it throws some error
the command is
mysql -u user -p<pwd> -h <server> --local-infile bsm -sse LOAD DATA LOCAL INFILE '/tmp/file.txt' INTO table test_jan2 FIELDS terminated by '|' LINES terminated by '\n' (value1,value2,value3) set id = NULL;
the error it throws is
bash: syntax error near unexpected token `('
the table structure is
+---------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| value1 | varchar(50) | YES | | NULL | |
| value2 | varchar(50) | YES | | NULL | |
| value3 | varchar(50) | YES | | NULL | |
| date_created | varchar(50) | YES | | NULL | |
+---------------+-------------+------+-----+---------+----------------+
A:
Try:
$ mysql -u user -p<pwd> -h <server> --local-infile bsm -e \
"LOAD DATA LOCAL INFILE '/tmp/file.txt'
INTO table test_jan2
FIELDS TERMINATED BY '|'
LINES TERMINATED BY '\n'
(value1,value2,value3)"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
grep count of a string with a filter condition
I need to do a grep count of a string with a filter condition .
The context is
Data will be genearetd in the below format in our log files
2013-05-17 10:06:40,693[qtp1957835280-12 Selector1] ERROR(CustomThread.java:<disconnect>:202)- onDisconnect: CustomThread [customerId=122, formattedId=testuser] reason : 1004, reasonMessage : closed
The log file is having data of all the previous days also (ie 17 , 16 , 15 , 14 , 13)
But i want to find the count of reason : 1004 for the present day that is 2013-05-17
If i execute grep -c 1004 application.log its giving me the count of the previous daya also
Please let me know is it possible to get the count of 1004 for the current day only
A:
try
grep -c '^2013-05-17.*reason : 1004' file
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to normalise a table which can link to one or more tables?
I was wondering if someone can help me with a normalisation issue I am facing, when trying to create a seperate communication table, for a personal project I am working on. Lets say I have the following tables and table columns:
Table A:
Table_A_Id, Date, Name, Agent_Id (FK), Notes
Agent Table:
Agent_Id, Date, Name, Phone, Email, Notes
Direct Contact Table:
D_C_Id, Date, Name, Phone, Email, Notes
Above is a sample of my actual tables, but describes my issue.
Essentially to normalise the above table to 1NF, I need to split the Notes column into its on seperate table, to help make the tables atomic, and comply with the 1NF rules. I want to split it out to a seperate column called Communication Table, which can allow me to keep track of when I made a conversation relating to the respective table and what I discussed.
I am not sure how to best to handle the split out Communication Table. because the Notes in Table A also links to an Agent from within the table, however the Notes column in the Agent table, only relates to communications done with the Agent.
So which of the following would you recommend is best for communication table:
EXAMPLE 1:
COMMUNICATION TABLE
Com_Id, Date, Link_Table, Link_Table_Id, Notes
Here the Link_Table should define what specific table is being dealt with and Link_Table_Id is the specific Id on the Link_Table
UPDATE:
Sorry I forgot, I need to also add another column called Communicated_With to the above, because there may be instances where communication related to Table A, could occur with another agent or person.
So the table would look like:
Com_Id, Date, Link_Table, Link_Table_Id, Communicated_With, Notes
OR
EXAMPLE 2:
COMMUNICATION TABLE
Com_Id, Date, Table_A_Id, Agent_Id, D_C_Id, Notes
Here all the unrelated Id columns would have to be set to null, whilst the related colum defined with an Id.
OR
EXAMPLE 3:
COMMUNICATION TABLE
Com_Id, Date, Notes
Here all other tables have a foreign key to this table. (However, this may force me to repeat the rest of the columns just to identify its a different column).
UPDATE 2
Thought of a new solution, after reviewing some youtube videos, I noticed that maybe a join table may work.
EXAMPLE 4
COMMUNICATION TABLE (Same as Example 1, without the "Comminicated_With" Column)
Com_Id, Date, Link_Table, Link_Table_Id, Communicated_With, Notes
COMM_AGENT_JOIN TABLE
com_Id, Agent_Id
I feel this may work, because it would allow me use the Link_Table, and Link_Table_Id to match the table being represented, and then finally the COMM_AGENT_JOIN_Id, can be used to specify which agent was communicated with, when the Link_Table is linked to Table_A.
Sorry if the answer is straight forward, I last did normalisation 2 years ago, and therefore have been struggling to do it.
Thank you.
A:
This is not going to be an answer on how to put the tables into 1NF. I hope it will be helpful, though.
When creating a database, we usually don't think in 1NF, 2NF etc. We think about what to model and what entities there are. When we think this through, then very often the database is already in 5NF or so. If in doubt we can use the NFs as a kind of checklist.
I don't know your exact requirements, so there is a lot of guessing or just general advice here. Maybe one of your problems is that you are using the noun "notes" which doesn't describe exactly what this is about. Later you call this "correspondence", but are all "notes" = "correspondence"?
Your database is about services you take from an agent or from a service company directly. So one entity that I see is this provider:
provider
provider_id
name
contact_person_name
phone
email
type (agent or final service provider)
If a provider can have multiple contacts, phones and emails, you'd make this a provider_contact table instead:
provider
provider_id
name
type (agent or final service provider)
provider_contact
provider_contact_id
name
phone
email
provider_id
As to notes: well if there are notes on a provider ("Always ask for Jane; she's the most professional there.") or contact ("Jane has worked in London and Madrid."), I'd usually make this just one text column where you can enter whatever you like. You can even store HTML or a Word document. No need for multiple documents per provider, I suppose.
Now there are also services. Either you need a list of who offers which service, then add these tables: service (which services exist) and provider_service (who provides which service). But maybe you can do without that, because you know what services exist and who provides them anyway and don't want to have this in your model.
I don't know if you want to enter service enquiries or only already fixed service contracts. In any case you may want a service_contract table either with a status or without.
service_contract
service_contract_id
provider_id (or maybe provider_contact_id?)
service (free text or a service_id referencing a service table)
valid_from
valid_to
Here again you may have notes like "We are still waiting for the documents. Jane said, they will come in March 2018.", which again would be just one column.
Then you said you want the correspondence, which could be an additional table service_contract_correspondance:
service_contract_correspondance
service_contract_correspondance_id
service_contract_id
type (received from provider or sent to provider)
text
But then again, maybe you can do without it. Will you ever have to access single correspondances (e.g. "give me all correspondences from December 2017" or "Delete all correspondances older than one year")? Or will there be thousands of correspondences on a single contract? Mabe not. Maybe you can again see this as one single document (text, HTML, Word, ...) and add this as a mere field to the table.
Having a text consisting of multiple contacts like
January 2, 2018 Jane
She says they'll need to weeks to make an offer.
January 20, 2018
I asked about the status. Talked with some Thomas Smith. He says they'll call us tomorrow.
January 21, 2018 Jane
She has emailed the contract for us to sign.
is not per se against NF1. As long as you are not interested in details in your database (e.g. you'll never select all January correspondence alone on the contract), then to the database this is atomic; no need to change this.
Same with contacts. If you have a string column only with "Jane (sales person) 123-45678 [email protected], Jack (assistent) 123-98765 [email protected]", this is not per se against NF1 again. As long as you don't want to select names only or check phone numbers, but always treat the string as a whole, as the contact, then just do so.
You see, it all boils down to what exactly you want to model and how you want to work with the data. Yes, there are agents and direct providers, but is the difference between the two so big that you need two different tables? Yes there is a chronology of correspondence per contract, but do you really need them separated into single correspondencies in your database?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Model null when use Route attribute
In my WebAPI I have model
public class ListRequest
{
public int Skip { get; set; } = 0;
public int Take { get; set; } = 30;
}
My action is
[HttpGet]
[Route("api/users")]
public IHttpActionResult Get([FromUri] ListRequest request) {
...
}
I need to have possibility to not pass any query parameters, then default values should be used. But, when I go to http://localhost:44514/api/users the request is null. If I remove [Route("api/users")] then request is not null and has default values for parameters.
How can I reach that behavior with Route attribute?
A:
If you want to init model using Route attributes try
Route("api/users/{*pathvalue}")]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CSS Mega Drop down Menu
Fiddle Link
I just want to make a mega drop down menu for my website . the above link is what I've done for now . what i just want is make all main titles inline . but it just stay like block . how can i make the header "Loans", ""Leasing (Automotive)" in one line and other lists under them ?
A:
Demo
css
body {
font: 300 86% helvetica, arial, sans-serif;
color: #000;
background: #fff;
margin: 0;
padding: 0;
}
#wrapper {
width: 980px;
min-height: 600px;
margin: 0 auto;
}
nav {
display: block;
position: relative;
width: 980px;
height: 50px;
margin: 0 auto;
background: #8dc63f;
}
nav ul#menu {
display: block;
margin: 0;
padding: 0;
list-style: 0;
}
nav ul#menu li {
position: relative;
display: inline-block;
}
nav ul#menu li a {
display: block;
height: 50px;
font-size: 1em;
line-height: 50px;
color: #fff;
text-decoration: none;
padding: 0 15px;
}
nav ul#menu li a:hover, nav ul#menu li:hover > a {
background: #333;
}
nav ul#menu li:hover > #mega {
display: block;
}
#mega {
position: absolute;
top: 100%;
left: 0;
width: 920px;
height: auto;
padding: 20px 30px;
background: #333;
display: none;
}
ul#menu ul {
float: left;
width: 23%;
margin: 0 2% 15px 0;
padding: 0;
list-style: none;
}
ul#menu ul li {
display: block;
}
ul#menu ul li a {
float: left;
display: block;
width: 100%;
height: auto;
line-height: 1.3em;
color: #888;
text-decoration: none;
padding: 6px 0;
}
ul#menu ul li:first-child a {
font-size: 1.2em;
color: #8dc63f;
}
ul#menu ul li a:hover {
color: #fff;
background: none;
}
ul#menu ul li:first-child a:hover {
color: #fff;
}
/* clearfix */
nav ul:after {
content:".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
nav ul {
display: inline-block;
}
html[xmlns] nav ul {
display: block;
}
* html nav ul {
height: 1%;
}
#content {
padding: 30px 0;
}
html
<!-- begin wrapper -->
<div id="wrapper">
<!-- begin nav -->
<nav>
<ul id="menu">
<li><a href="#">Products & Services</a>
<div id="mega">
<ul>
<li><a href="#">Loans</a>
</li>
<li><a href="#">Mortgage Loans</a>
</li>
<li><a href="#">SME Loans</a>
</li>
<li><a href="#">Revolving Loans</a>
</li>
<li><a href="#">Professional Loans</a>
</li>
<li><a href="#">Personal Loans</a>
</li>
<li><a href="#">Micro Loans</a>
</li>
<li><a href="#">Commercial Credit</a>
</li>
</ul>
<ul>
<li><a href="#">Leasing (Automotive)</a>
</li>
<li><a href="#">Three Wheeler Leasing</a>
</li>
<li><a href="#">Motorcyvle Leasing</a>
</li>
<li><a href="#">Motorcar Leasing</a>
</li>
<li><a href="#">Mini trucks Leasing</a>
</li>
</ul>
<ul>
<li><a href="#">Leasing (Automotive)</a>
</li>
<li><a href="#">Three Wheeler Leasing</a>
</li>
<li><a href="#">Motorcyvle Leasing</a>
</li>
<li><a href="#">Motorcar Leasing</a>
</li>
<li><a href="#">Mini trucks Leasing</a>
</li>
</ul>
<ul>
<li><a href="#">Leasing (Automotive)</a>
</li>
<li><a href="#">Three Wheeler Leasing</a>
</li>
<li><a href="#">Motorcyvle Leasing</a>
</li>
<li><a href="#">Motorcar Leasing</a>
</li>
<li><a href="#">Mini trucks Leasing</a>
</li>
</ul>
<ul>
<li><a href="#">Loans</a>
</li>
<li><a href="#">Mortgage Loans</a>
</li>
<li><a href="#">SME Loans</a>
</li>
<li><a href="#">Revolving Loans</a>
</li>
<li><a href="#">Professional Loans</a>
</li>
<li><a href="#">Personal Loans</a>
</li>
<li><a href="#">Micro Loans</a>
</li>
<li><a href="#">Commercial Credit</a>
</li>
</ul>
<ul>
<li><a href="#">Leasing (Automotive)</a>
</li>
<li><a href="#">Three Wheeler Leasing</a>
</li>
<li><a href="#">Motorcyvle Leasing</a>
</li>
<li><a href="#">Motorcar Leasing</a>
</li>
<li><a href="#">Mini trucks Leasing</a>
</li>
</ul>
<ul>
<li><a href="#">Leasing (Automotive)</a>
</li>
<li><a href="#">Three Wheeler Leasing</a>
</li>
<li><a href="#">Motorcyvle Leasing</a>
</li>
<li><a href="#">Motorcar Leasing</a>
</li>
<li><a href="#">Mini trucks Leasing</a>
</li>
</ul>
</div>
</li>
<li><a href="#">Locations</a>
</li>
<li><a href="#">Our Team</a>
</li>
<li><a href="#">Testimonials</a>
</li>
<li><a href="#">FAQ</a>
</li>
<li><a href="#">News & Events</a>
</li>
<li><a href="#">Contact</a>
</li>
</ul>
</nav>
<!-- /nav -->
<div id="content">
<p>Page content...</p>
</div>
</div>
<!-- /wrapper -->
|
{
"pile_set_name": "StackExchange"
}
|
Q:
List to Map of List using java streams
I have a class Company
public class Company {
private String companyid;
private List<Employee> employees;
}
Which is related to Employee in One2Many relationship
public class Employee {
private String employeeId;
private Company company;
}
I am supplied with a list of employees and I want to generate a map like Map<companyId, List<Employee>> using java streams as it has to be performant.
employees.stream().collect(
Collectors.groupingBy(Employee::getCompany, HashMap::new, Collectors.toCollection(ArrayList::new));
But the problem is I can't call something like Employee::getCompany().getCompanyId()
How can I do this. Any suggestions are welcome
A:
Use a lambda expression instead of a method reference:
Map<String,List<Employee> output =
employees.stream()
.collect(Collectors.groupingBy(e -> e.getCompany().getCompanyId(),
HashMap::new,
Collectors.toCollection(ArrayList::new)));
Or simply:
Map<String,List<Employee> output =
employees.stream()
.collect(Collectors.groupingBy(e -> e.getCompany().getCompanyId()));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Adding UIBarButtonItem to all Navigation View Controllers inside a UITabBarController programmatically
The structure is as follows:
View
Tab Bar Controller
Navigation Controller
View Controller
Navigation Controller
View Controller
Navigation Controller
View Controller
Navigation Controller
View Controller
Navigation Controller
View Controller
Navigation Controller
View Controller
The above controllers have been initialised in interface builder.
What I'm trying to do is add a right UIBarButtonItem to each navigation controller but not having any success.
Here's what I've tried:
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor clearColor];
self.view.opaque = NO;
self.tabBarController.view.frame = self.view.bounds;
NSArray *currentViewControllers = self.tabBarController.viewControllers;
NSMutableArray *updatedViewControllers = [NSMutableArray array];
for (int i=0; i<currentViewControllers.count; i++) {
UINavigationController *tempNav = [[UINavigationController alloc]init];
tempNav = [currentViewControllers objectAtIndex:i];
UIBarButtonItem *dismissButton = [[UIBarButtonItem alloc]
initWithTitle:@"Done"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(dismissLibraryBrowser)];
tempNav.navigationItem.rightBarButtonItem = dismissButton;
[updatedViewControllers addObject:tempNav];
[dismissButton release];
[tempNav release];
NSLog(@"Added controller number %d",i);
}
self.tabBarController.viewControllers = [NSArray arrayWithArray:updatedViewControllers];
[self.view addSubview:tabBarController.view];
}
The code executes without any errors, but the button doesn't appear. I'm sure I've misunderstood something here. Would appreciate some guidance.
A:
You are over complicating things slightly with recreating viewControllers and temporary arrays. You just need to manipulate the objects loaded from the nib
[self.tabBarController.viewControllers enumerateObjectsUsingBlock:^(UINavigationController *navigationController, NSUInteger idx, BOOL *stop) {
UIViewController *rootViewController = [navigationController.viewControllers objectAtIndex:0];
UIBarButtonItem *rightBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(dismissLibraryBrowser)];
rootViewController.navigationItem.rightBarButtonItem = rightBarButtonItem;
}];
As for the structure of your app - the docs for UITabBarController say
When deploying a tab bar interface, you must install this view as the root of your window. Unlike other view controllers, a tab bar interface should never be installed as a child of another view controller.
So I would suggest having a look at restructuring some stuff, if you need it only occasionally why not consider presenting it modally?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I create a plot like this in mathematica?
I think this is called a caterpillar plot. The dot is the mean and the lines represent a 95% confidence interval.
On the x axis there are several different test cycles, the red line is the true value.
A:
Here is a cheat using BoxWhiskerChart. The error bars are quantiles (0.05, 0.95) and not symmetric confidence interval. It is not ideal wrt placement of mean marker.
Using:
rv = RandomVariate[NormalDistribution[10, 3], {20, 10}];
BoxWhiskerChart[rv, {{"MeanMarker", Style[\[FilledSmallCircle], 20],
Blue}}, Method -> {"BoxRange" -> (Quantile[#, {0.05, 0.5, 0.5, 0.5,
0.95}, {{1, -1}, {0, 1}}] &)}, ChartStyle -> White,
GridLines -> {None, {{4, Dashed}, 10, {16, Dashed}}},
GridLinesStyle -> Red]
Here is an example using $\mu \pm 1.96 \sigma/\sqrt{n}$ to illustrate how you can adapt:
fun[d_] := {#1 - 1.96 #2, #3, #3, #3, #1 + 1.96 #2} & @@ {Mean[d],
StandardDeviation[d]/Sqrt[Length@d], Median[d]}
BoxWhiskerChart[rv, {{"MeanMarker", Style[\[FilledSmallCircle], 20],
Blue}}, Method -> {"BoxRange" -> (fun@# &)}, ChartStyle -> White,
GridLines -> {None, {{4, Dashed}, 10, {16, Dashed}}},
GridLinesStyle -> Red]
yielding:
A:
You can use ErrorListPlot as described in: How to : Add Error Bars to Charts and Plots.
(This might be considered "easily found" however I don't believe "caterpillar plot" would find it.)
The first example from the documentation:
Needs["ErrorBarPlots`"]
ErrorListPlot[Table[{i, RandomReal[{0.2, 1}]}, {i, 10}]]
By the way if you find that the error bars are being cut off by the edges of the plot you can use Show with a PlotRange of All:
ErrorListPlot[Table[{i, RandomReal[{1, 3}]}, {i, 10}]];
Show[%, PlotRange -> All]
The fact that the error bars are not taken into consideration for the plot range in ErrorListPlot itself might be considered a bug.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Setting the sku name and tier of Azure ARM template serverfarm
We are creating a deployment template using Azure resource manager. We have virtually everything set up however the created hostplan does not pick up the correct pricing tier. No matter what values we use it always seems to default to the 'Free' 'F1' pricing plan.
Here is the section
{
"apiVersion": "2015-08-01",
"type": "Microsoft.Web/serverfarms",
"name": "[variables('sitePlanName')]",
"location": "[resourceGroup().location]",
"sku": {
"name": "B1",
"tier": "Basic",
"capacity": 1
},
"properties": {
"numberOfWorkers": 1
}
},
Any thoughts would be much appreciated.
Regards
A:
Can you try to specify the SKU inside the "properties" node of the serverfarms description, something like that :
{
"apiVersion":"2015-08-01",
"name":"[variables('hostingPlanName')]",
"type":"Microsoft.Web/serverfarms",
"location":"[resourceGroup().location]",
"properties":{
"name":"[variables('hostingPlanName')]",
"sku":"Basic",
"workerSize":"1"
"numberOfWorkers":1
}
}
Possible values for "sku" are : Free, Shared, Basic, Standard, Premium
For Basic, Standard and Premium SKUs, the "workerSize" possible values could be 0 (small), 1 (medium) or 2 (large) :
"sku": {
"type": "string",
"allowedValues": [
"Free",
"Shared",
"Basic",
"Standard",
"Premium"
],
"defaultValue": "Free"
},
"workerSize": {
"type": "string",
"allowedValues": [
"0",
"1",
"2"
],
"defaultValue": "0"
}
}
Hope this helps.
Julien
A:
Try with this resource block (works for me) to create S1 instance:
{
"apiVersion": "2015-08-01",
"type": "Microsoft.Web/serverfarms",
"name": "[parameters('hostingPlanName')]",
"location": "[resourceGroup().location]",
"properties": {
"name": "[parameters('hostingPlanName')]",
"workerSize": "0",
"numberOfWorkers": 1
},
"sku": {
"name": "S1",
"tier": "Standard",
"size": "S1",
"family": "S",
"capacity": "1"
}
}
For basic Tier use this sku:
"sku": {
"name": "B1",
"tier": "Basic",
"size": "B1",
"family": "B",
"capacity": 1
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In kubernetes POD will have IP address and Node will have IP address
In kubernetes POD will have IP address and Node will have IP address.
I know we use POD IP address for accessing the containers in it with containers port. Do we use Node IP for any purpose?
Also Will kubernetes takes care of creating IP address for pods.
A:
Kubernetes networking plugin creates a separate pod network ( calico, flannel , waeve etc)
Pods are assigned IPs from that pod network
All the containers in a pod have the same IP address since the network namespace is shared
NodeIP can be used to access the service running on the pod , from external systems , such as in case , you expose the service using kubernetes Service of type Nodeport , or expose the service using ingress resource
More:
Every Pod is allocated an IP address, and the CNI plug-in is
responsible for its allocation and assignment to a Pod. You may be
asking yourself, “If a Pod can have multiple containers, how does the
CNI know which one to connect?” If you have ever interrogated Docker
to list the containers running on a given Kubernetes node, you may
have noticed a number of pause con‐ tainers associated with each of
your Pods. These pause containers do nothing meaningful
computationally. They merely serve as pla‐ ceholders for each Pod’s
container network. As such, they are the first container to be
launched and the last to die in the life cycle of an individual Pod
|
{
"pile_set_name": "StackExchange"
}
|
Q:
git checkout my_branch vs. git checkout origin/my_branch
I was on branch1 when I checkout branch2 like this (both branches are existing).
git checkout origin/branch2
then I got a detached head error:
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
But then I just checkout branch2 (without origin) then it works ok:
git checkout branch2
So what's the difference between git checkout with and without origin/; and why there was the detached HEAD error when using origin/?
A:
The "detached HEAD" message is a warning, not an error.
The reason for it is simple enough. Git has two states you can be in with respect to branches:
on a branch, or
not on a branch.
When you are on a branch and make new commits, the branch automatically advances to include the new commits.
When you are not on a branch and make new commits, the non-branch also advances, but—here's the reason for the warning—if you then switch to some other branch (so that you are on it), git forgets where you were.1 When you are on a branch, the branch name remembers the new commits; when you are not, there is nothing to remember them.
You can't be on a remote-tracking branch
The branch origin/branch2 is a remote-tracking branch: that is, a branch that remembers "where branch2 was on origin the last time we (our git and origin's git) had a conversation about branches". Because the point of this is to track where they were, git won't let you get "on" that branch and make new commits (which would then remember where you are instead of where they were).
Because you can't be on it, checking it out gives you that "detached HEAD" state instead.
But you can be on a normal (local) branch
The branch branch2 is a normal, ordinary, local branch. It is yours to do with as you wish. You can get on it and make new commits.
(Your local branch can also remember the remote-tracking branch, as its so-called upstream. Git's confusing terminology for this is that your local branch is then "tracking" the remote-tracking branch. The word "tracking" appears too many times here, as does the word "branch", all with different meanings.)
1Actually it saves it for a while, in the reflog for HEAD, but this is only good for 30 days by default.
A:
you should use git checkout --track origin/branch2 to create a local branch of branch2, which tracking the remote origin/branch2
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I print all lines of current file with list command in gdb?
How do I print all lines of current file with list command in gdb?
list command show only 10 lines by default, so I want to show all lines of current file.
How do I do it?
A:
You can use list 1,10000 where 10000 is large enough number so that the size of a file you debugging is less than this large enough number. See builtin gdb help:
(gdb) help list
List specified function or line.
With no argument, lists ten more lines after or around previous listing.
"list -" lists the ten lines before a previous ten-line listing.
One argument specifies a line, and ten lines are listed around that line.
Two arguments with comma between specify starting and ending lines to list.
Lines can be specified in these ways:
LINENUM, to list around that line in current file,
FILE:LINENUM, to list around that line in that file,
FUNCTION, to list around beginning of that function,
FILE:FUNCTION, to distinguish among like-named static functions.
*ADDRESS, to list around the line containing that address.
With two args, if one is empty, it stands for ten lines away from
the other arg.
By default, when a single location is given, display ten lines.
This can be changed using "set listsize", and the current value
can be shown using "show listsize".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I need to expand my root partition by deleting another partition apparently not in use
This is a screen shot of my gparted:
I am new to Linux. I had a d:\ drive on my Windows machine which I intended to use for Linux but during installation failed to create a root partition.. ended up shrinking C: too create the root partition. I thought my d:\ (/dev/sda4) would be my /home but only realized it wasn't, so when I was getting space errors.
I therefore need to either:
delete /dev/sda4 and extend /dev/sda3
or move my /home to /dev/sda4 so that I have space for /root. possibly extend /root as well for future growth.
A:
first doing any operation on a mounted disk can cause errors.
boot from a live CD or an external drive with linux on it.
option 1:
use gparted to delete sda4. then grow sda3 and sda5 to fill the free space.
you will get a warning about moving the root partition causing boot errors.
this can be ignored because you aren't moving the files just growing the end.
option 2, separate home folder:
record the uuid of the sda4 for the next step.
edit /etc/fstab to add the lines:
#/home
UUID=(the uuid of sda4) /home ext4 defaults 0 2
rename /home folder to /homeback. and make a new folder /home.
copy everything from /homeback to the new partition
reboot your computer. if everything mounts correctly. you can delete /homeback
as mentioned above, it would be a good idea to add a 3 GB swap partition. instead of using a swapfile. this should be placed after sda5 and before the partition for home.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Htaccess redirect subdirectory extension and query string
I have url like this http://www.example.com/subdir/Subcontent?QUERY=420501 i want to redirect it to http://www.example.com/subcontent.html?QUERY=420501 so if Subcontent is dynamic in url then it will change first letter of Subcontent to small and redirect to final url http://www.example.com/subcontent.html?QUERY=420501
I have tried with this
RewriteCond %{QUERY_STRING} QUERY=([0-9]+) [NC]
RewriteCond %{REQUEST_URI} !\.html
RewriteRule ^subdir/(.*)$ /$1 [L,R=301]
But it does not seems to work i think sequence is not proper of conditions cangetting clueless on this.
A:
Add this RewriteMap in Apache or vhost server config:
RewriteMap lc int:tolower
Also you have an extra condition, use this rule to redirect and lowercase your URLs:
RewriteCond %{QUERY_STRING} (^|&)QUERY=([0-9]+) [NC]
RewriteRule ^subdir/([\w-]+)/?$ /${lc:$1}.html [L,NC,R=301]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how do i get the position in the original string where the last character of the captured substring found
Guys this is my original string,
'010000111'
i need to find this pattern '10000111'.So i used below regular expression to do that.
Match m = Regex.Match("010000111", @"[1][0][0][0][0][1]+");
I get the correct answer from this Regex.But the problem is i need to get the position in the original string where the last character of the captured string,that's mean according to my example my captured pattern is '10000111'
According to the captured pattern my last index is 7,but when it is compare to the original string it is 8.
i used lastIndexOf('1') function.but it gives the index of the captured string.
can you please help me to solve this problem ?
A:
You don't need regex to do this.
To check if the string contains another, use the someString.IndexOf("someOtherString") method. This will give you the index of the first character in the sequence.
To get the position of the last char, all you have to do is sum the length of the tested string and subtract 1:
var firstString = "010000111";
var secondString = "10000111";
var positionOfSecondOverFirst = firstString.IndexOf(secondString); // 1
var firstContainsSecond = (positionOfSecondOverFirst >= 0); // true
var positionOfLastChar = positionOfSecondOverFirst + secondString.Length - 1; // 8
Reference: https://msdn.microsoft.com/library/k8b1470s(v=vs.110).aspx
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.