text:
Q: Finding the Number of Business Hours Between Two Date/Times (8am -5pm) I am using Salesforce and I want to find the difference in hours when a ticket is open and closed/now(when still open). For this case, I am using the following query
ROUND( 8 * (
   ( 5 * FLOOR( ( DATEVALUE( ClosedDate ) - DATE( 1900, 1, 8) ) / 7) +
    MIN(5,
     MOD( DATEVALUE(ClosedDate ) - DATE( 1900, 1, 8), 7) +
     MIN( 1, 24 / 8 * ( MOD(ClosedDate  - DATETIMEVALUE( '1900-01-08 16:00:00' ), 1 ) ) )
    )
   )
 -
   ( 5 * FLOOR( ( DATEVALUE(CreatedDate) - DATE( 1900, 1, 8) ) / 7) +
     MIN( 5,
      MOD( DATEVALUE( CreatedDate ) - DATE( 1996, 1, 1), 7 ) +
      MIN( 1, 24 / 8 * ( MOD( CreatedDate - DATETIMEVALUE( '1900-01-08 16:00:00' ), 1) ) )
    )
   )
  ),
0 )

Which is shown here
But I'm getting this error

Is there any other way I can get the difference in dates in the number of hours?

A: To find the difference for the exact age of a case and compare the opened date with closed date, you should use the following formula:
IF(
ClosedDate - CreatedDate > 0 ,
TEXT( FLOOR( ClosedDate - CreatedDate ) ) & " days "
& TEXT( FLOOR( MOD( (ClosedDate - CreatedDate ) * 24, 24 ) ) ) & " hours "
& TEXT( ROUND( MOD( (ClosedDate - CreatedDate ) * 24 * 60, 60 ), 0 ) ) & " minutes",
""
)

The result of this would be a returned as a text that would look like this:
6 days 15 hours 45 minutes

You can modify this slightly to get the numerical value to use in reports. However, the numbers are going to be in base ten.
In order to factor in the business hours the following formula worked for me:
ROUND( 8 * (
   ( 5 * FLOOR( ( DATEVALUE( ClosedDate ) - DATE( 1900, 1, 8) ) / 7) +
    MIN(5,
     MOD( DATEVALUE( ClosedDate ) - DATE( 1900, 1, 8), 7) +
     MIN( 1, 24 / 8 * ( MOD( ClosedDate - DATETIMEVALUE( '1900-01-08 16:00:00' ), 1 ) ) )
    )
   )
 -
   ( 5 * FLOOR( ( DATEVALUE( CreatedDate ) - DATE( 1900, 1, 8) ) / 7) +
     MIN( 5,
      MOD( DATEVALUE( CreatedDate ) - DATE( 1996, 1, 1), 7 ) +
      MIN( 1, 24 / 8 * ( MOD( CreatedDate - DATETIMEVALUE( '1900-01-08 16:00:00' ), 1) ) )
    )
   )
  ),
0 )

The result of this would be returned as a number that would look like this: 91.00 hours


text:
Q: Non-Ridge Kernelized Regression? Every presentation that I have seen for kernelized regression focuses on finding
$$\underset{f \in \mathcal{H}_k}{\min} \sum_{i=1}^{n}(y_i-f(\mathbf{x}_i))^2+\lambda \|f\|^2_{\mathcal{H}_k}.$$
Here, $\mathcal{H}_k$ is a Reproducing kernel Hilbert space (RKHS).
I was wondering

*

*Why the focus on ridge regression? Can we use other penalties here, or is there something about the ridge penalty that is natural in this setting?

*Can we do un-penalized kernelized regression? Why is this not usually presented prior to kernel ridge regression?

A: Great question!
Alternative Norms Exist (kind of): Though we call it "Kernel Ridge", let's take a second to note that the norm we're using is the RKHS norm (whereas regular "ridge regression" penalizes the $\ell_2$ norm of the parameter vector). One could consider a different function space norm to be penalized instead, like an $L_p$ norm. Alternatively, we could directly penalize the kernel coefficients, as in this article about kernel lasso. But yeah, what's so nice about the RKHS penalty is that its solution is available in closed form (from the Bayesian perspective, it is a conjugate prior to the normal likelihood). GPs wouldn't be nearly as popular if you needed to solve a nonlinear optimization program to use them. (but you often do anyways if you have enough kernel hyperparameters to estimate...)
Other Approaches than Penalties Exist (kind of): The reason we usually use regularization in kernel regression is because we have, in effect, an infinite dimensional parameter space, with one "column" associated with each possible input location: $k(\mathbf{x},.)$. Without regularization, there are not only infinitely many solutions which interpolate our data (which is possible in underdetermined, finite-dimensional regression), but indeed most of those solutions are made of infinitely many kernel functions $\hat{f}=\sum_{i=1}^\infty a_i k(\mathbf{x}_i,.)$. So we want some way of simplifying things. But it doesn't have to be a penalty per se. Usually we solve:
$$ \min_{f\in\mathcal{H}_k} \sum_{i=1}^N (f(\mathbf{x}_i)-y_i)^2+\lambda||f||_{\mathcal{H}_k} $$
which has solution given by $\alpha = (\mathbf{K}+\lambda \mathbf{I})^{-1}\mathbf{y}$ then $\hat{f}=\sum_{i=1}^N \alpha_i k(\mathbf{x}_i,.)$.
But instead of solving a penalized problem, we could instead solve this constrained one:
$$ \min_{f\in\mathcal{H}_k} ||f||_{\mathcal{H}_k}$$
$$\textrm{Such that:}$$
$$\sum_{i=1}^N (f(\mathbf{x}_i)-y_i)^2 = 0 $$
Which has solution given by $\alpha = (\mathbf{K})^{\dagger}\mathbf{y}$, where $\mathbf{A}^\dagger$ gives the Moore-Penrose Pseudoinverse of $\mathbf{A}$. [I should mention I have the noiseless case in mind here, where $y_i$ is observed exactly as $f(\mathbf{x}_i)$].
Now the reason I put "kind of" above is that this is clearly what the limit of our penalty method gives us as $\lambda\to 0$, so while not a penalty method, it is a limit of them. There may be other, truly different ways of sieving it down to a finite dimensional approximation space that are useful in applications, but I haven't personally run into them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Colouring Pins on a Map I'm trying to mark a starting pin and ending pin on my map with different colours. Maybe the starting pin in green and the ending pin in red.
My code below, reads the latitude / longitude coordinates from core data and loops around placing a red pin for each object found in core data.
MapPin.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface MapPin : NSObject <MKAnnotation>{

    CLLocationCoordinate2D coordinate;
}

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

-(id)initwithCoordinates:(CLLocationCoordinate2D)location;

@end

MapPin.m
#import "MapPin.h"

@implementation MapPin

@synthesize coordinate;

-(id)initwithCoordinates:(CLLocationCoordinate2D)location
{
    self = [super init];
    if (self != nil) {
        coordinate = location;
    }
    return self;
}

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

MapViewController.m
-(void)addAnnotations
{
    if (![sharedMapID isEqualToString:@""]){
        NSFetchRequest *request = [[NSFetchRequest alloc] init];

        NSEntityDescription *entity = [NSEntityDescription entityForName:@"WayPoint" inManagedObjectContext:managedObjectContext];
        [request setEntity:entity];

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"waypoint_map_id contains[cd] %@", sharedMapID];
        [request setPredicate:predicate];

        NSError *error = nil;
        NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];

        // Check for errors from the FetchRequest
        if (nil == results || nil != error)
            NSLog(@"Error getting results : %@", error);

        listArray = [results mutableCopy];
        [request release];

        // Loop through the array, get the coordinates and display on the map.
        for (int i = 0; i < [listArray count]; i++)
        {
            NSString *strXCoordinate = [[listArray objectAtIndex: i] valueForKey:@"waypoint_x"];
            NSString *strYCoordinate = [[listArray objectAtIndex: i] valueForKey:@"waypoint_y"];

            double dblXCoordinate = [strXCoordinate doubleValue];
            double dblYCoordinate = [strYCoordinate doubleValue];

            CLLocationCoordinate2D coordinate = {dblYCoordinate, dblXCoordinate};
            MapPin *pin = [[MapPin alloc]initwithCoordinates:coordinate];
            [self.mapView addAnnotation:pin];
            [pin release];
        }

        [listArray release];
    }
}

From what I've read and some examples I found when googling the following code is called for each pin on the map. Its not placing any green pins on my map. Maybe I should passing coordinates to this method and allowing it to place the pin on the map instead of the code above.
    - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
    {
        MKPinAnnotationView *annView = nil;
        annView.pinColor = MKPinAnnotationColorGreen;
        annView.animatesDrop = TRUE;
        annView.canShowCallout = YES;
        annView.calloutOffset = CGPointMake(-5, 5);
        return annView;
}

Any help or a push in the right direction (excuse the pun) is very much appreciated.
Regards,
Stephen

A: MKPinAnnotationView *annView = nil;
...

You do not create annotation view here, just operate with nil object (that works fine but does nothing) and return nil - so naturally pin is not display (as it does not exists).
Correct method will look like:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKPinAnnotationView *annView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"SomeID"];
    if (!annView){
        annView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"SomeID"] autorelease];
        annView.pinColor = MKPinAnnotationColorGreen;
        annView.animatesDrop = TRUE;
        annView.canShowCallout = YES;
        annView.calloutOffset = CGPointMake(-5, 5);
    }
    annView.annotation = annotation;
    return annView;
}

Here you try to reuse annotation view if possible (similar way you do with cells in table view), create and setup new one if not


text:
Q: IntelliSense suggestions for method parameter input I have static class as container for some static strings:
public static class Constants
    {
        public static string ERROR_MESSAGE_LOGIN= "Unable to login with {0}";
        public static string ERROR_MESSAGE_SEND_MAIL= "Unagle to send mail to {0}";

        public static string GetFormatedString(string constantName, object [] params)
        {
            return
            string.Format((string)typeof(Constants).GetField(constantName).GetValue(null),params);
        }
    }

As you can see I want to return formatted string, that based on name provided. And it is seems to work. However, when I writing method call in some other class I want that it give me list of suggestion for first parameter that contains "ERROR_MESSAGE_LOGIN" and "ERROR_MESSAGE_SEND_MAIL".
I know that I can create enum with those name or just use it like
Constants.GetFormatedString(Constants.ERROR_MESSAGE_SEND_MAIL, someparams);

But is there any way to tell method there is list of string parameters that you accept and show it to user in Visual Studio IntelliSense?
Thank you.


text:
Q: What would p(a,b|a) be equal to? What is p(a,b|a) equal to in conditional probability? Any sort of breakdown as to why it might be equal to p(b|a) would be helpful (if it is true in all cases).
My reasoning for asking this question came from a Hastie's (2001) book where one is trying to find E(f(a,b)|a) in the partial dependence plots section. It then got me curious about p(a,b|a).

A: If $a$, $b$ are some events, e.g. $a$: it is raining, $b$: you have your umbrella with you, then, you are asking for P(it is raining and you have umbrella | it is raining). You know that it is raining, so, intuitively, no need to question if it is raining or not again, and this probability equals to P(you have umbrella | it is raining), which will mean $p(a,b|a)=p(b|a)$.
In case of random variables, as @Robin points out, if $A$ and $B$ are the RVs responsible for $a$ and $b$ respectively, the expression should be written in this form: $P(A=a, B=b|A=a)$ in order to prevent any confusions. Because, if $a$ and $b$ are just constants, then what you are asking seems like $p(1,2|1)$, which is ambiguous.
If $a$ and $b$ are random variables themselves, then we lack the particular values. The expression should be like $P(a=a',b=b'|a=a'')$. Here, if $a'' \neq a'$, then given that $a$ equals to $a''$, it cannot be equal to $a'$, and the probability will be $0$. If, $a''=a'$, then again, since we know what the value of $a$ is, the probability will be equal to $p(b=b'|a=a')$, which can be summarized with the help of a $\delta$ function if you like to write it in a compact form, as in @Robin's answer. (P.S. Don't confuse $\delta$ with continuous dirac-delta function).

A: You have $P(A = a', B = b \mid A = a) = P(B = b \mid A = a) \delta(a = a')$ where $\delta(a = a')$ is equal to 1 only if $a = a'$


text:
Q: Optimizing libraries with web pack I am attempting to publish a small library of react UI components. These components have dependencies: Matarial UI, React Rotuer, etc;
When I build my code I get a warning about exceeding the recommended bundle size. I am at 451Kib. When I analyze my bundle I notice that 96.1% of it is dependencies that have been added to the bundle from node_modules.
Since I am only going to be publishing a handfull of components that are also going to be imported with webpack, is there a way to exclude the dependencies from my bundle and have them packaged in the bundle of any app that uses my components?
I think I need to use code-splitting, or lazy-loading, or something, but I am not sure of the proper way to get started.

A: Pieces of Advice I can give you:

*

*Use webpack-node-externals to exclude node_modules from bundle. If your code depends on packages that won't be included in the user app - use whitelist to bundle them as well.

*Also mark Matarial UI, React Rotuer (and probably react) as peerDependecies in package.json.


text:
Q: Signal R Hub Conventions in regards to Web Api's I am trying out signalR with a simple blog poster and i am unsure as to what would be best practice in implementing it.
First Solution:
Have the client invoke the post method on the server which will in turn either supply the data to the relevant web api or other method of uploading the data. my intention here to use the already open connection.
public class BlogHub : Hub
{
    public void Post(string text)
    {
        //Internal Webapi call / other method of DB Update.

        Clients.All.BroadcastPost(text);
    }
}

Second Solution:
Have the client do a ajax call to a web api which then calls the post method and broadcasts it back to the client.
public void PostPost(string text) //May have to call this method something different...
{
    db.posts.add(new PostModel(text));
    db.SaveChanges();
    Post(string Text);
}

third solution:
Another (probably better) method i haven't thought of.
fourth Solution:
I'm horribly abusing how signalR should be used.
Thanks in advance!

A: You should use whatever is the most direct way of satisfying your requirements. That said, calling a WebAPI action from a SignalR hub or vice versa is not a good approach. WebAPI actions and Hub methods provide an interface for a specific type of communication. Any internal calls should then go to specific classes which handle your business logic. You can access your hub context in those classes with GlobalHost.ConnectionManager.GetHubContext<MyHub>(); See the hub documentation for an example.
As long as you're only talking about strings and other data which can be serialized to JSON effectively, I don't see why you would need to involve WebAPI at all. If the work you need to do in your hub method is (potentially) long-running (e.g. a DB call), you can make the hub method asynchronous by returning a Task so it doesn't block the SignalR connection.
If, however, you want to upload binary data (images etc.), it would make sense to upload this to a WebAPI action. Note that you cannot call a hub method directly; instead (as I said above) you should factor out the code that updates all clients to a separate shared class which you then can call from your action.


text:
Q: Z-index issue with "You earned a new privilege" A picture is worth a thousand words:

Basically, as you can see, the "You earned a new privilege" box covers up the stackexchange drop-down.  Same thing with the notifications and achievements drop downs:

Not a critical bug, but probably not too difficult to clean up.  :)
I'm using Chrome 55 (latest stable version) on Ubuntu 16.04.


text:
Q: ejs support in nodejs. how I can got started to learning ejs? I want to use ejs framework in nodjes which is supported in nodejs through express framework. Do someone know any website or place which make me seen the code then I can get know how to write thing in ejs.

A: http://embeddedjs.com/
https://github.com/visionmedia/ejs


text:
Q: Procedurally set ImageVIew of GridView based on number I'm attempting to create a Gridview of icons with the Imageview set to one of two images like in my example below:

I'm retrieving two values from the sqlite content provider, one for the number of stamps and the other for the max number of stamps.
I use a custom adapter with a view holder pattern so I attempt to set the model onLoadFinished() in the Fragment.  The model I've currently tried is an int[] with either value of 0 or 1 in the values to determine if green stamp is used or gray.  This isn't working however as nothing is being displayed in the GridView.
Here's the code snippet from onLoadFinished() from the Fragment:
imageSourceModel = new int[data.getInt(data.getColumnIndex(RewardsEntry.COLUMN_REW_MAX_POINTS))];
        int i = data.getInt(data.getColumnIndex(RewardsEntry.COLUMN_REW_POINTS));
        for (int j = 0; j < imageSourceModel.length; j++, i--)   {
            if (i > 0)  {
                imageSourceModel[j] = 1;
            } else  {
                imageSourceModel[j] = 0;
            }
        }
        stampGridAdapter.setModel(imageSourceModel);

and the code from the custom Adapter:
@Override
public View getView(int i, View view, ViewGroup parent) {
    ViewHolder viewHolder;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.list_item_discover, parent, false);
        viewHolder = new ViewHolder(view);

        view.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) view.getTag();
    }
    if (model[i] > 0)   {
        viewHolder.stampView.setImageResource(R.drawable.ic_approved_stamp);
    } else  {
        viewHolder.stampView.setImageResource(R.drawable.ic_approved_stamp_disabled);
    }
    return view;
}

And simple ViewHolder:
private class ViewHolder {
    public ImageView stampView;

    public ViewHolder(View view)    {
        stampView = (ImageView) view.findViewById(R.id.grid_stamp_image);
    }
}

If I had to guess, I would say that it fails because of the creation order such that getView() is completed before onLoadFinished() can pass the model in.  I'm just not sure how to work around this or what other methods I could use.  Any help is appreciated.

A: For what you want to achieve, this seems unnecessary complicated to me, especially the double variable loop. To cut it simple I'd just do this:
in onLoadFinished()
int maxPoints = data.getInt(data.getColumnIndex(RewardsEntry.COLUMN_REW_MAX_POINTS));
int currentPoints = data.getInt(data.getColumnIndex(RewardsEntry.COLUMN_REW_POINTS));
mGridView.setAdapter(new RewardPointAdapter(getActivity(), currentPoints, maxPoints);

your adapter could look like this:
public class RewardPointAdapter extends BaseAdapter {
    private LayoutInflater mLayoutInflater;
    private int mMaxRewardPoints;
    private int mCurrentRewardPoints;

    public RewardPointAdapter(Context context, int currentRewardPoints, int maxRewardPoints) {
        mLayoutInflater = LayoutInflater.from(context);
        mMaxRewardPoints = maxRewardPoints;
        mCurrentRewardPoints = currentRewardPoints;
    }

    @Override
    public int getCount() {
        return mMaxRewardPoints;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.list_item_discover, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        if (position < mCurrentRewardPoints)   {
            viewHolder.stampView.setImageResource(R.drawable.ic_approved_stamp);
        } else  {
            viewHolder.stampView.setImageResource(R.drawable.ic_approved_stamp_disabled);
        }
        return convertView;
    }

    private class ViewHolder {
        public ImageView stampView;

        public ViewHolder(View view)    {
            stampView = (ImageView) view.findViewById(R.id.grid_stamp_image);
        }
    }

}


text:
Q: Unable to load images from image urls in App Notification Widget I am trying to show list of images in a collection view inside App Notification Widget.
Its giving me the error "Unable to load" if I am loading from urls, other than its working fine.
Can anyone please help me in this ?
TodaysCusCell *catTrendingCusCell = (TodaysCusCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"TodaysCusCellID" forIndexPath:indexPath];
NSDictionary *trendingDic = (NSDictionary *)[trendingArr objectAtIndex:indexPath.row];

//Loading Images
NSString *imageURL = [trendingDic objectForKey:@"image_url"];
[catTrendingCusCell.trendingImgView sd_setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"grayBackground"]];


text:
Q: Is there a way to connect to existing store instance I want to connect to the existing store instance in development mode to dispatch some actions to simulate the production environment.
I tried using:
https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/API/Methods.md#connect
but looks like it is creating a new instance every time. Is there a way to connect to existing store and dispatch an action using API?

A: If you want to use __REDUX_DEVTOOLS_EXTENSION__.connect() to connect to an existing instance, you need to know and reuse its instanceId. You can set this explicitly on the connect options object:
const instanceA = window.__REDUX_DEVTOOLS_EXTENSION__.connect({
  instanceId: 1234
});
const instanceB = window.__REDUX_DEVTOOLS_EXTENSION__.connect({
  instanceId: 1234
});

While instanceA !== instanceB, messages you .send to instanceA and instanceB should still end up together in the Redux DevTools extension.


text:
Q: task.getResult() is throwing a java.lang.ClassCastException I am using what is recommended by too many developers in order to retrieve the Uri of an image stored in the firebase storage , this my code :
final StorageReference filereference = storageReference.child(System.currentTimeMillis()
                    +"."+getFileExtension(imageUri));
uploadTask =filereference.putFile(imageUri);
uploadTask.continueWith(new Continuation<UploadTask.TaskSnapshot,Task<Uri>>() {
  @Override
  public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws
  Exception {
             if(!task.isSuccessful()){
             throw task.getException();
             }
             return filereference.getDownloadUrl();

}

}).addOnCompleteListener(new OnCompleteListener<Uri>() {
 @Override
 public void onComplete(@NonNull Task<Uri> task) {
 if(task.isSuccessful()){
 try{
     Uri downloadUri = task.getResult();
     String mUri =downloadUri.toString();
     }catch (Exception e){
     Log.e("testingerror",e.toString());
     }

it throws me this error :
com.example.asus.fireapp E/stayinsh: java.lang.ClassCastException: com.google.android.gms.tasks.zzu cannot be cast to android.net.Uri

A: Your code should work if your using a FirebaseStorage Api of 10.0.1 or less
what i mean is
 implementation 'com.google.firebase:firebase-storage:10.0.1'  or less
but if its greater use
StorageReference filepath=user_Image_ref.child(user_id+".jpg");
        filepath.putFile(resulturi).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                if(task.isSuccessful()) {
                    String getimageurl = task.getResult().getDownloadUrl().toString();

                    databaseReference.child("PHOTO").setValue(getimageurl);

                }else {
                    Toast.makeText(Register_activity.this,"errr",Toast.LENGTH_LONG).show();

                }
                String getimageurl = task.getResult().getDownloadUrl().toString();

                databaseReference.child("PHOTO").setValue(getimageurl);
            }
        });

A: It should be continueWithTask instead of continueWith
uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot,Task<Uri>>() {
  @Override
  public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws
  Exception {
             if(!task.isSuccessful()){
             throw task.getException();
             }
             return filereference.getDownloadUrl();

}


text:
Q: Listen to Browser's requests Using the following code:
HttpListener listener = new HttpListener();
//listener.Prefixes.Add("http://*:80/");
listener.Prefixes.Add("http://*:8080/");
listener.Prefixes.Add("http://*:8081/");
listener.Prefixes.Add("http://*:8082/");
listener.Start();
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;

The program hangs on the GetContext(); despite loading http (not https) pages in IE and Firefox.
When I uncomment the first line I get the error:

Failed to listen on prefix 'http://*:80/' because it conflicts with an
  existing registration on the machine.

So how do I listen to a browser's requests?

A:
@L.B I want to write a "proxy"

Don't reinvent the wheel and just use the FiddlerCore
public class HttpProxy : IDisposable
{
    public HttpProxy()
    {
        Fiddler.FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
        Fiddler.FiddlerApplication.Startup(8764, true, true);
    }

    void FiddlerApplication_BeforeRequest(Fiddler.Session oSession)
    {
        Console.WriteLine(String.Format("REQ: {0}", oSession.url));
    }

    public void Dispose()
    {
        Fiddler.FiddlerApplication.Shutdown();
    }
}

EDIT
You can start with this rectangular wheel :)
void SniffPort80()
{
    byte[] input = new byte[] { 1 };
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
    socket.Bind(new IPEndPoint(IPAddress.Broadcast, 80));
    socket.IOControl(IOControlCode.ReceiveAll, input, null);

    byte[] buffer = new byte[0x10000];

    Task.Factory.StartNew(() =>
        {
            while (true)
            {
                int len = socket.Receive(buffer);
                if (len <= 40) continue; //Poor man's check for TCP payload
                string bin = Encoding.UTF8.GetString(buffer, 0, len); //Don't trust to this line. Encoding may be different :) even it can contain binary data like images, videos etc.
                Console.WriteLine(bin);
            }
        });
}

A: this port is probably being used...
run netstat -ano on the command line, youll see list of the ports that are being used and the their process ids.

A: I dont know, why the GetContext(); hangs, because there is too less information about what happens with the listerner variable, but the problem with port 80 usually is caused by Skype, because it uses port 80 by default. To fix that, open Skype's preferences, go to advanced->connection and uncheck "Use Port 80 and 443 as an alternative for incoming Connections".

A: I would consider looking into this package http://www.nuget.org/packages/Microsoft.AspNet.WebApi.OwinSelfHost/
It uses HttpListener under the covers and with the WebApi HttpMessageHandler it is very easy to create a proxy.

A: It hangs because GetContext() is waiting for a request to be received, as said in its documentation:

This method blocks while waiting for an incoming request. If you want incoming requests to be processed asynchronously (on separate threads) so that your application does not block, use the BeginGetContext method.

For more info see: https://msdn.microsoft.com/en-us/library/system.net.httplistener.getcontext(v=vs.110).aspx
Using Asynchronous model tends to be complex, another alternative is running all that code in a different Thread but it depends on your goals.

A: Replace * in your prefixes with +
listener.Prefixes.Add("http://+:8080/");


text:
Q: How to create a frontend plugin in TYPO3 I'm trying to create a simple frontend plugin in TYPO3, .
I want to be able do putit into my backend template, just like I am able to put a regular text element, a table or a bullet list.

The plugin should have two textfields, that people should be able to fill in:
Invoice Number & Title
Then when the it is put into the page, the frontend should render it as following:
<a href="domain/invoices/{invoice number}.pdf"> {title} </a>

How can I achieve this, I tried using the Extension Builder, but I couldn't get the fields to end up in the typo3 backend.
N.B. I'm not looking for a specific solution for this problem, I'm just trying to create (more complex) frontend plugins and simplified this problem for the sake of understanding the general principle.

A: I described creating plugins and inserting it to the Wizard tabs in the other answer so probably all you must do is to follow it step by step.
Additionall fields of plugin you just need to define the FlexForm (sorry, it's too broad to describe, hope you know the approach)

A: If you only need a content element to display a link to an invoice, based on the invoice number entered in the content element on that page, you can use fluidcontent & flux to generate a content element of your taste. Have a look at the fluidcontent_bootstrap for examples.
If you want to creating an ext. where you can can retrieve a list of invoiced that has been added to the DB (or some other source) , then the extension_builder is a good kickstarter. If you set a front end plugin in the builder, it would shown up in the plugin list (not in the tab itself, but in the dropdown list if you would choose general plugin, first)
For the extra field: What you propably missed it the use of flexforms in your extension.


text:
Q: Get the class type name of a UIView subclass in Swift Description of problem
If I type
print(someSubview)

I get something like this:
<UIButton: 0x7fb063e3d330; frame = (46 64; 464 41); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x7fb063e3b010>>

What I would like is to just get name without all that other text:
UIButton

Of course, I could extract the substring programmatically, but I was wondering if there was something built in already. I only want this for debugging.
These don't work
print(someSubview.description)
print(someSubview.class)
print(someSubview.name)


text:
Q: Loading same image with `image_tag` does not evaluate to same path I think I don't know enough about Rails for understanding what is happening here.
I am trying to load an image and I have:

*

*item.logo == "my-cool-image.gif" => True

*item.logo.class => String

*Rails version: 4.2.0

*Asset pipeline: yes

this is my code:
<%= image_tag "my-cool-image.gif" %>
<%= image_tag item.logo %>

and it evaluates to:

Why is it trying to load the image from a different path?
How can I make <%= image_tag item.logo %> load the image from where <%= image_tag "my-cool-image.gif" %> is loading it?

A: You can force using your Path:
<%= image_tag "/my-app/#{item.logo}" %>


text:
Q: Trouble with Django annotation with multiple ForeignKey references I'm struggling with annotations and haven't found examples that help me understand. Here are relevant parts of my models:
    class Team(models.Model):
        team_name = models.CharField(max_length=50)

    class Match(models.Model):
        match_time = models.DateTimeField()
        team1 = models.ForeignKey(
            Team, on_delete=models.CASCADE, related_name='match_team1')
        team2 = models.ForeignKey(
            Team, on_delete=models.CASCADE, related_name='match_team2')
        team1_points = models.IntegerField(null=True)
        team2_points = models.IntegerField(null=True)

What I'd like to end up with is an annotation on the Teams objects that would give me each team's total points. Sometimes, a team is match.team1 (so their points are in match.team1_points) and sometimes they are match.team2, with their points stored in match.team2_points.
This is as close as I've gotten, in maybe a hundred or so tries:
teams = Team.objects.annotate(total_points =
Value(
  (Match.objects.filter(team1=21).aggregate(total=Sum(F('team1_points'))))['total'] or 0 +
  (Match.objects.filter(team2=21).aggregate(total=Sum(F('team2_points'))))['total'] or 0,
  output_field=IntegerField())
)

This works great, but (of course) annotates the total_points for the team with pk=21 to every team in the queryset. If there's a better approach for all this, I'd love to see it, but short of that, if you can show me how to turn those '21' values into a reference to the outer team's pk, I think that will work?
EDIT: I ended up using a combination of elyas' answers and annotating a raw SQL statement to solve my issues. I was not able to keep normal annotations from dropping non-unique scores from the queryset, but raw SQL seems to work.
Here's that raw annotation:
teams = Team.objects.raw('select id, sum(points) as total_points from (select team1_id as id, team1_points as points from leagueman_match union all select team2_id as id, team2_points as points from leagueman_match) group by id order by total_points desc;')

A: An alternative solution to annotating the QuerySet might be to make total_points a @property of the Team model (depending on the use case):
from django.db.models import Case, Q, Sum, When

class Team(models.Model):
    team_name = models.CharField(max_length=50)

    @property
    def total_points(self):
        return Match.objects.filter(Q(team1=self.id) | Q(team2=self.id)).aggregate(
            total_points=Sum(Case(
                When(team1=self.id, then='team1_points'),
                When(team2=self.id, then='team2_points')
            ))
        )['total_points']

The disadvantage is that it can't be used in subsequent QuerySet operations e.g. .values(), .order_by().
Django also has a @cached_property decorator which will cache the output of the attribute when it is first called.
Other solutions tried
Originally I thought you could leverage the reverse relations match_team1 and match_team2 from the Team model to generate a simple annotation:
teams = Team.objects.annotate(
    total_points=(
        Sum('match_team1__team1_points', distinct=True)
        + Sum('match_team2__team2_points', distinct=True)
    )
)

Unfortunately this solution encounters difficulties in handling duplicates. The distinct=True argument eliminates the issue of points from the same match being summed more than once. But it introduces a different issue where different matches with the same points scored will be excluded.

A: Maybe I would advice to refactor your data model. Even if you find a solution for this specific problem, you may want to think little ahead.
This is a solution:
class Team(models.Model):
    team_name = models.CharField(max_length=50)

class Match(models.Model):
    match_time = models.DateTimeField()
    team1 = models.ForeignKey(
        Team, on_delete=models.CASCADE, related_name='match_team1')
    team2 = models.ForeignKey(
        Team, on_delete=models.CASCADE, related_name='match_team2')

class Points(models.Model):
    match = models.ForeignKey(
        Match, on_delete=models.CASCADE, related_name='match')
    team = models.ForeignKey(
        Team, on_delete=models.CASCADE, related_name='team')
    points = models.IntegerField(null=True)

With this you can sum up easily the points of any team, and also filter it by matches.


text:
Q: Need a hint on how to solve this inequality I want to show that, whenever $\frac{u_1^2}{p^2}+\frac{u_2^2}{q^2} \leq 1$ and $\frac{v_1^2}{p^2}+\frac{v_2^2}{q^2} \leq 1$, then
$$
  \frac{(\lambda \, u_1 + (1 - \lambda) \, v_1)^2}{p^2} + \frac{(\lambda \, u_2 + (1 - \lambda) \, v_2)^2}{q^2} \leq 1
$$
for all $0 \leq \lambda \leq 1$.
My (failed) attempt: I tried to apply the Cauchy-Schwarz inequality and got
$$
\frac{(\lambda \, u_1 + (1 - \lambda) \, v_1)^2}{p^2} + \frac{(\lambda \, u_2 + (1 - \lambda) \, v_2)^2}{q^2} \leq
\left(\lambda^2 + (1-\lambda)^2\right)
\left(
  \frac{u_1^2}{p^2} + \frac{u_2^2}{q^2} + \frac{v_1^2}{p^2} + \frac{v_2^2}{q^2}
\right) \leq 2
$$
What is the correct way to approach this?

A: HINT
Let use convexity for $f(x)=x^2$, that is by Jensen's inequality
$$f(\lambda x+(1-\lambda)y) \le \lambda f(x)+(1-\lambda)f(y)$$

A: Using simpler variable names,
we are given
$\frac{a^2}{p^2}+\frac{c^2}{q^2}
\le 1$
and
$\frac{b^2}{p^2}+\frac{d^2}{q^2}
\le 1$.
$\begin{array}\\
\frac{(ra + (1 - r) b)^2}{p^2} + \frac{(rc + (1 - r)d)^2}{q^2}
&=\frac{r^2a^2+2r(1-r)ab+(1-r)^2b^2}{p^2} + \frac{r^2c^2+2r(1-r)cd+(1-r)^2d^2}{q^2}\\
&=r^2(\frac{a^2}{p^2}+\frac{c^2}{q^2})+2r(1-r)(\frac{ab}{p^2}+\frac{cd}{q^2})+(1-r)^2(\frac{b^2}{p^2}+\frac{d^2}{q^2})\\
&\le r^2+2r(1-r)(\frac{ab}{p^2}+\frac{cd}{q^2})+(1-r)^2\\
\end{array}
$
If we can show that
$\frac{ab}{p^2}+\frac{cd}{q^2}
\le 1$,
the upper bound is
$r^2+2r(1-r)+(1-r)^2
=(r+(1-r))^2
=1
$
and we are done.
But
$\begin{array}\\
(\frac{ab}{p^2}+\frac{cd}{q^2})^2
&=(\frac{a}{p}\frac{b}{p}+\frac{c}{q}\frac{d}{q})^2\\
&\le(\frac{a^2}{p^2}+\frac{c^2}{q^2})(\frac{b^2}{p^2}+\frac{d^2}{q^2})
\quad\text{by Cauchy-Schwarz}\\
&\le 1\\
\end{array}
$


text:
Q: Edit an already exisiting wordpress website what is the best possible way to edit codes of a Wordpress theme of an existing website? Say for instance I have a menu bar with all the features like About Us, Contact, Objectives. But i want to add one more to it(say Gallery). So how am i supposed to proceed?

A: If you just want to change the content of the website, you don't have to change anything in the theme.
If you are using any GUI for changing just search around. In the wordpress-site you have to go to: My website -> themes (adapt) -> Menu
there you can add or change the entries.
If you have a complete website made with a wordpress-theme on a server you will need some html knowledge to solve this problem. But its not that complex.
Without the code, noone here can tell you the solution.


text:
Q: Logistic regression: 'odds ratio' is essentially just the ratio - what's the point? Trying to understand the use of logistic regression. I have the following data:
Gender  Age No.transcation  Transaction
female  18-24   138485  4047
male    18-24   144301  3766
female  25-34   248362  7559
male    25-34   295800  8126
female  35-44   265514  7171
male    35-44   379872  9047
female  45-54   295002  7072
male    45-54   421432  9648
female  55-64   382198  7529
male    55-64   456308  9016
female  65+ 352501  4856
male    65+ 465253  6889

Running logistic regression in R I get the following summary output
    > mod2 <- glm(cbind(Transaction, No.transcation) ~ Gender + Age, data = csvd,
family = binomial())
    > summary(mod2)

    Call:
    glm(formula = cbind(Transaction, No.transcation) ~ Gender + Age,
        family = binomial(), data = csvd)

    Deviance Residuals:
          1        2        3        4        5        6
     1.8732  -1.9018   2.2654  -2.1473   3.4810  -3.0228
             7        8        9       10       11    12
     -0.2772   0.2377  -2.5500   2.3717  -4.9638   4.3408

    Coefficients:
                 Estimate Std. Error  z value Pr(>|z|)
    (Intercept) -3.562800   0.011984 -297.290  < 2e-16 ***
    Gendermale  -0.051852   0.006993   -7.415 1.22e-13 ***
    Age25-34     0.044091   0.014042    3.140  0.00169 **
    Age35-44    -0.090757   0.013966   -6.499 8.11e-11 ***
    Age45-54    -0.164705   0.013894  -11.855  < 2e-16 ***
    Age55-64    -0.334841   0.013900  -24.088  < 2e-16 ***
    Age65+      -0.651142   0.014767  -44.094  < 2e-16 ***
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

    (Dispersion parameter for binomial family taken to be 1)

        Null deviance: 4490.792  on 11  degrees of freedom
    Residual deviance:   93.866  on  5  degrees of freedom
    AIC: 235.5

    Number of Fisher Scoring iterations: 3

Exponentiation the coefficients to get the odds ratio, I find they are almost identical to just the ratio of users with transactions:
> exp(summary(mod2)$coefficients)
              Estimate Std. Error       z value Pr(>|z|)
(Intercept) 0.02835931   1.012056 7.735499e-130 1.000000
Gendermale  0.94946976   1.007018  6.022806e-04 1.000000
Age25-34    1.04507762   1.014141  2.310243e+01 1.001691
Age35-44    0.91323954   1.014064  1.505641e-03 1.000000
Age45-54    0.84814413   1.013991  7.106341e-06 1.000000
Age55-64    0.71545181   1.013998  3.455562e-11 1.000000
Age65+      0.52145005   1.014877  7.084264e-20 1.000000

Comparing the odds ratios to just taking the relative ratio of users with transactions divided by total users per group (and comparing it vs the male and 18-24 base group) I get pretty much the same numbers:
female
male    94.68%

18-24
25-34   104.21%
35-44   91.17%
45-54   84.82%
55-64   71.97%
65+ 52.66%

So what's even the point of running logistic regression here? This dataset only has 2 features, but it might as well be extended to 50 features. What use does LR have vs just looking at the ratio for each group in this case? Is it because all variables are nominal that it doesn't add much?

A: You would hope that the estimated odds ratio is close to the realised proportions like this. You are estimating the probability pr(Y=1|X=x) ; the probability of a transaction given age rage and gender. With categorical predictors like this an intuitive estimator would be the proportions of outcomes in the data. Logistic regression becomes more interesting when the predictors are continuous variables, and you'd like to predict the probability of an outcome for some value of the predictor that you haven't observed. In these cases LR lets you map an unbounded linear function of your predictor onto a probability which must by definition be bounded between 0 and 1.


text:
Q: Matlab Table / Dataset type optimization I am searching some optimized datatypes for "observations-variables" table in Matlab, that can be fast and easily accessed by columns (through variables) and by rows (through observations).
Here is сomparison of existing Matlab datatypes:

*

*Matrix is very fast, hovewer, it has no built-in indexing labels/enumerations for its dimensions, and you can't always remember variable name by column index.

*Table has very bad performance, especially when reading individual rows/columns in a for loop (I suppose it runs some slow convertion methods, and is designed to be more Excel-like).

*Scalar structure (structure of column arrays) datatype - fast column-wise access to variables as vectors, but slow row-wise conversion to observations.

*Nonscalar structure (array of structures) - fast row-wise access to observations as vectors, but slow column-wise conversion to variables.

I wonder if I can use some simpler and optimized version of Table data type, if I want just to combine row-number and column-variable indexing with only numerical variables -OR- any variable type.
Results of test script:
----
TEST1 - reading individual observations
Matrix: 0.072519 sec
Table: 18.014 sec
Array of structures: 0.49896 sec
Structure of arrays: 4.3865 sec
----
TEST2 - reading individual variables
Matrix: 0.0047834 sec
Table: 0.0017972 sec
Array of structures: 2.2715 sec
Structure of arrays: 0.0010529 sec

Test script:
Nobs = 1e5; % number of observations-rows
varNames = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O'};
Nvar = numel(varNames); % number of variables-colums

M = randn(Nobs, Nvar); % matrix

T = array2table(M, 'VariableNames', varNames); % table

NS = struct; % nonscalar structure = array of structures
for i=1:Nobs
    for v=1:Nvar
        NS(i).(varNames{v}) = M(i,v);
    end
end

SS = struct; % scalar structure = structure of arrays
for v=1:Nvar
    SS.(varNames{v}) = M(:,v);
end

%% TEST 1 - reading individual observations (row-wise)
disp('----'); disp('TEST1 - reading individual observations');

tic; % matrix
for i=1:Nobs
   x = M(i,:); end
disp(['Matrix: ', num2str(toc()), ' sec']);

tic; % table
for i=1:Nobs
   x = T(i,:); end
disp(['Table: ', num2str(toc), ' sec']);

tic;% nonscalar structure = array of structures
for i=1:Nobs
    x = NS(i); end
disp(['Array of structures: ', num2str(toc()), ' sec']);

tic;% scalar structure = structure of arrays
for i=1:Nobs
    for v=1:Nvar
        x.(varNames{v}) = SS.(varNames{v})(i);
    end
end
disp(['Structure of arrays: ', num2str(toc()), ' sec']);

%% TEST 2 - reading individual variables (column-wise)
disp('----'); disp('TEST2 - reading individual variables');

tic; % matrix
for v=1:Nvar
   x = M(:,v); end
disp(['Matrix: ', num2str(toc()), ' sec']);

tic; % table
for v=1:Nvar
   x = T.(varNames{v}); end
disp(['Table: ', num2str(toc()), ' sec']);

tic; % nonscalar structure = array of structures
for v=1:Nvar
    for i=1:Nobs
        x(i,1) = NS(i).(varNames{v});
    end
end
disp(['Array of structures: ', num2str(toc()), ' sec']);

tic; % scalar structure = structure of arrays
for v=1:Nvar
    x = SS.(varNames{v}); end
disp(['Structure of arrays: ', num2str(toc()), ' sec']);

A: I would use matrices, since they're the fastest and most straightforward to use, and then create a set of enumerated column labels to make indexing columns easier. Here are a few ways to do this:

Use a containers.Map object:
Given your variable names, and assuming they map in order from columns 1 through N, you can create a mapping like so:
varNames = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O'};
col = containers.Map(varNames, 1:numel(varNames));

And now you can use the map to access columns of your data by variable name. For example, if you want to fetch the columns for variables A and C (i.e. the first and third) from a matrix data, you would do this:
subData = data(:, [col('A') col('C')]);

Use a struct:
You can create a structure with the variable names as its fields and the corresponding column indices as their values like so:
enumData = [varNames; num2cell(1:numel(varNames))];
col = struct(enumData{:});

And here's what col contains:
struct with fields:

  A: 1
  B: 2
  C: 3
  D: 4
  E: 5
  F: 6
  G: 7
  H: 8
  I: 9
  J: 10
  K: 11
  L: 12
  M: 13
  N: 14
  O: 15

And you would access columns A and C like so:
subData = data(:, [col.A col.C]);
% ...or with dynamic field names...
subData = data(:, [col.('A') col.('C')]);

Make a bunch of variables:
You could just create a variable in your workspace for every column name and store the column indices in them. This will pollute your workspace with more variables, but gives you a terse way to access column data. Here's an easy way to do it, using the much-maligned eval:
enumData = [varNames; num2cell(1:numel(varNames))];
eval(sprintf('%s=%d;', enumData{:}));

And accessing columns A and C is as easy as:
subData = data(:, [A C]);

Use an enumeration class:
This is probably a good dose of overkill, but if you're going to use the same mapping of column labels and indices for many analyses you could create an enumeration class, save it somewhere on your MATLAB path, and never have to worry about defining your column enumerations again. For example, here's a ColVar class with 15 enumerated values:
classdef ColVar < double
  enumeration
    A (1)
    B (2)
    C (3)
    D (4)
    E (5)
    F (6)
    G (7)
    H (8)
    I (9)
    J (10)
    K (11)
    L (12)
    M (13)
    N (14)
    O (15)
  end
end

And you would access columns A and C like so:
subData = data(:, [ColVar.A ColVar.C]);


text:
Q: How to disable ancestor violates the following Content Security Policy directive: "frame-ancestors 'none'" in docker I am building a dockerized (version 20.10.11) application with php7,nginx(1.21) images. I am adding colorbox jquery library for youtube popup.
Upon clicking youtube thumbnail link popup appears but videos not playing. In console errors appears like

Refused to frame 'http://myapp.docker.localhost:8000/' because an
ancestor violates the following Content Security Policy directive:
"frame-ancestors 'none'".

but it works without any issues in xampp,wamp etc.
How can I disable this restriction in docker?
I am pretty new to docker and nginx.


text:
Q: Codeception Error : Call to undefined method Exception::getStatusCode() When I run functional tests in Codeception in Laravel, every now and then I get the error:
 [Symfony\Component\Debug\Exception\FatalErrorException]
  Call to undefined method Exception::getStatusCode()

These are my configs:
codeception.yml

actor: Tester
paths:
    tests: tests
    log: tests/_output
    data: tests/_data
    support: tests/_support
    envs: tests/_envs
settings:
    bootstrap: _bootstrap.php
    colors: true
    memory_limit: 1024M
extensions:
    enabled:
        - Codeception\Extension\RunFailed
modules:
    config:
        Db:
            dsn: 'mysql:host=127.0.0.1;port=3306;dbname=la51'
            user: 'root'
            password: 'root'
            populate: false
            cleanup: false
            reconnect: true

functional.suite.yml
class_name: FunctionalTester
modules:
    enabled:
        # add framework module here
        - \Helper\Functional
        - Asserts
        - Db
        - Laravel5
    config:
        Laravel5:
            cleanup: false

This is what I get in my terminal when I "codecept run":
Rubens-MacBook-Pro:la51 rubenbijker$ codecept run -vvv
Codeception PHP Testing Framework v2.1.3
Powered by PHPUnit 4.8.10 by Sebastian Bergmann and contributors.

Acceptance Tests (0) ------------------------
Modules: PhpBrowser, \Helper\Acceptance
---------------------------------------------
---------------------------------------------

Functional Tests (9) -------------------------------------------------------------------------------------------------------------------------------
Modules: \Helper\Functional, Asserts, Db, Laravel5
----------------------------------------------------------------------------------------------------------------------------------------------------
Create a boat (AdminCreatesBoatCept)
Scenario:
* As an a guest
* I am on page ""

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Call to undefined method Exception::getStatusCode()

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Call to undefined method Exception::getStatusCode()

FATAL ERROR. TESTS NOT FINISHED.
Call to undefined method Exception::getStatusCode()
in /Applications/MAMP/htdocs/la51/app/Exceptions/Handler.php:71
Rubens-MacBook-Pro:la51 rubenbijker$

I reported the issue with Codeception but they said it is a Laravel error so they can't help me.
Is this caused because of an error in my code? Or by a misconfiguration between Codeception and Laravel?

A: The problem has nothing to do with Codeception itself. It rather Looks like you have edited your Handler.php file manually. You have to fix the error in your changes ( Call to undefined method is quite clear ) or revert it to its orignal state.


text:
Q: identify each iphone device in iOS SDK I need to determine each iOS device.
In the past SDKS, there's a way to identify UUID by the command
 [[UIDevice currentDevice] uniqueIdentifier];

But in iOS 5.0, this function is deprecated. Is there any way to do this similar task?
Thank you!

A:
uniqueIdentifier
An alphanumeric string unique to each device based on various hardware
  details. (read-only) (Deprecated in iOS 5.0. Instead, create a unique
  identifier specific to your app.) @property (nonatomic, readonly,
  retain) NSString *uniqueIdentifier Special Considerations
Do not use the uniqueIdentifier property. To create a unique
  identifier specific to your app, you can call the CFUUIDCreate
  function to create a UUID, and write it to the defaults database using
  the NSUserDefaults class. Availability
Available in iOS 2.0 and later.
Deprecated in iOS 5.0.

Related Sample Code
GKTank

Declared In UIDevice.h

So use CFUUIDCreate and you will get and uniqID and save it to the NSUDefaults.
Note that the CFUUIDCreate will give you a new id on each call. That is why you have to save it.
If you really need to know if the app was installed on that device you can read the mac address of the wifi card.

A: For iOS 6 and latter you can use.

NSString *U_ID = [[NSUUID UUID] UUIDString];

A: Please check the answer of @suchi here How to create a GUID/UUID using the iPhone SDK.
use [[UIDevice currentDevice] uniqueDeviceIdentifier] to retrieve the unique identifier (it's a hash of your Bundle ID + MAC address)
use [[UIDevice currentDevice] uniqueGlobalDeviceIdentifier] to retrieve a global unique identifier (it's a hash of the MAC address, used for tracking between different apps).


text:
Q: Bad trained cascade in OpenCV I can't train the classifier properly.. When I use the generated cascade.xml the object is not recognized. Instead some parts of the object are.
The command line for training is this:
opencv_traincascade -data data -vec samples.vec -bg negatives.txt -numPos 200 -numNeg 100 -numStages 13 -w 80 -h 80 -featureType LBP -minHitRate 0.999 -maxFalseAlarmRate 0.5

While training the output looks like this:
===== TRAINING 10-stage =====
<BEGIN
POS count : consumed   200 : 200
NEG count : acceptanceRatio    100 : 0.00586029
Precalculation time: 2
+----+---------+---------+
|  N |    HR   |    FA   |
+----+---------+---------+
|   1|        1|        1|
+----+---------+---------+
|   2|        1|     0.09|
+----+---------+---------+
END>
Training until now has taken 0 days 0 hours 6 minutes 9 seconds.

===== TRAINING 11-stage =====
<BEGIN
POS count : consumed   200 : 200
NEG count : acceptanceRatio    100 : 0.00724585
Precalculation time: 3
+----+---------+---------+
|  N |    HR   |    FA   |
+----+---------+---------+
|   1|        1|        1|
+----+---------+---------+
|   2|        1|     0.09|
+----+---------+---------+
END>
Training until now has taken 0 days 0 hours 6 minutes 49 seconds.

===== TRAINING 12-stage =====
<BEGIN

And when I use it to detect my object (in my case the object is a steering wheel) the result is:

A: You are using too few images as a samples for the image which has a 80x80 dimension.
I'd minimize the dimension of the images, meanwhile adding some more samples.
Another thing is the set of the negative images. What are you using as a negative samples? Try to enlarge your negative image set by adding this false detected chunks.


text:
Q: Some fields are empty after deserialization in Silverlight project I have a problem with deserialization in my silverlight project. I have class Obj with this methods and variables.
public class Obj
{
    private string _name;
    private Uri _iconUri;
    private string _stringUri;
    private List<ObjItem> _items = new List<ObjItem>();

    public List<ObjItem> Items
    {
        get { return _items; }
    }
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    public Uri IconUri
    {
        get
        {
            return _iconUri;
        }
    }
    public string StringUri { get { return _stringUri; } }
    public int Count
    {
        get { return _items.Count; }
    }

    public Obj(string name,string uriString = null)
    {
        _name = name;
        if (uriString == null)
        {
            _iconUri = null;
        }
        else
        {
            _iconUri = new Uri(uriString, UriKind.Relative);
        }
        _stringUri = uriString;
    }
    // for deserialization
    public Obj()
    {
    }

}
Before serialization all fields are not empty!
After deserialization all fields are not empry except _iconUri and _stringUri fields.
Why is it happened?
I'll be waiting for your replies.
Thank you!

A: Those two don't have setters. Silverlight has a restricted security model, where you cant can't cheat by accessing private fields; only public members can be accessed. So: add public setters to those properties if you want them to work with most serializers on SL.
To be specific: _name is being set by the Name setter, and _items is being set in the constructor via the field-initializer.


text:
Q: pushing from one --bare repo to another --bare repo on same server I have a remote repo on a server that I push to for staging purposes.  I then have a post-receive to push that to the file directory where http://stage.xxxx.com files live on.
Now that I have everything on my staging repo and it's presumed to be bug free, how do I push it from my staging repo to my live repo on the same server?
I would prefer to not have to push my local code directly to the production git repo because I'm shall we say not the best at keeping track of that kind of stuff.  Would I have to login directly to the server and do a push from there to the live repo?

A: Yes, you would have to log in directly to the server, and that solution seems a little bit overcomplicated, because you can just do something like this:
git fetch --all
git push livesite staging/master:master

This will push the state of staging/master to livesite/master and you do not have to keep track of anything.


text:
Q: Print bibliography using biber backend I am new with latex and i have a problem in printing the bibliography.
I exported a file .bib and inserted in a folder called References. I copy in the following line what I wrote in the main script to print the biblio.
\cleardoublepage

\printbibliography[heading=bibintoc, title={References}]

while in the preamble i wrote
\usepackage[style=numeric,backend=biber]{biblatex}

\RequirePackage[backend=biber, style=numeric-comp, citestyle=numeric, sorting=nty, natbib=true]{biblatex}

\addbibresource{tesi.bib}

\fi

\renewcommand{\bibname}{References}
\usepackage{hyperref}


text:
Q: Excavator Badge not in my profile
Possible Duplicate:
How long does it take for badges to be awarded? How are they generated?
Should I have earned an "Excavator" badge for this?

I have edited the following question that has been inactive for more than 6 months. Silverlight Animation without DispatcherTimer
However I do not see the Excavator badge in my profile. What is the reason for this?
https://stackoverflow.com/badges?tab=general&filter=all


text:
Q: Cypress automation for status check I'm trying to automate the application to check the status for 1000 employees and Below if the code. First it tries to open and next when it tries to hit another time the pop-up comes so, the test fails. But I have to open in 1000 tabs to check the status. Is there any way to do it. For example:
  it('check status functionaltiy', function () {
    cy.visit('https://egov.uscis.gov/casestatus/landing.do')

    var genArr = Array.from({length:1000},(v,k)=>k+1)
    cy.wrap(genArr).each((index) => {
      cy.get('input[type="text"]')
      .type(`IOE1234567${index}`)
      cy.log(`IOE1234567${index}`,'ppppppppp')
      cy.get('input[type="submit"]').click();
    })
})


text:
Q: Is there a way to trim/strip whitespace in multiple columns of a pandas dataframe? I have a pandas dataframe with 5 columns and 3 of those columns are string columns. I want to trim all the leading and trailing whitespaces in those 3 columns. Is there a way to achieve this in one go.
  ID    col_1  col_2    col_3   col_4
0  1      AA     XX      200     PP
1  2      BB     YY      300     QQ
2  3      CC     ZZ      500     RR

I want to trim 'col_1', 'col_2', 'col_4'
I know df['col_1'].str.strip() works on a individual column. But can i do all the columns at one go?

A: df.columns = df.columns.str.strip()

A: Use DataFrame.apply with list of columns:
cols = ['col_1', 'col_2', 'col_4']
df[cols] = df[cols].apply(lambda x: x.str.strip())

Or parse only object columns, it is obviously strings:
cols = df.select_dtypes(object).columns
df[cols] = df[cols].apply(lambda x: x.str.strip())


text:
Q: Is it legitimate for a tokenizer to have a stack? I have designed a new language for that I want to write a reasonable lexer and parser.
For the sake of brevity, I have reduced this language to a minimum so that my questions are still open.
The language has implicit and explicit strings, arrays and objects. An implicit string is just a sequence of characters that does not contain <, {, [ or ]. An explicit string looks like <salt<text>salt> where salt is an arbitrary identifier (i.e. [a-zA-Z][a-zA-Z0-9]*) and text is an arbitrary sequence of characters that does not contain the salt.
An array starts with [, followed by objects and/or strings and ends with ].
All characters within an array that don't belong to an array, object or explicit string do belong to an implicit string and the length of each implicit string is maximal and greater than 0.
An object starts with { and ends with } and consists of properties. A property starts with an identifier, followed by a colon, then optional whitespaces and then either an explicit string, array or object.
So the string [ name:test <xml<[]>xml> {name:<b<test>b>}<b<bla>b> ] represents an array with 6 items: " name:test ", "[]", " ", { name: "test" }, "bla" and " " (the object is notated in json).
As one can see, this language is not context free due to the explicit string (that I don't want to miss). However, the syntax tree is nonambiguous.
So my question is: Is a property a token that may be returned by a tokenizer? Or should the tokenizer return T_identifier, T_colon when he reads an object property?
The real language allows even prefixes in the identifier of a property, e.g. ns/name:<a<test>a> where ns is the prefix for a namespace.
Should the tokenizer return T_property_prefix("ns"), T_property_prefix_separator, T_property_name("name"), T_property_colon or just T_property("ns/name") or even T_identifier("ns"), T_slash, T_identifier("name"), T_colon?
If the tokenizer should recognize properties (which would be useful for syntax highlighters), he must have a stack, because name: is not a property if it is in an array. To decide whether bla: in [{foo:{bar:[test:baz]} bla:{}}] is a property or just an implicit string, the tokenizer must track when he enters and leave an object or array.
Thus, the tokenizer would not be a finite state machine any more.
Or does it make sense to have two tokenizers - the first, which separates whitespaces from alpha-numerical character sequences and special characters like : or [, the second, which uses the first to build more semantical tokens? The parser could then operate on top of the second tokenizer.
Anyways, the tokenizer must have an infinite lookahead to see when an explicit string ends. Or should the detection of the end of an explicit string happen inside the parser?
Or should I use a parser generator for my undertaking? Since my language is not context free, I don't think there is an appropriate parser generator.
Thanks in advance for your answers!

A: flex can be requested to provide a context stack, and many flex scanners use this feature. So, while it may not fit with a purist view of how a scanner scans, it is a perfectly acceptable and supported feature. See this chapter of the flex manual for details on how to have different lexical contexts (called "start conditions"); at the very end is a brief description of the context stack. (Don't miss the sentence which notes that you need %option stack to enable the stack.) [See Note 1]
Slightly trickier is the requirement to match strings with variable end markers. flex does not have any variable match feature, but it does allow you to read one character at a time from the scanner input, using the function input(). That's sufficient for your language (at least as described).
Here's a rough outline of a possible scanner:
%option stack
%x SC_OBJECT

%%
 /* initial/array context only */
[^][{<]+ yylval = strdup(yytext); return STRING;
 /* object context only */
<SC_OBJECT>{
  [}]                     yy_pop_state(); return '}';
  [[:alpha:]][[:alnum:]]* yylval = strdup(yytext); return ID;
  [:/]                    return yytext[0];
  [[:space:]]+            /* Ignore whitespace */
}
 /* either context */
<*>{
  [][]     return yytext[0]; /* char class with [] */
  [{]      yy_push_state(SC_OBJECT); return '{';
  "<"[[:alpha:]][[:alnum:]]*"<" {
           /* We need to save a copy of the salt because yytext could
            * be invalidated by input().
            */
           char* salt = strdup(yytext);
           char* saltend = salt + yyleng;
           char* match = salt;
           /* The string accumulator code is *not* intended
            * to be a model for how to write string accumulators.
            */
           yylval = NULL;
           size_t length = 0;
           /* change salt to what we're looking for */
           *salt = *(saltend - 1) = '>';
           while (match != saltend) {
             int ch = input();
             if (ch == EOF) {
               yyerror("Unexpected EOF");
               /* free the temps and do something */
             }
             if (ch == *match) ++match;
             else if (ch == '>') match = salt + 1;
             else match = salt;
                /* Don't do this in real code */
             yylval = realloc(yylval, ++length);
             yylval[length - 1] = ch;
           }
           /* Get rid of the terminator */
           yylval[length - yyleng] = 0;
           free(salt);
           return STRING;
         }
  .      yyerror("Invalid character in object");
}

I didn't test that thoroughly, but here is what it looks like with your example input:
[ name:test <xml<[]>xml> {name:<b<test>b>}<b<bla>b> ]
Token: [
Token: STRING: -- name:test --
Token: STRING: --[]--
Token: STRING: -- --
Token: {
Token: ID: --name--
Token: :
Token: STRING: --test--
Token: }
Token: STRING: --bla--
Token: STRING: -- --
Token: ]

Notes

*

*In your case, unless you wanted to avoid having a parser, you don't actually need a stack since the only thing that needs to be pushed onto the stack is an object context, and a stack with only one possible value can be replaced with a counter.
Consequently, you could just remove the %option stack and define a counter at the top of the scan. Instead of pushing the start condition, you increment the counter and set the start condition; instead of popping, you decrement the counter and reset the start condition if it drops to 0.
%%
  /* Indented text before the first rule is inserted at the top of yylex */
  int object_count = 0;
<*>[{]         ++object_count; BEGIN(SC_OBJECT); return '{';
<SC_OBJECT[}]  if (!--object_count) BEGIN(INITIAL); return '}'

*Reading the input one character at a time is not the most efficient. Since in your case, a string terminate must start with >, it would probably be better to define a separate "explicit string" context, in which you recognized [^>]+ and [>]. The second of these would do the character-at-a-time match, as with the above code, but would terminate instead of looping if it found a non-matching character other than >. However, the simple code presented may turn out to be fast enough, and anyway it was just intended to be good enough to do a test run.

A: I think the traditional way to parse your language would be to have the tokenizer return T_identifier("ns"), T_slash, T_identifier("name"), T_colon for ns/name:
Anyway, I can see three reasonable ways you could implement support for your language:

*

*Use lex/flex and yacc/bison. The tokenizers generated by lex/flex do not have stack so you should be using T_identifier and not T_context_specific_type. I didn't try the approach so I can't give a definite comment on whether your language could be parsed by lex/flex and yacc/bison. So, my comment is try it to see if it works. You may find information about the lexer hack useful: http://en.wikipedia.org/wiki/The_lexer_hack

*Implement a hand-built recursive descent parser. Note that this can be easily built without separate lexer/parser stages. So, if the lexemes depend on context it is easy to handle when using this approach.

*Implement your own parser generator which turns lexemes on and off based on the context of the parser. So, the lexer and the parser would be integrated together using this approach.
I once worked for a major network security vendor where deep packet inspection was performed by using approach (3), i.e. we had a custom parser generator. The reason for this is that approach (1) doesn't work for two reasons: firstly, data can't be fed to lex/flex and yacc/bison incrementally, and secondly, HTTP can't be parsed by using lex/flex and yacc/bison because the meaning of the string "HTTP" depends on its location, i.e. it could be a header value or the protocol specifier. The approach (2) didn't work because data can't be fed incrementally to recursive descent parsers.
I should add that if you want to have meaningful error messages, a recursive descent parser approach is heavily recommended. My understanding is that the current version of gcc uses a hand-built recursive descent parser.


text:
Q: reference request: Riesz/Newton potential and HLS inequality in L1.logL1 Let's consider in dimension $d\geq 3$ the Newton/riesz potential $f=I_2[g]$
$$
f(x)=\int_{R^d}\frac{1}{|x-y|^{d-2}}g(y)dy,
$$
which solves $-\Delta f=g$ (up to positive normalizing constants, which I shall ignore).
The classical Hardy-Littlewood-Sobolev inequality guarantees that
$$
|f|_{L^q(R^d)}\leq C|g|_{L^p(R^d)},\qquad q=\frac{dp}{d-2p}
$$
as soon as $g\in L^p(R^d)$ for some $p\in (1,d/2)$.
If $g$ is only in $L^1$ the naive guess $|f|_{L^{d/(d-2)}}\leq C|g|_{L^1}$ fails, but we know that the singular integral converges for almost every $x\in R^d$ and that there is a weak type estimate
$$
\forall \lambda\geq 0, \qquad\mathcal{L}(\{x:\,|f|(x)\geq \lambda\})\leq C\left(\frac{|g|_{L^1}}{\lambda}\right)^{d/(d-2)}
$$
($\mathcal{L}$ denoting the usual Lebesgue measure on $R^d$).
My question is the following: what can we say if $g$ is in the slightly better space $g\in L^1\log L^1$, i-e if $|g|.|\log(|g|)|\in L^1(R^d)$? I don't think we can expect $f\in L^{d/(d-2)+\varepsilon}$ for any $\varepsilon>0$, but maybe $f\in L^{d/(d-2)}\log L^1$ or something like that? I would expect at least some improvement and in particular $f\in L^{d/(d-2)}$, but maybe not.
Thank you in advance for your comments and input.
PS: I wrote my question in dimension $d\geq 3$ for simplicity, but I'm also interested in the borderline case $d=2$ when the Poisson kernel $1/|x-y|^{d-2}$ is replaced by $-\log|x-y|$.

A: This is just a guess, I'm writing it since nobody commented on your question. You might want to check Yano's extrapolation theorem (see here for a nice exposition) which states that: if an operator $T$ is bounded on all $L^p$ for $p>1$ close to 1, and the norm grows at most like $(p-1)^{-1}$, then $T$ extends to a bounded operator on $Llog L$. Not exactly what you are asking, but this might give you some ideas to get started.


text:
Q: Relevance of gauge transformations in physical interpretations of a system In the simple example of a stationary electric field (and some other quantum mechanical examples) it is shown in the papers
https://arxiv.org/abs/physics/0506203
https://arxiv.org/abs/1302.1212
that a particular gauge transformation can lead to different Hamiltonian's and Lagrangian's for what are established as closed systems which then lead to different physical interpretations. In one calculation, energy is conserved due to a time-independent Hamiltonian and with the addition of a time dependent gauge transformation, the Hamiltonian becomes time-dependent which means energy is not conserved.
My question is what is the significance of this result in terms of the changes a particular gauge can make on the Hamiltonian of a system which may leads to nonsensical physical interpretations? Although now learning about this area, it seems to me that a particular gauges ability to change a conserved quantity of a system is negative thing. Thus, in the grand scheme of things, I would ask what the resolution of this seeming paradox is, why it comes about, the meaning behind the existence of these paradoxes, and the relation between the Hamiltonian and Lagrangian formalism and gauge transformations.
Mathematical details are welcome and if there any any sources I should read up on myself I would appreciate such suggestions.


text:
Q: Combining C++ header files Is there an automated way to take a large amount of C++ header files and combine them in a single one?
This operation must, of course, concatenate the files in the right order so that no types, etc. are defined before they are used in upcoming classes and functions.
Basically, I'm looking for something that allows me to distribute my library in two files (libfoo.h, libfoo.a), instead of the current bunch of include files + the binary library.

A: As your comment says:

.. I want to make it easier for library users, so they can just do one single #include and have it all.

Then you could just spend some time, including all your headers in a "wrapper" header, in the right order. 50 headers are not that much. Just do something like:
// libfoo.h
#include "header1.h"
#include "header2.h"
// ..
#include "headerN.h"

This will not take that much time, if you do this manually.
Also, adding new headers later - a matter of seconds, to add them in this "wrapper header".
In my opinion, this is the most simple, clean and working solution.

A: A little bit late, but here it is. I just recently stumbled into this same problem myself and coded this solution: https://github.com/rpvelloso/oneheader

How does it works?

*

*Your project's folder is scanned for C/C++ headers and a list of headers found is created;

*For every header in the list it analyzes its #include directives and assemble a dependency graph in the following way:

*

*If the included header is not located inside the project's folder then it is ignored (e.g., if it is a system header);

*If the included header is located inside the project's folder then an edge is create in the dependency graph, linking the included header to the current header being analyzed;

*The dependency graph is topologically sorted to determine the correct order to concatenate the headers into a single file. If a cycle is found in the graph, the process is interrupted (i.e., if it is not a DAG);
Limitations:

*

*It currently only detects single line #include directives (e.g., #include );

*It does not handles headers with the same name in different paths;

*It only gives you a correct order to combine all the headers, you still need to concatenate them (maybe you want remove or modify some of them prior to merging).

  Compiling:
g++ -Wall -ggdb -std=c++1y -lstdc++fs oneheader.cpp -o oneheader[.exe]
Usage:
./oneheader[.exe] project_folder/ > file_sequence.txt

A: (Adapting an answer to my dupe question:)
There are several other libraries which aim for a single-header form of distribution, but are developed using multiple files; and they too need such a mechanism. For some (most?) it is opaque and not part of the distributed code. Luckily, there is at least one exception: Lyra, a command-line argument parsing library; it uses a Python-based include file fuser/joiner script, which you can find here.
The script is not well-documented, but they way you use it is with 3 command-line arguments:

*

*--src-include - The include file to convert, i.e. to merge its include directives into its body. In your case it's libfoo.h which includes the other files.

*--dst-include - The output file to write - the result of the merging.

*--src-include-dir - The directory relative to which include files are specified (i.e. an "include search path" of one directory; the script doesn't support the complex mechanism of multiple include paths and search priorities which the C++ compiler offers)

The script acts recursively, so if file1.h includes another file under the --src-include-dir, that should be merged in as well.
Now, I could nitpick at the code of that script, but - hey,  it works and it's FOSS - distributed with the Boost license.

A: If your library is so big that you cannot build and maintain a single wrapping header file like Kiril suggested, this may mean that it is not architectured well enough.
So if your library is really huge (above a million lines of source code), you might consider automating that, with tools like

*

*GCC make dependency generator preprocessor options like -M -MD -MF etc, with another hand made script sorting them

*expensive commercial static analysis tools like coverity

*customizing a compiler thru plugins or (for GCC 4.6) MELT extensions

But I don't understand why you want an automated way of doing this. If the library is of reasonable size, you should understand it and be able to write and maintain a wrapping header by hand. Automating that task will take you some efforts (probably weeks, not minutes) so is worthwhile only for very large libraries.

A: If you have a master include file that includes all others available, you could simply hack a C preprocessor re-implementation in Perl. Process only ""-style includes and recursively paste the contents of these files. Should be a twenty-liner.
If not, you have to write one up yourself or try at random. Automatic dependency tracking in C++ is hard. Like in "let's see if this template instantiation causes an implicit instantiation of the argument class" hard. The only automated way I see is to shuffle your include files into a random order, see if the whole bunch compiles, and re-shuffle them until it compiles. Which will take n! time, you might be better off writing that include file by hand.
While the first variant is easy enough to hack, I doubt the sensibility of this hack, because you want to distribute on a package level (source tarball, deb package, Windows installer) instead of a file level.

A: What you want to do  sounds "javascriptish" to me :-) . But if you insist, there is always "cat" (or the equivalent in Windows):
$ cat file1.h file2.h file3.h > my_big_file.h

Or if you are using gcc, create a file my_decent_lib_header.h with the following contents:
#include "file1.h"
#include "file2.h"
#include "file3.h"

and then use
$ gcc -C -E my_decent_lib_header.h -o my_big_file.h

and this way you even get file/line directives that will refer to the original files (although that can be disabled, if you wish).
As for how automatic is this for your file order, well, it is not at all; you have to decide the order yourself. In fact, I would be surprised to hear that a tool that orders header dependencies correctly in all cases for C/C++ can be built.

A: You really need a build script to generate this as you work, and a preprocessor flag to disable use of the amalgamate (that could be for your uses).
To simplify this script/program, it helps to have your header structures and include hygiene in top form.

*

*Your program/script will need to know your discovery paths (hint: minimise the count of search paths to one if possible).

*Run the script or program (which you create) to replace include directives with header file contents.

*Assuming your headers are all guarded as is typical, you can keep track of what files you have already physically included and perform no action if there is another request to include them. If a header is not found, leave it as-is (as an include directive) -- this is required for system/third party headers -- unless you use a separate header for external includes (which is not at all a bad idea).

*It's good to have a build phase/translation that includes header alone and produces zero warnings or errors (warnings as errors).
Alternatively, you can create a special distribution repository so they never need to do more than pull from it occasionally.

A: usually you don't want to include every bit of information from all your headers into the special header that enables the potential user to actually use your library. The non-trivial removal of type definitions, further includes or defines, that are not necessary for the user of your interface to know can not be automatedly done. As far as I know.
Short answer to your main question:

*

*No.

My suggestions:

*

*manually make a new header, that contains all relevant information (nothing more, nothing less) for the user of your library interface. Add nice documentation comments for each component it contains.

*use forward declarations where possible, instead of full-fledged included definitions. Put the actual includes in your implementation files. The less include statements you have in your headers, the better.

*don't build a deeply nested hierarchy of includes. This makes it extremely hard to keep an overview on the contents of every bit you include. The user of your library will look into the header to learn how to use it. And he will probably not be able to distinguish relevant code from irrelevant on the first sight. You want to maximize the ratio of relevant code per total code in the main header for your library.
EDIT
If you really do have a toolkit library, and the order of inclusion really does not matter, and you have a bunch of independent headers, that you want to enumerate just for convenience into a single header, then you can use a simple script. Like the following Python (untested):
import glob
with open("convenience_header.h", 'w') as f:
  for header in glob.glob("*.h"):
    f.write("#include \"%s\"\n" % header)


text:
Q: How using DataContext from singleton in repository? Ef generate MyDataModel.edmx with class MyDataEntities for my database MyData.
I create a singleton class SingletonMyDataContext
public sealed class SingletonMyDataContext
    {
        private static readonly MyDataEntities_instance = new MyDataEntities();
        private SingletonMyDataContext() { }
        static SingletonMyDataContext() { }

        public static MyDataEntitiesInstance { get; private set; }
    }

I want to create a Repository class for work with data in DB, but i don't now, how to use in repository context(MyDataEntities _instance), because after using need call dispose().
How using DataContext from singleton in repository?
public class Repository
{
private DbContext _context = SingletonMyDataContext.Instance;

//logic for work with data
}

A:
How using DataContext from singleton in repository

Obviously, you should not make your data context as a singleton. Moreover, in most cases it's a bad practice. EF data context caches metadata itself, after first creation of context instance. Don't try to do it twice.


text:
Q: What is Bouziani space and what are its applications in mathematics? I have accrossed a new topological space seems were derived from Hilbert Space and it used to solve some boundary value problem for PDE and ODE , Inspired by this paper (page 4, Definition 3.1) , The definition 3.1 talks about Weighted Bouziani space this means that is a well known space which I didn't got it in the web or in wikipedia page , My question :What is Bouziani space and what are its applications in mathematics ?

A: It looks to me that the ordinary Bouziani space is the space $B^1_2(\Omega)$ discussed in the references [4] and [5] from the paper you cite.
It also seems like Bouziani, who wrote the paper you cite, is in fact the only author who uses the term ``Bouziani space''.


text:
Q: document.onmousedown is an event then why? I have javascript code to disable right click.
here it is:
 document.onmousedown=disableclick;
status="Right Click Disabled";
function disableclick(event){
  if(event.button==2)
   {
     alert(status);
     return false;
   }

}

although this code is working as expected but i have a problem about document.onmousedown,what i know about it that it is an event accessed through DOM then  it is assigned a value and the strange thing to me is that later this value is declared as function, how??

A: This function is event handler that is called when event happens.


text:
Q: react-native-localization android problem When user presses on changeLocale button this error happens and the app is crashing.

any help would be appreciated. thanks.
Homepage.js
constructor(props) {
    super(props);

    this.state = {
        locale: {},
        token: '',
    };

    this._changeLocale = this._changeLocale.bind(this);
}

_changeLocale() {

    if(this.state.locale.short === 'TR') {

        changeLocale({id: 2, short: 'EN'}, this.state.token);
        this.setState({
            locale: {id: 2, short: 'EN'}
        })
    } else {
        changeLocale({id: 1, short: 'TR'}, this.state.token);
        this.setState({
            locale: {id: 1, short: 'TR'}
        })
    }

}

renderContent() {

    return(
        <Container style={styles.container}>

            <HomepageHeader _changeLocale={this._changeLocale} locale={this.state.locale} />
        ...
        </Container>
}

HomepageHeader.js
render() {

    return(

        <Header style={styles.header} androidStatusBarColor={'#243f65'}>
         ...

            <Right style={styles.right}>
                <TouchableOpacity style={styles.loginButton} onPress={() => {this.props._changeLocale()}}>
                    <Text style={styles.loginText}>{this.props.locale.short}</Text>
                </TouchableOpacity>
            </Right>

        </Header>
    );
}

Function.js
export function changeLocale(locale, token) {

Variables.LOCALE.setLanguage(locale.short);

AsyncStorage.setItem('locale', JSON.stringify(locale));

return axios({
    method: 'POST',
    url: Variables.API_URL + 'auth/changeLocale',
    data: {
        locale_id: locale.id
    },
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + token
    },
});

}
Variables.js
static LOCALE = new LocalizedStrings({
    TR: {
        pages: {
            invitation: 'Davet',
            boards: 'Kurullar',
            program: 'Bilimsel Program',
            accommodation: 'Kayıt & Konaklama',
            courses: 'Kurslar',
            general: 'Genel Bilgiler',
            contact: 'İletişim',
            live: 'Canlı',
            papers: 'Bildiriler',
            search: 'Ara',
            speakers: 'Konuşmacılar',
            favorites: 'Favoriler'
        },
    },
    EN: {
        pages: {
            invitation: 'Invitation',
            boards: 'Boards',
            program: 'Scientific Program',
            accommodation: 'Registration & Accommodation',
            courses: 'Courses',
            general: 'General Information',
            contact: 'Contact',
            live: 'Live',
            papers: 'Papers',
            search: 'Search',
            speakers: 'Speakers',
            favorites: 'Favorites'
        }
    }
});

So basically i want to press a button to change the localization of project which is in Variables.js file.
I was able to do it my previous projects but in this, i can not manage it.
I think that the problem might have been occur because of Android API level. I just read this https://facebook.github.io/react-native/docs/improvingux#use-android-ripple
But still i have no solutions.


text:
Q: Stoke's Theorem Theory Question If $C$ is the boundary of a surface $S$ and $\phi$ and $\psi$ are arbitrary smooth scalar fields, Show that
$$\int_C \phi \nabla \psi \cdot dr = - \int_C \psi \nabla \phi \cdot d r = \iint_S (\nabla \phi \times \nabla \psi) \cdot n dS$$
I've tried working backwards, letting $\phi$ and $\psi$ be arbitrary and then generating something, but I just get a mess of symbols. Can't seem to figure it out.

A: Use $$\text{curl} (fX) = \nabla \times fX = f\, \nabla \times X + \nabla f \times X$$
and
$$\text{curl} (\nabla f) = \nabla \times \nabla f = 0 $$
for every smooth scalar field (function) $f$ and vector field $X$.
Then Stokes Theorem implies
\begin{align*}
\int_C \phi \nabla \psi \cdot dr & = \iint_S (\nabla\times (\phi \nabla \psi)) \cdot n dS = \iint_S (\nabla \phi \times \nabla\psi + \phi \nabla \times \nabla\psi) \cdot n dS = \\
%
& = \iint_S (\nabla \phi \times \nabla\psi) \cdot n dS = -\iint_S (\nabla \psi \times \nabla\phi) \cdot n dS = - \int_C \psi \nabla \phi \cdot dr
\end{align*}


text:
Q: Jenkins SCM polling is not working when hosted on AWS Linux 18.04.1
EDIT:
I found out that, on UBUNTU 16.0.4 the SCM Service is working fine and I do not face the problem. However, I'm having this problem on
  Ubuntu 18.0.4.
Any idea how can I check the SCM service logs?

Problem:

*

*Jenkins is not able to Poll for changes in the git repo. However, if
manually triggered, the recent changes are fetched and then the job
is built.

Jenkins Config:

*

*Jenkins master machine is in AWS cloud behind a load balancer.

*All slaves are in my local network which can connect to Jenkins
Master and execute jobs as per Master's command.

Solutions tried so far:

*

*I suspected some problem with the local firewall and tried connecting the node to a network which did not have any firewall. Still, this did not work.

*I tried deleting the existing nodes and adding them freshly. Still, it did not work.

*I tried with Bitbucket branch source plugin since all our code is on Bitbucket cloud.

What I'm expecting to solve this:

*

*If anyone has faced this issue before, please let me know how to resolve this.

*Else, I want to know is there any way that I can see the polling logs at
the system level.

*Please note: Not in the Jenkins (which I know). Please note, I do not
want to see the logs at https://mydomain/jobs/SCMpollLog as they do
print only after polling is triggered and then polling is a success
or not. I want to know the reason behind why polling is not
occurring.
Pleaes let me know if you need any additional info.

A: As a workaround, I would recommend you using the git hook: it will create an event once the repository has been updated and push it to Jenkins.
https://wiki.jenkins.io/display/JENKINS/GitHub+Plugin#GitHubPlugin-GitHubhooktriggerforGITScmpolling


text:
Q: Centering in 2 level Multilevel modeling When two level-1 variables interact with each other,
some articles recommend using cluster mean centering, rather than the grand mean centering.
However, I do not understand why I should not use grand mean centering when level 1 predictors are interact with each other.
Would anyone explain this point?


text:
Q: MySQL number of days until next occurrence of a date? I'm looking for a way to have an accurate countdown until Christmas, in number of day. I tried...
(SELECT DATEDIFF(CONCAT(YEAR(CURDATE()), '-12-25'), NOW())) as days

However this will return a negative date between Christmas and New Years.
I thought I could just add 365 if the number was negative but that won't account for leap years. Any suggestions for a better solution?
Many thanks!

A: This is pretty crude, but should do the trick. See if the result is negative, and if so then add one to the year:
Select Case DateDiff(Concat(Year(CurDate()), '-12-25'), Now())) < 0
         Then DateDiff(Concat(Year(CurDate())+1, '-12-25'), Now()))
         Else DateDiff(Concat(Year(CurDate()), '-12-24'), Now())) End As "days"


text: Q: how to get a different default dir in 2 terminal in vscode Well I need multiple terminal with different directory in Visual Studio Code both terminal should be PowerShell or CMD but not both. And I need them to stay at the same directory even after a restart.


text:
Q: Use Universal Image Loader to load PHOTO_URI of contact Righ now i'm getting some problems following:

05-14 16:20:59.355: D/ImageLoader(31397): Start display image task
  [content://com.android.contacts/contacts/281/photo_120x120] 05-14
  16:20:59.360: D/ImageLoader(31397): Load image from network
  [content://com.android.contacts/contacts/281/photo_120x120] 05-14
  16:20:59.360: D/ImageLoader(31397): Cache image on disk
  [content://com.android.contacts/contacts/281/photo_120x120]
05-14 16:20:59.445: E/ImageLoader(31397): URI:
  content://com.android.contacts/contacts/281/photo/photo 05-14
  16:20:59.445: E/ImageLoader(31397):
  java.lang.IllegalArgumentException: URI:
  content://com.android.contacts/contacts/281/photo/photo 05-14
  16:20:59.445: E/ImageLoader(31397):     at
  android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  android.content.ContentProviderProxy.query(ContentProviderNative.java:385)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  android.content.ContentResolver.query(ContentResolver.java:417) 05-14
  16:20:59.445: E/ImageLoader(31397):     at
  android.content.ContentResolver.query(ContentResolver.java:360) 05-14
  16:20:59.445: E/ImageLoader(31397):     at
  android.provider.ContactsContract$Contacts.openContactPhotoInputStream(ContactsContract.java:1982)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  android.provider.ContactsContract$Contacts.openContactPhotoInputStream(ContactsContract.java:2013)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  com.view.widget.ContactDownloader.getStreamFromContent(ContactDownloader.java:26)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStream(BaseImageDownloader.java:88)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.downloadImage(LoadAndDisplayImageTask.java:290)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryCacheImageOnDisk(LoadAndDisplayImageTask.java:273)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:229)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:135)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
  05-14 16:20:59.445: E/ImageLoader(31397):     at
  java.lang.Thread.run(Thread.java:841)

I try to extend BaseImageDownloader and override getStreamFromContent(...) method in issue 564:
https://github.com/nostra13/Android-Universal-Image-Loader/issues/564
same:
@Override
protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException {
        ContentResolver res = context.getContentResolver();
        Uri uri = Uri.parse(imageUri);
        if (imageUri.startsWith("content://com.android.contacts/")) {
            return ContactsContract.Contacts.openContactPhotoInputStream(res, uri);
        } else {
            return res.openInputStream(uri);
        }
    }

but not success.
Please help me.
Thanks & regards

A: I think you're running into the issue described (and solved) here: Load Contact Image Into Bitmap. For reference, the solution is to pass the URI of the contact itself to openContactPhotoInputStream(), not the URI of the contact's photo.

A: Use below code its working fine for me. I hope it will also work for you as well...
public class BaseImageLoaderClass extends BaseImageDownloader {

public BaseImageLoaderClass(Context context) {
    super(context);

}

@Override
protected InputStream getStreamFromContent(String imageUri, Object extra)
        throws FileNotFoundException {
    ContentResolver res = context.getContentResolver();
    Uri uri = Uri.parse(imageUri);
    if (imageUri.startsWith("content://com.android.contacts/")) {
        // return ContactsContract.Contacts.openContactPhotoInputStream(res,
        // uri);
        return getContactBitmapFromURI(context, uri);
    } else {
        return res.openInputStream(uri);
    }
}

public static InputStream getContactBitmapFromURI(Context context, Uri uri)
        throws FileNotFoundException {
    InputStream input = context.getContentResolver().openInputStream(uri);
    if (input == null) {
        return null;
    }
    return input;
    // return BitmapFactory.decodeStream(input);
}
}


text:
Q: Function satisfying $f(x)^{f^{-1}(x)}=x^2$ with $ f^{-1}$ is a compositional inverse of $f$ and $f:\mathbb{R+}\to \mathbb{R+}$? Let $f$ be a function such that   :$f:\mathbb{R+}\to \mathbb{R+}$  and $f^{-1}$ is a compositional inverse of $f$ , I have tried to find solution of the following functional  $f(x)^{f^{-1}(x)}=x^2$, I took $f(x)=x$ but it doesn't work it coincide only for $x=1$ and for $f(x)=\exp(x)$ I come up to $x^x=x^2$ then coincide only for $x=1$ and $x=2$ , so $f(x)^{f^{-1}(x)} > x$ for $x >2$ which means no trivial solution exists probably  a formel power series exist arround $x=1$ or $x=2$,Then my question here is : How I can solve  $f(x)^{f^{-1}(x)}=x^2$ with $ f^{-1}$  is a compositional inverse of $f$ ?
Edit I suspect such trigonometric function would be works for the titled function,like $\tan x$ as shown here but this need a restriction of our Domain of definitions for which $\tan x$ to be defined
Edit I have edited the question according to the answer given by @Robert I without changing the meaning I missed that I search about a real valued function not complex as stated in the below answer

A: When $f(x) < 0$ (which must happen for uncountably many $x$ if $f^{-1}$ is defined on $\mathbb R$), the fact that $f(x)^{f^{-1}(x)} > 0$ requires $f^{-1}(x)$ to be a rational number (presuming we define $a^b = \exp(b \log(a))$ for some branch of the logarithm; note all branches of logarithm of a negative number have imaginary part an integer multiple of $\pi i$, and $\exp(b k \pi i)$ is a positive real only when $b k$ is an even integer). Since $f$ can't map a countable set onto an uncountable one, we conclude there is no such function.
Or did you want to just define $f$ and $f^{-1}$ on $(0,\infty)$?