text:
Q: LinkedIn menu iPhone app I would like to develop an app with a menu which looks like the ios Linkedin app one. Like this (the left picture)

There is 4 glimpses (miniatures) which are associated to the four principal views.
And the miniature always shows the updated state of the view.
I would like to know we can do a menu like this one ?
Thanks in advance for your help !
Sébastien ;)

So why do you put the 4 UIView in an other UIView and not directly on the UIViewController ?
And you talked about buttons but there are only UIView in your example ? I wonder if the 4 buttons are on the 4 views and are transparent in order to apply the transformation.
Do you have a code example for the transformation ?
Thanks a lot for your help !

A: - (void)viewDidLoad {
[super viewDidLoad];
[self.navigationItem setTitle:@"About us"];

presentationViewController = [[PresentationViewController alloc] initWithNibName:@"PresentationViewController" bundle:nil];
secteursViewController = [[SecteursViewController alloc] initWithNibName:@"SecteursViewController" bundle:nil];
engagementsViewController = [[EngagementsViewController alloc] initWithNibName:@"EngagementsViewController" bundle:nil];
interviewsViewController = [[InterviewsViewController alloc] initWithNibName:@"InterviewsViewController" bundle:nil];

presentationApercu = presentationViewController.view;
secteursApercu = secteursViewController.view;
videosApercu = interviewsViewController.view;
engagementsApercu = engagementsViewController.view;

presentationApercu.transform = CGAffineTransformMakeScale(1/(320./107), 1/(367./122.));
presentationApercu.frame = CGRectMake(27., 18., presentationApercu.frame.size.width, presentationApercu.frame.size.height);

secteursApercu.transform = CGAffineTransformMakeScale(1/(320./107), 1/(367./122.));
secteursApercu.frame = CGRectMake(185., 18., secteursApercu.frame.size.width, secteursApercu.frame.size.height);

videosApercu.transform = CGAffineTransformMakeScale(1/(320./107), 1/(367./122.));
videosApercu.frame = CGRectMake(27., 196., videosApercu.frame.size.width, videosApercu.frame.size.height);;

engagementsApercu.transform = CGAffineTransformMakeScale(1/(320./107), 1/(367./122.));
engagementsApercu.frame = CGRectMake(185., 196., engagementsApercu.frame.size.width, engagementsApercu.frame.size.height);

presentationApercu.tag = 1;
secteursApercu.tag = 2;
videosApercu.tag = 3;
engagementsApercu.tag = 4;

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
[tap setNumberOfTapsRequired:1];
[presentationApercu addGestureRecognizer:tap];
[tap release];

tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
[tap setNumberOfTapsRequired:1];
[secteursApercu addGestureRecognizer:tap];
[tap release];

tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
[tap setNumberOfTapsRequired:1];
[videosApercu addGestureRecognizer:tap];
[tap release];

tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
[tap setNumberOfTapsRequired:1];
[engagementsApercu addGestureRecognizer:tap];
[tap release];

[self.view addSubview:presentationApercu];
[self.view addSubview:secteursApercu];
[self.view addSubview:videosApercu];
[self.view addSubview:engagementsApercu];

}

#pragma mark - IBActions

- (void)zoomReverse {
[self.navigationItem setLeftBarButtonItem:nil];
UITapGestureRecognizer *tap = nil;

switch (tagEnCours) {
    case 1:
        [self.view bringSubviewToFront:presentationApercu];

        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
        [tap setNumberOfTapsRequired:1];
        [presentationApercu addGestureRecognizer:tap];
        [tap release];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        presentationApercu.transform = CGAffineTransformMakeScale(1/(320./107), 1/(367./122.));
        presentationApercu.frame = CGRectMake(27., 18., presentationApercu.frame.size.width, presentationApercu.frame.size.height);

        [UIView commitAnimations];

        break;

    case 2:
        [self.view bringSubviewToFront:secteursApercu];

        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
        [tap setNumberOfTapsRequired:1];
        [secteursApercu addGestureRecognizer:tap];
        [tap release];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        secteursApercu.transform = CGAffineTransformMakeScale(1/(320./107), 1/(367./122.));
        secteursApercu.frame = CGRectMake(185., 18., secteursApercu.frame.size.width, secteursApercu.frame.size.height);

        [UIView commitAnimations];

        break;

    case 3:
        [self.view bringSubviewToFront:videosApercu];

        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
        [tap setNumberOfTapsRequired:1];
        [videosApercu addGestureRecognizer:tap];
        [tap release];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        videosApercu.transform = CGAffineTransformMakeScale(1/(320./107), 1/(367./122.));
        videosApercu.frame = CGRectMake(27., 196., videosApercu.frame.size.width, videosApercu.frame.size.height);

        [UIView commitAnimations];

        break;

    case 4:
        [self.view bringSubviewToFront:engagementsApercu];

        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
        [tap setNumberOfTapsRequired:1];
        [engagementsApercu addGestureRecognizer:tap];
        [tap release];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        engagementsApercu.transform = CGAffineTransformMakeScale(1/(320./107), 1/(367./122.));
        engagementsApercu.frame = CGRectMake(185., 196., engagementsApercu.frame.size.width, engagementsApercu.frame.size.height);

        [UIView commitAnimations];

        break;

    default:
        break;
}
}

- (void)zoomAction:(UITapGestureRecognizer *)sender {
[self.navigationItem setLeftBarButtonItem:[[[UIBarButtonItem alloc] initWithTitle:@"About us" style:UIBarButtonItemStyleDone target:self action:@selector(zoomReverse)] autorelease]];
tagEnCours = sender.view.tag;
switch (sender.view.tag) {
    case 1:
        [self.view bringSubviewToFront:presentationApercu];
        [presentationApercu removeGestureRecognizer:[presentationApercu.gestureRecognizers objectAtIndex:0]];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        presentationApercu.transform = CGAffineTransformIdentity;
        presentationApercu.frame = CGRectMake(0., 0., presentationApercu.frame.size.width, presentationApercu.frame.size.height);

        [UIView commitAnimations];

        break;

    case 2:
        [self.view bringSubviewToFront:secteursApercu];
        [secteursApercu removeGestureRecognizer:[secteursApercu.gestureRecognizers objectAtIndex:0]];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        secteursApercu.transform = CGAffineTransformIdentity;
        secteursApercu.frame = CGRectMake(0., 0., secteursApercu.frame.size.width, secteursApercu.frame.size.height);

        [UIView commitAnimations];
        break;

    case 3:
        [self.view bringSubviewToFront:videosApercu];
        [videosApercu removeGestureRecognizer:[videosApercu.gestureRecognizers objectAtIndex:0]];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        videosApercu.transform = CGAffineTransformIdentity;
        videosApercu.frame = CGRectMake(0., 0., videosApercu.frame.size.width, videosApercu.frame.size.height);

        [UIView commitAnimations];
        break;

    case 4:
        [self.view bringSubviewToFront:engagementsApercu];
        [engagementsApercu removeGestureRecognizer:[engagementsApercu.gestureRecognizers objectAtIndex:0]];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        engagementsApercu.transform = CGAffineTransformIdentity;
        engagementsApercu.frame = CGRectMake(0., 0., engagementsApercu.frame.size.width, engagementsApercu.frame.size.height);

        [UIView commitAnimations];
        break;

    default:
        break;
}
}

A: I think that this application is structured as follows:
UIViewController
  | UIView
    | UIView
    | UIView
    | UIView
    | UIView

The first contains the main view controller (the one containing the 4 buttons), these are reduced by (I assume) a transform and then the View is superimposed by a view of the secondary, the second requirement.
This is what I think, because if you try to scroll the table and immediately go back, even in the thumbnail view scrolling.
Hope that was of some help.

A: Consider this as a draft from which to take inspiration:
//.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

//.m
#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) UIView *v1;
@property (nonatomic, strong) UIView *v2;
@property (nonatomic, strong) UIView *v3;
@property (nonatomic, strong) UIView *v4;

@end

@implementation ViewController

@synthesize v1 = _v1;
@synthesize v2 = _v2;
@synthesize v3 = _v3;
@synthesize v4 = _v4;

- (void)viewDidLoad {
    [super viewDidLoad];

    _v1 = [[UIView alloc] initWithFrame:self.view.bounds];
    _v2 = [[UIView alloc] initWithFrame:self.view.bounds];
    _v3 = [[UIView alloc] initWithFrame:self.view.bounds];
    _v4 = [[UIView alloc] initWithFrame:self.view.bounds];

    [_v1 setBackgroundColor:[UIColor redColor]];
    [_v2 setBackgroundColor:[UIColor yellowColor]];
    [_v3 setBackgroundColor:[UIColor blueColor]];
    [_v4 setBackgroundColor:[UIColor greenColor]];

    _v1.transform = CGAffineTransformMakeScale(1/(320./140.), 1/(460./210.));
    _v1.frame = CGRectMake(10., 10., _v1.frame.size.width, _v1.frame.size.height);

    _v2.transform = CGAffineTransformMakeScale(1/(320./140.), 1/(460./210.));
    _v2.frame = CGRectMake(170., 10., _v2.frame.size.width, _v2.frame.size.height);

    _v3.transform = CGAffineTransformMakeScale(1/(320./140.), 1/(460./210.));
    _v3.frame = CGRectMake(10., 240., _v3.frame.size.width, _v3.frame.size.height);

    _v4.transform = CGAffineTransformMakeScale(1/(320./140.), 1/(460./210.));
    _v4.frame = CGRectMake(170., 240., _v4.frame.size.width, _v4.frame.size.height);

    _v1.tag = 1;
    _v2.tag = 2;
    _v3.tag = 3;
    _v4.tag = 4;

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
    [tap setNumberOfTapsRequired:1];
    [_v1 addGestureRecognizer:tap];
    [tap release];

    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
    [tap setNumberOfTapsRequired:1];
    [_v2 addGestureRecognizer:tap];
    [tap release];

    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
    [tap setNumberOfTapsRequired:1];
    [_v3 addGestureRecognizer:tap];
    [tap release];

    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
    [tap setNumberOfTapsRequired:1];
    [_v4 addGestureRecognizer:tap];
    [tap release];

    [self.view addSubview:_v1];
    [self.view addSubview:_v2];
    [self.view addSubview:_v3];
    [self.view addSubview:_v4];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setFrame:CGRectMake(10, 10, 100, 30)];
    [btn setTitle:@"Close" forState:UIControlStateNormal];
    btn.tag = 1;
    [btn addTarget:self action:@selector(zoomReverse:) forControlEvents:UIControlEventTouchUpInside];
    [_v1 addSubview:btn];

    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setFrame:CGRectMake(10, 10, 100, 30)];
    [btn setTitle:@"Close" forState:UIControlStateNormal];
    btn.tag = 2;
    [btn addTarget:self action:@selector(zoomReverse:) forControlEvents:UIControlEventTouchUpInside];
    [_v2 addSubview:btn];

    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setFrame:CGRectMake(10, 10, 100, 30)];
    [btn setTitle:@"Close" forState:UIControlStateNormal];
    btn.tag = 3;
    [btn addTarget:self action:@selector(zoomReverse:) forControlEvents:UIControlEventTouchUpInside];
    [_v3 addSubview:btn];

    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setFrame:CGRectMake(10, 10, 100, 30)];
    [btn setTitle:@"Close" forState:UIControlStateNormal];
    btn.tag = 4;
    [btn addTarget:self action:@selector(zoomReverse:) forControlEvents:UIControlEventTouchUpInside];
    [_v4 addSubview:btn];
}

- (void)zoomReverse:(UIButton *)sender {
    UITapGestureRecognizer *tap = nil;

    switch (sender.tag) {
        case 1:
            [self.view bringSubviewToFront:_v1];

             tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
            [tap setNumberOfTapsRequired:1];
            [_v1 addGestureRecognizer:tap];
            [tap release];

            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:1];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

            _v1.transform = CGAffineTransformMakeScale(1/(320./140.), 1/(460./210.));
            _v1.frame = CGRectMake(10., 10., _v1.frame.size.width, _v1.frame.size.height);

            [UIView commitAnimations];

            break;

        case 2:
            [self.view bringSubviewToFront:_v2];

            tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
            [tap setNumberOfTapsRequired:1];
            [_v2 addGestureRecognizer:tap];
            [tap release];

            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:1];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

            _v2.transform = CGAffineTransformMakeScale(1/(320./140.), 1/(460./210.));
            _v2.frame = CGRectMake(170., 10., _v2.frame.size.width, _v2.frame.size.height);

            [UIView commitAnimations];

            break;

        case 3:
            [self.view bringSubviewToFront:_v3];

            tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
            [tap setNumberOfTapsRequired:1];
            [_v3 addGestureRecognizer:tap];
            [tap release];

            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:1];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

            _v3.transform = CGAffineTransformMakeScale(1/(320./140.), 1/(460./210.));
            _v3.frame = CGRectMake(10., 240., _v3.frame.size.width, _v3.frame.size.height);

            [UIView commitAnimations];

            break;

        case 4:
            [self.view bringSubviewToFront:_v4];

            tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomAction:)];
            [tap setNumberOfTapsRequired:1];
            [_v4 addGestureRecognizer:tap];
            [tap release];

            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:1];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

            _v4.transform = CGAffineTransformMakeScale(1/(320./140.), 1/(460./210.));
            _v4.frame = CGRectMake(170., 240., _v4.frame.size.width, _v4.frame.size.height);

            [UIView commitAnimations];

            break;

        default:
            break;
    }
}

- (void)zoomAction:(UITapGestureRecognizer *)sender {
    switch (sender.view.tag) {
        case 1:
            [self.view bringSubviewToFront:_v1];
            [_v1 removeGestureRecognizer:[_v1.gestureRecognizers objectAtIndex:0]];

            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:1];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

            _v1.transform = CGAffineTransformIdentity;
            _v1.frame = CGRectMake(0., 0., _v1.frame.size.width, _v1.frame.size.height);

            [UIView commitAnimations];

            break;

        case 2:
            [self.view bringSubviewToFront:_v2];
            [_v2 removeGestureRecognizer:[_v2.gestureRecognizers objectAtIndex:0]];

            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:1];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

            _v2.transform = CGAffineTransformIdentity;
            _v2.frame = CGRectMake(0., 0., _v2.frame.size.width, _v2.frame.size.height);

            [UIView commitAnimations];
            break;

        case 3:
            [self.view bringSubviewToFront:_v3];
            [_v3 removeGestureRecognizer:[_v3.gestureRecognizers objectAtIndex:0]];

            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:1];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

            _v3.transform = CGAffineTransformIdentity;
            _v3.frame = CGRectMake(0., 0., _v3.frame.size.width, _v3.frame.size.height);

            [UIView commitAnimations];
            break;

        case 4:
            [self.view bringSubviewToFront:_v4];
            [_v4 removeGestureRecognizer:[_v4.gestureRecognizers objectAtIndex:0]];

            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:1];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

            _v4.transform = CGAffineTransformIdentity;
            _v4.frame = CGRectMake(0., 0., _v4.frame.size.width, _v4.frame.size.height);

            [UIView commitAnimations];
            break;

        default:
            break;
    }
}

- (void)viewDidUnload {
    [super viewDidUnload];

    [self setV1:nil];
    [self setV2:nil];
    [self setV3:nil];
    [self setV4:nil];
}

@end

I hope it can help.


text:
Q: Excel: max() of count() with column grouping in a pivot table I have a pivot table fed from a MySQL view. Each returned row is basically an instantiation of "a person, with a role, at a venue, on a date". The each cell then shows count of person (lets call it person_id).
When you pivot this in excel, you get a nice table of the form:
        | Dates -->
--------------------------
Venue   |
   Role | -count of person-

This makes a lot of sense, and the end user likes this format BUT the requirement has changed to group the columns (date) into a week.
When you group them in the normal way, this count is then applied in columns as well. This is, of course, logical behaviour, but what I actually want is max() of the original count().
So the question: Does anyone know how to have cells count(), but the grouping perform a max()?
To illustrate this, imagine the columns for a week. Then imaging the max() grouped as a week, giving:
Old:
         | M | T | W | T | F | S | S ||
---------------------------------------   .... for several weeks
Venue X  |
   Role Y| 1 | 1 | 2 | 1 | 2 | 3 | 1 ||

New (grouped by week)
         | Week 1 |    ...
---------------------------
Venue X  |
   Role Y|    3   |    ...

A: I'm not on my pc, but the steps below should be broadly correct:

*

*You should be able to right click on the date field on pivot table and select group.

*Then highlight week, you may have to select year also.

*Lastly right click on the count data you already have and expand the summarise by, and select max.

redpajama_set_name: RedPajamaStackExchange


text:
Q: retrieve image resources from drawables dynamically by using names i am thinking of a simple program which will retrieve the appropriate image file (there will be many image files within drawable) from drawables depending on the user input from an EditText view. this input will match with 1 of the the png file names in my drawable resource folder. The program will thus retrieve the png file with the name that has the same name as the text in edittext. following is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="enter the resource id and press getit button to retrieve it"
    />
<EditText
    android:id="@+id/edtxt"
    android:layout_width="100px"
    android:layout_height="100px"
    />
<EditText
    android:id="@+id/stedtxt"
    android:layout_width="100px"
    android:layout_height="100px"
    />

<TextView
    android:id="@+id/txtved"
    android:layout_width="60px"
    android:layout_height="50px"

    />
<Button
    android:id="@+id/Button01"
    android:layout_width="70px"
    android:layout_height="70px"
    android:clickable="true"
/>

and following is my .java file.
package com.example.retrievedrawable;

import java.lang.reflect.Field;
import android.app.Activity;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class RetrieveDrawable extends Activity {
    private Editable resid;
    private String residst;
    private String TAG;
    private int drawableId;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        EditText edresid=  (EditText)findViewById(R.id.edtxt);
        final EditText stdtxt=  (EditText)findViewById(R.id.stedtxt);
        Button setit = (Button) findViewById(R.id.Button01);
        final Editable resid=(Editable)edresid.getText();
        residst=resid.toString();

        try {
            Field field = com.example.retrievedrawable.R.drawable.class.getField(residst);
            try {
                drawableId= field.getInt(null);
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (NoSuchFieldException e) {
            Log.e(TAG, "Can't find resource drawable with name " + residst);
        }

        setit.setOnClickListener(new View.OnClickListener() {
          public void onClick(View view) {
              stdtxt.setText(drawableId);
            }

            });
    }

}

i followed Vladimir's suggestions..but its giving me a force close..also once i get the id of the image in drawable..i want to set that image on the UI..

A: Use reflection in order to do it:
        try {
            Field field = com.lid.lines.R.drawable.class.getField(imageResource);
            return field.getInt(null);
        } catch (NoSuchFieldException e) {
            Log.e(TAG, "Can't find resource drawable with name " + imageResource);
        } catch (IllegalAccessException e) {
            Log.e(TAG, "Can't access to resource drawable with name " + imageResource);
        }
        throw new IllegalStateException("Failed to get resource id of " + imageResource);

A: OK i got the solution using a hashmap following is my new java file:
    import android.app.Activity;
    import android.content.res.Resources;
    import android.content.res.TypedArray;
    import android.graphics.drawable.Drawable;
    import android.os.Bundle;
    import android.text.Editable;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.Toast;

    public class RetrieveDrawable extends Activity {
        private Editable resid;
        private String residst;
        private String TAG;
        private int drawableId;
        private Object ImageView;
        public static final String PREFIX = "img";
        public static final Map mImageMap = new HashMap<String, Drawable>();

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            EditText edresid=  (EditText)findViewById(R.id.edtxt);
            final EditText stdtxt=  (EditText)findViewById(R.id.stedtxt);
            Button setit = (Button) findViewById(R.id.Button01);
            final ImageView imview =(ImageView)findViewById(R.id.imageView);
            final Editable resid=(Editable)edresid.getText();
            residst=resid.toString();
            if (mImageMap.size() == 0) {
                   mImageMap.put(PREFIX + "a", getResources().getDrawable(R.drawable.fl1a1));
                   mImageMap.put(PREFIX + "2", getResources().getDrawable(R.drawable.lf1a1));
                   mImageMap.put(PREFIX + "3", getResources().getDrawable(R.drawable.st1a1));
                }

            setit.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) {
                  String exampleInput = resid.toString();
                  Drawable d = (Drawable) mImageMap.get(PREFIX + exampleInput);
                  imview.setBackgroundDrawable(d);

              }

             });

        }

 }


text:
Q: binding selectionArgs to a FTS3 query that spans across multiple columns I construct selection string to perform FTS3 search across multiple columns:
final String selection = "table MATCH 'column1:? OR column2:?'"

I am also passing selectionArgs containing the search terms.  The problem is that I'm getting an exception during argument binding:

11-30 13:22:27.475  26281-26323/com.example.myapp
  W/SuggestionsAdapter﹕ Search suggestions query threw an exception.
      java.lang.IllegalArgumentException: Cannot bind argument at index 2 because the index is out of range.  The statement has 0 parameters.
              at android.database.sqlite.SQLiteProgram.bind(SQLiteProgram.java:212)
              at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:166)

When I replace question marks in the MATCH argument string with hard-coded search terms and set selectionArgs = null, the query works and returns correct results.
How can I bind selectionArgs to a FTS3 query that searches across multiple columns?

A: The following approach worked for me:

*

*Use String.format() to construct selectionArgs, using search terms as arguments.

*Use single argument to construct selection
In code:
final String selection = "table MATCH ?"
final String[] selectionArgs = { String.format("column1:%s* OR column2:%s*", term1, term2) };


text:
Q: UITableView: I want to use an approach in which it is easy modify sections and rows (add, remove). Our app has changed every month. It is very hard to modify sections and rows (add, remove). I need to scan every UITableViewDelegate's method and changed it. I'm using switch-case approach. I'm need more elegant approach.
I posted my code for two methods but in reality I have to modify 5 methods.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
 NSInteger rows;

 switch (section)
 {
    case 0:
    {
        rows = 3;
        break;
    }
    case 1:
    {
        rows = 4;
        break;
    }
    case 2:
    {
        rows = 4;
        break;
    }
    case 3:
    {
        rows = 4;
        break;
    }
    case 4:
    {
        rows = 7;
        break;
    }

    default:
        rows = 1;
        break;
 }

 return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 switch (indexPath.section)
 {
    case 0:
    {
        switch (indexPath.section)
        {
            case 0:
            {
                break;
            }
            case 1:
            {
                break;
            }
            case 2:
            {
                break;
            }
            default:
                break;
        }

        break;
     }
  }
}

A: Use a .plist file where you can change directly its content and the UIViewController will just build his UITableView based on that. Work like a charm for me.

A: Create a class say TableManager
Pass your table view to this class and let this class provide the data for all your tableviews. Differentiate between the tableviews by settings tag values to them.
So now you will have control of all your tableviews in this one class.
Instead of the numbers in the switch case use enum. It will increase readability in your code.
Depending upon your actual requirement you can manipulate this class's behavior from a plist perhaps.
Let me provide some code:
Define an enumerator
typedef enum { FIRST_TABLE, SECOND_TABLE, THIRD_TABLE } TableViews;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

[TableManager getNumberOfRowsForTableView:tableView];

}

In your TableManager
+ (NSInteger)getNumberOfRowsForTableView:(UITableView*)theTableView
{

if(theTableView.tag == FIRST_TABLE) //FIRST_TABLE is an enum
{
 //Your conditions goes here
 return 3;
}

}

A: I created this class that does exactly what you want: https://github.com/Morbix/TableManager
Basic Usage of TableManager
import TableManager // 1 - import TableManager

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let data = (1...1_000).map { "Row \($0)" }

        data.forEach { element in
            let row = tableView.addRow() // 2 - Add a row

            row.setConfiguration { (row, cell, indexPath) in // 3 - And configure it
                cell.textLabel?.text = element
            }
        }

        tableView.reloadData()
    }

}

You can add Section and Rows, control the visibility, configure header and footer, etc...


text:
Q: Redirect user if not logged I want to redirect users to index page if they are not logged when they try to go directly to another page like "search or inbox. Now this is what I did but it keeps redirecting both logged and not-logged.
$u = "";
$isOwner = "no";
if($u == $log_username && $user_ok == true) {
     $isOwner = "yes";
}
if($isOwner != "yes") {
     header("location: index.php");
     exit();
}

What is the best approach to this?

A: When a user logs in to your application, you want to set a flag on the user's session stating he/she is properly authenticated and logged in. On subsequent requests, based on what the session variable says, you redirect your user to the login page or let the user continue further in your application. In very simple form, it would look like this.
In your login handler e.g. login.php,
if (authenticate($_POST['username'], $_POST['password']) {
    $_SESSION['authenticated'] = true;
    # redirect to the main page
}

Now, on subsequent requests, early in your application, before invoking appropriate handlers,
if (empty($_SESSION['authenticated'])) {
    # redirect to login page
}

# invoke handlers for the request

For this to work, you need to make sure the PHP session auto starts or start it manually using session_start() early in your application flow.

A: I later tried this method and it works perfectly for me.
if($user_ok == true){}
else{
    header("location: login.php?u=".$_SESSION["username"]);
exit();
}

I just want to thank you all for your ideas.


text:
Q: Wifi is fine on Ubuntu but very slow on window 7 this is the first time i come here, so sorry if i make some mistakes.
My question is: when my computer(Ubuntu 13.04) connect to wifi router, other computer(install window 7) will have slow connection but my computer is fine.
I try to config(router) to 11b 11g ... but nothing change.
Thank for your help!
EDIT: The result when i execute command sudo lspci  :
00:00.0 Host bridge: Intel Corporation 2nd Generation Core Processor Family DRAM Controller (rev 09)
00:01.0 PCI bridge: Intel Corporation Xeon E3-1200/2nd Generation Core Processor Family PCI Express Root Port (rev 09)
00:02.0 VGA compatible controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09)
00:16.0 Communication controller: Intel Corporation 6 Series/C200 Series Chipset Family MEI Controller #1 (rev 04)
00:1a.0 USB controller: Intel Corporation 6 Series/C200 Series Chipset Family USB Enhanced Host Controller #2 (rev 05)
00:1b.0 Audio device: Intel Corporation 6 Series/C200 Series Chipset Family High Definition Audio Controller (rev 05)
00:1c.0 PCI bridge: Intel Corporation 6 Series/C200 Series Chipset Family PCI Express Root Port 1 (rev b5)
00:1c.2 PCI bridge: Intel Corporation 6 Series/C200 Series Chipset Family PCI Express Root Port 3 (rev b5)
00:1c.4 PCI bridge: Intel Corporation 6 Series/C200 Series Chipset Family PCI Express Root Port 5 (rev b5)
00:1c.5 PCI bridge: Intel Corporation 6 Series/C200 Series Chipset Family PCI Express Root Port 6 (rev b5)
00:1d.0 USB controller: Intel Corporation 6 Series/C200 Series Chipset Family USB Enhanced Host Controller #1 (rev 05)
00:1f.0 ISA bridge: Intel Corporation HM67 Express Chipset Family LPC Controller (rev 05)
00:1f.2 SATA controller: Intel Corporation 6 Series/C200 Series Chipset Family 6 port SATA AHCI Controller (rev 05)
00:1f.3 SMBus: Intel Corporation 6 Series/C200 Series Chipset Family SMBus Controller (rev 05)
01:00.0 VGA compatible controller: Advanced Micro Devices [AMD] nee ATI Whistler [Radeon HD 6600M/6700M/7600M Series]
02:00.0 Network controller: Broadcom Corporation BCM4313 802.11b/g/n Wireless LAN Controller (rev 01)
03:00.0 USB controller: NEC Corporation uPD720200 USB 3.0 Host Controller (rev 04)
04:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168 PCI Express Gigabit Ethernet controller (rev 06)

A: I have the exact same wireless card that you have. It's an ASUS eeepc 1015PEM with a Broadcom 4313. It looks like an issue with the drivers for this wireless card. I'm no expert in wifi radio, so can't really understand how and why this is happening.
If you are ok with experimenting, take a look at this thread: How do I get my Broadcom BCM4313 working correctly?


text:
Q: Bandwidth Manager Using Squid I am trying to create a internet distribution software for an ISP (an internet distributor or a school or other such organizations) like the one here
It will have restrictions and policies for users to limit bandwidth/speed/duration etc according to their internet connection package. Also, the administrator should be able to monitor their speed and block/allow users and renew packages.
The architecture is like:

Non https client request work fine. But https request are giving SSL_ERROR as expected.
I read Squid cannot handle https connections in transparent proxy mode, but I do not want users to set proxy in their browser every time.
Is there any other way so that we can count all the traffic, including the encrypted traffic, used by a user and shape the traffic accordingly?

A: This is not a limitation of Squid, it is a limitation of the HTTPS protocol itself. If you try setting up a transparent HTTPS proxy, you invariably would need to break the encryption channel - otherwise the proxy has no way of knowing which web site to load. So you basically choose between

*

*setting a HTTP proxy in browsers (which might be done through autodiscovery BTW)

*breaking HTTPS security by terminating the encryption channel at your Squid proxy - BumpSSLServerFirst has been written with this in mind. For this to work though, your clients would need to trust the Squid's CA to sign any certificate - it would have to be installed as a trusted root CA on every client.

As setting up trusted CA certs on all clients seems more labor-intensive than just setting a HTTPS proxy in the browser settings, it would only make sense if you plan on working with the decrypted data in ACLs or for request/response body checking.


text:
Q: Access dynamically rendered children's state I'm working on a system to multi-select elements from a FlatList to then remove from AsyncStorage the data related to the selected elements. How it works is:
-Parent component passes to child inside FlatList a state that will hold children's functions, like this:
export default function Parent({ navigation }) {
   const [ productsInfo, setProductsInfo ] = useState([]);
   const [ selectedProducts, setSelectedProducts ] = useState([]);
   const [ selectCount, setSelectCount ] = useState(0);

   <FlatList data={productsInfo}
            renderItem={({ item }) => (
            <Child item={item}
            selectedProducts={selectedProducts}
            selectCount={selectCount}
            setSelectCount={setSelectCount}/>
        )}/>

-Children components fill parent's array state with their callback functions:
const Child = ({ item, selectedProducts, selectCount, setSelectCount }) => {
    const [ selected, setSelected ] = useState(false);

    useEffect(() => {
        selectedProducts.push([selected, setSelected]); //filling parent's state
    }, []);

-Parent handles children's state through callback functions passed on previous step (with useEffect)
export default function Parent({ navigation }) {
    const [ selectedProducts, setSelectedProducts ] = useState([]);
    const [ selectCount, setSelectCount ] = useState(0);

const selectAll = () => {
        selectedProducts.map(product => {
            let setSelected = product[1]; //second element is the setState of child
            setSelected(true);
        });
        setSelectCount(selectedProducts.length);
    }

-Children handle their own state when they're pressed:
const Child = ({ item, selectedProducts, selectCount, setSelectCount }) => {
    const [ selected, setSelected ] = useState(false);

    const handleSelect = () => {
        setSelected(!selected);
        let count = selected ? selectCount - 1 : selectCount + 1;
        setSelectCount(count); //parent's state
    }

Now this all works, everything gets highlighted correctly and the counter of selected elements checks out. The problem is when I go to confirm deletion of selected elements (or the data they're rendered upon) and I iterate through the children's boolean state. They all turn out as false, even if they're true since they are highlighted, since they change color based on that state.
export default function Parent({ navigation }) {

const deleteSelected = async () => {
        await selectedProducts.map(product => {
            let selected = product[0]; //first element is the state's value, boolean
            console.log(selected); //all false
        });
    }

It needs to know at which index there are true value so it can delete data at those indexes, but they never turn out true.
Do you know why this happens? I'll leave the whole code below.
import React, { useEffect, useState } from 'react';
import {
  FlatList,
  StyleSheet,
  View,
  Text,
  TouchableHighlight,
  Alert
} from 'react-native';
import Icon from '@expo/vector-icons/MaterialIcons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { TouchableNativeFeedback } from 'react-native-gesture-handler';

const Product = ({ item, selectedProducts, selectCount, setSelectCount }) => { //Child
    const [ selected, setSelected ] = useState(false);

    const handleSelect = () => {
        setSelected(!selected);
        let count = selected ? selectCount - 1 : selectCount + 1;
        setSelectCount(count);
    }

    useEffect(() => {
        selectedProducts.push([selected, setSelected]);
    }, []);

    return (
        <TouchableHighlight onPress={() => handleSelect()}>
            <View style={[styles.productContainer, {backgroundColor: selected ? '#DDDDDD' : '#F8F8F8'}]}>
                <View>
                    <Text style={styles.productTitle}>{item.name}</Text>
                </View>
                <View style={styles.productDetailsContainer}>
                    <View style={styles.productDetails}>
                        <Text style={styles.productDetailsTitle}>Prezzo attuale</Text>
                        <Text>{item.currentPrice}</Text>
                    </View>
                    <View style={styles.productDetails}>
                        <Text style={styles.productDetailsTitle}>Prezzo più basso</Text>
                        <Text>{item.lowestPrice}</Text>
                    </View>
                    <View style={styles.productDetails}>
                        <Text style={styles.productDetailsTitle}>Prezzo target</Text>
                        <Text>{item.targetPrice}</Text>
                    </View>
                </View>
            </View>
        </TouchableHighlight>);
}

export default function WatchlistDeleteScreen({ navigation }) { //Parent
    const [ productsInfo, setProductsInfo ] = useState([]);
    const [ selectedProducts, setSelectedProducts ] = useState([]);
    const [ selectCount, setSelectCount ] = useState(0);

    const selectAll = () => {
        selectedProducts.map(product => {
            let setSelected = product[1];
            setSelected(true);
        });
        setSelectCount(selectedProducts.length);
    }

    const deleteSelected = async () => {
        await selectedProducts.map(product => {
            let selected = product[0];
            console.log(selected);
        });
    }

    useEffect(() => {
        const getData = async () => {
            await AsyncStorage.getItem('productsInfo')
            .then(data => JSON.parse(data))
            .then(jsonData => {
                setProductsInfo(jsonData);
            })
            .catch(error => {});
        }

        getData();
    }, []);

    return (
        <View style={{flex: 1}}>
            <View style={styles.header}>
                <View style={styles.headerIconsContainer}>
                    <TouchableNativeFeedback onPress={() => { navigation.pop() }}
                    background={TouchableNativeFeedback.Ripple('default', true)}>
                        <Icon name={'close'} size={27} color={'black'} />
                    </TouchableNativeFeedback>
                    <Text style={{fontWeight: 'bold', fontSize: 20, marginLeft: 25}}>{selectCount}</Text>
                </View>
                <View style={styles.headerIconsContainer}>
                    <View style={styles.icons}>
                        <TouchableNativeFeedback onPress={() => { selectAll() }}
                        background={TouchableNativeFeedback.Ripple('default', true)}>
                            <Icon name={'select-all'} size={27} color={'black'} />
                        </TouchableNativeFeedback>
                    </View>
                    {selectCount > 0 &&
                    <View style={styles.icons}>
                        <TouchableNativeFeedback onPress={() => { deleteSelected() }}
                        background={TouchableNativeFeedback.Ripple('default', true)}>
                                <Icon name={'check'} size={27} color={'black'} />
                        </TouchableNativeFeedback>
                    </View>}
                </View>
            </View>
            <FlatList data={productsInfo}
                renderItem={({ item }) => (
                <Product item={item}
                selectedProducts={selectedProducts}
                selectCount={selectCount}
                setSelectCount={setSelectCount}/>
            )}/>
        </View>
    );
}

const styles = StyleSheet.create({
    header: {
        backgroundColor: 'white',
        height: 58,
        elevation: 4,
        justifyContent: 'space-between',
        paddingLeft: 10,
        paddingRight: 10,
        flexDirection: 'row',
        alignItems: 'center'
    },
    headerIconsContainer: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    screenTitle: {
        fontWeight: 'bold',
        fontSize: 20
    },
    productContainer: {
        padding: 10
    },
    productTitle: {
        fontWeight: 'bold',
        fontSize: 19,
        borderBottomColor: 'grey',
        borderBottomWidth: 0.2
    },
    productDetailsTitle: {
        fontWeight: 'bold',
        fontSize: 14
    },
    productDetailsContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        padding: 5,
        justifyContent: 'space-between'
    },
    productDetails: {
        flexWrap: 'wrap'
    },
    icons: {
        marginLeft: 25
    }
});

A: The problem
This is wrong:
    useEffect(() => {
        selectedProducts.push([selected, setSelected]);
    }, []);

The selectedProducts is a state variable and should be considered immutable: push does not mutates the variable itself (its the same array), but adds an element to it (a side effect). You should avoid this and only use setSelectedProducts instead. Even more, in the browser console you should have a message warning about useEffect not having the correct dependencies array. Try this instead:
// Add extra argument setSelectedProducts
const Child = ({ item, selectedProducts, setSelectedProducts, selectCount, setSelectCount }) => {
    const [ selected, setSelected ] = useState(false);

    useEffect(() => {
       // Filling parent's state
       setSelectedProducts([
         ...selectedProducts,
         [selected, setSelected],
       ]);
    }, [setSelectedProducts, selectedProducts, selected, setSelected]);

Now, this shows part of the problem here: there are circular dependencies. In this fixed useEffect example, it will be fired each time one or more of its dependencies changes. As we are changing selectedProducts in the callback (indirectly, using setSelectedProducts), it will be called again, and again, and again.
The solution
You need to pass the responsibility of managing the list of states (and, thus, the list of selected ones) to the list containing them (here, WatchlistDeleteScreen). This will receive a (un)select me message from each product:
const Product = ({ item, selected, toggleSelected }) => { //Child
  return (
    <TouchableHighlight onPress={toggleSelected}> // Without `()`: No extra function
    //...
    </TouchableHighlight>
  );
}

export default function WatchlistDeleteScreen({ navigation }) { //Parent
  const [ productsInfo, setProductsInfo ] = useState([]);
  const [ selectedProducts, setSelectedProducts ] = useState([]);

  // Mark all products as selected
  const selectAll = () => {
    setSelectedProducts(
      productsInfo.map(() => true)
    );
  }

  // Mark all products as unselected
  const deleteSelected = () => {
    setSelectedProducts(
      productsInfo.map(() => false)
    );
  }

  // Toggles a single product selection state
  const toggleSelected = (index) => {
    const selectedProductsNew =
      selectedProducts.map(
        // Only toggle the matching index product
        (poductState, i) => i === index ? !value : value
      );

    // But full array is updated, respecting React
    // immutability and state change controller
    setSelectedProducts( selectedProductsNew );
  }

  // Fetch items. No need to async/await if you use .then/.catch
  useEffect(() => {
    AsyncStorage.getItem('productsInfo')
      .then(data => JSON.parse(data))
      .then(jsonData => {
        setProductsInfo(jsonData);
        // Also create an array with the states of all
        // products to unselected
        deleteSelected();
      })
      .catch(error => {});
  }, [setProductsInfo, deleteSelected]);

  // Just to be clear. You can use selectedProducts.length directly
  // from the JSX
  const selectCount = selectedProducts.length;

  return (
    // ...
       <FlatList
         data={productsInfo}
         // Also get `index` from FlatList
         // https://reactnative.dev/docs/flatlist#renderitem
         renderItem={({ item, index }) => (
            <Product
              item={item}
              // Pass `selected` state (managed in parent, used in child)
              selected={selectedProducts[index]}
              // Pass `index` to the `toggleSelected` function
              toggleSelected={toggleSelected.bind(this, index)}/>
         )}
       />
    // ...
  )
}


text:
Q: Xcode 11 : iOS 13 specifically no longer triggers `viewDidAppear` when unit testing Specifically this used to pass when testing using iOS 12:
let viewController = ViewController()
let _ = viewController.view
let window = UIWindow(frame: UIScreen.main.bounds)
window.layer.speed = 10
viewController.modalPresentationStyle = .fullScreen
viewController.beginAppearanceTransition(true, animated: false)
window.rootViewController = viewController
window.makeKeyAndVisible()
viewController.endAppearanceTransition()
...
XCTAssert(vc.viewDidAppearCalled == true)

No longer passes.
The ViewController's viewDidLoad and viewWillAppear still gets called.
Any ideas what's going on?
Full example found here: https://github.com/nickm01/Test13ViewWillAppear

A: In iOS13, there was a subtle change to the ViewController lifecycle.  viewWillAppear etc now get loaded asynchronously so for testing some level of asynchronous testing (or waiting) is needed.  Couldn't find any documentation on this and I'm sure there's subtleties but this fixed the issue.


text:
Q: Update Query issue for multiple rows I have below update query to set some values and controle the data flow.But i am  getting error "Too many values" from the condtion(subquery)when i execute the bellow query.
UPDATE MTB       ----- TABLE NAME
SET MTB_EXTR_FLAG='N',
MTB_ALOC_PROCESS='DC1'
WHERE MTB_I IN      --- PRIMARY KEY
(
SELECT * FROM
(
SELECT MTB_I ,ROW_NUMBER() OVER (ORDER BY ROWID) AS RN
FROM MTB
)
WHERE RN BETWEEN 100 AND 500
)

Here my intension is selecting the different set up data per processing of one job.
I want to  set MTB_EXTR_FLAG='N',MTB_ALOC_PROCESS='DC1' each time before running of the job with different set of data.
Can someone please help me to resolve the error issue or propose different query.
Thank you.

A: I think this is just a matter of number of columns not matching (2 - MTB_I and RN - instead of 1 - MTB_I):
UPDATE MTB
SET MTB_EXTR_FLAG='N',
MTB_ALOC_PROCESS='DC1'
WHERE MTB_I IN      --- PRIMARY KEY
(
SELECT MTB_I FROM -- Else RN will be taken !!
(
SELECT MTB_I ,ROW_NUMBER() OVER (ORDER BY ROWID) AS RN
FROM MTB
)
WHERE RN BETWEEN 100 AND 500
)

You can't do where x in (...) with a subquery returning more fields than expected.


text:
Q: HAProxy override backend cookie using query parameter Based on this answer, I can successfully override the backend with a query parameter:
backend servers
  balance roundrobin
  cookie SERVERID insert indirect nocache
  use-server web1 if { urlp(SERVERID) -i web1 }
  use-server web2 if { urlp(SERVERID) -i web2 }
  server web1 web1-internal:80 check cookie web1
  server web2 web2-internal:80 check cookie web2

However, I would like for this to "persist" in subsequent requests; i.e. I want a new Set-Cookie with the value from the query parameter to overwrite any existing SERVERID cookies. HAProxy doesn't add a Set-Cookie if the request came in with a valid SERVERID Cookie. Removing the indirect option didn't work.
Is the only solution to use preserve and have the backend always respond with Set-Cookie, or is there a way to do this in HAProxy?

A: I did this by creating new backends that set the SERVERID cookie and routing to them via frontend directives.
frontend http_in
  acl set_current_site_cookie urlp(current_site) true
  acl set_snapshot_site_cookie urlp(snapshot_site) true

  bind *:80
  use_backend set_current_site_cookie if set_current_site_cookie
  use_backend set_snapshot_site_cookie if set_snapshot_site_cookie
  default_backend servers

backend set_current_site_cookie
  cookie SERVERID insert
  server current_site server.com:80 cookie current_site

backend set_snapshot_site_cookie
  cookie SERVERID insert
  server snapshot_site snapshot-server:80 cookie snapshot_site

backend servers
  cookie SERVERID insert indirect nocache
  server current_site server.com:80 cookie current_site weight 50
  server snapshot_site snapshot-server:80 cookie snapshot_site weight 50

We use this for staged rollouts, setting the weight in the servers backend to 0, and then testing using the query param current_site=true.


text:
Q: Django and viewing dates in templates in the correct timezone I can't seem to be able to use the timezones in django. I have read this here but when i try to apply it it won't work.
my model
class Model(models.Model)
    name = models.CharField(max_length=30)
    date = models.DateTimeField()

My view is:
from django.utils.timezone import timezone
def view(request):
    today = datetime.now().replace(tzinfo=utc)
    model = Model.objects.filter(date__gte=today, date__lte=today + timedelta(days=2)
    return render_to_response('template.html', {'models':model}, context_instance=RequestContext(request)

in my template.html
{%for model in models%}
    {{model.date.hour}}:{{model.date.hour}} - {{model.name}}
{%endfor%}

My settings file
TIME_ZONE = 'Europe/Athens'
USE_TZ = True
USE_L10N = True

So as i read if USE_TZ is true then datetimes are saved in UTC in database, and then django presents them in localtime (according to TIME_ZONE variable) when presenint them in forms.But my template presents the dates as they are saved in the database (meaning two hours behind from localtime e.g i wanted 18:30, it saved 16:30, it shows 16:30). I tried
{%load tz%}
{%for model in models%}
    {{model.date.hour|localtime}}:{{model.date.minute|localtime}} - {{model.name}}
{%endfor%}

nothing. To be more precise it didn't show any dates at all, it went blank. I tried
{%load tz%}
{%for model in models%}
    {%localtime on %}
        {{model.date.hour}}:{{model.date.time}} - {{model.name}}
    {%endlocaltime%}
{%endfor%}

But the time remained as is with no modifications.
The thing is that lower in my template i do this in a similar for
{{model.date}} - {{model.name}}

Where it shows the date in the correct timezone(e.g 14:30 becomes 16:30) but not in 24h format (in which i saved it).
Can someone help me a bit with timezones and django to clear it once and for all


text:
Q: Separate RSS feed link/s I am using the feedparser module to create a news feed in my program.
The Yahoo! Finance API link element actually has two links: the Yahoo link, and the actual article link (external site/source). The two are separated by an asterisks, with the following being an example:
'http://us.rd.yahoo.com/finance/external/investors/rss/SIG=12shc077a/*http://www.investors.com/news/technology/click/pokemon-go-hurting-facebook-snapchat-usage/'
Note the asterisk between the two items.
I was just wondering if there is a pythonic way to separate these two, and only read the second link to a file.
Thank you for your time.
Here is my relevant code:
def parse_feed(news_feed_message, rss_url):
    ''' This function parses the Yahoo! RSS API for data of the latest five articles, and writes it to the company news text file'''

    # Define the RSS feed to parse from, as the url passed in of the company the user chose
    feed = feedparser.parse(rss_url)

    # Define the file to write the news data to the company news text file
    outFile = open('C:\\Users\\nicks_000\\PycharmProjects\\untitled\\SAT\\GUI\\Text Files\\companyNews.txt', mode='w')

    # Create a list to store the news data parsed from the Yahoo! RSS
    news_data_write = []
    # Initialise a count
    count = 0
    # For the number of articles to append to the file, append the article's title, link, and published date to the news_elements list
    for count in range(10):
        news_data_write.append(feed['entries'][count].title)
        news_data_write.append(feed['entries'][count].published)
        news_data_write.append(feed['entries'][count].link)
        # Add one to the count, so that the next article is parsed
        count+=1
        # For each item in the news_elements list, convert it to a string and write it to the company news text file
        for item in news_data_write:
            item = str(item)
            outFile.write(item+'\n')
        # For each article, write a new line to the company news text file, so that each article's data is on its own line
        outFile.write('\n')
        # Clear the news_elements list so that data is not written to the file more than once
        del(news_data_write[:])
    outFile.close()

    read_news_file(news_feed_message)

A: You can split this the following way:
link = 'http://us.rd.yahoo.com/finance/external/investors/rss/SIG=12shc077a/*http://www.investors.com/news/technology/click/pokemon-go-hurting-facebook-snapchat-usage/'

rss_link, article_link = link.split('*')

Keep in mind that this requires the link to always contain the asterisk, otherwise you'll get the following exception:
ValueError: not enough values to unpack (expected 2, got 1)

If you only need the second link, you could also write:
_, article_link = link.split('*')

This indicates that you want to discard the first return value.
Another alternative is:
article_link = link.split('*')[1]

Regarding your code: if you have an exception anywhere after you've opened your output file, it won't be closed properly. Either use the open context manager (docs) or a try ... finally block (docs) to make sure you close your file whatever happens.
Context manager:
with open('youroutputfile', 'w') as f:
    # your code
    f.write(…)

Exception handler:
try:
    f = open('youroutputfile', 'w')
    f.write(…)
finally:
    f.close()


text:
Q: circular rotation path in CSS I want to ask if there is a way to rotate the Div of the Circle without rotating the images inside the DIV like the image below.
the main problem is that the image rotates by default with its DIV but I need to display it in its default position while rotating.
so any advice please?

here is the HTML and CSS code

@keyframes rotate{
    from{ transform: rotate(0deg); }
    to{ transform: rotate(360deg); }
}

  #clock_two {
    width: 280px;
    height: 280px;
    background: #25283d;
    border: 18px solid black;
    border-radius: 50%;
    margin: 100px auto;
    position: relative;
    top: 5%;
    z-index: 9999;
    animation-name: rotate;
    animation-duration: 20s;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
  }

  .numbers {
    position: absolute;
    width: 100%;
    height: 100%;
    padding: 0%;
    text-align: center;
  }

  .numbers span {
    display: block;
    color: #dbe7fd;
    text-shadow: 0 5px 18px #00000026, 0 2px 3px #00000033;
  }
  .numbers img{
    width: 20px;

  }

  .numbers:nth-child(1) {
    transform: rotate(40deg);
  }
  .numbers:nth-child(1) span {

    transform: rotate(-40deg);
  }
  .numbers:nth-child(2) {
    transform: rotate(80deg);

  }
  .numbers:nth-child(2) span {
    transform: rotate(-80deg);
  }
  .numbers:nth-child(3) {
    transform: rotate(120deg);
  }
  .numbers:nth-child(3) span {
    transform: rotate(-120deg);
  }
  .numbers:nth-child(4) {
    transform: rotate(160deg);
  }
  .numbers:nth-child(4) span {
    transform: rotate(-160deg);
  }
  .numbers:nth-child(5) {
    transform: rotate(200deg);
  }
  .numbers:nth-child(5) span {
    transform: rotate(-200deg);
  }
  .numbers:nth-child(6) {
    transform: rotate(240deg);
  }
  .numbers:nth-child(6) span {
    transform: rotate(-240deg);
  }
  .numbers:nth-child(7) {
    transform: rotate(280deg);
  }
  .numbers:nth-child(7) span {
    transform: rotate(-280deg);
  }
  .numbers:nth-child(8) {
    transform: rotate(320deg);
  }
  .numbers:nth-child(8) span {
    transform: rotate(-320deg);
  }
  .numbers:nth-child(9) {
    transform: rotate(360deg);
  }
  .numbers:nth-child(9) span {
    transform: rotate(-360deg);
  }


text:
Q: Is modern 'five countries' English the only type of English with stress patterns that change across the entire word depending on the suffix? The capital letters represent where the main stress in each word lies
TELephone, telePHONic, teLEphony.
PHOTograph, photoGRAphic, photOgraphy.
biOLogy, bioLOGical.
What about in the past, including older forms of English? Or is modern English unique in this respect?
Does every dialect of modern English have this (I'm thinking about Singlish and Indian English and other non 'five country' varieties/ descendants/blends of English, if they are dialects of English and not something else like creoles, say. Am out of my depth here.)?

A: Going into detail on other languages is beyond the scope of this site, but, it's not just English. You can use the term "lexical stress" to look up examples of languages where two words can differ in stress and nothing else: many languages with lexical stress have stress patterns based on how a word is put together. Other examples are Russian, Spanish, and Italian. (E.g. in Spanish the first-person singular present tense suffix -o in the verb canto doesn't take stress, but the third-person singular future tense suffix -ó in cantó does take stress.)
Old English stress was somewhat lexical, but more predictable than modern English stress. Old English did not have stressed or stress-attracting suffixes; instead, suffixes were unstressed and stress regularly fell on the first syllable of a root (roots were mostly monosyllabic, but some had unstressed second syllables). So when a word was built on one root plus one or more suffixes, the stress fell on the first syllable.
Compounds and prefixes are where things get a little bit more complicated. Old English had a few unstressed prefixes such as ge- and be-. But it also had stressed prefixes. Some prefixes (mainly ones derived from prepositions) could be either stressed or unstressed, depending on the grammatical structure of the word in which they occurred.
Old English also had noun-noun compounds (among other types of compounds), and as in modern English, the main stress in compounds fell on the first root.
The modern English stress system (where there are suffixes like -ic(al) that appear to have the power to attract stress to a preceding syllable) is derived from reinterpretation of the stress patterns of words inherited from English alongside words derived from Latin and the Romance languages that had stress in other positions. The latter set of words entered English mainly in the Middle English period (older loans were adapted more to the Old English stress patterns.) Some analyses of English stress still treat it as having separate and somewhat distinct "systems" for assigning stress to words, although it's unclear if this is really accurate except as a historical explanation. (The suffix -ly is supposed to belong to the system of non-stress-affecting suffixes, but many speakers stress different syllables in necessary and necessarily).


text:
Q: Sync user in google admin console without password Is there any way to  create user in google admin console without password?
Users can create a  new password with First Time Login
I am using google admin sdk API with service account Bearer token to create user.
Url: https://admin.googleapis.com/admin/directory/v1/users
Payload: {
   "primaryEmail":"sampleuser@orgdomain.com",
   "name":{
      "givenName":"Test",
      "familyName":"User"
   },
   "suspended":false,
   "password":"Password1234",
   "changePasswordAtNextLogin":true,
   "ipWhitelisted":false,
   "emails":[
      {
         "address":"sampleuser@orgdomain.com",
         "type":"home",
         "customType":"",
         "primary":true
      }
   ]
}

The API is failing without the password field.  Is there any way to enable or disable any configuration in admin console to achieve same.? Related Answers will be helpful. Thanks

A: You can't create a user without a password within the API.
The method users.insert requires an instance of the Resource: users on the request body and the Resource: Users states that the password is required when creating a new user:

password:
Stores the password for the user account. The user's password value is required when creating a user account. It's optional when updating a user and should only be provided if the user is updating their account password. The password value is never returned in the API's response body.
A password can contain any combination of ASCII characters, and must be between 8-100 characters.
We recommend sending the password parameter as a hexadecimal-encoded hash value and setting hashFunction accordingly. If hashFunction is specified, the password must be a valid hash key.


text:
Q: How to partition dataframe by column in pyspark for further processing? I need to partition my dataframe by column. I know that it is possible for saving in separate files. But I need to partition for further processing (I need to sort partitions in a certain order and apply udf to the ordered partitions).
My code is:
df = spark.createDataFrame([(2,), (1,), (2,), (1,), (2,)], ("name",)) \
    .repartitionByRange(2, "name") \
    .rdd.glom().collect()
print(df)

# [[Row(name=2), Row(name=1), Row(name=2), Row(name=1), Row(name=2)], []]

I need to get something like that:
[[(2,), (2,), (2,)], [(1,), (1,)]]

A: You can use repartition instead of repartitionByRange:
df = spark.createDataFrame([(2,), (1,), (2,), (1,), (2,)], ("name",)) \
    .repartition(2, "name") \
    .rdd.glom().collect()

print(df)
# [[Row(name=2), Row(name=2), Row(name=2)], [Row(name=1), Row(name=1)]]

repartitionByRange uses sampling to estimate ranges and could result in errors as you have observed.


text:
Q: jQuery: animation gets stuck/crashes in Chrome Browser only Here's my code which I hosted in a public folder in dropbox
This simple animation freezes after a while when running on google chrome, I tested on 4 different browsers(Chrome, IE 9, Opera, Firefoc). The "page loading" animation runs smooth on all browsers except chrome, what might be causing this?(wont run on jsfiddle as well)
PS: It may take up to 10 - 15 secs until the animation freezes, I know this wouldn't be a problem in the application later, but I still wanna know why it does so because it doesnt on other browsers.

A: you call infiniteLoop with a few setTimeouts. Why don't us simply use recusion for this?
EDIT: This one works as you may want it to work. It uses jQuery's step callback to calculate the percentage. if it is > 70 %, it starts the next animation.
$(document).ready(function() {

var parent = $('.loadingBar').width(),
  parentWidth = parent.toString(),
  colors = ["red","blue","yellow","green"],
  idx = 0;

var extend = function(color) {
    var colorClass = '#' + color + 'Bar',
    currentIndex = parseInt($(colorClass).css('z-index')),
    afterIndex = currentIndex + 4;

var backColor = $(colorClass).css('background-color');

$(colorClass).css('z-index', afterIndex)
.animate({width:parentWidth},
    {step:function(width,tween){
        var percent = Math.round(width/parentWidth*100);
        if((typeof $(this).data("next") === "undefined" || $(this).data("next") === null) && percent >= 70){
            $(this).data("next",true);

            if(idx > colors.length-2)
                idx = 0;
            else
                idx++;
            extend(colors[idx]);
        }

    },
    duration:2000,
    complete:function(){
        $(this).data("next",null);
        $(this).css('width', '0px');
        $('.loadingBar').css('background-color', backColor);
    }
});

}

extend(colors[0]);

});


text:
Q: How to set wpf image source from string data? I have a string value in cs code from [Image] column of mytable in mydatabase that type is varbinary(Max), now want to set value to source of Image control.
I wrote this code, but not set image to source :
string strImage = "0xFFD8FFE000104A46494600010....."

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

In constructor :
var bytes = GetBytes(strImage);
var myImage = new MyImageModel {Content = bytes};
MyImg.DataContext = myImage;

In Xaml:
<Image x:Name="MyImg" Source="{Binding Path=Content}"/>

The above code does not work and is not an error.

A: You can use a converter and bind your byte string to the Source property of the image. (So Content is your byte string)
<converters:BytesToImageConverter x:Key="BytesToImageConverter" />
<Image x:Name="MyImg" Source="{Binding Path=Content, Converter={StaticResource BytesToImageConverter}}"/>

Converter code:
   public class BytesToImageConverter : IValueConverter
   {
       public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
       {
           if (value == null)
               return null;

           if (!(value is byte[]))
               throw new ArgumentException("Only byte[] values are supported.");

           if (((byte[])value).Length == 0)
               return null;

           // return new ImageSourceConverter().ConvertFrom(value);
           BitmapImage image = new BitmapImage();
           using (MemoryStream ms = new MemoryStream((byte[])value))
           {
               ms.Position = 0;
               image.BeginInit();
               image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
               image.CacheOption = BitmapCacheOption.OnLoad;
               image.UriSource = null;
               image.StreamSource = ms;
               image.EndInit();
           }
           image.Freeze();

           return image;
       }

       public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
       {
           return value;
       }
   }

A: For converting string code to Image File Use the conversion Like this
public BitmapImage Base64ToImage( byte[] byteArray)
{
  byteArray;  // your bytes
                        BitmapImage img = new BitmapImage();
                        using (MemoryStream stream = new MemoryStream(byteArray))
                        {
                            img.BeginInit();
                            img.StreamSource = stream;
                            img.CacheOption = BitmapCacheOption.OnLoad;
                            img.EndInit();
                            img.Freeze();
                        }
                       return img;
}

It will Give you a Image you can Directly Bind this Image to UI


text:
Q: WPF: Cannot see my custom control in the toolbox I have created 2 WPF control which reside in the same folder and i want to add one control to the other.
The controls are added in a Win Forms project.
the thing is that in a custom Win Forms control I can see my two WPF controls in the toolbox but in the WPF designer I cannot see any WPF controls. Any ideas why?
And how can I add my control is XAML without dragging from the toolbox
I tried with
<UserControl x:
xmlns:my2="my.name.space"
Height="300" Width="300">
<Grid>
    <my2:MyControlName>

    </my2:MyControlName>
</Grid>

But that doesn't work with the type "my2:MyControlName" doesn not exist

A: I'm not sure why the controls don't show up in the toolbox, as I generally don't use the designer, but in order to access your controls in XAML, the xmlns should be:
<UserControl xmlns:my2="clr-namespace:my.name.space;assembly=my.assembly"

If the controls are in the assembly that is creating the UserControl, you should drop the ";assembly=my.assembly" part.

A: Thanks Abe.. I also needed to go to "Choose Item" in the toolbox, go to browse in the WPF components section, browse to the dll add the controls and drop them onto the designer, not onto the XAML view


text:
Q: Bad Image Format Exception when creating record in database I'm using Entity Framework(model first) in my C# project ,and i am using SQL Server as database.When i'm trying to add a record in a table i encounter this exception.
What's the problem?

A: Your error is unrelated to that line. If you view the documentation for that exception, it says:

The exception that is thrown when the file image of a dynamic link library (DLL) or an executable program is invalid.

Together with the message, "Bad IL range," I would think you have a corrupted assembly somewhere.
Possible solutions

*

*Look at the exception details to determine which file for which the exception was thrown

*

*If it's a file built by your project, try to clean solution and rebuild

*If it's a library, reinstall it

*Check if you have anything processing your assemblies, like an obfuscator -- see this post

*Last resort: check for viruses, hardware issues, and reinstall .NET


text:
Q: minimizing the image size I want to minimize the image size in latex i tried so many times with different codes but non gave me the required result.
 here is my code:
\begin{figure}
\centering % l b r t
\includegraphics[trim=0.0cm 0cm 0cm 0cm, clip=true,
 width=\linewidth]
{Files/PN.pdf}
\caption{Petri nets components}
\label{fig:bb}
\end{figure}

A: for exercise (of using petri library)  i redraw your image:

it can be scaled by changing scale from 1 to desired size. The image was generated with the following code:
\documentclass[tikz, crop]{standalone}
\usetikzlibrary{arrows.meta,
                automata,
                petri,
                positioning}

\begin{document}
    \begin{tikzpicture}[scale=1, % <--- here you can adjust image size
    transform shape,
    node distance = 8mm,
                > = Triangle,
     place/.style = {circle, semithick, draw, minimum size=6mm},
transition/.style = {thick, draw, minimum size=6mm},
pre/.append style = {shorten <=0pt}
                        ]
\node [place,tokens=2,
       pin=80:Place ]   (n1)    {};
\node [transition,pin={[xshift=-2.2mm]80:Transition},
       right=of n1]     (n2)    {}
            edge [pre]  (n1);
\node [place,
       right=of n2]  (n3) [] {}
            edge [pre]  (n2);
\path ([xshift=1.2mm] n1) coordinate[pin=280:Token] (aux)
      (n2) -- coordinate[pin=280:Arc] (aux)   (n3);
    \end{tikzpicture}
\end{document}

(it take me slightly more than 5 minutes, since i use petri library first time :-) ). this code can be used inside figure environment:
\begin{figure}
    \centering % l b r t
\begin{tikzpicture}[... ]
<image code>
\end{tikzpicture}
\caption{Petri nets components}
\label{fig:bb}
\end{figure}

or store above code as PN.tex and generated pdf file include in document with
\begin{figure}
    \centering
\includegraphics{Files/PN.pdf}
\caption{Petri nets components}
    \label{fig:bb}
\end{figure}


text:
Q: Why jquery datapicker inconsistently shows up? Here is my problem. It seems that datapicker does not show up when clicked the first time on the dynamically added input (I have to click two or more times on it or best if I click above the input (label area)), does anyone see the problem. I tried a lot of live(), bind() .hasDatapicker and #datep1 variants. If possible test your answer first. Thanks.
script side:

Html:
Seminars
<input type="radio" name="pasirink" id="rod_sem" value="rod_sem" checked="checked" />

Attendees
<input type="radio" name="pasirink" id="rod_klaus" value="rod_klaus" />

A: Try with jQuery LiveQuery plugin:
   $("#datep1").livequery("click", function(event) {
        $(this).datepicker();
   });

A: Change this part:
$("#datep1").live("click", function() {
        $("#datep1").datepicker();
    })

To this:
$("#datep1").datepicker();

The datepicker plugin is activated when the input is clicked, so you do not have to wrap this in a click event.


text:
Q: Calculate minimum distance between GPS points using geosphere gives inaccuate values I am trying to calculate the mean distance between nearest neighbor of a series of GPS points in R. I found two codes to get the values. But it doesn't appear to give the correct distance in meters. When I check against Google Maps, its' way off.
I found this answer: R - Finding closest neighboring point and number of neighbors within a given radius, coordinates lat-long
library(geosphere)
sp.groups <- groups
coordinates(sp.groups) <- ~Long+Lat
class(sp.groups)
d<- distm(sp.groups)
min.d<- apply(d, 1, function(x) order(x, decreasing=F)[2])
min.d
mean(min.d)
groupdist<- cbind(groups, groups[min.d,], apply(d, 1, function(x) order(x, decreasing=F)[2]))
colnames(groupdist)<- c(colnames(groups), 'neighbor', 'n.lat', 'n.long','dist')

And here using the package rgeos, but it gives the same results: Calculate the distance between two points of two datasets (nearest neighbor)
library(rgeos)
sp.groups <- groups
coordinates(sp.groups) <- ~Long+Lat
proj4string(sp.groups) <-CRS("+proj=utm +datum=WGS84")
class(sp.groups)
d<- gDistance(sp.groups, byid=TRUE)
min.d<- apply(d, 1, function(x) order(x, decreasing=F)[2])
min.d
mean(min.d)
groupdist<- cbind(groups, groups[min.d,], apply(d, 1, function(x) order(x, decreasing=F)[2]))
colnames(groupdist)<- c(colnames(groups), 'neighbor', 'n.lat', 'n.long','dist')

When I go and check on Google Earth the distances can be way off. And it even gives different values for nearest neighbors by 160-200m. Also some of the nearest neighbors don't have the same distance values, see K11 and K3 then K3 and K11. Here's the results I get, and I added expected values from Google Maps:
Group Lat        Long      neighbor  n.lat      n.long    dist  GMaps
K1    -26.96538  21.80965  K34       -26.96503  21.80940  27    44
K10   -26.96575  21.81132  K1        -26.96538  21.80965  1     172
K11   -26.96249  21.81120  K3        -26.96387  21.81053  22    166
K24   -26.96033  21.81090  K11       -26.96249  21.81120  3     240
K3    -26.96387  21.81053  K11       -26.96249  21.81120  3     166
K34   -26.96503  21.80940  K1        -26.96538  21.80965  1     44

What is wrong?
My data
groups<-data.frame(Group = c('K1', 'K10', 'K11', 'K24', 'K3', 'K34'),
Lat = c(-26.96538, -26.96575, -26.96249, -26.96033, -26.96387, -25.96503),
Longitude = c(21.80965, 21.81132, 21.81120, 21.80190, 21.81053, 21.80940))

A: I am not sure what you tried to calculate here but the column distance just refers to the position/number of the point with the minimum distance. I added a number with the actual minimum distances which look like the result you expected.
library(geodist, include.only = NULL)
library(sp, include.only = NULL)

groups <- data.frame(Group = c('K1', 'K10', 'K11', 'K24', 'K3', 'K34'),
                     Lat   = c(-26.96538, -26.96575, -26.96249, -26.96033, -26.96387, -25.96503),
                     Long  = c(21.80965, 21.81132, 21.81120, 21.80190, 21.81053, 21.80940))

sp.groups <- groups
sp::coordinates(sp.groups) <- ~Long+Lat

# mindistance Matrix
d <- geodist::geodist(groups, measure = "cheap")

# position of minimum distance
diag(d) <- Inf
min.d <- max.col(-d)
min.d
#> [1] 2 1 5 5 3 4

groupdist <- cbind(groups, groups[min.d,], min.d)
colnames(groupdist) <- c(colnames(groups), 'neighbor', 'n.lat', 'n.long','closest_to')

# get minimum distance for each pair of coordinates
groupdist$distance <- d[cbind(seq_along(min.d), min.d)]
groupdist
#>     Group       Lat     Long neighbor     n.lat   n.long closest_to    distance
#> 2      K1 -26.96538 21.80965      K10 -26.96575 21.81132          2    171.1554
#> 1     K10 -26.96575 21.81132       K1 -26.96538 21.80965          1    171.1554
#> 5     K11 -26.96249 21.81120       K3 -26.96387 21.81053          5    167.2225
#> 5.1   K24 -26.96033 21.80190       K3 -26.96387 21.81053          5    944.4119
#> 3      K3 -26.96387 21.81053      K11 -26.96249 21.81120          3    167.2225
#> 4     K34 -25.96503 21.80940      K24 -26.96033 21.80190          4 110613.1362

Created on 2021-08-22 by the reprex package (v2.0.1)


text:
Q: Bootstrap variable overriding with LESS I have been investigating for the whole day as I considered it would be worthwhile spending some time to learn best practice for customizing Bootstrap.
I can see that there is a friendly page available for customizing elements selectively from http://twitter.github.io/bootstrap/customize.html but I want to have more control than this without touching original bootstrap source files.
To start with, I basically wanted to test out changing the grid from 12 to 16 columns and to do this, I created my own variable less file and added @gridColumns:16; only to this file and imported this custom less inside bootstrap.less as follows.
// Core variables and mixins
@import "variables.less"; // Modify this for custom colors, font-sizes, etc
@import "mixins.less";
**@import "../custom-variables.less"; //Override variables**

Then, using WinLess I compiled the bootstrap.less file to get new bootstrap.css with overridden variable import call and linked the css with html file but the grid won't change to 16 columns.
Can anyone please point out what I am doing wrong?

A: I work on a similar project where we have bootstrap in a 'third-party' location and then override only mixins.less and variables.less. The pattern we use for this adds three files and doesn't touch bootstrap at all (allowing you to drop in replacements easily):
/style
|- bootstrap-master/
|    |- less/
|    |- js/
|   ...
|- shared/
    |- shared.less
    |- variables.less
    |- mixins.less

the mixins file
/*
 *    /style/shared/mixins.less
 */

@import "../bootstrap-master/less/mixins.less";
// override any mixins (or add any of your third party mixins here)

the variables file, which is where you would override grids
/*
 *    /style/shared/variables.less
 */

@import "../bootstrap-master/less/variables.less";

@gridColumns: 16; // let's pretend this is your site-specific override

The file which is actually imported (or fed through to a less compiler):
/*
 *    /style/shared/shared.less
 */

@import "variables.less";
@import "mixins.less";

@import "../bootstrap-master/less/grid.less";
//and any other bootstrap less files we need here

in my setup, if i do this, i get a css file with some weird .span15 values (since i didn't update @gridColumnWidth or @gridGutterWidth but the .row-fluid values actually work out just the way you'd expect them to since they're calculated by straightforward division).
I like this setup because i can cd into bootstrap-master and git pull and fetch new updates without having to merge any of my specific kludges (it also gives me a good handle on what i've actually overridden)
The other thing is that it's very clear that shared.less is only using grid.less (rather than all of bootstrap). This is intentional since in most instances you don't need all of bootstrap, just a few parts of it to get going. Most bootstrap less files at least are nice in that their only hard dependencies are shared.less and mixins.less
if this still isn't working, then maybe WinLess is getting confused

A: Overriding variables after importing the original bootstrap.less works great for me:
@import "less/bootstrap.less";

@body-bg:     red;
@text-color:  green;
@link-color:  blue;

Compiling the above LESS source outputs properly customized Bootstrap CSS code.
Relevant info: http://lesscss.org/features/#variables-feature-lazy-loading

A: Another example that may help someone:
@import 'bootstrap/bootstrap/variables';

// Prgress bar
@progress-bar-bg: #f5f5f5;
@progress-bar-default-color: @gray-base;

@import 'bootstrap/bootstrap';

A: An easy way is just to override the styles in your style doc, using the same name, and marking it as !important.


text:
Q: warning message '+' not meaningful for factors Using for self-defined variables, I am receiving the following error when trying to run odds ratio analysis.
dat1 <- escalc(measure="OR", ai=a, bi=b, ci=c, di=d, data=dat.turnover)
warnings(dat1)

Warning messages:
  1: In Ops.factor(ai, bi) : '+' not meaningful for factors
  Error in cat(list(...), file, sep, fill, labels, append) :
    argument 2 (type 'list') cannot be handled by 'cat'

All the data I am using for a, b, c, and d are numeric.

A: Without having access to your data, the best I can say is that any attempt to sum factor variables (try checking their str() to ensure R knows they are numeric and hasn't factored them) will cause NA values to be imputed, or an exception. The only time I have seen this Ops.factor() error is when the data are factors and not numeric.
That said, to ensure numeric calculations I would try:
dat.turnover$a <- as.numeric(dat.turnover$a)
dat.turnover$b <- as.numeric(dat.turnover$b)
dat.turnover$c <- as.numeric(dat.turnover$c)
dat.turnover$d <- as.numeric(dat.turnover$d)

dat1 <- escalc(measure="OR", ai=a, bi=b, ci=c, di=d, data=dat.turnover)


text:
Q: For a Fixed Variance, Gaussian Distribution Maximizes Entropy? I was reading this paper. In page 5, second column, they mention that,
$$h(Q) + h(P) \ge log(e \pi) => \sigma(Q) * \sigma(P) >= \frac{1}{2}$$
Where entropy $h$ is defined in the following way:
$$h(Q) = - \int_{-\infty}^{\infty} \Gamma(q) * log( \Gamma(q)) dq$$.
Then it was mentioned that if $\Gamma(q)$ follows a Gaussian distribution, then for a fixed variance, the entropy $h(Q)$ will be maximized. They said it can be shown by variational calculus with Lagrange multipliers. Could anyone please give a hint how do I proceed to prove it?

A: First, some properties of $\Gamma(q)$.  It is a probability distribution so
$$
\int_{-\infty}^\infty \Gamma(q) \,dq = 1
$$
We can without loss of generality assume we have shifted the variable $q$ such that the mean is zero, so that
$$
\int_{-\infty}^\infty q\, \Gamma(q)\, dq = 0
$$
We can rescale $q$ in a linear way so that the "fixed variance" is one.
$$
\int_{-\infty}^\infty q^2\, \Gamma(q)\, dq = 1
$$
Subject to those three constraints we wish to find an extremum of
$$\int_{-\infty}^\infty \Gamma(q)\, \log(\Gamma(q))\,dq $$
We re-write the fixed variance constraint in such a way that we can ignore the first constraint until the end of the problem, and normalize the resulting function at the end.  Namely,
$$
\int_{-\infty}^\infty q^2\, \Gamma(q)\, dq =
\int_{-\infty}^\infty \Gamma(q) \,dq
$$
So we have Lagrange multipliers $\lambda_1, \lambda_2$ associated with the mean and variance, and out Euler equation is
$$
\frac\partial{d\Gamma} \left( \Gamma(q)\, \log(\Gamma(q)) \right)+\lambda_1 \frac\partial{d\Gamma}\left( q\, \Gamma(q)\right)+\lambda_2 \frac\partial{d\Gamma}\left( q^2\, \Gamma(q) -\Gamma(q)\right) =0
$$
or
$$
1+\log(\Gamma(q)) + \lambda_1q + \lambda_2 (q^2-1) = 0
$$
which says that any extremum must be of the form
$$ \Gamma(q) = e^{\lambda_2 q^2+ (\lambda_1-\lambda_2)q + (1-\lambda_2)}
$$
and now we have to choose $\lambda_1$ and $\lambda_2$ such that the mean and variance will come out right (which is something like $\lambda_1 = \lambda_2 = -\sigma^2/2)$ and finally normalize the function because we had punted the constraint that the probability integrates to $1$.


text:
Q: Let $G$ be a group, Then $x^{a} = e \iff o(x) | a$ Let $G$ be a group, Then $x^{a} = e \iff o(x) | a$
This should be a very trivial statement, but I'm having trouble with it.
Here $e$ is the identity an $o(x)$ is the order of element $x$.
$(\Rightarrow)$
If $ x^{a} = e$, then, as $x^{o(x)}=e$, $x^{a} = x^{o(x)}$.
Suppose w.l.g. $o(x)>a$. Then there are $r,s$ unique integers such that
$o(x) = a.s+r$ So $x^{a} = x^{a.s+r} = (x^{a})^{s}.x^{r}$, then $s=1,r=0$, which means $o(x) = a$. In particular $o(x)|a$.
$(\Leftarrow)$
Suppose $o(x)|a$. Then $a=p.o(x)$, for some integer $p$. Then $x^{a} = x^{p.o(x)} = x^{o(x).p} = \{x^{o(x)}\}^p = e^{p} = e$
I can feel my proof is weird. There is probably something wrong in it.
Can someone please verify it to me? Thanks.

A: For the first part: by definition $o(x)$ is the smallest nonzero natural number such that $x^{o(x)} = e$, so $x^a = e$ implies that $o(x) \leq a$. Now there are unique natural numbers $q,r$ such that $a = qo(x) + r$ with $0 \leq r < o(x)$. (This last part is very important!) Hence $e = x^a = (x^{o(x)})^{q}x^r = x^r$, but $r < o(x)$ contradicts the definition of $o(x)$ unless $r = 0$.
The second part is fine.

A: In the first part you have supposed $o(x)>a$, and at the end you say $o(x)=a$. Then $s\in \mathbb{Z}$ and $s\neq 1$.
The other part is correct!


text:
Q: Unprotected Windows Shares Still Requiring Password in Linux Mint I am trying to access my windows shares from linux mint.
I have 2 windows computers (both Win 10) and my laptop on Linux Mint.
My office PC is password protected and can access those files from my laptop and Loung PC by entering the username and password for that PC.
My Lounge PC is open, however, password protected sharing is turned off. I can access the shares from the Office PC but on my laptop it prompts me for username (required), domain (required, default 'WORKGROUP) and password.
Entering the username alone for the Lounge PC doesn't work and I don't have a password set to enter in the password field.
I have tried reinstalling Linux Mint, adding name resolve order = bcast host lmhosts wins to /etc/samba/smb.conf and restarting samba.
Does anyone know how to access windows unprotected network locations without being prompted for a username and password from Nemo?


text:
Q: How can I create a new session with a new User login on the application? How can I create a new session in JSF 2.0 as soon as a new User logs in on the application?

A: You don't need to. It makes in well designed webapps no sense. The servletcontainer does already the session management. Just put the logged-in user in the session scope.
@ManagedBean
@RequestScoped
public class LoginController {

    private String username;
    private String password;

    @EJB
    private UserService userService;

    public String login() {
        User user = userService.find(username, password);
        FacesContext context = FacesContext.getCurrentInstance();

        if (user == null) {
            context.addMessage(null, new FacesMessage("Unknown login, try again"));
            username = null;
            password = null;
            return null;
        } else {
            context.getExternalContext().getSessionMap().put("user", user);
            return "userhome?faces-redirect=true";
        }
    }

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "index?faces-redirect=true";
    }

    // ...
}

The logged-in user will be available as #{user} in all pages throughout the same session and also in @ManagedProperty of other beans.
On logout, however, it makes more sense to invalidate the session. This will trash all session scoped beans as well. You can use ExternalContext#invalidateSession() for this.
    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "index?faces-redirect=true";
    }

See also:

*

*How do servlets work? Instantiation, sessions, shared variables and multithreading

*How to handle authentication/authorization with users in a database?

*How to choose the right bean scope?


text:
Q: Entity framework code first approach - one to one relationship My model association is (as i believe) one-to-one:
public class Account
{
    [Key]
    [ForeignKey("BlockedAccount")]
    public virtual Guid AccountId { get; set; }
    public virtual string UserName { get; set; }

    public virtual BlockedAccount BlockedAccount { get; set; }
}

public class BlockedAccount
{
    [Key]
    public virtual Guid BlockedAccountId { get; set; }
    public virtual int BanLevel { get; set; }
    public virtual DateTime BannedDate { get; set; }
    public virtual DateTime ExpirationDate { get; set; }
    public virtual string Reason { get; set; }
}

But when I am trying to use it, the program crashes and it gives me following exception:

The INSERT statement conflicted with the FOREIGN KEY constraint
  "FK_dbo.Accounts_dbo.BlockedAccounts_AccountId". The conflict occurred
  in database "Accounts", table "dbo.BlockedAccounts", column
  'BlockedAccountId'. The statement has been terminated.

What am i doing wrong here? I want AccountId to point at BlockedAccountId.

A: How are you attaching your entities?  You don't need to actually set the foreign key, simply attaching to the navigation properties will make the connection.  This code, with your model above works for me:
     public class Account
{
    [Key]
    [ForeignKey("BlockedAccount")]
    public virtual Guid AccountId { get; set; }
    public virtual string UserName { get; set; }

    public virtual BlockedAccount BlockedAccount { get; set; }
}

public class BlockedAccount
{
    [Key]
    public virtual Guid BlockedAccountId { get; set; }
    public virtual int BanLevel { get; set; }
    public virtual DateTime BannedDate { get; set; }
    public virtual DateTime ExpirationDate { get; set; }
    public virtual string Reason { get; set; }

    public BlockedAccount()
    {
        BannedDate = DateTime.Now;
        ExpirationDate = DateTime.Now;
    }
}

public class Model : DbContext
{
    public DbSet<BlockedAccount> BlockedAccounts { get; set; }
    public DbSet<Account> Accounts { get; set; }
}
class Program
{

    static void Main(string[] args)
    {
        var b = new BlockedAccount()
            {
               BlockedAccountId = Guid.NewGuid()
            };
        var a = new Account();

        a.BlockedAccount = b;
        Model m = new Model();
        m.Accounts.Add(a);
        m.SaveChanges();
    }
}


text:
Q: python scipy linprog simplex example v 1.5 All the scipy examples are using the older versions and I'm looking for an example on how to use the newer version.
https://docs.scipy.org/doc/scipy/reference/optimize.linprog-simplex.html
I created a super simple code and it prints that the problem is unbounded. Any help is appreciated.
Minimize x - y

with
x >= 2
y <= 3

In standard form
-x - s1 = -2
y + s2 = 3

One of many solutions should be x = 2, y = 3
c = [1, -1]
A = [[-1, 0, -1, 0],[0, 1, 0, 1]]
b = [-2, 3]
linprog(c, method="simplex", options={'A': A, 'b': b})

result
------------------
     con: array([], dtype=float64)
     fun: -inf
 message: 'The problem is (trivially) unbounded because there are no non-trivial constraints and a) at least one decision variable is unbounded above and its corresponding cost is negative, or b) at least one decision variable is unbounded below and its corresponding cost is positive. '
     nit: 0
   slack: array([], dtype=float64)
  status: 3
 success: False
       x: array([ 0., inf])

A:
scipy.optimize.linprog(c, method='simplex', callback=None, options={'c0': None, 'A': None, 'b': None, 'postsolve_args': None, 'maxiter': 1000, 'tol': 1e-09, 'disp': False, 'bland': False}, x0=None)
Minimize a linear objective function subject to linear equality and non-negativity constraints

It means that you can't solve your problem while using this interface. Read the Note in the documentation.
You should use top level linprog module instead. As you do not have equality and inequality constraints, your A_ub, b_ub, A_eq and b_eq matrices are None and you only need to define bounds.
c = [1, -1]
x_bounds = [2, None]
y_bounds = [None, 3]
res = linprog(c, bounds=[x_bounds, y_bounds], method='simplex')

res
Out[]:
     fun: -1.0
 message: 'Optimization terminated successfully.'
     nit: 2
   slack: array([0., 0., 0., 0.])
  status: 0
 success: True
       x: array([ 2., 3.])


text:
Q: Node.js (express framework): Post method not working I am able to run the Get method and HTML form also visible on browser using Get method but when I am clicking on submit button nothing is happening, no error nothing. it shows the same HTML form page.
HTML code:

  <!DOCTYPE html>enter code here

    <meta charset="utf-8">
    <title>Calculator</title>

<form action="/" method="post">

Calculator

  <input type="text" name="num1" placeholder="Number 1">
  <input type="text" name="num2" placeholder="Number 2">
  <button action="/" type="button" name="button">Submit</button>
</form>

Node Js code:
//jshint esversion:6

const express=require("express");
const app=express();

app.get("/", function(req,res){
res.sendFile( __dirname+"/index.html");
});

app.post("/", function(req,res){
  res.send("Thanks for post");
});

app.listen(3000, function(){
  console.log("Server Started On Port 3000");
});

A: Your button type should be Submit
    <button type="submit" value="Submit">Calculator</button>


text:
Q: Read whitespace-split words from text file and put into array in shell I'm trying to read text from a file and then put this in an array split by spaces. I've been trying to follow examples online but my string still appears to not be being split correctly into the array.
    nameList=$(cat "test.txt")
    echo $nameList
    array=($nameList)
    echo $array
    echo $array[1]

Which just returns the result
    this is a test
    this
    this[1]

As you can see only the first word is being captured by the variable array.
Any suggestions are much appreciated.

A: To read just one line, split by spaces:
read -r -a array <test.txt

...or to read until the first NUL in the file or its end:
read -r -d '' -a array <test.txt

To access an element of that array:
echo "${array[1]}"

...or better (reliably functional even in cases where the specification for echo is ambiguous, such as if your word is -n or contains backslash literals):
printf '%s\n' "${array[1]}"


text:
Q: How do I vectorize a function in numpy with some fixed parameters? I have written a code for approximating a function with the Bernstein polynomials ( https://en.wikipedia.org/wiki/Bernstein_polynomial )
at
https://github.com/pdenapo/metodos-numericos/blob/master/python/bernstein.py
I have a function that gives the polynomial approximating f as bernstein(f, n, p) (where f is the function that I want to approximate, n is the degree and p the point where it is evaluated.
def bernstein(f, n, p):
    return np.sum(
        [f(k / n) * st.binom.pmf(k, n, p) for k in np.arange(0, n + 1)])

Now I want to generate a plot of this function where f and n es fixed, and p runs though a vector generated by np.arrange
So I am vectorizing the function in the following way:
 bernstein3 = lambda x: bernstein(f, 3, x)
 bernstein3 = np.vectorize(bernstein3)
 y3 = bernstein3(x)
 plt.plot(x, y3, 'green', label='$B_3$')

It works. But I guess there must be some more elegant, or perhaps more pythonic way of doing this. Any suggestions? Many thanks

A: Since SciPy statistic functions are vectorized, your bernstein function can be modified in a straightforward manner to work that way:
import numpy as np
import scipy.stats

def bernstein(f, n, p):
    # Vector of k values
    k = np.arange(n + 1)
    # Add a broadcasting dimension to p
    pd = np.expand_dims(p, -1)
    # Compute approximation
    return np.sum(f(k / n) * scipy.stats.binom.pmf(k, n, pd), -1)

It would be used simply as this:
import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return np.abs(1 / 2 - x)

x = np.linspace(0, 1, 100)
y = f(x)
plt.plot(x, y, 'blue', label='f(x)')
y_approx = bernstein(f, 10, x)
plt.plot(x, y_approx, 'orange', label='f_approx(x)')
plt.show()