Q: Is it possible to make fast big circular buffer arrays for stream recording in Haskell? I'm considering converting a C# app to Haskell as my first "real" Haskell project.  However I want to make sure it's a project that makes sense.  The app collects data packets from ~15 serial streams that come at around 1 kHz, loads those values into the corresponding circular buffers on my "context" object, each with ~25000 elements, and then at 60 Hz sends those arrays out to OpenGL for waveform display.  (Thus it has to be stored as an array, or at least converted to an array every 16 ms).  There are also about 70 fields on my context object that I only maintain the current (latest) value, not the stream waveform.
There are several aspects of this project that map well to Haskell, but the thing I worry about is the performance.  If for each new datapoint in any of the streams, I'm having to clone the entire context object with 70 fields and 15 25000-element arrays, obviously there's going to be performance issues.
Would I get around this by putting everything in the IO-monad?  But then that seems to somewhat defeat the purpose of using Haskell, right?  Also all my code in C# is event-driven; is there an idiom for that in Haskell?  It seems like adding a listener creates a "side effect" and I'm not sure how exactly that would be done.

A: Look at this link, under the section "The ST monad":
http://book.realworldhaskell.org/read/advanced-library-design-building-a-bloom-filter.html

Back in the section called “Modifying array elements”, we mentioned
  that modifying an immutable array is prohibitively expensive, as it
  requires copying the entire array. Using a UArray does not change
  this, so what can we do to reduce the cost to bearable levels?
In an imperative language, we would simply modify the elements of the
  array in place; this will be our approach in Haskell, too.
Haskell provides a special monad, named ST, which lets us work
  safely with mutable state. Compared to the State monad, it has some
  powerful added capabilities.
We can thaw an immutable array to give a mutable array; modify the
  mutable array in place; and freeze a new immutable array when we are
  done.

...

The IO monad also provides these capabilities. The major difference between the two is that the ST monad is intentionally designed so that we can escape from it back into pure Haskell code.

So should be possible to modify in-place, and it won't defeat the purpose of using Haskell after all.

A: Yes, you would probably want to use the IO monad for mutable data.  I don't believe the ST monad is a good fit for this problem space because the data updates are interleaved with actual IO actions (reading input streams).  As you would need to perform the IO within ST by using unsafeIOToST, I find it preferable to just use IO directly.  The other approach with ST is to continually thaw and freeze an array; this is messy because you need to guarantee that old copies of the data are never used.
Although evidence shows that a pure solution (in the form of Data.Sequence.Seq) is often faster than using mutable data, given your requirement that data be pushed out to OpenGL, you'll possible get better performance from working with the array directly.  I would use the functions from Data.Vector.Storable.Mutable (from the vector package), as then you have access to the ForeignPtr for export.
You can look at arrows (Yampa) for one very common approach to event-driven code.  Another area is Functional Reactivity (FRP).  There are starting to be some reasonably mature libraries in this domain, such as Netwire or reactive-banana.  I don't know if they'd provide adequate performance for your requirements though; I've mostly used them for gui-type programming.


Q: FileNotFoundException when calling C# dll from C++/CLI I have a C# dll, with some methods, which I am trying to access in my native project with /CLR support.
I reference this DLL using a #using directive, and the DLL is recognized and the project compiles.
However, during runtime, I get a FileNotFoundException, which is pretty weird since the DLL is present in the source directory of the project.
TheDLL is compiled inVS 2015 with .NET Version 4.5.2. Since I have CLR support on my C++ mixed, I have edited the project file to make TargetFrameworkVersion as 4.5.2, but still the runtime does not work.
Kindly advise on what could be the issue?
EIDT - ADDED SOME CODE
C#
namespace TestManagedLibrary
{
    public class Class1
    {
        public int i;
        public Class1()
        {
            i = 5;
        }

        public int returnValue()
        {
            return i;
        }
    }
}

C++/CLI
#using <TestManagedLibrary.dll>

using namespace System;
using namespace System::Runtime::InteropServices; // Marshal
using namespace TestManagedLibrary;

ref class ManagedFoo
{
public:
    ManagedFoo()
    {
        Console::WriteLine(_T("Constructing ManagedFoo"));
        Class1 ^testObject = gcnew Class1();
        int a = testObject->returnValue();
    }
};

A: First of all you need to ensure that the TestManagedLibrary.dll file is located in a place where Fusion could find it. Your first try should be the location of the executable you are running.
One way to handle this is via the reference properties. If the reference to your TestManagedLibrary.dll is set with the copy local flag than during the build the referenced library is going to be copied from the referenced location to the output directory.
You can enable the internal fusion logging to find out the details:

*

*Run Developer Command Prompt with administrative privileges.

*Run fuslogvw

*In the Assembly Binding Log Viewer hit settings and set either Log bind failures to disk or Log all binds to disk.

*Start your service

*Hit Refresh in the Assembly Binding Log Viewer, pick your executable and hit View Log

A: The compiled DLL should have been in the same location as the executable for the CLR to search for it. In my case, the .NET compiled DLL was in the solution folder and not searchable.


Q: What is a good reference for compound Poisson processes? I've seen a couple of descriptions of the basic statistics of a compound Poisson process, basically just simple statements about how to compute the mean and variance given the mean and variance of the underlying processes. Unfortunately I haven't found anything which I feel comfortable citing in a professional context.
Can anybody recommend a good desk reference that would cover compound Poisson processes/distributions?
Preferably it would be general enough to serve as a good desk reference on statistics for an engineer (with a tendency to do a lot of numerical analysis), rather than focusing purely on compound processes. Bonus points if it also gives a good outline of Bayesian inference in general.

A: This book on Non-Life Insurance Mathematics might actually work for you. It is oriented towards applications, though not engineering applications, but it is completely theoretically sound. If I am not mistaken, there is something in the book on Bayes estimation too.
Note that you should look for the Cramèr-Lundberg model in the context of the book to find the compound Poisson process.


Q: Getting Index of an Object from NSArray? i am trying to get index of an array through indexOfObject method as follows but when i try to log the value to test the index i get a garbage value.. for testing purposes i am having an array with values {57,56,58..} to get an index of lets say 56,
NSNumber *num = [NSNumber numberWithInteger:56];
NSInteger Aindex = [myArray indexOfObject:num];
NSLog(@" %d",Aindex);

the value i get is something like 2323421. what am i possibly doing wrong??

A: NSNumber *num1 = [NSNumber numberWithInt:56];
    NSNumber *num2 = [NSNumber numberWithInt:57];
    NSNumber *num3 = [NSNumber numberWithInt:58];
    NSMutableArray *myArray = [NSMutableArray arrayWithObjects:num1,num2,num3,nil];
    NSNumber *num=[NSNumber numberWithInteger:58];

    NSInteger Aindex=[myArray indexOfObject:num];

    NSLog(@" %d",Aindex);

Its giving the correct output, may be u have done something wrong with storing objects in ur array.

A: Try this:
NSArray's indexOfObject: method. Such as the following:
NSUInteger fooIndex = [someArray indexOfObject: someObject];

A: Folks,
When an object is not found in the array the indexOfObject method does NOT return a 'garbage' value. Many systems return an index of -1 if the item is not found.
However, on IOS - because the indexOfObject returns an UNSIGNED int (aka NSUInteger) the returned index must be greater than or equal to zero. Since 'zero' is a valid index there is no way to indicate to the caller that the object was not found -- except by returning an agreed upon constant value that we all can test upon. This constant agreed upon value is called NSNotFound.
The method:
- (NSUInteger)indexOfObject:(id)anObject;

will return NSNotFound if the object was not in the array. NSNotFound is a very large POSITIVE integer (usually 1 minus the maximum int on the platform).

A: The index returned by indexOfObject will be the first index for an occurence of your object. Equality is tested using isEqual method.
The garbage value you get is probably equal to NSNotFound.
Try testing anIndex against it. The number you are looking for isn't probably in your array :
NSNumber *num=[NSNumber numberWithInteger:56];
NSInteger anIndex=[myArray indexOfObject:num];
if(NSNotFound == anIndex) {
    NSLog(@"not found");
}

or log the content of the array to be sure :
NSLog(@"%@", myArray);

A: If you're using Swift and optionals make sure they are unwrapped.  You cannot search the index of objects that are optionals.

A: I just checked. Its working fine for me. Check if your array has the particular number. It will return such garbage values if element is not present.

A: indexOfObject methord will get the index of the corresponding string in that array if the string is like @"Test" and you find like @"TEST" Now this will retun an index like a long number


Q: MKMapView zoom User Location and Annotation I want my MKMapView to zoom 'User Location' and the Annotation as close as possible.
The map already show both, but is zoomed out to the whole country.
How can I do that?
And I don’t know why the Annotation and Pin are not animated.
My Code:
//Coords User
CLLocationCoordinate2D user_location;
user_location.latitude = mapView.userLocation.location.coordinate.latitude;
user_location.longitude = mapView.userLocation.location.coordinate.longitude;
//Coords Annotation
CLLocationCoordinate2D club_location;
club_location.latitude = [self.clubInfo.latitude doubleValue];
club_location.longitude = [self.clubInfo.longitude doubleValue];

MKMapPoint userPoint = MKMapPointForCoordinate(user_location);
MKMapPoint annotationPoint = MKMapPointForCoordinate(club_location);

MKMapRect userRect = MKMapRectMake(userPoint.x, userPoint.y, 0, 0);
MKMapRect annotationRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);

MKMapRect unionRect = MKMapRectUnion(userRect, annotationRect);

MKMapRect unionRectThatFits = [mapView mapRectThatFits:unionRect];
[mapView setVisibleMapRect:unionRectThatFits animated:YES];

// Add an annotation
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = club_location;
annotation.title = self.clubInfo.clubName;
annotation.subtitle = @"Pin!";
[mapView addAnnotation:annotation]; // This was missing
[mapView selectAnnotation:annotation animated:YES];

Logs:
userRect: {{134217728.0, 134217728.0}, {0.0, 0.0}}
annotationRect: {{99775488.0, 152579328.0}, {0.0, 0.0}}

unionRect: {{99775488.0, 134217728.0}, {34442240.0, 18361600.0}}

mapView.visibleMapRect: {{96025087.6, 116070015.1}, {41943040.7, 54657025.8}}

A: If I understand well, you want those two annotations to be visible with maximum possible zoom. I found this solution that does not reqire any calculations.
// You have coordinates
CLLocationCoordinate2D user = ...;
CLLocationCoordinate2D annotation = ...;
// Make map points
MKMapPoint userPoint = MKMapPointForCoordinate(user);
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation);
// Make map rects with 0 size
MKMapRect userRect = MKMapRectMake(userPoint.x, userPoint.y, 0, 0);
MKMapRect annotationRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
// Make union of those two rects
MKMapRect unionRect = MKMapRectUnion(userRect, annotationRect);
// You have the smallest possible rect containing both locations
MKMapRect unionRectThatFits = [mapView mapRectThatFits:unionRect];
[mapView setVisibleMapRect:unionRectThatFits animated:YES];

CoreLocation and MapKit structures are hell.

A: For anyone coming here later: The shortest way of doing this is (iOS7+) this:
Assuming you have a @property MKMapView *mapView, and an MKPointAnnotation *theAnnotation, call:
[self.mapView showAnnotations:@[theAnnotation, self.mapView.userLocation] animated:NO];

Now this could cause some problems if called too early (i.e. when self.mapView.userLocation is not yet set). If so, you can call in viewWillAppear:
[self.mapView.userLocation addObserver:self forKeyPath:@"location" options:0 context:NULL];

Then, implement:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"location"]) {
        [self.mapView showAnnotations:@[theAnnotation, self.mapView.userLocation] animated:NO];
    }
}

That way you're sure it's set. Don't forget to remove the observer at viewWillDisappear:
[self.mapView.userLocation removeObserver:self forKeyPath:@"location"];

A: Use these 4 classes - it works like a charm!
//MapViewController.h file

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface MapViewController : UIViewController <CLLocationManagerDelegate>  {
    IBOutlet UIButton *buttonBack;
    IBOutlet MKMapView *mapView;
    IBOutlet UILabel *labelTitle;
    NSString *lon,*lat,*nickName;
    BOOL isFirstLaunch;
}
@property(nonatomic,retain) NSString *lon,*lat,*nickName;
@property(nonatomic,retain) IBOutlet UIButton *buttonBack;
@property(nonatomic,retain) IBOutlet UILabel *labelTitle;
@property(nonatomic,retain) IBOutlet MKMapView *mapView;
-(IBAction)buttonBackAction:(UIButton *)_btn;
-(void)zoomToFitMapAnnotations;
@end

//
//  MapViewController.m
//
#import "MapViewController.h"
#import "Annotation.h"

@implementation MapViewController
@synthesize buttonBack,mapView,labelTitle;
@synthesize lon,lat,nickName;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */
-(IBAction)buttonBackAction:(UIButton *)_btn{
    [self.navigationController popViewControllerAnimated:1];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    CLLocationManager* locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [locationManager startUpdatingLocation];
    NSLog(@"MapViewController");
    labelTitle.text = @"anscacorona.blogspot.in"
    CLLocationCoordinate2D location;
    location.latitude = [self.lat floatValue];
    location.longitude = [self.lon floatValue];

    Annotation *annotation = [[Annotation alloc] init];
    annotation.theCoordinate = location;
    annotation.theTitle = [NSString stringWithFormat:@"%@",labelTitle.text];

    [mapView addAnnotation:annotation];
    [annotation release];
    mapView.showsUserLocation = 1;

    [self zoomToFitMapAnnotations];
    [super viewDidLoad];
}

// Shows the location of both users. called when the device location changes to move the map accordinly. necessary ONLY once when the window is opened. afterwards the user can move the map as he choises.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    if (isFirstLaunch) {
        CLLocationCoordinate2D topLeftCoord;
        CLLocationCoordinate2D bottomRightCoord;

        topLeftCoord.longitude = fmin([self.lon floatValue], newLocation.coordinate.longitude);
        topLeftCoord.latitude = fmax([self.lat floatValue], newLocation.coordinate.latitude);

        bottomRightCoord.longitude = fmax([self.lon floatValue], newLocation.coordinate.longitude);
        bottomRightCoord.latitude = fmin([self.lat floatValue], newLocation.coordinate.latitude);

        MKCoordinateRegion region;
        region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
        region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
        region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.5; // Add a little extra space on the sides
        region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.5;  // Add a little extra space on the sides

        region = [mapView regionThatFits:region];
        [mapView setRegion:region animated:YES];
        isFirstLaunch = NO;
    }

}

-(void)zoomToFitMapAnnotations
{
    if([mapView.annotations count] == 0)
        return;

    CLLocationCoordinate2D topLeftCoord;
    CLLocationCoordinate2D bottomRightCoord;
    topLeftCoord.longitude = fmin(mapView.userLocation.location.coordinate.longitude, [self.lon floatValue]);
    topLeftCoord.latitude = fmax(mapView.userLocation.location.coordinate.latitude, [self.lat floatValue]);

    bottomRightCoord.longitude = fmax(mapView.userLocation.location.coordinate.longitude, [self.lon floatValue]);
    bottomRightCoord.latitude = fmin(mapView.userLocation.location.coordinate.latitude, [self.lat floatValue]);

    MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };

    CLLocationCoordinate2D userCoord = {[self.lat floatValue],[self.lon floatValue]};
    region.center = userCoord;
    region.span.latitudeDelta = 0.05f;//fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
    region.span.longitudeDelta = 0.05f;//fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;  // Add a little extra space on the sides

    [mapView setRegion:region animated:YES];
    [mapView regionThatFits:region];
}
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}
#pragma mark - View Lifecycle

-(void)viewWillAppear:(BOOL)animated{
    isFirstLaunch=YES;
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {

    [super dealloc];
}

@end

//anotation classes- Annotation.h
#import <MapKit/MapKit.h>

@interface Annotation : NSObject  <MKAnnotation>{
    CLLocationCoordinate2D theCoordinate;
    NSString *theTitle;
    NSString *restId;
    NSString *theSubtitle;
}
@property(nonatomic,retain) NSString *restId;
@property(nonatomic,retain) NSString *theTitle;
@property(nonatomic,retain) NSString *theSubtitle;
@property CLLocationCoordinate2D theCoordinate;
@end

//Annotation.m
#import "Annotation.h"

@implementation Annotation
@synthesize theCoordinate,theTitle,theSubtitle,restId;
- (CLLocationCoordinate2D)coordinate;
{
    return theCoordinate;
}

// required if you set the MKPinAnnotationView's "canShowCallout" property to YES
- (NSString *)title
{
    return theTitle;
}

// optional
- (NSString *)subtitle
{
    return theSubtitle;
}

- (void)dealloc
{
    [super dealloc];
}

@end


Q: Datadog: How to automate configuring Log Archives How can I automate configuring Log Archives on GCP?
I can do it manually by following steps
https://docs.datadoghq.com/logs/archives/?tab=googlecloudstorage
I guess selenium can help this
but I looking for a more programmatic way like Terraform or REST API
Thank you.

A: I’m not sure if it is a recent addition, but the Datadog public API supports configuring Log Archives: https://docs.datadoghq.com/api/latest/logs-archives/
You can also use tools like Terraform to configure them: https://registry.terraform.io/providers/DataDog/datadog/latest/docs/resources/logs_archive (it uses the Datadog API internally)


Q: JComboBox - out of bounds exception i have a small problem. I'm trying to import logins from my database to a vector and then to use that vector for JComboBox. My method for downloading logins :
public void loginReader (Vector<String> loginy, String tableName)
{
    String query = "select login from " + tableName;

    try {

        Statement statement = mConnection.createStatement();
        ResultSet rs = statement.executeQuery(query);
        while (rs.next())
            {
             Vector<String> vstring = new Vector<String>();

                vstring.add(rs.getString("login"));

                loginy.addAll(vstring);
            }
        } catch (SQLException e)
            {
                e.printStackTrace();

            }
}

That's in class DatabaseManagement. I made another class (GUI) and there's that JComboBox. Why it doesn't work ?
package DataBase_Hospital;

 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.SQLException;
 import java.text.ParseException;
 import java.util.Properties;
 import java.util.Vector;

 import javax.swing.ImageIcon;
 import javax.swing.JButton;
 import javax.swing.JComboBox;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import javax.swing.JScrollPane;
 import javax.swing.JTextArea;
 import javax.swing.JTextField;

 public class Message extends JFrame implements ActionListener {

JButton SEND_MESSAGE;
JButton READ_MESSAGE;
public JLabel background;

JLabel NAME_LABEL;

JTextField NAME_FIELD;

JTextArea DATABASE_FIELD;
static Vector<String> loginy = new Vector<String>();

private static DatabaseManagement DATABASE;

public Message() {

    setSize(290, 500);
    setTitle("Message Panel");

    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
    JLabel background=new JLabel(new ImageIcon("/Users/Dominik/Desktop/messageFrame.png"));
    add(background);

    DATABASE_FIELD = new JTextArea(3,3);
    JScrollPane scrollPane = new JScrollPane(DATABASE_FIELD);
    scrollPane.setBounds(45, 50, 200, 200);
    background.add(scrollPane);
    DATABASE_FIELD.setEditable(true);

    NAME_LABEL = new JLabel("Odbiorca :");
    NAME_LABEL.setBounds(40, 380, 140, 20);
    background.add(NAME_LABEL);

    SEND_MESSAGE = new JButton();
    SEND_MESSAGE.setIcon(new ImageIcon("/Users/Dominik/Desktop/sendMail.jpg"));
    SEND_MESSAGE.setBounds(75, 270, 60, 60);
    background.add(SEND_MESSAGE);
    SEND_MESSAGE.addActionListener(this);
    SEND_MESSAGE.setToolTipText("Send message");

    READ_MESSAGE = new JButton();
    READ_MESSAGE.setIcon(new ImageIcon("/Users/Dominik/Desktop/jwj.png"));
    READ_MESSAGE.setBounds(150, 270, 60, 60);
    background.add(READ_MESSAGE);
    READ_MESSAGE.addActionListener(this);
    READ_MESSAGE.setToolTipText("Read message");

  JComboBox loginList = new JComboBox(loginy);
  loginList.setSelectedIndex(loginy.capacity());
  loginList.addActionListener(this);
  loginList.setBounds(145, 380, 100, 20);
  background.add(loginList);

}

public static void main(String[] args) {

    Message window = new Message();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
    DATABASE.loginReader(loginy,"uzytkownicy");
}

public void actionPerformed(ActionEvent e)
{
    Object EVENT_SOURCE = e.getSource();
    DATABASE = new DatabaseManagement("pacjent");

    if (EVENT_SOURCE == SEND_MESSAGE)
    {
        DATABASE.sendMessage(DATABASE_FIELD.getText(), "uzytkownicy", NAME_FIELD.getText()) ;
    }

}
}

A: After creating your JComboBox with your empty Vector, you set the selectedIndex to loginy.capacity (). The problem is that while the capacity of your Vector is 10 (as stated in the JavaDoc for the default constructor), it's actual size is 0. Hence the ArrayOutOfBoundsException. You should check for the size of your Vector before setting the selected index of your JComboBox.

A: I suspect the problem is you are trying to set the selected index of your combo box to the capacity of your vector.
loginList.setSelectedIndex(loginy.capacity());

From the docs .capacity():

Returns the current capacity of this vector.
  Returns:
  the current capacity (the length of its internal data array, kept in the field elementData of this vector)

This is not the size i.e. the number of logins in your database. this is the capacity of internal datastructure which will always be >= the number of elements in the vector.
Try using Vector#size() but you will still need to subtract one (provided there is actually data in the vector) from this so your code should be:
loginList.setSelectedIndex(loginy.size() - 1);

And this will set the last login in the comboBox. Which is not required in your case as you are populating the vector after creating the combobox so you could just remove this line from your code until you populate the vector.

Edit as per comments
All you should need to do to have the logins is reorder the execution order. I.e populate your vector then create your combo box, Change your main method to something like this:
public static void main(String[] args) {
    //First initialise your database (dont do this in the action performed method)
    //  you should only need one and not need to create a new one on each action
    DATABASE = new DatabaseManagement("pacjent");
    // Read logins (I assume this is the method that does it)
    DATABASE.loginReader(loginy,"uzytkownicy");
    // Then create your message window...
    Message window = new Message();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
}


Q: problems with cookies i'm using restful-authentication plugin with rails 2.3.8
i've problems with cookies store
i've put a logger instruction in this function for check the cookie:
 def send_remember_cookie!
      cookies[:auth_token] = {
        :value   => @current_user.remember_token,
        :expires => @current_user.remember_token_expires_at }
      logger.error "--------------#{cookies[:auth_token].keys}"
    end

But when i launch the program i receive this error:
undefined method `keys' for nil:NilClass

why?
How can i set the cookie?
thanks

A: The cookies object is an instance ApplicationController::CookieJar. It's almost like a Hash but the behavior of the [] and []= methods are not symmetric. The setter sets the cookie value for sending to the browser. The getter retrieves the value which comes back form the browser. Hence when you access it in your code having just set the outgoing value the incoming value will be unset. There some more info on this here
Also did you intentionally mean to say cookie[:auth_token].keys or did you mean cookie.keys?


Q: Column not found: 1054 Field Field 'email' unknown in where I have 3 rubrics for now.

When, I login in the rubric Studentwith the email test.gmail.com I can see my informations private

Then, I LOGIN in the rubric Feedback always with the email test.gmail.com I have like error message:
SQLSTATE [42S22]: Column not found: 1054 Field Field 'email' unknown in where (SQL: select count (*) as aggregate fromreturnswhere email= test@gmail.com)
my fields on the table Feedbacks are:
protected  $fillable = ['user_id','instruction', 'description', 'fk_eleve'];
My function index() is the following:
public function index(Request $request)

{
    $user = $request->user();

    $feedbacks = Feedback::query()
    ->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
        $query->where('email', $user->email);
    })
    ->when($request->has('search'), function (Builder $query) use ($request) {
     $query->join('eleves', 'feedbacks.fk_eleve', '=', 'eleves.id')->orderBy('eleves.nom', 'asc')->where('eleves.nom','like','%'.$request->input('search').'%');
     })
    ->paginate(5);

    return view('admin.feedbacks.index', compact('feedbacks'))
        ->with('display_search', $user->hasRole('admin'));
}

Thank you for your help.

A: You most likely need to add the email column to your fillable array:
protected $fillable = ['user_id','instruction', 'description', 'fk_eleve', 'email'];

Did you further create a proper migration for this, like does the table have the column email?


Q: I want to use this. $ axios with Vuex constants What I want to come true
I use this.$axios many times, so I tried to put it in a constant, but it doesn't work.
I read the official docs but didn't understand.
Is it because this isn't available in the Nuxt.js lifecycle?
Code
url.js
export const AXIOS_POST = this.$axios.$post

export const POST_API = '/api/v1/'

export const POST_ITEMS_API = '/api/v1/post_items/'

Vuex
import * as api from './constants/url.js'  // url.js in this.

export const state = () => ({
  list: [],
  hidden: false
})

export const mutations = {

  add (state, response) {
    state.list.push({
      content: response.content,
      status: response.status
    })
  },

  remove (state, todo) {
    state.list.splice(state.list.indexOf(todo), 1)
  },

  edit (state, { todo, text }) {
    state.list.splice(state.list.indexOf(todo), 1, { text })
  },

  toggle (state, todo) {
    todo.status = !todo.status
  },

  cancel (state, todo) {
    todo.status = false
  },

  // アクション登録パネルフラグ
  switching (state) {
    state.hidden = !state.hidden
  }
}

export const actions = {

  post ({ commit }, text) {

//I want to use it here

    this.$axios.$post(api.POST_ITEMS_API + 'posts', {
      post_items: {
        content: text,
        status: false
      }
    })
      .then((response) => {
        commit('add', response)
      })
  }
}

Error

Uncaught TypeError: Cannot read property '$axios' of undefined

A: Since your file is located into a constants directory, you should probably use some .env file.
Here is a guide on how to achieve this in Nuxt: https://stackoverflow.com/a/67705541/8816585

If you really want to have access to it into a non .vue file, you can import it as usual with something like this
/constants/url.js
import store from '~/store/index'

export const test = () => {
  // the line below depends of your store of course
  return store.modules['@me'].state.email
}

PS: getters, dispatch and everything alike is available here.
Then call it in a page or .vue component like this
<script>
import { test } from '~/constants/url'

export default {
  mounted() {
    console.log('call the store here', test())
  },
}
</script>

As for the lifecyle question, since the url.js file is not in a .vue file but a regular JS one, it has no idea about any Vue/Nuxt lifecycles.


Q: how to upload an image to aws s3 bucket and get the saved url in Android studio using java I need to upload the image to the AWS s3 bucket in android. I implemented that the user has taken a photo from the gallery after having the image path I need to save that in a bucket and get the url from bucket in android.
I HAVE access key and secret key and bucket name. I am not clear how to implement this in android. Please help me out.
// This is the code of taking an image from the gallary
private void selectImage() {
        final CharSequence[] options = {"Choose from Gallery", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Upload Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Choose from Gallery")) {
                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);
                } else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 2) {
                Uri selectedImage = data.getData();
                String[] filePath = {MediaStore.Images.Media.DATA};
                Cursor c = this.getContentResolver().query(selectedImage, filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                thumbnail = getResizedBitmap(thumbnail, 400);
                Log.w("path of image from gallery......******************.........", picturePath + "");
                imageView.setImageBitmap(thumbnail);
                BitMapToString(thumbnail);
            }
        }
    }

    private void BitMapToString(Bitmap userImage1) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        userImage1.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        Document_img1 = Base64.encodeToString(b, Base64.DEFAULT);
        System.out.println(Document_img1 + "........IMAGE");
    }

    private Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();

        float bitmapRatio = (float) width / (float) height;
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        return Bitmap.createScaledBitmap(image, width, height, true);
    }

A: Please check out the Storage category in the AWS Amplify library.
There's some setup/configuration to do (as noted in that guide), but the actual upload will look like this:
Amplify.Storage.uploadFile(
    "remoteS3Key",
    localFile,
    result -> Log.i("Demo", "Successfully uploaded: " + result.getKey()),
    failure -> Log.e("Demo", "Upload failed", failure)
);


Q: Configuring ASP.NET MVC app's IIS 7.5 Application Pool identity as login on SQL Server 2008 R2 I am trying to use IIS 7.5 Application Pool identity as login on SQL Server 2008 R2 so that my ASP.NET web app can connect to the database...
Using this approach worked fine on my local dev machine (IIS 7.5 and SQL Server 2008 R2 on same machine).
However, when I try to set up the same on production (IIS and SQL servers are separate) I am unable to add "IIS APPPOOL\MyAppAppPool" login to SQL Server 2008 R2.
Notice that in either case you cannot use "Browse..." when creating a login in SQL Server since "IIS APPPOOL\MyAppAppPool" user identity is dynamic (or "special")...
Any ideas?
Update:
For more info on Application Pool Identities see here.
From article:

Whenever a new Application Pool is
  created, the IIS management process
  creates a security identifier (SID)
  that represents the name of the
  Application Pool itself. For example,
  if you create an Application Pool with
  the name "MyNewAppPool," a security
  identifier with the name
  "MyNewAppPool" is created in the
  Windows Security system. From this
  point on, resources can be secured by
  using this identity. However, the
  identity is not a real user account;
  it will not show up as a user in the
  Windows User Management Console.

A: That articles states (under "Accessing the Network") you still use the <domainname>\<machinename>$ aka machine account in the domain.
So if both servers are in "foobar" domain, and the web box is "bicycle", the login used to the SQL Server Instance is foobar\bicycle$
If you aren't in a domain, then there is no common directory to authenticate against. Use a SQL login with username and password for simplicity
Edit, after comment
If the domains are trusted then you can use the machien account still (use domain local groups for SQL Server, into which add a global groups etc)
As for using app pool identities, they are local to your web server only as per article. They have no meaning to SQL Server. If you need to differentiate sites, then use proper domain accounts for the App Pools.
You can't have it both ways...


Q: Django include template tag alternative in python class I know there is a Django template tag that allows to include other templates like so:
{% include 'template.html' %}

I am wondering if I could do the same, but in a separate python class (not in  the HTML template)?
I know that for example the url tag has an equivalent, like so:
{% url 'some_url_name' %} -> reverse('some_url_name')

A: I think you might be looking for render_to_string.
from django.template.loader import render_to_string
context = {'foo': 'bar'}
rendered_template = render_to_string('template.html', context)


Q: I need help identifying this resistor
I read it as 1 ohm 5% tolerance 250 ppm/k but I can’t seem to find it anywhere.

A: Ok, so it is a 1 ohm 5% 250 ppm resistor. Looks to be metal film and flame proof. Looking at the circuit it looks like a reactive power supply, becoming more common these days for LED night-lights, etc.
The AC line goes through the resistor which limits in-rush a bit and can be a fuse if it has to be. The capacitor is next and is likely 470 nF to 680 nF to allow a few tens of milliamps to feed the bridge rectifier made of SMD diodes which feed a 9V to 12V zener and bypass cap, which feed a IR motion detector or sound detection IC to activate an LED.
Notice the small MOV on the AC hot and neutral inputs (maybe after the resistor). They could have saved a few pennies, but why risk it.


Q: Custom setting on a network printer I´m setting up a HP Color Laserjet 4730mfp printer on our network and I was wondering if I could someow set it up with a custom configuration for each user. We want to set it up so that every jobs will be stored as a locked job and the user needs to walk to the printer, select the job and insert his pin. This is fairly easy to set up manually on the client but I want to set it up so that when the printer is installed they are configured like that and with a default pin 1111

A: You should be able to do this with HP's Web JetAdmin software.

A: I found it in the Printer Properties under Printing defaults.


Q: A problem involving power series We define an entire function on $\mathbb{C}^m$ by
$$
f(z_1,\cdots,z_m)=\sum_{n=0}^{\infty}\frac{(-1)^n}{(2n)!}t^{2n}(z_1^2+\cdots+z_m^2)^n,
$$
here $t$ is some (positive) real number. Of course, $f(x)=\text{cos} (t|x|)$ for $x=(x_1,\cdots,x_m)\in\mathbb{R}^m$ hence is bounded by the constant $1$. My question is:

For $x=(x_1,\cdots,x_m)\in\mathbb{R}^m$ and $z=(z_1,\cdots,z_m)\in \mathbb{C}^m$, if $|z_k-x_k|=1, k=1,\cdots, m$, then could we get a reasonable bound for $|f(z)|$ in terms of $t$ and $x=(x_1,\cdots,x_m)$?

I hope it can be bounded by a polynomial of $(t, x)$.

A: $f(z_1, \ldots, z_m) = \cos(t \sqrt{z_1^2 + \ldots + z_m^2})$ so
if $s$ is a square root of $z_1^2 + \ldots + z_m^2$, $$\sinh^2(t \; \text{Im}(s)) \le |f(z_1, \ldots, z_m)|^2 \le \cosh^2(t\; \text{Im}(s))$$
If  $z_k = x_k + e^{i \theta_k}$ for all $k$, then write
$$ \sum_{k=1}^m z_k^2 =  A+2iB = R e^{i\theta}$$
where $$\eqalign{
A &= \sum_k (x_k^2 + 2 x_k \cos(\theta_k) + \cos(2\theta_k))\cr
B &= \sum_k (2 x_k \sin(\theta_k) + \sin(2 \theta_k))\cr
R &= \sqrt{A^2 + B^2}\cr
\sin \theta &=  B/R\cr
\cos \theta &= A/R\cr
\text{Im}(s) &= \sqrt{R} \sin(\theta/2)\cr }$$
For example, we could take all $x_k =  x > 1$, all $\theta_k = \pi/2$,
so $$\eqalign{ \sum_{k=1}^m z_k^2 &= m (x+i)^2\cr
\text{Im}(s) &= \sqrt{m}\cr
\sinh^2&(t \sqrt{m}) \le |f(z_1, \ldots, z_m)|^2 \le \cosh^2(t \sqrt{m})}$$


Q: Installing on a Vaio S I have a new Vaio S 15" with Windows 8 pre-installed and UEFI. It had both Intel on-board graphics and nVidia discrete graphics. Installing Ubuntu has turned into a nightmare.

*

*Installing from Live USB with default settings results in a black screen and freeze after the splash screen.

*Replacing quick splash with nomodeset in GRUB (this seems fairly common) gets further - but the install then hangs with fb: conflicting fb hw usage inteldrmfb vs VESA VGA - removing generic driver as the last message.

*I can 'Try without installing' and get to the command line with i915.modeset=0, but I am not sure where - if anywhere - I can go after that. This does not work for the install.
I have run out of bug reports that match mine and not at all sure where to go from here.

A: Try using the 64-bit version instead of the 32-bit version. The 64-bit version handles UEFI better than the 32-bit one.


Q: How to clear a window in PySimpleGUI I am using PySimpleGUI to build a GUI. How do you clear all the widgets on the window? In tkinter you have the code:
widget.destroy()

If you attempt this in PySimpleGUI you get the error:
NameError: name 'RWG' is not defined

if my widget is called RWG. I tried making RWG a global variable but I got the same error. Can I have some help?
My code that gets the error:
def oof():
    RWG.destroy()

import PySimpleGUI as sg
sg.theme("DarkAmber")
layout = [[sg.Text("Don't Even Try!!!")],
          [sg.Button("RWG")]]

window = sg.Window("Don't Even Try It", layout).Finalize()
window.Maximize()

while True:
    event, values = window.read()

    if event == "RWG":
        oof()

I would appreciate any help

A: You can clear elements with:
window.FindElement(key).Update('')

Have you tried this?


Q: Rails 4: From which step in the boot process can I check the ActiveRecord::Base class? I would like to perform some checking on the database resources only when the app starts/restarts (if any new migrations happen in between) by calling:
resources = ActiveRecord::Base.send(:subclasses).map { |subclass| subclass.name }

I tried inserting this code at different steps of the initialization process without any success (getting an empty array as a result).  Why? And where should I insert it?
If I perform this checking in the ApplicationController , it will be always be executed.  I only need to run it once after boot.
Where can I insert it?

A: Compiling the gist of answers other people have given before:
In the development environment your model classes will not be eager loaded.
Only when you invoke some code that references a model class, the corresponding file will be loaded. (Read up on 'autoloading' for further detail.)
So if you need to do some checks upon startup of the rails server, you can manually invoke
Rails.application.eager_load!

and after that get a list of all model classes with
model_classes = ActiveRecord::Base.descendants

For a list of model names associated with their database tables, you might use
model_classes.map{ |clazz| [clazz.model_name.human, clazz.table_name] }.sort

You can put your code in an arbitrarily named file in the config/initializers directory. All ruby files in that directory will get loaded at startup in alphabethical order.
The eager loading will of course take some time and thus slow down server and console start-up in the development environment a bit.
Other approaches such as parsing a list of filenames in the app/models directory are not reliable in more complex Rails applications.
If in a Rake task, make sure your Application is properly initialized before you send eager_load!. To that end, let your rake task depend on :environment.
HTH!


Q: Real Grassmann manifold and orthonormal groups I'm trying to prove that the Grassmann manifold
$$G_k(\mathbb{R}^n) = \{E = {\rm {\it k} - dimensional\ subspace\ of\ } \mathbb{R}^n\}$$
is equivalent to:
$$G_k(\mathbb{R}^n) = \frac{O(n)}{O(k)\times O(n - k)}  \tag1$$
Where $O(n)$ is the orthonormal group of $n\times n$ matrices.
From my research I've seen that Eq. (1) is due to the idea of splitting the original $n$-dimensional subspace into a $k$-dimensional one and its orthonormal complement of $n - k$ dimension; but I don't get how this Grassmann manifold, which is made of vectors ($(k\times 1)$-dimensional matrices - column vectors), is related to $n\times n$ matrices since the quotient in Eq. (1) is the following set, as usual:
$$\frac{O(n)}{O(k)\times O(n - k)} = \{M_n\cdot (O(k)\times O(n - k))\ |\ M_n \in O(n)\}    \tag2$$
Can anyone explain me this relation and the prove of Eq. (1)? Thanks in advace! ;)

A: Let $S_k(\mathbb{R}^n)$ be the Steifel manifold of $k$-frames in $\mathbb{R}^n$:
$$ S_k(\mathbb{R}^n) = \{(v_1, \ldots, v_k) \mid \text{the $v_i$ are orthonormal} \}$$
The group $O(n)$ acts transitively on $S_k(\mathbb{R}^n)$ by acting on each vector: $g \cdot (v_1, \ldots, v_k) = (gv_1, \ldots, gv_k)$. The stabiliser of a frame $(v_1, \ldots, v_k)$ will be the subgroup of $O(n)$ which fixes the span of $(v_1, \ldots, v_k)$ and acts nontrivially on its orthogonal complement. This subgroup is isomorphic to $O(n - k)$, and hence we have
$$ S_k(\mathbb{R}^n) \cong O(n) / O(n - k)$$
Next, there is a natural map $\phi: S_k(\mathbb{R}^n) \to G_k(\mathbb{R}^n)$ by taking the span of the frame. The fibre of this map over a point $E \in G_k(\mathbb{R}^n)$ will be the set of $k$-frames spanning $E$, which is a set isomorphic to $O(k)$ (an isomorphism of $O(k)$-sets). Hence $$G_k(\mathbb{R}^n) \cong S_k(\mathbb{R}^n) / O(k)$$
These together give the equality you were after.


Q: HTTPHandler for all files in directory I have created an HTTPHandler to handle all files within a certain folder ("Files"). When i run it locally from Visual Studio it works fine. However when i deploy it on the server (IIS 7, Classic Mode), the handler is not firing for files of types such as pdf, jpg, gif...etc (although requests for files with extensions .aspx, .axd...etc do work).
How exactly should i configure web.config to handle these files as well. I placed a web.config file inside the Files folder with the following:
<configuration>
    <system.web>
      <httpHandlers>
        <add verb="*" path="*.*" type="MyProject.Web.FileSecurityHandler, MyProject.Web"/>
      </httpHandlers>
    </system.web>
</configuration>

Please help...

A: add one more element in your HTTPHandler tag for specific file type for example
<configuration>
<system.web>
  <httpHandlers>
    <add verb="*" path="*.*" type="MyProject.Web.FileSecurityHandler, MyProject.Web"/>
   <add path="*.jpg,*.jpeg,*.bmp,*.tif,*.tiff" verb="*" type="NameofYourHandler" />
  </httpHandlers>
</system.web>
</configuration>


Q: Integrating Angular 4 into ASP.NET Core MVC app - how to mix routing I'm trying to integrate my Angular 4 app into asp.net mvc core project. And I'd like to have Angular app available within my Core MVC project with this Url - mydomain.com/ngx.
Here's how I do it now (and it doesn't work):
I build Angular app with angular-cli and use ng build ... --base-href /ngx (notice the slash). Then I copy everything from dist folder (where the build is placed by CLI) and copy it into wwwroot/ngx folder into my Core MVC project. But when I open localhost/ngx/index.html I get 404 errors for main.bundle.js and other js files. I checked the requests and for some reason it tries to get it as localhost://main.bundle.js - why from root?
now, if I build it with --base-href ngx (no slash) and open the site, it gets redirected to /ngx/ngx (doubles the ngx). so... wtf? :)
Core MVC routing doesn't have anything special, I haven't touched that part.
So how can I make it work as localhost/ngx ASP.NET Core MVC project?

A: Works fine here with
ng build --base-href /ngx/ --output-path dist/ngx,

running http-server from the dist directory, and going to http://localhost:8080/ngx/index.html


Q: typing effect in Arabic language appear disconnected So I used this tutorial to make a typing effect and it appears great in English, I tried
to use Arabic text (which is a connected letter language) and it appears good on my device.
when I sent the app prototype for the client to test it, the Arabic language letters appear disconnected in his device! so weird as I couldn't debug it because it does not happen on my laptop and mobile phone!
I found this library which has a test demo at the bottom of the page, I asked him to test Arabic words on it, it appears like this on his device (iPhone xs max, chrome browser):

but it appears like this on my device (Linux, chrome browser):

any idea why this happens and how to solve it?


Q: Is it possible to prove that the cardinality of a set is unique using only the definition of bijection and cardinality. By definition, the function $f$ from $X$ to $Y$ is a bijection if every element $y$ in $Y$ is a value of $f(x)$ for exactly one $x$ in $X$. Also by definition, if there is a bijective correspondence between the sets $S$ and $\mathbb{N_m}$ then S has cardinality $m$, which can be denoted by $|S|=m$.
I want to prove that if we have a set S such that $|S|=s$ and $|S|=t$, then $s=t$.
Given is that there are bijections $f:S\to\mathbb{N_s}$ and $g:S\to\mathbb{N_t}$. Now we can use the pigeonhole principle for the composite functions $f\circ g^{-1}$ and $f^{-1}\circ g$ to obtain $s\le t$ and $t\ge s$, respectively.
Now my question is: why can we not say directly, from the definition of a bijection, that the cardinality of $X$ and $Y$ are equal. So that we can prove it by saying that if $|S|=s$ and $|S|=t$ then $s=t$ because both $f$ and $g$ are bijections with the same domain.

A: What you want to prove is that if $\mathbb N_s\cong\mathbb N_t$ then $s=t$. WLOG we can assume that $s\le t$.
Basically you may prove this by showing that there can be no smallest such cardinality that allows this, because if you find one you can create a case with one element less - unless one is $\emptyset$. You end up with the claim that $\emptyset\cong X$ for some non-empty $X$.
Formally one starts with showing that cardinality is a total order. So if $X\prec Y$ and $Y\preceq Z$ we have that $X\prec Z$. We can use this to show that if $\mathbb N_s \prec \mathbb N_{s+1}$ then it's true for all $t>s$ that $\mathbb N_s\prec\mathbb N_t$. That is we only have to show that $\mathbb N_s \prec\mathbb N_{s+1}$.
Next is to use induction. Obviously $\emptyset=\mathbb N_0\prec\mathbb N_1$ (since to have a bijection with the empty set the other need to be empty). Now assume it's true for some $s$. Now assume that we have $\mathbb N_{s+1}\cong\mathbb N_{s+2}$ that is there's a bijettion $\Phi$, but then we can restrict that to $\phi:\mathbb N_s\to\Phi(\mathbb N_s) = \mathbb N_{s+2}\setminus \{\Phi(s+1)\}$. Now we use this latest form to form a bijection to $\mathbb N_{s+1}$ which would show that $\mathbb N_s\cong\mathbb N_{s+1}$ which we assumed not to be possible.


Q: nicer typesetting of some subreaction I hope that this question is not a duplicate but I could not find it on this forum. I'd like to typeset a reaction as displayed here:

However, what I got is rather ugly, and my question is whether there are some better options. This is the code to produce it:
    \documentclass{article}
    \usepackage[T1]{fontenc}
    \usepackage{amsmath,amssymb,graphicx}
    \begin{document}
    \begin{align}
     \pi^+~\to~&\mu^++\nu_\mu\notag\\
     &\,\rotatebox[origin=c]{180}{$\Lsh$}\, e^++\bar\nu_\mu+\nu_e\;.
    \end{align}
    \end{document}

Is there a simple way to have a more reasonable output, i.e. larger arrow which is also closer to \mu^+ ?

A: Here's another option.
\begin{align}
\pi^+~\to~&\mu^++\nu_\mu\notag\\[-.7ex]
& \put(3.5,2.5){\line(0,1){10}}\to e^++\bar\nu_\mu+\nu_e\;.
\end{align}

If you want the arrow to start closer to the \mu you can make the -.7 more negative. Adjust the length of the vertical part of the arrow by changing the 10.

A: You can use the \drsh symbol  from mathabx. Here is how to load it without loading the full mathabx fonts (which would replace  the symbol fonts from amsmath). I also replaced \to with \longrightarrow, and removed the unbreakble spaces. See if it corresponds to what you want:
\documentclass{article}
\usepackage[utf8]{inputenc} \usepackage[T1]{fontenc}
\usepackage{amsmath,amssymb,graphicx}

 \DeclareFontFamily{U}{mathb}{\hyphenchar\font45}
\DeclareFontShape{U}{mathb}{m}{n}{
<-6> mathb5 <6-7> mathb6 <7-8> mathb7
<8-9> mathb8 <9-10> mathb9
<10-12> mathb10 <12-> mathb12
}{}
\DeclareSymbolFont{mathb}{U}{mathb}{m}{n}
\DeclareFontSubstitution{U}{mathb}{m}{n}

\DeclareMathSymbol{\drsh}{\mathrel}{mathb}{"EB}

\begin{document}

\begin{align}
 \pi^+ \longrightarrow{} &\mu^+ + \nu_\mu\notag\\
 & \drsh e^+ +\bar \nu_\mu + \nu_e\;.
\end{align}

\end{document}


Q: How to safely create a file if it doesn't exist from concurrently-running processes without using locking? Suppose two (or more) concurrently-running Java processes need to check for the existence of a file, create it if it doesn't exist, and then potentially read from that file over the course of their runs. We want to protect ourselves against the possibility of multiple writer processes clobbering each other and/or reader processes reading an incomplete or inconsistent version of the file.
What we're currently doing to arbitrate this situation is to use Java NIO FileLocks. One process manages to acquire an exclusive lock on the file to be created using FileChannel.tryLock() and creates it, while the other concurrently-running processes fail to acquire a lock and fall back to using an in-memory version of the file for their runs.
Locking is causing various problems for us on our compute farm, however, so we're exploring alternatives. So my question to you is: is there a way to do this safely without using file locks?
Could, eg., the processes write to independent temporary files when they find a file doesn't exist, and then more or less "atomically" move the temp file(s) into place after they've been written? In this scenario, we might end up with multiple writer processes, but that would be ok provided that any processes reading from the file always read one version or another, and not a mix of two or more versions. However, I don't think all operating systems guarantee that if you have a file open for reading, you'll continue reading from the original version of the file even if it's overwritten mid-way through the read.
Any suggestions would be much appreciated!

A:
Suppose two (or more) concurrently-running Java processes need to check for the existence of a file, create it if it doesn't exist, and then potentially read from that file over the course of their runs.

I don't quite understand the create and read part of the question.  If you are looking to make sure that you have a unique file then you could use new File(...).createNewFile() and check to make sure that it returns true.  To quote from the Javadocs:

Atomically creates a new, empty file named by this abstract pathname if
  and only if a file with this name does not yet exist.  The check for the
  existence of the file and the creation of the file if it does not exist
  are a single operation that is atomic with respect to all other
  filesystem activities that might affect the file.

This would give you a unique file that only that process (or thread) would then "own".  I'm not sure how you were planning on letting the writer know which file to write to however.
If you are talking about creating a unique file that you write do and then moved into a write directory to be consumed then the above should work.  You would need to create a unique name in the write directory once you were done as well.
You could use something like the following:
private File getUniqueFile(File dir, String prefix) {
    long suffix = System.currentTimeMillis();
    while (true) {
        File file = new File(dir, prefix + suffix);
        // try creating this file, if true then it is unique
        if (file.createNewFile()) {
           return file;
        }
        // someone already has that suffix so ++ and try again
        suffix++;
    }
}

As an alternative, you could also create a unique filename using UUID.randomUUID() or something to generate a unique name.


Q: Wrong file input I have to enter string x in reverse order, but it outputs null. Why and how to fix it?
Sorry in advance for the name of the variables, but also for the double loop (I know it's bad, but this is the only thing that came to my mind)
The main question is why null is entered in the file
public static void OutputOfFile(char[] x)throws IOException {
        File file = new File("test");
        PrintWriter out = new PrintWriter(file.getAbsoluteFile());

        out.print(x);
        out.close();
    }

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String x = reader.readLine();
        char[] x1 = x.toCharArray();
        char[] x2 = new char[x1.length];
        for(int i = x1.length - 1; i < -1; i--) {
            for (int k = 0; k > x1.length; k++) {
                x2[i] = x1[k];
            }
        }
        OutputOfFile(x2);
    }

A: the problem is with your loop, you need to iterate in one loop instead of an inner loop:
public static void OutputOfFile(char[] x) throws IOException {
    File file = new File(""test"");
    PrintWriter out = new PrintWriter(file.getAbsoluteFile());

    out.print(x);
    out.close();
}

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String x = reader.readLine();
    char[] x1 = x.toCharArray();
    char[] x2 = new char[x1.length];

    for (int i = x1.length - 1, k = 0; i >= 0; i--, k++) {
        x2[k] = x1[i];
    }

    OutputOfFile(x2);
}


Q: pymssql (python module) losing item when fetching data I have a database named "sina2013",and the columus is Title,Content
Now I want to use pymssql module to get the data.At the same time ,using the Title as the filename of a txt file,the Content as the content of the txt file.
The strange thing is the number of files is less than the items in database.
where is the error?
the code i have tried is:
import pymssql
conn = pymssql.connect(...)
cur = conn.cursor()
cur.execute('SELECT Title,Content FROM sina2013')
count=len(cur.fetchall()) #Will return the right number :5913
for Title,Content in cur:
    filename=file(str(Title)+r'.txt',r'w')
    filename.write(Content )
    filename.close()
cur.close()

The number of txt file is less than it should be.
what is the reason?

A: Perhaps changing your for loop into this:
# cursor fetchall() method returns all rows from a query
for Title,Content in cur.fetchall():

... will fix the issue?


Q: How do I get arrayMaxConsecutiveSum from CodeSignal more efficient? I am working through some problems on CodeSignal. I came across this one, arrayMaxConsecutiveSum. I got it to pass almost all tests, but it is timing out on the last one. If I move the test into custom tests, it passes there, so I'm not sure what to do. How do I code it better so that it doesn't time out?
Problem:

Given array of integers, find the maximal possible sum of some of its k consecutive elements.
Example: For inputArray = [2, 3, 5, 1, 6] and k = 2, the output should be
arrayMaxConsecutiveSum(inputArray, k) = 8. All possible sums of 2 consecutive elements are:
2 + 3 = 5;
3 + 5 = 8;
5 + 1 = 6;
1 + 6 = 7.
Thus, the answer is 8.

function arrayMaxConsecutiveSum(inputArray, k) {
    let max = 0;

    for(let i = 0; i < inputArray.length; i++){
        let sum = 0;
        let newArr = inputArray.slice(i, i + k);
        sum = newArr.reduce((accumulator, currentVal) => accumulator + currentVal);
        if(sum > max){
            max = sum;
        }
    }

    return max;
}

Error: Tests passed: 19/20. Execution time limit exceeded on test 20: Program exceeded the execution time limit. Make sure that it completes execution in a few seconds for any possible input.

A: Your current algorithm is O(n ^ 2) because it requires a nested loop.
You can make it O(n) by using a rolling sum instead. Start with the sum of elements 0 to k, then on each iteration, subtract the earliest element that makes up the sum and add the next element not included in the sum yet.
For example, with a k of 2:

*

*start out with the sum of elements [0] and [1]

*subtract [0], add [2], compare the new sum

*subtract [1], add [3], compare the new sum

and so on.

function arrayMaxConsecutiveSum(inputArray, k) {
    let rollingSum = inputArray.slice(0, k).reduce((a, b) => a + b);
    let max = rollingSum;
    for(let i = 0; i < inputArray.length - k; i++){
        rollingSum += inputArray[i + k] - inputArray[i];
        max = Math.max(max, rollingSum);
    }
    return max;
}

console.log(arrayMaxConsecutiveSum([2, 3, 5, 1, 6], 2));

A:

function arrayMaxConsecutiveSum(inputArray, k) {

    var max = inputArray.slice(0,k).reduce((a,b)=>a+b);
    var cur = max;
    for(var i = k; i < inputArray.length; i++) {
        cur = cur + inputArray[i] - inputArray[i-k];
        if(cur>max)
            max = cur
    }
        return max

}

console.log(arrayMaxConsecutiveSum([2, 3, 5, 1, 6], 2));


Q: Make SliverAppBar have an image as a background instead of a color I have a SliverAppBar with a background image.
When collapsed it has a blue color as a background:

But instead of the blue color I want it to show the background image when collapsed:

How can I achieve this?
I've already tried to give the app bar a transparent background color,
but it did not work.
Code:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  var scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Home());
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: DefaultTabController(
          length: 2,
          child: NestedScrollView(
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return [
                SliverAppBar(
                  expandedHeight: 200.0,
                  floating: false,
                  pinned: true,
                  flexibleSpace: FlexibleSpaceBar(
                      centerTitle: true,
                      title: Text("Collapsing Toolbar",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.0,
                          )),
                      background: Image.network(
                        "https://images.pexels.com/photos/396547/pexels-photo-396547.jpeg?auto=compress&cs=tinysrgb&h=350",
                        fit: BoxFit.cover,
                      )),
                ),
                SliverPadding(
                  padding: new EdgeInsets.all(16.0),
                  sliver: new SliverList(
                    delegate: new SliverChildListDelegate([
                      TabBar(
                        labelColor: Colors.black87,
                        unselectedLabelColor: Colors.grey,
                        tabs: [
                          new Tab(icon: new Icon(Icons.info), text: "Tab 1"),
                          new Tab(
                              icon: new Icon(Icons.lightbulb_outline),
                              text: "Tab 2"),
                        ],
                      ),
                    ]),
                  ),
                ),
              ];
            },
            body: Center(
              child: Text("Sample text"),
            ),
          ),
        ));
  }
}

A: Please check below code :
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  var scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Home());
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: DefaultTabController(
      length: 2,
      child: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverAppBar(
              expandedHeight: 200.0,
              floating: true,
              pinned: true,
              snap: true,
              actionsIconTheme: IconThemeData(opacity: 0.0),
              flexibleSpace: Stack(
                children: <Widget>[
                  Positioned.fill(
                      child: Image.network(
                    "https://images.pexels.com/photos/396547/pexels-photo-396547.jpeg?auto=compress&cs=tinysrgb&h=350",
                    fit: BoxFit.cover,
                  ))
                ],
              ),
            ),
            SliverPadding(
              padding: new EdgeInsets.all(16.0),
              sliver: new SliverList(
                delegate: new SliverChildListDelegate([
                  TabBar(
                    labelColor: Colors.black87,
                    unselectedLabelColor: Colors.grey,
                    tabs: [
                      new Tab(icon: new Icon(Icons.info), text: "Tab 1"),
                      new Tab(
                          icon: new Icon(Icons.lightbulb_outline),
                          text: "Tab 2"),
                    ],
                  ),
                ]),
              ),
            ),
          ];
        },
        body: Center(
          child: Text("Sample text"),
        ),
      ),
    ));
  }
}


Q: SSE (Server Sent Events) Client library for Clojure? I would like to handle a Server Sent Events stream in Clojure.
Does anyone know a small client library to just do that please ?
I was expecting to find something like https://github.com/stalefruits/gniazdo, which is for Websockets, but for SSE.
I could not find anything though and the only lib that may have been a good candidate is not maintained anymore https://github.com/clojurewerkz/ssese
thanks in advance ...

A: Here are some overviews on the topic:

*

*https://sweetcode.io/using-html5-server-sent-events/

*https://juxt.pro/blog/posts/course-notes.html

*https://www.lucagrulla.com/posts/server-sent-events-with-ring-and-compojure/

*Server push of data from Clojure to ClojureScript

*https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
Here is a highly voted comparison on StackOverflow between Server Sent Events and WebSockets (my favorite):

*

*WebSockets vs. Server-Sent events/EventSource
And here is a nice comparison from IBM (2017):

*

*https://www.ibm.com/developerworks/library/wa-http-server-push-with-websocket-sse/index.html

A: immutant.web has support for SSE built in: http://immutant.org/documentation/current/apidoc/guide-web.html#h3155
There is also this middleware for other web servers: https://github.com/kumarshantanu/ring-sse-middleware, although I have not tried it myself.


Q: How to provide tunnel between my own app and my own server? I have implemented an Android App which connects my home server.  I want  to implement a tunnel between my app and the server. when ever app connects to server it will be connected through the secure tunnel. Tunnel might be anything. Is  there any suggestion???
P.S.: I want to create tunnel just for this particular app not for all.


Q: Boolean Algebra Product of Sums I have a question to solve the following expression and get it in terms of product of sums
(AB' + A'B)C

And I tried taking the compliment of this

[(AB' + A'B)C]'

[(AB' + A'B)' + C']

[(AB')'.(A'B)' + C']

[(A' + B).(A + B') + C']

[(A' + B + C').(A + B' + C')]

Is this the correct method and is this the answer? I took the compliment because of the fact that Sum of products are 1's and Products of sums are 0's

A: As @coffeemath noted, your answer is actually the complement of the original expression. So this method is not correct.
I think the easiest way is to use the identities $(x + y)' = x'y'$ and $(xy)' = x' + y'$ (known as De Morgan's laws) and $x'' = x$. We have $$AB' + A'B = ((AB')'(A'B)')' = ((A'+B)(A+B'))'=$$
$$=(A'A + A'B' + AB + BB')' = (AB + A'B')' = (AB)'(A'B')' = (A'+B')(A+B).$$
Hence the original expression equals $$ (AB'+A'B)C = (A'+B')(A+B)C.$$
Alternatively, if you're familiar with how to get a SOP or a POS from the truth table, then you can just construct the truth table for the function $f(A, B)$ realized by the expression $AB' + A'B$ and construct a POS directly from it. In our case the truth table looks like this:
$$\begin{array}{|c|c|}
\hline
A & B & f(A, B) \\ \hline
0 & 0 & 0 \\
0 & 1 & 1 \\
1 & 0 & 1 \\
1 & 1 & 0 \\ \hline
\end{array}$$
To construct the POS representation of $f(A, B)$ you should look at pairs $(a, b)$ with $f(a, b) = 0$. With every such pair you associate a sum $A^\sigma + B^\tau$, where $A^\sigma = A$ if $a = 0$ and $A^\sigma = A'$ if $a = 1$, and same for $B^\tau$. After that you just construct the product of all these sums. In our case we have two pairs $(0, 0)$ and $(1, 1)$. Corresponding sums are $A + B$ and $A' + B'$. Finally, we have the POS $(A'+B')(A+B)$.


Q: Symfony2 using jsroutingbundle and got login error I am using Jsroutingbundle and I add these two lines in my base.html.twig and it works fine.
<script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script src="{{ path('fos_js_routing_js', {"callback": "fos.Router.setData"}) }}"></script>

But when I login next time, it jumped to a page like this:
fos.Router.setData({"base_url":"\/Symfony\/web\/app_dev.php","routes":[],"prefix":"","host":"localhost","scheme":"http"});

And the url is:
http://localhost/Symfony/web/app_dev.php/My/Test/js/routing?callback=fos.Router.setData

I am actually logged in because I can jump to other pages. But it is just unfriendly. How should I handle this problem?

A: In the access_control of your security add:
    - { path: ^/js/, role: IS_AUTHENTICATED_ANONYMOUSLY }


Q: Hi everyone! My question is about the Charles-proxy certificate My question is about the Charles-proxy certificate. I've already installed Charles on my laptop. The real problem is when I tried to install it on my mobile. I have a Xiaomi with the android 11 version, with this one is impossible. I did everything I could. I have another mobile a Moto G. When I try to link the mobile with Charles I couldn't see the connection between the mobile and the laptop. Can somebody help me?
Thanks in advance!


Q: Trick for evaluating integrals over the whole real line (possible alternative derivation of gamma function?) Consider the integral,
$$ I_n= \int_{\Bbb{R}} f_n(x) dx \tag{1}$$
Where, $$f_n(x) = \begin{cases} 0, x \leq 0 \\
x^n e^{-x} , x > 0 \end{cases}$$
An interesting property of the integral is that, we can shift it by any amount $\epsilon$ and the value should be same since we would still be integrating over the same domain :
$$I_n = \int_{\Bbb{R}} f_n(x+ \epsilon)  dx \tag{2}$$
Substracting (1) and (2),
$$ 0 = \int_{\Bbb{R}} \left[ f_n(x+ \epsilon) - f_n(x) \right] dx$$
Divide both side by $\epsilon$ and sending $\epsilon \to 0 $, we have:
$$ 0 =\int_{\Bbb{R}} f_n'(x) dx$$
For $n>1$ , the function is differentiable at $x=0$, and hence:
$$ \int_{\Bbb{R}} f_n'(x) dx = \int_0^{\infty} nx^{n-1} e^{-x} - x^n e^{-x} dx =0$$
Using (1), we have:
$$ n I_{n-1} = I_n$$
By finding $I_1$, we can solve the above recurrence relation which leads to $I_n = n!$.

*

*Is there a name for the method I've used here?

*Are there other integrals where this method would be helpful in evaluating?

A: If $\int_{\Bbb R}g(x)dx$ converges$$0=\lim_{\epsilon\to0}\int_{\Bbb R}\frac{g(x+\epsilon)-g(x)}{\epsilon}dx\stackrel{!}{=}\int_{\Bbb R}\lim_{\epsilon\to0}\frac{g(x+\epsilon)-g(x)}{\epsilon}dx=\int_{\Bbb R}g^\prime(x)dx$$assumes the integration operator commutes with the limit operator, while$$\int_{\Bbb R}g^\prime(x)dx\stackrel{!}{=}\lim_{x\to\infty}g(x)-\lim_{x\to-\infty}g(x)$$assumes the limits exist. For $g=f_n$, your strategy is the top approach and the usual strategy is the bottom one (and I leave it to you to explain why both strategies' assumptions hold), but both note $f_n^\prime=nf_{n-1}-f_n$. I think that answers part $2$. To address part $1$, I think all that would be named is theorems that justify the aforementioned operator exchange (six are listed here).


Q: Why does isEqualToString not work for NSString? I am trying to code the login process for an iPhone app in XCode. The problem is with the NSString serverOutput below. When I print it using printf(serverOutput.UTF8String); it prints 'Yes' to the console. However when I compare serverOutput to "Yes" it doesn't work. Any help would be appreciated. Here's my code:
- (IBAction) loginButton: (id) sender
{
    // TODO: spawn a login thread

    indicator.hidden = FALSE;
    [indicator startAnimating];
    NSString *post =[NSString stringWithFormat:@"username=%@&password=%@",userName.text, password.text];

    NSString *hostStr = @"http://10.243.1.184/connectDB.php?";
    hostStr = [hostStr stringByAppendingString:post];
    NSData *dataURL =  [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
    NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
    printf(serverOutput.UTF8String);

    if([serverOutput isEqualToString:@"Yes"]){

        UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Congrats" message:@"You are authorized"
        delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

        [alertsuccess show];
        [alertsuccess release];

    }
    else {
        UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Username or Password Incorrect"
        delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
        [alertsuccess show];
        [alertsuccess release];
        //[self.navigationController pushViewController:DashboardViewController animated:YES];
        loginbutton.enabled = TRUE;

    }

    loginbutton.enabled = FALSE;
}

A: Based on helping others with similar situations I would say the problem is that the response from the server isn't just the string "Yes". Most likely there is some whitespace before and/or after the text. Perhaps a stray newline or two.
Try this:
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(@"Result = '%@'", serverOutput); // look for space between quotes
serverOutput = [serverOutput stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


Q: php limit mail () this might be easy but I don´t see the way. I have a shopping cart at my side where user can buy things. for this the buyer can  imput his email-adress into an input-form. the order is sent with php mail() to the shopowner and the buyer.
I´m looking for a way to limit mail to sent only two email, this for preventing spam.
I see the risk that spammers could input a semicolon string like this:
email@examplecom;email@xxyz.com;hans@jdkdl.com

A: Y can't you validate using .
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
  $headers .= "Reply-to: $validemail\r\n";
}else
{
//redirect.
}

considering your actual question .
<?php
$emails = explode(';',$emailList);
if(count ($emails)<3)
{
if(filter_var_array($emails, FILTER_VALIDATE_EMAIL))
    {
    mail();
    }
  else
    {
    //die
    }
}
?>

A: You could check the number of email in the string like this:
if(count(explode(';',$emailList))<3)
{
    // send email
}
else
{
    // Oh no, jumbo!
}

This code will explode your email string based on the ; characters into an array while at the same time use a count function on the array and execute one of two scenarios based on the number.

A: This should work to only pick maximum two emails (the first two):
$emailString = "email@examplecom;email@xxyz.com;hans@jdkdl.com";
$emails = explode(";", $emailString);
$emails = array_slice($emails, 0, 2);
$emailString = implode(";", $emails);
var_dump($emailString);

Outputs:
string(31) "email@examplecom;email@xxyz.com"


Q: Kinect Html5 Stream to web in existing C# Application For our university project we need the kinect video Stream accessible from another Device in the network. Preferable as a HTML5 Webserver. The Microsoft.Samples Webserver works only with the kinect1 and we need it for kinect 2. Another interesting solution is the one from intrael but we need to implement it in our own application.
Are there any solutions I didn't find or could anyone give us a working example or hint how to proceed?

A: If someone stumbles across this we solved this now with using a simple TCP Listener which listens for a connection:
 TcpListener srv = new TcpListener(IPAddress.Any, 51530);
        srv.Start(1);

        client = srv.AcceptTcpClient();

Then we changed the Kinectpicture into a Bitmap and on every new picture we send the bitmap to the connected device:
NetworkStream ns = client.GetStream();

            Graphics g = Graphics.FromImage(bitmap);

            MemoryStream imageStream = new MemoryStream();

            using (var ms = new MemoryStream())
            {
                Bitmap bmp = new Bitmap(bitmap);
                bmp.Save(imageStream, ImageFormat.Bmp);
            }

           // bitmap.Save(imageStream, ImageFormat.Bmp);
            Console.WriteLine("Bild wird über Socket geschickt");
            //reset the memory stream to start of stream
            imageStream.Position = 0;
            //copy memory stream to network stream
            imageStream.CopyTo(ns);
            //make sure copy is completed
            imageStream.Flush();
            imageStream.Close();

            //Makes sure everything is sent before closing it
            ns.Flush();

on the other side there is an android device which gets the network stream and translates it into a bitmap and shows it in an imageview.
Feel free to ask additional questions for needed clarification.


Q: Response.Redirect not sending string i've got a bit of a problem trying to set up a general error page in MVC.
I am handling all app errors in Global.asax.cs with the following code ->
protected void Application_Error(object sender, EventArgs e)
{
    //if (Request.Url.ToString().StartsWith("http://localhost:"))
    //    return;
    string msg;
    Exception ex = Server.GetLastError().GetBaseException();
    StringBuilder sb = new StringBuilder();
    sb.AppendLine("Exception Found");
    sb.AppendLine("Timestamp: " + System.DateTime.Now.ToString());
    sb.AppendLine("Error in: " + Request.Url.ToString());
    sb.AppendLine("Browser Version: " + Request.UserAgent.ToString());
    sb.AppendLine("User IP: " + Request.UserHostAddress.ToString());
    sb.AppendLine("Error Message: " + ex.Message);
    sb.AppendLine("Stack Trace: " + ex.StackTrace);
    msg = sb.ToString();
    Server.ClearError();
    Response.Redirect(string.Format("~/Error/Error?w={0}", msg ));
}

My problem is that i'm not getting a redirect. I see the same page URL and a blank page when i'm creating an error.
If i remove "errorMsg" and add a SIMPLE STRING, it works, redirects with the required param. Ex:
string test = "testme";
Response.Redirect(string.Format("~/Error/Error?w={0}", test));

That does redirect me to the error page with param "testme". What am i doing wrong here?

A: You to need escape all the parameters (UrlEncode). At the moment it is unescaped and has a whole bunch of new lines too.
Before you do that, I suggest you just append "hello world" parameter and re-display that to ensure your redirect page is working


Q: Display from database if 2 columns match I am new to Laravel and am currently I am working on a very basic private messaging system.
Currently I am trying to display a page which shows the messages between 2 users (sent and received), however I am only able to display the messages which the user has sent. Here is my viewMessage function in my MessageController file.
MessageController.php
public function viewMessage($recipient_id){

    $user = auth()->user()->id;

    $messages = Message::where('sender_id', $user)->where('recipient_id', $recipient_id)->get();

    return view ('pages.messages.view', compact('user', 'messages'));
}

View Blade

    @foreach ($messages as $message)

{{$message->body}}

    @endforeach

As you can see from the $messages variable, i have a query builder which should match the sender ID with the ID of the current logged in user. It should also match the recipient ID with the ID of the user from the parameter, however this does not currently work.
I have used dd() and both sender id and recipient id is coming through correctly so I am at a loss as to why this is not working. I am assuming I am probably using the query builder incorrectly?
Thanks

A: You are only asking for messages the user sent. You need to also get messages that the user received.
$user = auth()->user()->id;

$messages = Message::where('sender_id', $user)->where('recipient_id', $recipient_id)->get();

$receivedMessages= Message::where('sender_id', recipient_id)->where('recipient_id', $user)->get();


Q: More than 5 Batch Apex issue I am getting the below issue, while performing Run All test in my Org. we have a good amount of batch classes,around 15, and we wrote the test classes for them where we are calling the batch Database.execute to cover the batch class. we have put all execute call between Test.startTest and Test.stopTest

Failure Message: "System.LimitException: Attempted to schedule too
  many concurrent batch jobs in this org (limit is 5)."

Please suggest the solution..

A: Have you tried to disable parallen apex testing, as you're already making use of Test.startTest and Test.StopTest this should prevent test methods to run at the same time.
Setup > Develop > Apex Test Execution > options (button on the top)
---> chek the Disable Parallel Apex Testing chekbox

A: By default now Salesforce runs tests at the same time. So the combination of several tests might be pushing you over the limit. You can disable this behaviour in setup | develop | apex Test Execution then click on the Options button.

Edit--
You can read more about this in the Spring release notes, page 111 https://na10.salesforce.com/help/doc/en/salesforce_spring13_release_notes.pdf. Note "Tests that are run as part of a deployment, a package install, or a package upload still run synchronously."

A: If you are running into this limit in a non test context there is no such easy cure. You basically have to build you own Apex queue. Which I did ;) and as part of a GitHub project
I would love to get your feedback and invite you to fork and collaborate on it.


Q: How to export strings from Java (Android) to MS Word I want to know how to export typed strings to a word document file.
The application I'm trying to make should be simple; User has his application on his Android phone and he types in some text.
It will have few PlainText and MultilineText text fields, in which the user will be able to type, whatever he wants.
So, when a user connects his mobile to the computer, he should be able to click some button and 'generate report'.
That way, all the text he typed in should be transformed into a word doc.
Is there a way of doing this?

A: You'll want to use some sort of java library for Microsoft Office. Take a look at Apache POI for this. Here's an example of using Apache POI.
As a side note, I would also recommend that the user doesn't have to actually connect their device to the computer, but rather make an export feature which will create the Word Document and they can e-mail it or share it in some other way. This would improve your User Experience :)


Q: Handling entities in react? I am very new to react, redux, prop-types and so on. I am coming from the Angular2 world with TypeScript support. There I had my own entity classes which I imported in the components where I need them. Now in react I only have prop-types which I define for each component.
All fine and good but how would you solve this data structure with prop-types:
{
    "order": {
        "date": "2018-03-20",
        "customer": {
            "firstName": "John",
            "lastName": "Brown"
        },
        "product": {
            "category": "book",
            "name": "XYZ"
        },
        "price": 99
    }
}

In Angular2 I would have made three entities, but how I will handle this in react with prop-types? Sure I can define the correct prop-types for this data structure in each component where I got an order entity passed via props but this looks like a huge code redundancy for me.
My question now: Is there any best practice solution for this problem? Maybe a central prop-types schema like this module: https://www.npmjs.com/package/react-entity?
(I don't want to use this module because it seems that it is not under development anymore)

A: If you want to use types in React that are richer than what PropTypes can provide you, you have two options:

*

*Use TypeScript. This does not come out of the box, so you have to change your build. There are a bunch of bootstrapper projects that can make your life easier.

*Use Flow. The standard bootstrappers such as CRA come with support for it out of the box.

Which one to use is a matter of preference at the end. Both have their advantages. Here you have a pretty good comparison of what both can do.


Q: Get multiple input type hidden value row button click for column in table This is sample column for single row where i have tried to get hidden value by button action event

    <input type="hidden" class="itemid" name="stockitemid" value="@item.ID"/>
    <input type="hidden" class="oid" name="outletid" value="@item.OUTLET_ID"/>

            <button class="btn btn-primary" id="btnitemaddtotray" data-toggle="modal" data-target="#addtotrayModal" title="Add Item"></button>

Hhere is my retrieval jquery code every time i get same "stockitemid" and "outletid"

I want to get hidden value from table where i have multiple row.

A: ID should always be unique to each element, so I am using a class instead. Use of parents() will give you the the container to find() the hidden inputs in to retrieve the values.

$('.btnitemaddtotray').on('click',function() {

  var btn = $(this),
      row = btn.parents('td').first();
      itemId = row.find('.itemid').val(),
      oid = row.find('.oid').val();

      console.log(itemId,oid);
});

    <input type="hidden" class="itemid" name="stockitemid" value="@item.ID"/>
    <input type="hidden" class="oid" name="outletid" value="@item.OUTLET_ID"/>

    <button class="btn btn-primary btnitemaddtotray" data-toggle="modal" data-target="#addtotrayModal" title="Add Item">Add Item</button>

    <input type="hidden" class="itemid" name="stockitemid" value="@item.ID2"/>
    <input type="hidden" class="oid" name="outletid" value="@item.OUTLET_ID2"/>

    <button class="btn btn-primary btnitemaddtotray" data-toggle="modal" data-target="#addtotrayModal" title="Add Item">Add Item</button>


Q: How do I stop my backtracking algorithm once I find and answer? I have wrote this code for solving a problem given to me in class, the task was to solve the "toads and frogs problem" using backtracking. My code solves this problem but does not stop once it reaches the solution (it keeps printing "states" showing other paths that are not a solution to the problem), is there a way to do this?. This is the code:
def solution_recursive(frogs):
    #Prints the state of the problem (example: "L L L L _ R R R R" in the starting case
    #when all the "left" frogs are on the left side and all the "right" frogs are on
    #the right side)
    show_frogs(frogs)

    #If the solution is found, return the list of frogs that contains the right order
    if frogs == ["R","R","R","R","E","L","L","L","L"]:
        return(frogs)

    #If the solution isn't the actual state, then start (or continue) recursion
    else:

        #S_prime contains possible solutions to the problem a.k.a. "moves"
        S_prime = possible_movements(frogs)

        #while S_prime contains solutions, do the following
        while len(S_prime) > 0:
            s = S_prime[0]
            S_prime.pop(0)
            #Start again with solution s
            solution_recursive(s)

Thanks in advancement!

A:
How do I stop my backtracking algorithm once I find an answer?

You could use Python exception facilities for such a purpose.
You could also adopt the convention that your solution_recursive returns a boolean telling to stop the backtrack.
It is also a matter of taste or of opinion.

A: I'd like to expand a bit on your recursive code.
One of your problems is that your program displays paths that are not the solutions. This is because each call to solution_recursive starts with
show_frogs(frogs)

regardless of whether frogs is the solution or not.
Then, you say that the program is continuing even after the solution has been found. There are two reasons for this, the first being that your while loop doesn't care about whether the solution has been found or not, it will go through all the possible moves:
while len(S_prime) > 0:

And the other reason is that you are reinitializing S_prime every time this function is called. I'm actually quite amazed that it didn't enter an infinite loop just checking the first move over and over again.
Since this is a problem in class, I won't give you an exact solution but these problems need to be resolved and I'm sure that your teaching material can guide you.


Q: In postgresql, which part of locale causes problems with LIKE operations? There's a lot of discussion around the net about locale other than C or POSIX causing performance problems in postgresql.  I'm not clear though as to which part(s) of the locale setting cause problems and why.
In the manpage for initdb(1), we see:
--locale=locale
 Sets the default locale for the database cluster. If this option is not specified, the locale is inherited from the environment that
 initdb runs in. Locale support is described in Section 22.1, \u201cLocale Support\u201d, in the documentation.

--lc-collate=locale, --lc-ctype=locale, --lc-messages=locale, --lc-monetary=locale, --lc-numeric=locale, --lc-time=locale
  Like --locale, but only sets the locale in the specified category.

We also see:
   To alter the default collation order or character set classes, use the --lc-collate and --lc-ctype options. Collation orders other than C or
   POSIX also have a performance penalty. For these reasons it is important to choose the right locale when running initdb.

Does this mean that I could use --lc-collate POSIX --lc-ctype UTF-8 and avoid performance penalties?  Or are there other performance issues involved?
I'm not surprised that collation affects sort performance, but is that the same issue that arises with LIKE comparisons not using indexes?  Can someone explain what the issue is with the LIKE operator?

A: It sounds like you're talking about the text_pattern_ops operator class and its application for databases that are in locales other than C.
The issue is not one of encoding, but of collation.
A b-tree index requires that everything have a single, stable sort order following some invariants, like the assumption that if a < b then b > a. Comparison operators are used to sort the tree when building and maintaining and index.
For text strings, the collation rules for the language get applied by the comparison operators when determining whether one string is greater than or less than another so that strings sort "correctly" as far as the user is concerned. These rules are locale-dependent, and can do things like ignore punctuation and whitespace.
The LIKE operator isn't interested in locales. It just wants to find a prefix string, and it can't just ignore punctuation. So it cannot use a b-tree index that was created with a collation that might ignore punctuation/whitespace, etc. LIKE walks down the index tree character by character to find a match, and it can't do that if the index might ignore characters.
That's why, if your DB uses a locale other than "C" (POSIX) you must create different indexes for use with LIKE.
Example of localised sorting, compare:
regress=> WITH x(v) AS (VALUES ('10'),('1'),('1.'),('2.'),('.2'),('.1'),('1-1'),('11')
)
SELECT v FROM x ORDER BY v COLLATE "en_AU";
  v
-----
 1
 .1
 1.
 10
 11
 1-1
 .2
 2.
(8 rows)

regress=> WITH x(v) AS (VALUES ('10'),('1'),('1.'),('2.'),('.2'),('.1'),('1-1'),('11')
)
SELECT v FROM x ORDER BY v COLLATE "C";
  v
-----
 .1
 .2
 1
 1-1
 1.
 10
 11
 2.
(8 rows)

The text_pattern_ops opclass serves this need. In newer PostgreSQL releases you can create an index with COLLATE "C" on the target column instead, serving the same need, e.g.:
CREATE INDEX idx_c ON t2(x COLLATE "C");

LIKE will use such an index, and it can also be used for faster sorting where you don't care about locale for a given operation, e.g.
SELECT x FROM t2 ORDER BY x COLLATE "C";


Q: Trying to understand the differences across these promises and setTimeouts I'm learning about promises, setTimeout and async calls and have done a great job of confusing myself. I think I'm lacking some understanding around the callback and how setTimeout works. I've been looking at Mozilla documentation and the various Stackoverflow posts regarding these topics. I'm still having some trouble wrapping my head around why some of the functions I've created behave the way they do regarding the timeouts that are set.
Between wait0 and wait1 I don't understand why the timeout for wait0 works properly and wait1 doesn't adhere to it. With wait2 it is like wait1 except wrapped in an arrow function expression. Why does that make the timeout work properly? wait3 isn't actually using the callback so that makes sense why the promise and then functions don't do anything. But it stops wait4 from running. Is it blocking progression indefinitely or actually ending execution? For wait4 I'm also not passing a value into the callback like with wait0 but the timeout isn't being adhered to.
function wait0() {
    return new Promise((resolve, failure)=>{
    setTimeout(resolve, 2000);
  });
}

function wait1() {
    return new Promise((resolve, failure)=>{
    setTimeout(resolve('resolved ' + new Date().toGMTString()), 2000);
  });
}

function wait2() {
    return new Promise((resolve, failure)=>{
    setTimeout(()=>{
        resolve('resolved ' + new Date().toGMTString());
    }, 2000);
  });
}

function wait3() {
    return new Promise((resolve, failure)=>{
    setTimeout(()=>{}, 2000);
  });
}

function wait4() {
    return new Promise((resolve, failure)=>{
    setTimeout(resolve(), 2000);
  });
}

async function test() {
  await wait0().then((result)=>console.log(result)); // Works as expected
  console.log(new Date().toGMTString());
    await wait1().then((result)=>console.log(result)); // Doesn't adhere to timeout
  console.log(new Date().toGMTString());
  await wait2().then((result)=>console.log(result)); // Works as expected
  console.log(new Date().toGMTString());
  await wait3().then((result)=>console.log(result)); // Never resolves
  console.log(new Date().toGMTString());
  await wait4().then((result)=>console.log(result)); // Doesn't adhere to timeout
  console.log(new Date().toGMTString());
}

test();


Q: modelsim script for compile all I have a modelsim project file (*.mpf), where it lists all the HDL files, and it provides a "compile_order" for each file.
So, when I load the (.mpf) file, I can see that each one of my HDL files have a compoile_order number next to it. So far so good.
Now, on the GUI, I can run "compile all", and it will compile all my files in correct order, since the orders are already pre-determined.
I want to know that what is the tcl command line that is equivalent to the "compile all" in the GUI?
In other words, I want to be able to type a command and it compiles all the files, rather than I do "compile all" through the GUI.

A: You're looking for the command project. You can use it in a "*.do" file this way :
project open MyProject.mpf
project compileall

For all others modelsim commands, you can look at the Modelsim Command Reference Manual. Project command is described in page 220.


Q: Plugin reload doesn't remove ToolButton from MenuBar I have this in my initGui() Function:
        self.add_action(
            icon_path,
            text=self.tr(u'ReKoTi Plugin'),
            callback=self.run,
            parent=self.iface.mainWindow())
        self.toolBar = self.iface.addToolBar("MY TOOLBAR tools")
        self.action = QAction(QIcon(icon_path), 'Validate Layers', self.iface.mainWindow())
        self.action.triggered.connect(self.validate_layers)
        self.iface.addPluginToMenu('&ReKoTi Plugin', self.action)
        self.iface.addToolBarIcon(self.action)

        self.toolBar = self.iface.mainWindow().findChild( QToolBar, u'ReKoTi Plugin' )
        if not self.toolBar:
            self.toolBar = self.iface.addToolBar( u'ReKoTi Plugin' )
            self.toolBar.setObjectName( u'ReKoTi Plugin' )

        self.popupMenu = QMenu(self.iface.mainWindow())
        self.actionMass = QAction("Mass", checkable=True)
        self.popupMenu.addAction(self.actionMass)
        self.toolButton = QToolButton(text="Calculations")

        self.toolButton.setMenu(self.popupMenu)
        self.toolButton.setPopupMode(QToolButton.InstantPopup)
        self.iface.addToolBarWidget(self.toolButton)

And this is my unload() Function:
       for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&ReKoTi Plugin'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar
        self.iface.removeToolBarIcon(self.action)
        self.iface.removePluginMenu('&ReKoTi Plugin', self.action)
        del self.action
        del self.toolButton
        del self.popupMenu

But when I reload my Plugin, the toolButton won't get deleted and a new one gets generated. What can I do so the old Button gets delted aswell? I also tried to set the visibility to False, but this didn't work.