问:
How to store and Retrieve images from the local device in android programmatically ?
My task is to take pictures and uploading it in cloud storage, In upload screen I have two buttons one is "Upload" and other is "Park",
i) if I select "Upload" it should upload the images on cloud.
ii) if I select "Park"  it should save the entire data into a activity with a button Load1.

What is Park ?

park should have the entire user data's stored previously

On clicking this load button I need to show the previously stored images in the thumbnail, eg. If I am taking 10 images I am showing those 10 images in the thumbnail as shown in below screenshot, while i m selecting the load it is showing 10th image for the three default images it is not showing all the 10 images which i have taken. How can I make it work properly?

This is my CameraActivity code where I am saving the images:

```<code> private void saveAndShowImage(byte[] data) {

    bmp1 = BitmapFactory.decodeByteArray(data, 0, data.length);
    //rotate the image by 90degree.
    bmp1 = RotateBitmap(bmp1, 90);
    bmp1 = Singleton.getResizedBitmap(bmp1);
    imageName = "img" + currentDateTimeString + ".png";
    saveImage(this, imageName, bmp1);
    LogEvent.Log(TAG,"bmp1"+bmp1);
    boolean isObjectReplaced = false;

    int size = 3;
    if(bitmapArray.size() < 3) {
        size = bitmapArray.size();
    }

    for (int i = 0; i < size; i++) {

        if (bitmapArray.get(i).imageName == null) {

            bitmapArray.set(i, new ImageNote("", currentDateTimeString, imageName));
            isObjectReplaced = true;
            break;
        }
    }

    if (!isObjectReplaced) {
        bitmapArray.add(new ImageNote("", currentDateTimeString, imageName));
    }

    Log.d(currentDateTimeString, "ss");
    Log.i("imagesize", "ImageWidth = " + bmp1.getWidth() + "ImageHeight = " + bmp1.getHeight());

    CameraActivity.this.runOnUiThread(new Runnable() {
        public void run() {

            if (imageCount > 2) {
                gv.scrollTo(convertDpToPixel(590 * bitmapArray.size()) + 10);
            }
            adapter.notifyDataSetChanged();
        }
    });
}

//it is saving the image and show in the gridview .
private class ImageSaveAndShow extends AsyncTask<String, String, Boolean> {

    private byte[] data;

    public ImageSaveAndShow(byte[] data, Camera camera) {
        this.data = data;

    }

    @Override
    protected Boolean doInBackground(String... strings) {

        saveAndShowImage(data);
        return true;
    }
}

public static void saveImage(Context context, String filename,
                             Bitmap bitmap) {

    File cacheDir = context.getExternalFilesDir(null);

    File backgroundImagesDir = new File(cacheDir.getAbsolutePath() + "/"
            + "LoadProof");
    if (!backgroundImagesDir.isDirectory()) {
        backgroundImagesDir.mkdir();
        Log.i(TAG, "LoadProof Directory Created");
    }

    OutputStream out = null;
    File file = null;

    try {

        file = new File(backgroundImagesDir.getAbsolutePath() + "/" + filename);
        Log.i(TAG, "saved to " + file.toString());

        // Storing the path to show the previously stored image

        if(loadClickCount==1) {

            SharedPreferences prefernces = context.getSharedPreferences("parkload", Context.MODE_APPEND);
            SharedPreferences.Editor editor = prefernces.edit();
            editor.putString("Path", String.valueOf(file));
            editor.commit();
            String old = prefernces.getString("Path",null);
            LogEvent.Log(TAG,"llll" + "   " + old + "     " + path);

        }

        out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        file = null;
        Log.i(TAG, "File Written");
        bitmap = null;
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

AdaperCode

```<code>public class Adapter extends ArrayAdapter<ImageNote> {
private final ArrayList<ImageNote> objects;
private Context context;
String TAG = "Adapter";
public Adapter(Context context, ArrayList<ImageNote> objects) {
    super(context, 0, objects);
    this.objects = objects;
    this.context = context;
}
@Override public View getView(final int pos, View convertView, ViewGroup parent) {

    ViewHolder holder = null;
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.cell_image, null);
        holder = new ViewHolder();
        holder.ivCampic = (ImageView) convertView.findViewById(R.id.ivCampic);
        holder.ivDeletion = (ImageView) convertView.findViewById(R.id.ivDeletion);
        holder.tvPos = (TextView) convertView.findViewById(R.id.txt_number_camera);
        convertView.setTag(holder);

    } else {
        convertView = inflater.inflate(R.layout.cell_image, null);
        holder = new ViewHolder();
        holder.ivCampic = (ImageView) convertView.findViewById(R.id.ivCampic);
        holder.ivDeletion = (ImageView) convertView.findViewById(R.id.ivDeletion);
        holder.tvPos = (TextView) convertView.findViewById(R.id.txt_number_camera);
    }

    if (objects.get(pos).imageName == null && pos < 3 && park1==false) {

        holder.ivCampic.setImageResource(R.drawable.placeholder);
        holder.ivDeletion.setVisibility(View.INVISIBLE);
        holder.tvPos.setVisibility(View.INVISIBLE);
    } else if (park1 == true) {

        // Assigning previously stored path

        SharedPreferences prefernces = context.getSharedPreferences("parkload", Context.MODE_APPEND);
        String load1Path = prefernces.getString("Path", null);
        LogEvent.Log(TAG,"lllll"+ "   " + load1Path);

        String path = load1Path;
        Bitmap bmp = BitmapFactory.decodeFile(path);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (bmp != null) {
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        }
        holder.ivCampic.setImageBitmap(bmp);
        holder.ivDeletion.setVisibility(View.VISIBLE);
        holder.tvPos.setVisibility(View.VISIBLE);
    } else {

        // Assigning path of the pictures from camera directly

        String path = context.getExternalFilesDir(null).getAbsolutePath() + "/LoadProof/"
                + objects.get(pos).imageName;
        Bitmap bmp = BitmapFactory.decodeFile(path);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (bmp != null) {
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        }
        holder.ivCampic.setImageBitmap(bmp);
        holder.ivDeletion.setVisibility(View.VISIBLE);
        holder.tvPos.setVisibility(View.VISIBLE);
    }

    LogEvent.Log(TAG,"text1 /"+String.valueOf(pos + 1)+"pos "+pos);
    holder.tvPos.setText(String.valueOf(pos+1));
    final ViewHolder finalHolder = holder;

    holder.ivDeletion.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            objects.remove(pos);
            CameraActivity.imageCount--;

            if (bitmapArray.size() < 3) {

                bitmapArray.add(new ImageNote("", null, null));
                finalHolder.ivCampic.setImageResource(R.drawable.placeholder);
                finalHolder.ivDeletion.setVisibility(View.INVISIBLE);

                if (pos == bitmapArray.size() - 1) {

                    //it is the last image which has been deleted when size()<=3.

                    finalHolder.ivCampic.setImageResource(R.drawable.placeholder);
                    finalHolder.ivDeletion.setVisibility(View.INVISIBLE);
                    finalHolder.tvPos.setVisibility(View.INVISIBLE);
                } else {

                    //it is not the last image which has been deleted when size()<=3.

                    finalHolder.ivCampic.setImageResource(R.drawable.placeholder);
                    finalHolder.ivDeletion.setVisibility(View.INVISIBLE);

                }
            } else {

                // when bitmapArray.size()>3

                view.setVisibility(View.GONE);
            }
            notifyDataSetChanged();
        }
    });

    return convertView;
}

private  class ViewHolder {

    public ImageView ivCampic;
    public ImageView ivDeletion;
    public TextView tvPos;
}
 }
</code>```

答: Since you are overwriting the path in the shared preference, only the latest path can be retrieved. It will be better if you could store it as an array in a file. so you can retrieve the path using the array index and no overwriting will happen.</p>

Body:
My task is to take pictures and uploading it in cloud storage, In upload screen I have two buttons one is "Upload" and other is "Park",
i) if I select "Upload" it should upload the images on cloud.
ii) if I select "Park"  it should save the entire data into a activity with a button Load1.

What is Park ?

park should have the entire user data's stored previously

On clicking this load button I need to show the previously stored images in the thumbnail, eg. If I am taking 10 images I am showing those 10 images in the thumbnail as shown in below screenshot, while i m selecting the load it is showing 10th image for the three default images it is not showing all the 10 images which i have taken. How can I make it work properly?

This is my CameraActivity code where I am saving the images:

 private void saveAndShowImage(byte[] data) {

    bmp1 = BitmapFactory.decodeByteArray(data, 0, data.length);
    //rotate the image by 90degree.
    bmp1 = RotateBitmap(bmp1, 90);
    bmp1 = Singleton.getResizedBitmap(bmp1);
    imageName = "img" + currentDateTimeString + ".png";
    saveImage(this, imageName, bmp1);
    LogEvent.Log(TAG,"bmp1"+bmp1);
    boolean isObjectReplaced = false;

    int size = 3;
    if(bitmapArray.size() < 3) {
        size = bitmapArray.size();
    }

    for (int i = 0; i < size; i++) {

        if (bitmapArray.get(i).imageName == null) {

            bitmapArray.set(i, new ImageNote("", currentDateTimeString, imageName));
            isObjectReplaced = true;
            break;
        }
    }

    if (!isObjectReplaced) {
        bitmapArray.add(new ImageNote("", currentDateTimeString, imageName));
    }

    Log.d(currentDateTimeString, "ss");
    Log.i("imagesize", "ImageWidth = " + bmp1.getWidth() + "ImageHeight = " + bmp1.getHeight());

    CameraActivity.this.runOnUiThread(new Runnable() {
        public void run() {

            if (imageCount > 2) {
                gv.scrollTo(convertDpToPixel(590 * bitmapArray.size()) + 10);
            }
            adapter.notifyDataSetChanged();
        }
    });
}

//it is saving the image and show in the gridview .
private class ImageSaveAndShow extends AsyncTask<String, String, Boolean> {

    private byte[] data;

    public ImageSaveAndShow(byte[] data, Camera camera) {
        this.data = data;

    }

    @Override
    protected Boolean doInBackground(String... strings) {

        saveAndShowImage(data);
        return true;
    }
}

public static void saveImage(Context context, String filename,
                             Bitmap bitmap) {

    File cacheDir = context.getExternalFilesDir(null);

    File backgroundImagesDir = new File(cacheDir.getAbsolutePath() + "/"
            + "LoadProof");
    if (!backgroundImagesDir.isDirectory()) {
        backgroundImagesDir.mkdir();
        Log.i(TAG, "LoadProof Directory Created");
    }

    OutputStream out = null;
    File file = null;

    try {

        file = new File(backgroundImagesDir.getAbsolutePath() + "/" + filename);
        Log.i(TAG, "saved to " + file.toString());

        // Storing the path to show the previously stored image

        if(loadClickCount==1) {

            SharedPreferences prefernces = context.getSharedPreferences("parkload", Context.MODE_APPEND);
            SharedPreferences.Editor editor = prefernces.edit();
            editor.putString("Path", String.valueOf(file));
            editor.commit();
            String old = prefernces.getString("Path",null);
            LogEvent.Log(TAG,"llll" + "   " + old + "     " + path);

        }

        out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        file = null;
        Log.i(TAG, "File Written");
        bitmap = null;
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

AdaperCode

public class Adapter extends ArrayAdapter<ImageNote> {
private final ArrayList<ImageNote> objects;
private Context context;
String TAG = "Adapter";
public Adapter(Context context, ArrayList<ImageNote> objects) {
    super(context, 0, objects);
    this.objects = objects;
    this.context = context;
}
@Override public View getView(final int pos, View convertView, ViewGroup parent) {

    ViewHolder holder = null;
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.cell_image, null);
        holder = new ViewHolder();
        holder.ivCampic = (ImageView) convertView.findViewById(R.id.ivCampic);
        holder.ivDeletion = (ImageView) convertView.findViewById(R.id.ivDeletion);
        holder.tvPos = (TextView) convertView.findViewById(R.id.txt_number_camera);
        convertView.setTag(holder);

    } else {
        convertView = inflater.inflate(R.layout.cell_image, null);
        holder = new ViewHolder();
        holder.ivCampic = (ImageView) convertView.findViewById(R.id.ivCampic);
        holder.ivDeletion = (ImageView) convertView.findViewById(R.id.ivDeletion);
        holder.tvPos = (TextView) convertView.findViewById(R.id.txt_number_camera);
    }

    if (objects.get(pos).imageName == null && pos < 3 && park1==false) {

        holder.ivCampic.setImageResource(R.drawable.placeholder);
        holder.ivDeletion.setVisibility(View.INVISIBLE);
        holder.tvPos.setVisibility(View.INVISIBLE);
    } else if (park1 == true) {

        // Assigning previously stored path

        SharedPreferences prefernces = context.getSharedPreferences("parkload", Context.MODE_APPEND);
        String load1Path = prefernces.getString("Path", null);
        LogEvent.Log(TAG,"lllll"+ "   " + load1Path);

        String path = load1Path;
        Bitmap bmp = BitmapFactory.decodeFile(path);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (bmp != null) {
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        }
        holder.ivCampic.setImageBitmap(bmp);
        holder.ivDeletion.setVisibility(View.VISIBLE);
        holder.tvPos.setVisibility(View.VISIBLE);
    } else {

        // Assigning path of the pictures from camera directly

        String path = context.getExternalFilesDir(null).getAbsolutePath() + "/LoadProof/"
                + objects.get(pos).imageName;
        Bitmap bmp = BitmapFactory.decodeFile(path);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (bmp != null) {
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        }
        holder.ivCampic.setImageBitmap(bmp);
        holder.ivDeletion.setVisibility(View.VISIBLE);
        holder.tvPos.setVisibility(View.VISIBLE);
    }

    LogEvent.Log(TAG,"text1 /"+String.valueOf(pos + 1)+"pos "+pos);
    holder.tvPos.setText(String.valueOf(pos+1));
    final ViewHolder finalHolder = holder;

    holder.ivDeletion.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            objects.remove(pos);
            CameraActivity.imageCount--;

            if (bitmapArray.size() < 3) {

                bitmapArray.add(new ImageNote("", null, null));
                finalHolder.ivCampic.setImageResource(R.drawable.placeholder);
                finalHolder.ivDeletion.setVisibility(View.INVISIBLE);

                if (pos == bitmapArray.size() - 1) {

                    //it is the last image which has been deleted when size()<=3.

                    finalHolder.ivCampic.setImageResource(R.drawable.placeholder);
                    finalHolder.ivDeletion.setVisibility(View.INVISIBLE);
                    finalHolder.tvPos.setVisibility(View.INVISIBLE);
                } else {

                    //it is not the last image which has been deleted when size()<=3.

                    finalHolder.ivCampic.setImageResource(R.drawable.placeholder);
                    finalHolder.ivDeletion.setVisibility(View.INVISIBLE);

                }
            } else {

                // when bitmapArray.size()>3

                view.setVisibility(View.GONE);
            }
            notifyDataSetChanged();
        }
    });

    return convertView;
}

private  class ViewHolder {

    public ImageView ivCampic;
    public ImageView ivDeletion;
    public TextView tvPos;
}
 }


来源: stackexchange

问:
Create groupings using GroupBY
I have a list of objects. I want to split this list into a list of objects based on specific property. Any object whose that specific property's value is some value should end up in one list and the rest in the other. I want to use one LINQ query that can achieve that.

Some pseudo code below:

```<code>class A {
   string X {get; set;}
}

var list = listOfAs;
List<A> listOfAWithXEqualAA;
List<A> listOfAWithXNotEqualAA;

var query = one LINQ query to populate above declared lists.
</code>```

Please suggest me such a query.

答:
You cannot achieve this through single LINQ, but have to write 2 queries

```<code>var listOfAWithXEqualAA = listofAs.Where(a => a.X == "AA").ToList();
var listOfAWithXNotEqualAA = listofAs.Where(a => a.X != "AA").ToList();
</code>```

Otherwise loop through the list and assign the values to respective lists with an "if"

ContentLicense: CC BY-SA 3.0

Title: Create groupings using GroupBY

Body:
I have a list of objects. I want to split this list into a list of objects based on specific property. Any object whose that specific property's value is some value should end up in one list and the rest in the other. I want to use one LINQ query that can achieve that.

Some pseudo code below:

class A {
   string X {get; set;}
}

var list = listOfAs;
List listOfAWithXEqualAA;
List listOfAWithXNotEqualAA;

var query = one LINQ query to populate above declared lists.

Please suggest me such a query.

Body:
You cannot achieve this through single LINQ, but have to write 2 queries

var listOfAWithXEqualAA = listofAs.Where(a => a.X == "AA").ToList();
var listOfAWithXNotEqualAA = listofAs.Where(a => a.X != "AA").ToList();

Otherwise loop through the list and assign the values to respective lists with an "if"


问:
How to call a tagged textfield
I am creating a series of textfields programmatically using tags.  I want to be able to access the data in each text field, but it keeps reverting back to the last tag.

In this example I am creating 10 textfields.  When you click on a field it should turn that field blue, but it always turns the last field blue.

How do I access the field tags so I can get to the correct textfield?

I added NSlog to test the sender #.

```<code>@implementation ViewController
@synthesize name = _name ;
- (void)viewDidLoad
{
    [super viewDidLoad];
    int y = 20 ;
    for(int i=1; i <= 10; i++)
    {
      CGRect frame = CGRectMake(20, y, 100, 30 ) ;
      name = [[UITextField alloc] initWithFrame:frame];
      [name setTag:i] ;
      [name setBackgroundColor:[UIColor whiteColor]] ;
      [name addTarget:self action:@selector(makeBlue:) forControlEvents:UIControlEventTouchDown];
      [self.view addSubview:name];
      y += 38;
    }
}

- (void)makeBlue:(id)sender
{
    int i = (int)[sender tag] ;
    [name setTag:i] ;
    NSLog(@"%d", i);
    [name setBackgroundColor:[UIColor blueColor]] ;
}
</code>```

EDIT:
That is great.  Thank you.  It certainly solved one of my problems.  I guess I was expecting a different answer that would lead me in a direction to solve my second problem.  I want to take the input from a tagged textfield to use it elsewhere.  I have the same problem that I am only getting the input from the last textfield.

```<code>- (void)viewDidLoad
{
[super viewDidLoad];

int y = 20 ;
for(int tag=1; tag <= 10; tag++)
{
    CGRect frame = CGRectMake(20, y, 100, 30 ) ;
    name = [[UITextField alloc] initWithFrame:frame];
    [name setTag:tag] ;
    [name setBackgroundColor:[UIColor whiteColor]] ;
    [name addTarget:self action:@selector(makeItSo:) forControlEvents:UIControlEventEditingDidEnd];
    [self.view addSubview:name];
    [name setDelegate:self] ;
    y += 38;
}
}

- (void)makeItSo:(id)sender
{
int tag = (int)[sender tag] ;
[name setTag:tag] ;
NSString * aName = [name text] ;
NSLog(@"%@", aName) ;
}
</code>```

In this example I don't need to use setTag again in the makeItSo method, but I don't know how to get the value from a particular tag.

答:
```<code>NSInteger i =    [sender tag];
</code>```

Title: How to call a tagged textfield

Body:
I am creating a series of textfields programmatically using tags.  I want to be able to access the data in each text field, but it keeps reverting back to the last tag.

In this example I am creating 10 textfields.  When you click on a field it should turn that field blue, but it always turns the last field blue.

How do I access the field tags so I can get to the correct textfield?

I added NSlog to test the sender #.

@implementation ViewController
@synthesize name = _name ;
- (void)viewDidLoad
{
    [super viewDidLoad];
    int y = 20 ;
    for(int i=1; i <= 10; i++)
    {
      CGRect frame = CGRectMake(20, y, 100, 30 ) ;
      name = [[UITextField alloc] initWithFrame:frame];
      [name setTag:i] ;
      [name setBackgroundColor:[UIColor whiteColor]] ;
      [name addTarget:self action:@selector(makeBlue:) forControlEvents:UIControlEventTouchDown];
      [self.view addSubview:name];
      y += 38;
    }
}

- (void)makeBlue:(id)sender
{
    int i = (int)[sender tag] ;
    [name setTag:i] ;
    NSLog(@"%d", i);
    [name setBackgroundColor:[UIColor blueColor]] ;
}

EDIT:
That is great.  Thank you.  It certainly solved one of my problems.  I guess I was expecting a different answer that would lead me in a direction to solve my second problem.  I want to take the input from a tagged textfield to use it elsewhere.  I have the same problem that I am only getting the input from the last textfield.

- (void)viewDidLoad
{
[super viewDidLoad];

int y = 20 ;
for(int tag=1; tag <= 10; tag++)
{
    CGRect frame = CGRectMake(20, y, 100, 30 ) ;
    name = [[UITextField alloc] initWithFrame:frame];
    [name setTag:tag] ;
    [name setBackgroundColor:[UIColor whiteColor]] ;
    [name addTarget:self action:@selector(makeItSo:) forControlEvents:UIControlEventEditingDidEnd];
    [self.view addSubview:name];
    [name setDelegate:self] ;
    y += 38;
}
}

- (void)makeItSo:(id)sender
{
int tag = (int)[sender tag] ;
[name setTag:tag] ;
NSString * aName = [name text] ;
NSLog(@"%@", aName) ;
}

In this example I don't need to use setTag again in the makeItSo method, but I don't know how to get the value from a particular tag.

Body: NSInteger i =    [sender tag];


问:
Complete Node Failure in Elasticsearch domain hosted in AWS
I am having a ES domain hosted in AWS the cluster of 6 nodes with 6 shards 2 primary  and 3 replica shards its very basic setup of ES. The primary shards are on node 1-3 and the replica shards on 4-6  nodes.  But I understand when one of the node holding primary goes down elasticsearch automatically  enables the replica as primary.  But how to recover the data in the node which  went down let say i won't able to restore that  back so how move the data of that  node to new node. Or should just  add a new nodes and it will start the replica of the newly elected primary  shard?  Could anyone please help me understanding this. </p>

<p>Thanks </p>

答:
Mostly, the data will be common in primary and replica shards.

If you can't restore the lost machine. (in your case)

You can add a new node, it will automatically create the replica. Once all the replica shards are initialized, it will balance the cluster by spreading primary & replica shards.

Body:
I am having a ES domain hosted in AWS the cluster of 6 nodes with 6 shards 2 primary  and 3 replica shards its very basic setup of ES. The primary shards are on node 1-3 and the replica shards on 4-6  nodes.  But I understand when one of the node holding primary goes down elasticsearch automatically  enables the replica as primary.  But how to recover the data in the node which  went down let say i won't able to restore that  back so how move the data of that  node to new node. Or should just  add a new nodes and it will start the replica of the newly elected primary  shard?  Could anyone please help me understanding this.

Thanks


问:
treating allocated memory as a different type
Suppose I allocate some memory.

```<code>char* buffer = (char*)my_malloc(2062);
</code>```

I assign char values to the first 14 bytes from a previously defined array named header.

```<code>memcpy(buffer, header, 14);
</code>```

Then I want to treat the rest of the allocated space as pointers to float.

```<code>float* float_buffer = (float*)(buffer + 14);
some_function(float_buffer);
</code>```

Then at some point later on I need to send all the data out.

```<code>transmit(buffer);
my_free(buffer);
</code>```

Is this correct way to treat memory?  Is the float* cast ok?  I am having issues where I am losing values and not getting the correct results.
My question is:
If you have to treat allocated memory as different types but then send it as char* at the end of the processing.....is this the correct way to do it?

I checked the ptr values and they are the same when they are float* and char* but I am not getting the correct result.

One of my restrictions is that I can only initially allocate one block of memory from a static buffer.  So calling another malloc as a different type (float*) is not allowed.

答:
To make this work (portably, at least), you would have to ensure (at a minimum) that the float_buffer was sizeof(float)-aligned. You could do this by allocating sizeof(float) - 1 extra bytes, observing the result of the malloc call modulo sizeof(float), and ignoring the first few bytes as appropriate. (You would, of course, have to keep the original pointer around in order to make the free() call.)

You probably don't want to do this, though. It sounds like the purpose of the 'buffer' is to accumulate data to be sent over a network or something like that, and that the floats are going to be copied in from somewhere else. What you should really do is cast the other way around: treat the buffer as a char[] always, and reinterpret the source floats as a sequence of chars when you copy them over. That is

```<code>char* buffer = malloc(total_size);
char* float_start = buffer + header_size;
memcpy(float_start, (char*)float_source, sizeof(float) * float_count);
transmit(buffer, total_size);
free(buffer);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Suppose I allocate some memory.

char* buffer = (char*)my_malloc(2062);

I assign char values to the first 14 bytes from a previously defined array named header.

memcpy(buffer, header, 14);

Then I want to treat the rest of the allocated space as pointers to float.

float* float_buffer = (float*)(buffer + 14);
some_function(float_buffer);

Then at some point later on I need to send all the data out.

transmit(buffer);
my_free(buffer);

Is this correct way to treat memory?  Is the float* cast ok?  I am having issues where I am losing values and not getting the correct results.
My question is:
If you have to treat allocated memory as different types but then send it as char* at the end of the processing.....is this the correct way to do it?

I checked the ptr values and they are the same when they are float* and char* but I am not getting the correct result.

One of my restrictions is that I can only initially allocate one block of memory from a static buffer.  So calling another malloc as a different type (float*) is not allowed.

Body:
To make this work (portably, at least), you would have to ensure (at a minimum) that the float_buffer was sizeof(float)-aligned. You could do this by allocating sizeof(float) - 1 extra bytes, observing the result of the malloc call modulo sizeof(float), and ignoring the first few bytes as appropriate. (You would, of course, have to keep the original pointer around in order to make the free() call.)

You probably don't want to do this, though. It sounds like the purpose of the 'buffer' is to accumulate data to be sent over a network or something like that, and that the floats are going to be copied in from somewhere else. What you should really do is cast the other way around: treat the buffer as a char[] always, and reinterpret the source floats as a sequence of chars when you copy them over. That is

char* buffer = malloc(total_size);
char* float_start = buffer + header_size;
memcpy(float_start, (char*)float_source, sizeof(float) * float_count);
transmit(buffer, total_size);
free(buffer);


问:
How to install earlier version of mongodb with homebrew?
I'm on osx6.8 and need to install an earlier version of Mongodb, how do I install an earlier version with HomeBrew?

The below didn't work :(

```<code>dream-2:app2 star$ brew install mongodb-2.6.10
Error: No available formula for mongodb-2.6.10
Searching formulae...
Searching taps...
dream-2:app2 star$
</code>```

Edit:

I'm getting a message to explain how this post is unique compared to another one, well, the answer to the other question is super long and complex and it's specific to postgresql and doesn't really answer my question.

答:
```<code>curl -O https://fastdl.mongodb.org/osx/mongodb-osx-x86_64-3.2.12.tgz
tar -zxvf mongodb-osx-x86_64-3.2.12.tgz
mkdir -p mongodb
cp -R -n mongodb-osx-x86_64-3.2.12/ mongodb
export PATH=<mongodb-install-directory>/bin:$PATH #path to the dir created in step 3
mkdir -p /data/db
sudo chown -R $(whoami) /data/
mongod
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm on osx6.8 and need to install an earlier version of Mongodb, how do I install an earlier version with HomeBrew?

The below didn't work :(

dream-2:app2 star$ brew install mongodb-2.6.10
Error: No available formula for mongodb-2.6.10
Searching formulae...
Searching taps...
dream-2:app2 star$

Edit:

I'm getting a message to explain how this post is unique compared to another one, well, the answer to the other question is super long and complex and it's specific to postgresql and doesn't really answer my question.


问:
AngularJS: ng-click after createElement('div')
After app's loading with AngularJS, I create some div (using Ajax) with createElement('div').
At each div, I set the ng-click with

```<code>elem.setAttribute("ng-click","nameValue='"+data.name+"'");
</code>```

and in html a see

```<code><div ng-click="nameValue='Simone'">Click</div>
</code>```

but it doesn't work. It works if I put it in html, but it doesn't work if I create the div dynamically with Ajax.

EDIT: Thanks for your replies. I try to explain better my "project" (I'm studing AngularJS)

In my app, with ngRoute I load the home page template.

Then in HomePageController I call a function for create the post after an Ajax connection.

Until here it's all ok.

To fix my problem:

```<code>app.controller('HomePageController',['$scope', function($scope){
  ....
  createPostWithAjax($compile)
  ....
}]);

//ajax function
function createPostWithAjax($compile){
  //after ajax connection
  $compile("div.postCreateAfterCompilation")($scope);
}
</code>```

This is correct? Or have I completely change the method?

答:
or you can check this example

```<code>function compile(element){
  var el = angular.element(element);
  $scope = el.scope();
  $injector = el.injector();
  $injector.invoke(function($compile){
      $compile(el)($scope)
  })
}
</code>```

http://jsfiddle.net/r2vb1ahy/

Body:
After app's loading with AngularJS, I create some div (using Ajax) with createElement('div').
At each div, I set the ng-click with

elem.setAttribute("ng-click","nameValue='"+data.name+"'");

and in html a see

Click

but it doesn't work. It works if I put it in html, but it doesn't work if I create the div dynamically with Ajax.

EDIT: Thanks for your replies. I try to explain better my "project" (I'm studing AngularJS)

In my app, with ngRoute I load the home page template.

Then in HomePageController I call a function for create the post after an Ajax connection.

Until here it's all ok.

To fix my problem:

app.controller('HomePageController',['$scope', function($scope){
  ....
  createPostWithAjax($compile)
  ....
}]);

//ajax function
function createPostWithAjax($compile){
  //after ajax connection
  $compile("div.postCreateAfterCompilation")($scope);
}

This is correct? Or have I completely change the method?

Body:
or you can check this example

function compile(element){
  var el = angular.element(element);
  $scope = el.scope();
  $injector = el.injector();
  $injector.invoke(function($compile){
      $compile(el)($scope)
  })
}

http://jsfiddle.net/r2vb1ahy/


问:
Reloading TableView on iPhone from another class
So I have a FirstViewController, which is a UITableViewController, as well as delegate and dataSource. It has the table view.

I have another class, FeedParser, that parses the data - but after it's done parsing, I need it to go and refresh the UITableView or else it won't show anything.

This is probably a stupid question, so forgive me, but how should I go about calling FirstViewController's tableView.reloadData from FeedParser?

Is there a method to return that view?

Thanks!

答: Just store a reference to FirstViewController on your app delegate, then call [appDelegate.firstViewController.tableView reloadData].


问:
How to support TLS 1.1, 1.2 for Python (2.7)
I have developed an application in Python 2.7. But it only supports PROTOCOL_TLSv1. I have to somehow make it compatible with PROTOCOL_TLSv1_1 and PROTOCOL_TLSv1_2. I can't find any library or trick to do so. Is it necessary to upgrade the Python version?

Kindly guide me or help me find the better solution.
Isn't there any out of the way solution?

答:
libopenssl1 and python 2.7.9 provided you can force ssl.SSLContext like : </p>

```<code>import ssl, urllib2
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
response = urllib2.urlopen(url, context=ctx).read()
</code>```

Body:
libopenssl1 and python 2.7.9 provided you can force ssl.SSLContext like :

import ssl, urllib2
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
response = urllib2.urlopen(url, context=ctx).read()


问:
Why does class B<T> not see a protected member of parent class A<T>?
The following code fails to compile (ideone):

```<code>#include <iostream>

template <typename T>
class A {
public:
    A(T* t) : t_(t) {}

protected:
    T* t_;
};

template <typename T>
class B : public A<T> {
public:
    B(T* t) : A<T>(t) {}

    T get() { return *t_; }
};

int main()
{
    int i = 4;
    B<int> b(&i);
    std::cout << b.get() << std::endl;
}
</code>```

The error is as follows:

```<code>prog.cpp:17:20: error: use of undeclared identifier 't_'
        T get() { return *t_; }
                          ^
</code>```

By my understanding, B<T> should have access to protected members of its parent class. Why does B<T> not see the protected member A<T>::t_?

答:
Because the base class A<T> is dependent on tempalate parameter T, then is a dependent base class, and t_ is a nondependent name, which is not looked up in dependent base class.

You can make t_ dependent to solve the issue, e.g.

```<code>T get() { return *this->t_; }
</code>```

or

```<code>T get() { return *A<T>::t_; }
</code>```

or

```<code>T get() {
    using A<T>::t_;
    return *t_;
}
</code>```

Body:
The following code fails to compile (ideone):

#include <iostream>

template <typename T>
class A {
public:
    A(T* t) : t_(t) {}

protected:
    T* t_;
};

template <typename T>
class B : public A<T> {
public:
    B(T* t) : A<T>(t) {}

    T get() { return *t_; }
};

int main()
{
    int i = 4;
    B<int> b(&i);
    std::cout << b.get() << std::endl;
}

The error is as follows:

prog.cpp:17:20: error: use of undeclared identifier 't_'
        T get() { return *t_; }
                          ^

By my understanding, B<T> should have access to protected members of its parent class. Why does B<T> not see the protected member A<T>::t_?

Body:
Because the base class A<T> is dependent on tempalate parameter T, then is a dependent base class, and t_ is a nondependent name, which is not looked up in dependent base class.

You can make t_ dependent to solve the issue, e.g.

T get() { return *this->t_; }

or

T get() { return *A<T>::t_; }

or

T get() {
    using A<T>::t_;
    return *t_;
}


问:
Get User SID of remote computer
I'm learning and can't figure out how to get the below code to work on a remote computer.

I want to retrieve the SID of a particular user on a remote computer

The below snippet works to retrieve the SID of the logged in user on the local computer.  I am searching for a way to use this to find a specific SID for a remote system.  Any help is appreciated.

```<code>$currentusersid = Get-WmiObject -Class win32_computersystem |
Select-Object -ExpandProperty Username |
ForEach-Object { ([System.Security.Principal.NTAccount]$_).Translate([System.Security.Principal.SecurityIdentifier]).Value }
</code>```

答:
You are probably looking for the Invoke-Command cmdlet which takes a -Computername parameter.

```<code>Invoke-Command -ComputerName 'whatever' -ScriptBlock {
    $currentusersid = Get-WmiObject -Class win32_computersystem |
    Select-Object -ExpandProperty Username |
    ForEach-Object { ([System.Security.Principal.NTAccount]$_).Translate([System.Security.Principal.SecurityIdentifier]).Value }
}
</code>```

Title: Get User SID of remote computer

Body:
I'm learning and can't figure out how to get the below code to work on a remote computer.

I want to retrieve the SID of a particular user on a remote computer

The below snippet works to retrieve the SID of the logged in user on the local computer.  I am searching for a way to use this to find a specific SID for a remote system.  Any help is appreciated.

$currentusersid = Get-WmiObject -Class win32_computersystem |
Select-Object -ExpandProperty Username |
ForEach-Object { ([System.Security.Principal.NTAccount]$_).Translate([System.Security.Principal.SecurityIdentifier]).Value }

Body:
You are probably looking for the Invoke-Command cmdlet which takes a -Computername parameter.

Invoke-Command -ComputerName 'whatever' -ScriptBlock {
    $currentusersid = Get-WmiObject -Class win32_computersystem |
    Select-Object -ExpandProperty Username |
    ForEach-Object { ([System.Security.Principal.NTAccount]$_).Translate([System.Security.Principal.SecurityIdentifier]).Value }
}


问:
Porting XML parsing from Java to Objective C
I am trying to port code written in Java to Objective C (for iPhone), but I'm kind of confused about a few lines of my code (mentioned below). How should I port this efficiently?

```<code>Namespace nmgrhistory=Namespace.getNamespace("history", "http://www.mywebsite.com/History.xsd");
        pEventEl.addContent(new Element("History",nmgrhistory));
        Namespace nmgrState=Namespace.getNamespace("state", "http://www.mywebsite.com/State.xsd");
        pEventEl.addContent(new Element("State",nmgrState));

        Iterator<Element> eld=(Iterator<Element>) pEventEl.getChild(
                pEventEl.getName() == "event"?  "./history:history/state:state" : "./state:state",pEventEl.getNamespace());
</code>```

I'm not very sure about the replacements for the classes Namespace, Iterator and Element.

Anybody having idea or having done this before, please enlighten me.

答:
I don't know java, but the url's your are pointing at are .xsd files which are xml definition files. XML parsing on iOS is somewhat limited out of the box: NSXMLParser.

I strongly recommend one of the bazillion open source XML parsers. They're much more user friendly.

Body:
I am trying to port code written in Java to Objective C (for iPhone), but I'm kind of confused about a few lines of my code (mentioned below). How should I port this efficiently?

Namespace nmgrhistory=Namespace.getNamespace("history", "http://www.mywebsite.com/History.xsd");
        pEventEl.addContent(new Element("History",nmgrhistory));
        Namespace nmgrState=Namespace.getNamespace("state", "http://www.mywebsite.com/State.xsd");
        pEventEl.addContent(new Element("State",nmgrState));

        Iterator<Element> eld=(Iterator<Element>) pEventEl.getChild(
                pEventEl.getName() == "event"?  "./history:history/state:state" : "./state:state",pEventEl.getNamespace());

I'm not very sure about the replacements for the classes Namespace, Iterator and Element.

Anybody having idea or having done this before, please enlighten me.


问:
Tableview Cell Is override from bottom
I am Creating One tableview with tableview cell fro XIB.
When I integrate tableview cell with Tableview and run it it is not showing perfectly ,It shows me override.

Image is

Code is

```<code>static NSString *cellIdentifier =@"DiscussionTableViewCell";

            DiscussionTableViewCell *cell = (DiscussionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {

                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DiscussionTableViewCell" owner:self options:nil];
                cell = [topLevelObjects objectAtIndex:0];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                // [cell.btnConnect addTarget:self action:@selector(btnUserConnectClick:) forControlEvents:UIControlEventTouchUpInside];
                // [cell.btnNotnow addTarget:self action:@selector(btnNotNowClick:) forControlEvents:UIControlEventTouchUpInside];
                 self.cellHeight  += cell.frame.size.height;
                NSLog(@"Cell height is %f",self.cellHeight);
</code>```

答:
If you have added UILabel inside Storyboard to UITableviewCell, make sure you have did all changes as per below instractions:

In Storyboard do this changes:
Make sure you have given top, bottom, leading and trailing constrains to the UILabel to UITableViewCell contentView.

Then set number of lines to UILabel to '0' also Line Break to "Word Wrap".

In Controller for UITableViewDelegate heightForRow method:

```<code>  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
  {
    tableView.estimatedRowHeight = 50;
    return UITableViewAutomaticDimension
  }
</code>```

This will help to solve above requirement.

Title: Tableview Cell Is override from bottom

Body:
I am Creating One tableview with tableview cell fro XIB.
When I integrate tableview cell with Tableview and run it it is not showing perfectly ,It shows me override.

Image is

Code is

static NSString *cellIdentifier =@"DiscussionTableViewCell";

            DiscussionTableViewCell *cell = (DiscussionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {

                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DiscussionTableViewCell" owner:self options:nil];
                cell = [topLevelObjects objectAtIndex:0];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                // [cell.btnConnect addTarget:self action:@selector(btnUserConnectClick:) forControlEvents:UIControlEventTouchUpInside];
                // [cell.btnNotnow addTarget:self action:@selector(btnNotNowClick:) forControlEvents:UIControlEventTouchUpInside];
                 self.cellHeight  += cell.frame.size.height;
                NSLog(@"Cell height is %f",self.cellHeight);

Body:
If you have added UILabel inside Storyboard to UITableviewCell, make sure you have did all changes as per below instractions:

In Storyboard do this changes:
Make sure you have given top, bottom, leading and trailing constrains to the UILabel to UITableViewCell contentView.

Then set number of lines to UILabel to '0' also Line Break to "Word Wrap".

In Controller for UITableViewDelegate heightForRow method:

  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
  {
    tableView.estimatedRowHeight = 50;
    return UITableViewAutomaticDimension
  }

This will help to solve above requirement.


问:
I am not getting the tweets from twitter
I try to stream tweets by Flume in the HDFS , I am not getting the tweets from twitter.The process is stopping at this point mentioned below.... !! Nothing beyond this step.  </p>

```<code>INFO instrumentation.MonitoredCounterGroup: Monitoried counter group for type: SINK, name: HDFS, registered successfully.
INFO instrumentation.MonitoredCounterGroup: Component type: SINK, name: HDFS started
</code>```

<p>My flume.conf file :  </p>

```<code>TwitterAgent.sources = Twitter
TwitterAgent.channels = MemChannel
TwitterAgent.sinks = HDFS

TwitterAgent.sources.Twitter.type =       org.apache.flume.source.twitter.TwitterSource
TwitterAgent.sources.Twitter.channels = MemChannel
TwitterAgent.sources.Twitter.consumerKey = **************
TwitterAgent.sources.Twitter.consumerSecret =  *********
TwitterAgent.sources.Twitter.accessToken =************
TwitterAgent.sources.Twitter.accessTokenSecret = *********

TwitterAgent.sources.Twitter.keywords = big data,cloud,hadoop,data analysis,hive,pig,hbase,flume,datawarehouse
TwitterAgent.sinks.HDFS.channel = MemChannel
TwitterAgent.sinks.HDFS.type = hdfs
TwitterAgent.sinks.HDFS.hdfs.path = hdfs://localhost:9000/Big
TwitterAgent.sinks.HDFS.hdfs.fileType = DataStream
TwitterAgent.sinks.HDFS.hdfs.writeFormat = Text
TwitterAgent.sinks.HDFS.hdfs.batchSize = 1000
TwitterAgent.sinks.HDFS.hdfs.rollSize = 0
TwitterAgent.sinks.HDFS.hdfs.rollCount = 10000

TwitterAgent.channels.MemChannel.type = memory
TwitterAgent.channels.MemChannel.capacity = 10000
TwitterAgent.channels.MemChannel.transactionCapacity = 100
</code>```

答:
In flume.conf file

```<code>TwitterAgent.sinks.HDFS.hdfs.path = hdfs://localhost:**9000**/Big
</code>```

put your own Active localhost instade of 9000.

go to http://localhost:50070/ and you can see your active localhost. like in my case it is

```<code>TwitterAgent.sinks.HDFS.hdfs.path=hdfs://localhost:54310/user/flume/tweets
</code>```

Body:
I try to stream tweets by Flume in the HDFS , I am not getting the tweets from twitter.The process is stopping at this point mentioned below.... !! Nothing beyond this step.

INFO instrumentation.MonitoredCounterGroup: Monitoried counter group for type: SINK, name: HDFS, registered successfully.
INFO instrumentation.MonitoredCounterGroup: Component type: SINK, name: HDFS started

My flume.conf file :

TwitterAgent.sources = Twitter
TwitterAgent.channels = MemChannel
TwitterAgent.sinks = HDFS

TwitterAgent.sources.Twitter.type =       org.apache.flume.source.twitter.TwitterSource
TwitterAgent.sources.Twitter.channels = MemChannel
TwitterAgent.sources.Twitter.consumerKey = **************
TwitterAgent.sources.Twitter.consumerSecret =  *********
TwitterAgent.sources.Twitter.accessToken =************
TwitterAgent.sources.Twitter.accessTokenSecret = *********

TwitterAgent.sources.Twitter.keywords = big data,cloud,hadoop,data analysis,hive,pig,hbase,flume,datawarehouse
TwitterAgent.sinks.HDFS.channel = MemChannel
TwitterAgent.sinks.HDFS.type = hdfs
TwitterAgent.sinks.HDFS.hdfs.path = hdfs://localhost:9000/Big
TwitterAgent.sinks.HDFS.hdfs.fileType = DataStream
TwitterAgent.sinks.HDFS.hdfs.writeFormat = Text
TwitterAgent.sinks.HDFS.hdfs.batchSize = 1000
TwitterAgent.sinks.HDFS.hdfs.rollSize = 0
TwitterAgent.sinks.HDFS.hdfs.rollCount = 10000

TwitterAgent.channels.MemChannel.type = memory
TwitterAgent.channels.MemChannel.capacity = 10000
TwitterAgent.channels.MemChannel.transactionCapacity = 100

Body:
In flume.conf file

TwitterAgent.sinks.HDFS.hdfs.path = hdfs://localhost:**9000**/Big

put your own Active localhost instade of 9000.

go to http://localhost:50070/ and you can see your active localhost. like in my case it is

TwitterAgent.sinks.HDFS.hdfs.path=hdfs://localhost:54310/user/flume/tweets


问:
Write a basic program that takes number and returns its corresponding month abbreviation
I'm trying to write a basic function that takes a number and returns the abbreviation of each month. It sounds simple enough, but how can I use a "try-except"block to handle any exceptions?

Here's what I have so far.

```<code>def month():
    months = "JanFebMarchAprilMayJuneJulyAugSepOctNovDec"
    n = eval(input("Enter month Number: "))
    pos = (n-1)*3
    monthAbbrev = months

    return monthAbbrev
</code>```

I guess my question is how can I put in a try-expect handle indexes that are out of range?
I'm completely lost here. Thanks for your help

答:
This simply returns the month at the correct index and if it doesn't exist it retruns the String Error replace it by whatever you need.

```<code>def month(n):
        months = ("Jan", "Feb", "Mar", ...)
        try:
            return months[n-1]
        except IndexError:
            return "Error"
</code>```

Body:
I'm trying to write a basic function that takes a number and returns the abbreviation of each month. It sounds simple enough, but how can I use a "try-except"block to handle any exceptions?

Here's what I have so far.

def month():
    months = "JanFebMarchAprilMayJuneJulyAugSepOctNovDec"
    n = eval(input("Enter month Number: "))
    pos = (n-1)*3
    monthAbbrev = months

    return monthAbbrev

I guess my question is how can I put in a try-expect handle indexes that are out of range?
I'm completely lost here. Thanks for your help

Body:
This simply returns the month at the correct index and if it doesn't exist it retruns the String Error replace it by whatever you need.

def month(n):
        months = ("Jan", "Feb", "Mar", ...)
        try:
            return months[n-1]
        except IndexError:
            return "Error"


问:
preg_match_all - get part between pattern and string
In this example i have large string with many defined elements in it
part of example string here.
In this example i get matches from example file (Starting from first(~32) tilde, to ~120 3), which sloud be correct in my regex, but i need update regex so it get first closest match in reverse from ~120 3, so the result be:

PRIEDE EGLE BERZS LAPU KOKI

```<code><?php

        $regex = '/~[1-9](.*?)\~120 3/s';
        preg_match($regex, $str, $matches);

        echo '```';
        print_r($matches);
        exit();
    ?>
```

So the question is:
How should i set direction to get part of string in "reverse"? If i match ~120 3, then i get all results from ~120 3 in reverse until i match tilde symbol+number - ~[1-9]?

Attached image of my currect regex result and marked few elements:
 * Green - element which i know and in my imagination - will start search in reverse.
 * Grey - the correct result.
 * Red - firest match what was found in reverse from ~120 3

Thanks for recommendations in advance!

答:
So the question is:

How should i set direction to get part of string in "reverse"? If i match ~120 3, then i get all results from ~120 3 in reverse until i match tilde symbol+number - ~[1-9]?

IT is not possible to change Boost regex matching direction within the input, however, you may use lookaheads to restrict the text matched.

Acc. to the requirements, you need

```<code>~[1-9]([^~]*(?:~(?![1-9])[^~]*)*)~120 3
</code>```

See the regex demo.

Details:

~[1-9] - your initial delimiter

([^~]*(?:~(?![1-9])[^~]*)*) - Capturing group 1 matching:

[^~]* - any 0+ chars other than tilde

(?:~(?![1-9])[^~]*)* - 0+ sequences of:

~(?![1-9]) - a tilde that is not followed with a digit from 1 to 9

[^~]* - any 0+ chars other than tilde

~120 3 - end delimiter

However, it won't capture what you need since it will include some digits and space at the start. Maybe your starting delimiter should be ~[\d\s]+ and the lookahead then should be (?![\d\s]+). See another demo.

Body:
In this example i have large string with many defined elements in it
part of example string here.
In this example i get matches from example file (Starting from first(~32) tilde, to ~120 3), which sloud be correct in my regex, but i need update regex so it get first closest match in reverse from ~120 3, so the result be:

PRIEDE EGLE BERZS LAPU KOKI

<?php

        $regex = '/~[1-9](.*?)\~120 3/s';
        preg_match($regex, $str, $matches);

        echo '
';
        print_r($matches);
        exit();
    ?>

So the question is:
How should i set direction to get part of string in "reverse"? If i match ~120 3, then i get all results from ~120 3 in reverse until i match tilde symbol+number - ~[1-9]?

Attached image of my currect regex result and marked few elements:
 * Green - element which i know and in my imagination - will start search in reverse.
 * Grey - the correct result.
 * Red - firest match what was found in reverse from ~120 3

Thanks for recommendations in advance!

Body:
So the question is:

How should i set direction to get part of string in "reverse"? If i match ~120 3, then i get all results from ~120 3 in reverse until i match tilde symbol+number - ~[1-9]?

IT is not possible to change Boost regex matching direction within the input, however, you may use lookaheads to restrict the text matched.

Acc. to the requirements, you need

~[1-9]([^~]*(?:~(?![1-9])[^~]*)*)~120 3

See the regex demo.

Details:

~[1-9] - your initial delimiter

([^~]*(?:~(?![1-9])[^~]*)*) - Capturing group 1 matching:

[^~]* - any 0+ chars other than tilde

(?:~(?![1-9])[^~]*)* - 0+ sequences of:

~(?![1-9]) - a tilde that is not followed with a digit from 1 to 9

[^~]* - any 0+ chars other than tilde

~120 3 - end delimiter

However, it won't capture what you need since it will include some digits and space at the start. Maybe your starting delimiter should be ~[\d\s]+ and the lookahead then should be (?![\d\s]+). See another demo.


问:
PHP exec output is abbreviate and cut
I try to catch the output of git log files

the shell

```<code>/usr/bin/git log --stat --pretty=format:%an*_*%cd*_*%H*_*%s
</code>```

output

```<code>rrr*_*Wed Mar 29 15:03:44 2016 +0800*_*51c32954639dffbdba18050527ca56b0ec243453*_*bug#1395
 mine-web-manage/src/main/webapp/WEB-INF/views/organ/courseForm.jsp                                         |  6 +++++-
 mine-web-server/src/main/java/com/mine/web/server/controller/organ/RestPublicOrganTeacherController.java | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 58 insertions(+), 1 deletion(-)
</code>```

but with php exec, the string is cut off

the code

```<code>$cmd = "/usr/bin/git log --stat --pretty=format:%an*_*%cd*_*%H*_*%s";
exec($cmd, $list, $return);
var_dump($list);
</code>```

output

```<code>  string(90) "rrr*_*Wed Mar 29 15:03:44 2016 +0800*_*51c32954639dffbdba18050527ca56b0ec243453*_*bug#1395"
  [18] =>
  string(60) " .../main/webapp/WEB-INF/views/organ/courseForm.jsp |  6 ++-"
  [19] =>
  string(79) " .../organ/RestPublicOrganTeacherController.java    | 53 ++++++++++++++++++++++"
  [20] =>
  string(49) " 2 files changed, 58 insertions(+), 1 deletion(-)"
</code>```

and I tried the following methods, all not work，result all cut off

```<code>1, $cmd . " 2>&1"
2, $cmd . " > /tmp/cmd.txt"
3, passthru($cmd, $list, $return);
</code>```

i want to get full string in output

Anyone has some idea about what is happening?

Thank you very much in advance for your help.

答:
use the code is fine

```<code>git log  --stat=200 --pretty=format:%an*_*%cd*_*%H*_*%s
</code>```

show full file path in git log

Title: PHP exec output is abbreviate and cut

Body:
I try to catch the output of git log files

the shell

/usr/bin/git log --stat --pretty=format:%an*_*%cd*_*%H*_*%s

output

rrr*_*Wed Mar 29 15:03:44 2016 +0800*_*51c32954639dffbdba18050527ca56b0ec243453*_*bug#1395
 mine-web-manage/src/main/webapp/WEB-INF/views/organ/courseForm.jsp                                         |  6 +++++-
 mine-web-server/src/main/java/com/mine/web/server/controller/organ/RestPublicOrganTeacherController.java | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 58 insertions(+), 1 deletion(-)

but with php exec, the string is cut off

the code

$cmd = "/usr/bin/git log --stat --pretty=format:%an*_*%cd*_*%H*_*%s";
exec($cmd, $list, $return);
var_dump($list);

output

  string(90) "rrr*_*Wed Mar 29 15:03:44 2016 +0800*_*51c32954639dffbdba18050527ca56b0ec243453*_*bug#1395"
  [18] =>
  string(60) " .../main/webapp/WEB-INF/views/organ/courseForm.jsp |  6 ++-"
  [19] =>
  string(79) " .../organ/RestPublicOrganTeacherController.java    | 53 ++++++++++++++++++++++"
  [20] =>
  string(49) " 2 files changed, 58 insertions(+), 1 deletion(-)"

and I tried the following methods, all not work，result all cut off

1, $cmd . " 2>&1"
2, $cmd . " > /tmp/cmd.txt"
3, passthru($cmd, $list, $return);

i want to get full string in output

Anyone has some idea about what is happening?

Thank you very much in advance for your help.

Body:
use the code is fine

git log  --stat=200 --pretty=format:%an*_*%cd*_*%H*_*%s

show full file path in git log


问:
Excel formula to assist with filling dates in down column
Column A contains leave dates, Column B contains clinicians.  Data was extracted from VISTA and only includes leave date for first employee listed.  Is there an easier way than copying and pasting to extend the dates in column A to include each employee?  Most likely I would be working with over 50,000 total rows ( at least to begin with), so I would prefer to avoid copying and pasting.

Here is what the data currently looks like:
enter image description here

Here is what I would like the data to look like:
enter image description here

答:
Follow these steps:

Select entire column with Dates

Press Ctrl + g

Click Special...

Select Blanks

Click OK

With the blank cells selected (and assuming the first blank cells is A3) put this into the formula bar: =if(B3<>"",A2,"")

Instead of pressing Enter to save the formula to just the first blank cell, press Ctrl + Enter to save it to all selected cells

Right click on any selected cell and change the format to Date (Screenshot below at this point)

Select the entire column A again, then copy and paste special as values to convert the formulas to date values that you can sort/filter on. (Let me know if you need more detail on this step)


问:
Running an executable binary made w/ JET Excelsior in Docker
I'm starting out with Docker, trying to add my application into it, to run. The application is Java-based compiled using Jet Excelsior.

I use the following simple docker file for building.

```<code>#Dockerfile

FROM alpine:latest
COPY ["/", "/sandbox"]
WORKDIR /sandbox
ENTRYPOINT ["myapp"]
CMD ["-XX:+PrintFlagsFinal","-XX:+PrintGCDetails"]
</code>```

I build with the standard docker build -t sandbox .

I confirm that the folder structure and all files are properly transferred. I do this by docker run sandbox ls *. But when I do docker run sandbox I get the error:

container_linux.go:247: starting container process caused "exec: \"myapp\": executable file not found in $PATH"

I've tried not using the exec form i.e ENTRYPOINT / CMD myapp; even ENTRYPOINT / CMD ./myapp, to which I get:

/bin/sh: myapp: not found

Can anyone help?

答:
Try to copy the file and not the entire folder. If that doesnt work try CMD["myapp","arg1",...] without entrypoint.

Update: I think you might not have copied the file over. You could run ls inside the container to see how the file system in the container looks. You copy / this is the root directory of your file system. Did you maybe want to copy . (current directory)?

Body:
I'm starting out with Docker, trying to add my application into it, to run. The application is Java-based compiled using Jet Excelsior.

I use the following simple docker file for building.

#Dockerfile

FROM alpine:latest
COPY ["/", "/sandbox"]
WORKDIR /sandbox
ENTRYPOINT ["myapp"]
CMD ["-XX:+PrintFlagsFinal","-XX:+PrintGCDetails"]

I build with the standard docker build -t sandbox .

I confirm that the folder structure and all files are properly transferred. I do this by docker run sandbox ls *. But when I do docker run sandbox I get the error:

container_linux.go:247: starting container process caused "exec: \"myapp\": executable file not found in $PATH"

I've tried not using the exec form i.e ENTRYPOINT / CMD myapp; even ENTRYPOINT / CMD ./myapp, to which I get:

/bin/sh: myapp: not found

Can anyone help?


问:
Non Exhaustive List When Handling Errors Inside a Class Function in Swift
Running the following snippet in a playground / project:

```<code>class Piece {
    enum ParseError: Error {
        case unknown(string: String)
    }

    class func parse(string: String) throws {
        throw ParseError.unknown(string: string)
    }
}

class Board {
    class func parse(string: String) {
        do {
            try Piece.parse(string: string)
        } catch Piece.ParseError.unknown(let string) {
            print(string)
        }
    }
}
</code>```

Gives a Swift Compiler Error:

Errors thrown from here are not handled because the enclosing catch is not exhaustive

The following works fine:

```<code>enum ParseError: Error {
    case unknown(string: String)
}

func parse(string: String) throws {
    throw ParseError.unknown(string: string)
}

do {
    try parse(string: "rook")
} catch ParseError.unknown(let string) {
    print(string)
}
</code>```

Running Xcode 8.3 / Swift 3.1

What's the reason for the error?

答:
Take a look to this answer:

"Because your function can't say what kind of errors it throws (or might throw in the future), the catch blocks that catch it errors don't know what types of errors it might throw. So, in addition to handling the error types you know about, you need to handle the ones you don't with a universal catch statement -- that way if your function changes the set of errors it throws in the future, callers will still catch its errors."

https://stackoverflow.com/a/30720807/6203030

In your case, this can be solved by adding this:

```<code>class Board {
    class func parse(string: String) {
        do {
            try Piece.parse(string: string)
        } catch Piece.ParseError.unknown(let string) {
            print(string)
        } catch let error {
            print(error.localizedDescription)
        }
    }
}
</code>```

You need to catch all errors.

Body:
Running the following snippet in a playground / project:

class Piece {
    enum ParseError: Error {
        case unknown(string: String)
    }

    class func parse(string: String) throws {
        throw ParseError.unknown(string: string)
    }
}

class Board {
    class func parse(string: String) {
        do {
            try Piece.parse(string: string)
        } catch Piece.ParseError.unknown(let string) {
            print(string)
        }
    }
}

Gives a Swift Compiler Error:

Errors thrown from here are not handled because the enclosing catch is not exhaustive

The following works fine:

enum ParseError: Error {
    case unknown(string: String)
}

func parse(string: String) throws {
    throw ParseError.unknown(string: string)
}

do {
    try parse(string: "rook")
} catch ParseError.unknown(let string) {
    print(string)
}

Running Xcode 8.3 / Swift 3.1

What's the reason for the error?

Body:
Take a look to this answer:

"Because your function can't say what kind of errors it throws (or might throw in the future), the catch blocks that catch it errors don't know what types of errors it might throw. So, in addition to handling the error types you know about, you need to handle the ones you don't with a universal catch statement -- that way if your function changes the set of errors it throws in the future, callers will still catch its errors."

https://stackoverflow.com/a/30720807/6203030

In your case, this can be solved by adding this:

class Board {
    class func parse(string: String) {
        do {
            try Piece.parse(string: string)
        } catch Piece.ParseError.unknown(let string) {
            print(string)
        } catch let error {
            print(error.localizedDescription)
        }
    }
}

You need to catch all errors.


问:
php cake get value of radio button in html then pass to controller
I need help in getting the value of the radio button and using it as a variable in php cake controller.

```<code>              <li class="search-pref-list-items__item"><label><input type="radio" name="pref" value="1">a</label></li>
          <li class="search-pref-list-items__item"><label><input type="radio" name="pref" value="2">b</label></li>
          <li class="search-pref-list-items__item"><label><input type="radio" name="pref" value="3">c</label></li>
</code>```

I already tried  $this->request->data  but it only works on textbox,
$_GET[] and $_POST[] are also now working

how will I do this?

答:
Hi Rey Norbert Besmonte,

You need to create radio buttons by following cakephp method.
Please refere my code as below to create radio button by following cakephp framework standard.

```<code>$options = array('a'=>'1','b'=>'2','c'=>'3');
$attributes = array('div' => 'input', 'type' => 'radio', 'options' => $options,'class' => 'search-pref-list-items__item' ,'default' => '1');
echo $this->Form->radio('Filed Name',$attributes);
</code>```

So you need to remove  from your code and place above code.

Hope this will help you.

Body:
I need help in getting the value of the radio button and using it as a variable in php cake controller.

<input type="radio" name="pref" value="1">a

<input type="radio" name="pref" value="2">b

<input type="radio" name="pref" value="3">c

I already tried  $this->request->data  but it only works on textbox,
$_GET[] and $_POST[] are also now working

how will I do this?

Body:
Hi Rey Norbert Besmonte,

You need to create radio buttons by following cakephp method.
Please refere my code as below to create radio button by following cakephp framework standard.

$options = array('a'=>'1','b'=>'2','c'=>'3');
$attributes = array('div' => 'input', 'type' => 'radio', 'options' => $options,'class' => 'search-pref-list-items__item' ,'default' => '1');
echo $this->Form->radio('Filed Name',$attributes);

So you need to remove  from your code and place above code.

Hope this will help you.


答:
Simple method,

Create a object for your FirstViewController in appDelegate, assign property and synthesize it.

In ViewDidLoad of FirstViewController,

```<code>firstViewControllerObj = self;
</code>```

In feedParser.m, after the parsing done code as follows,

```<code>[appDelegate.firstViewControllerObj.tabelView reloadData];
</code>```

Title: Reloading TableView on iPhone from another class

Body:
So I have a FirstViewController, which is a UITableViewController, as well as delegate and dataSource. It has the table view.

I have another class, FeedParser, that parses the data - but after it's done parsing, I need it to go and refresh the UITableView or else it won't show anything.

This is probably a stupid question, so forgive me, but how should I go about calling FirstViewController's tableView.reloadData from FeedParser?

Is there a method to return that view?

Thanks!

Body:
Simple method,

Create a object for your FirstViewController in appDelegate, assign property and synthesize it.

In ViewDidLoad of FirstViewController,

firstViewControllerObj = self;

In feedParser.m, after the parsing done code as follows,

[appDelegate.firstViewControllerObj.tabelView reloadData];


问:
How can we test the return type of method by using sinon.spy?
We are using the sinon to test our api call in reactjs application Like this:-

```<code>import * as Actions from 'routes/actions/Actions';
const requestAction = {
  RequestShell() { Actions.request(); },
};
 describe('testing for Actions', () => {
  it('check whether request() method call is happening properly or not', () => {
   const requestData = sinon.spy(requestAction, 'RequestShell');
   requestAction.RequestShell();
   sinon.assert.calledOnce(requestData);
   requestData.restore();
 });
</code>```

Now I need to compare if Actions.request() return type is Json object or not. How can I test the return type of the action by using sinon? Please assist me.

答:
Try with this

JS

```<code> it('check whether request() method call is happening properly or not', () => {
    const requestData = sinon.spy(requestAction, 'RequestShell');
    requestAction.RequestShell();
    assert(requestData.calledOnce);
    requestAction.RequestShell.restore();
  });
</code>```

refer this linksinon spies

Body:
We are using the sinon to test our api call in reactjs application Like this:-

import * as Actions from 'routes/actions/Actions';
const requestAction = {
  RequestShell() { Actions.request(); },
};
 describe('testing for Actions', () => {
  it('check whether request() method call is happening properly or not', () => {
   const requestData = sinon.spy(requestAction, 'RequestShell');
   requestAction.RequestShell();
   sinon.assert.calledOnce(requestData);
   requestData.restore();
 });

Now I need to compare if Actions.request() return type is Json object or not. How can I test the return type of the action by using sinon? Please assist me.

Body:
Try with this

JS

 it('check whether request() method call is happening properly or not', () => {
    const requestData = sinon.spy(requestAction, 'RequestShell');
    requestAction.RequestShell();
    assert(requestData.calledOnce);
    requestAction.RequestShell.restore();
  });

refer this linksinon spies


问:
How to remove index.php from CodeIgniter URL?

.htaccess code it's working fine on local host but it's not working fine on godaddy server. I tried so many .htaccess codes but I am unable to solve the problem.

            RewriteEngine On
            RewriteBase /CI/

```<code>        #Removes access to the system folder by users.
        #Additionally this will allow you to create a System.php controller,
        #previously this would not have been possible.
        #'system' can be replaced if you have renamed your system folder.
        RewriteCond %{REQUEST_URI} ^system.*
        RewriteRule ^(.*)$ /index.php?/$1 [L]

        #When your application folder isn't in the system folder
        #This snippet prevents user access to the application folder
        #Submitted by: Fabdrol
        #Rename 'application' to your applications folder name.
        RewriteCond %{REQUEST_URI} ^application.*
        RewriteRule ^(.*)$ /index.php?/$1 [L]

        #Checks to see if the user is attempting to access a valid file,
        #such as an image or css document, if this isn't true it sends the
        #request to index.php
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php?/$1 [L]

        </IfModule>

        <IfModule !mod_rewrite.c>
        # If we don't have mod_rewrite installed, all 404's
        # can be sent to index.php, and everything works as normal.
        # Submitted by: ElliotHaughin

        ErrorDocument 404 /index.php
        </IfModule>
</code>```

答:
<b>None of .htaccess file worked for me then i made a web.config file and pasted below code there and then i uploaded that file inside of CI root folder then it worked for me.</b>                                                                                </p>

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        </conditions>
                        <action type="Rewrite" url="index.php?url={R:1}" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

Body:
.htaccess code it's working fine on local host but it's not working fine on godaddy server. I tried so many .htaccess codes but I am unable to solve the problem.

            RewriteEngine On
            RewriteBase /CI/

        #Removes access to the system folder by users.
        #Additionally this will allow you to create a System.php controller,
        #previously this would not have been possible.
        #'system' can be replaced if you have renamed your system folder.
        RewriteCond %{REQUEST_URI} ^system.*
        RewriteRule ^(.*)$ /index.php?/$1 [L]

        #When your application folder isn't in the system folder
        #This snippet prevents user access to the application folder
        #Submitted by: Fabdrol
        #Rename 'application' to your applications folder name.
        RewriteCond %{REQUEST_URI} ^application.*
        RewriteRule ^(.*)$ /index.php?/$1 [L]

        #Checks to see if the user is attempting to access a valid file,
        #such as an image or css document, if this isn't true it sends the
        #request to index.php
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php?/$1 [L]

        </IfModule>

        <IfModule !mod_rewrite.c>
        # If we don't have mod_rewrite installed, all 404's
        # can be sent to index.php, and everything works as normal.
        # Submitted by: ElliotHaughin

        ErrorDocument 404 /index.php
        </IfModule>

Body:
None of .htaccess file worked for me then i made a web.config file and pasted below code there and then i uploaded that file inside of CI root folder then it worked for me.

    <?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                        <conditions logicalGrouping="MatchAll">
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        </conditions>
                        <action type="Rewrite" url="index.php?url={R:1}" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>


问:
Laravel set checkboxes checked based on database value
I am trying to set checkboxes checked based on database value. One user can have have multiple checkbox values.

Checkboxes are generated from database table called child_age_groups:

```<code>   @foreach ($child_age_groups as $age)
      <div class="checkbox checkbox-info checkbox-inline">
         <input class="age_group_checkbox" type="checkbox" name="age_group[]" id="age_group{{$age->id}}" "/>
        <label for="age_group{{$age->id}}">{{$age->age_group}}</label>
     </div>
  @endforeach
</code>```

So in my controller I get all the options that user has like this

```<code>  $nanny_babysitting_ages      = Nanny_babysitting_ages::where('user_id', user()->id)->get();
</code>```

My nanny_babysitting_ages table is this

```<code>user_id | ages
</code>```

and my child_age_groups table where I populate the checkboxes are this:

```<code>id | age_group
</code>```

How can I set the checkboxes selcted based on the values from database?

答:
This is how I resolved it, I added foreach and if statement in the input to check if it the same value as from database:</p>

```<code>             <div class="form-group" id="ageCheckboxes">
                @foreach ($child_age_groups as $age)
                <div class="checkbox checkbox-info checkbox-inline">
                   <input class="age_group_checkbox" type="checkbox" value="{{$age->id}}" name="age_group[]" id="age_group{{$age->id}}" @foreach ($nanny_babysitting_ages as $ages) @if($age->id == $ages->ages ) checked @endif @endforeach />
                   <label for="age_group{{$age->id}}">{{$age->age_group}}</label>
                </div>
                @endforeach
             </div>
</code>```

Body:
I am trying to set checkboxes checked based on database value. One user can have have multiple checkbox values.

Checkboxes are generated from database table called child_age_groups:

   @foreach ($child_age_groups as $age)

         <input class="age_group_checkbox" type="checkbox" name="age_group[]" id="age_group{{$age->id}}" "/>
        id}}">{{$age->age_group}}

  @endforeach

So in my controller I get all the options that user has like this

  $nanny_babysitting_ages      = Nanny_babysitting_ages::where('user_id', user()->id)->get();

My nanny_babysitting_ages table is this

user_id | ages

and my child_age_groups table where I populate the checkboxes are this:

id | age_group

How can I set the checkboxes selcted based on the values from database?

Body:
This is how I resolved it, I added foreach and if statement in the input to check if it the same value as from database:

             <div class="form-group" id="ageCheckboxes">
                @foreach ($child_age_groups as $age)
                <div class="checkbox checkbox-info checkbox-inline">
                   <input class="age_group_checkbox" type="checkbox" value="{{$age->id}}" name="age_group[]" id="age_group{{$age->id}}" @foreach ($nanny_babysitting_ages as $ages) @if($age->id == $ages->ages ) checked @endif @endforeach />
                   <label for="age_group{{$age->id}}">{{$age->age_group}}</label>
                </div>
                @endforeach
             </div>


问:
how to assign a function return value in storedprocedure?
I have a function  ufnGetTVP  and needs to assign the return value to a table variable in stored procedure.

I have tried the below code but getting error. I couldnt find any relevant articles to fix this issue.

```<code>create proc testfunc( @input varchar(50))
as
begin
DECLARE @mt TABLE
set  @mt = select * from ufnGetTVP(@input)

end
</code>```

It will be helpful , if someone could identify what goes wrong here.

答:
First, you need to include the structure of the table you are declaring:

```<code>DECLARE @mt as TABLE
(
    <columns list>
)
</code>```

Second, you can't use set, you need to use insert:

```<code>INSERT INTO @mt (<columns list>)
SELECT <columns list> FROM dbo.ufnGetTVP(@input)
</code>```

Body:
I have a function  ufnGetTVP  and needs to assign the return value to a table variable in stored procedure.

I have tried the below code but getting error. I couldnt find any relevant articles to fix this issue.

create proc testfunc( @input varchar(50))
as
begin
DECLARE @mt TABLE
set  @mt = select * from ufnGetTVP(@input)

end

It will be helpful , if someone could identify what goes wrong here.

Body:
First, you need to include the structure of the table you are declaring:

DECLARE @mt as TABLE
(
    <columns list>
)

Second, you can't use set, you need to use insert:

INSERT INTO @mt (<columns list>)
SELECT <columns list> FROM dbo.ufnGetTVP(@input)


答:
import datetime
mydate = datetime.datetime.now()
mydate.strftime("%b")

Get month name from number

Surround that with a try except to catch any errors

Title: Write a basic program that takes number and returns its corresponding month abbreviation

Body:
I'm trying to write a basic function that takes a number and returns the abbreviation of each month. It sounds simple enough, but how can I use a "try-except"block to handle any exceptions?

Here's what I have so far.

def month():
    months = "JanFebMarchAprilMayJuneJulyAugSepOctNovDec"
    n = eval(input("Enter month Number: "))
    pos = (n-1)*3
    monthAbbrev = months

    return monthAbbrev

I guess my question is how can I put in a try-expect handle indexes that are out of range?
I'm completely lost here. Thanks for your help


问:
What does the regex (?<n>a)(b)\2(c) match?
What does this regex match?

```<code>(?<n>a)(b)\2(c)
</code>```

It doesn't match abc, abac, abbc, abcc, or ab\x02c and it doesn't throw an exception.

If you take off the (c) it matches aba. My understanding is that unnamed captures get numbered first, and then the named captures. So (c) should get 2, except that I try to back-reference it before it's defined, so I thought maybe it would match a and a would get renumbered when it hits c, but that doesn't appear to be the case either.

答:
\2 in your regex refers to the (c) group, as your experiments have shown. Sadly, your regex never matches anything.

You can find reference in the documentation (though it isn't too clear, and seems to be followed by an unrelated example):

If a group has not captured any substrings, a backreference to that group is undefined and never matches.

Body:
What does this regex match?

(?<n>a)(b)\2(c)

It doesn't match abc, abac, abbc, abcc, or ab\x02c and it doesn't throw an exception.

If you take off the (c) it matches aba. My understanding is that unnamed captures get numbered first, and then the named captures. So (c) should get 2, except that I try to back-reference it before it's defined, so I thought maybe it would match a and a would get renumbered when it hits c, but that doesn't appear to be the case either.


问:
Graph query - where out vs select expand
Is one of those solutions objectively better, or it all depends on the data? Explain option shows me that indeed, the optimizer does the query differently. This is just an example, I'm going to have lot's of such queries in my application, and I want to know the best way to perform such filtering.</p>

```<code>SELECT *
FROM
    (SELECT expand(in('hasPermission'))
     FROM Permission
     WHERE type IN ['USER'])
WHERE
    login >="admin"
ORDER BY
    login ASC
LIMIT 3

SELECT *
FROM User
WHERE login >= "admin"
  AND out("hasPermission").type IN ["USER"]
ORDER BY login ASC
LIMIT 3
</code>```

答:
It depends a lot on the domain. Consider that the query optimizer in v 2.2 just starts scanning (or querying an index on) the target class (Permission in the first query, User in the second one) and then proceeds with traversing.

The first query is more efficient if you have few Permission records that have "USER" in type attribute and if the number of incoming edges per permission is low. Even better if you have an index on type

The second query is more efficient if you have few users with login > "admin" (again, with an index likely) and if the number of outgoing edges per single user is low.

Body:
Is one of those solutions objectively better, or it all depends on the data? Explain option shows me that indeed, the optimizer does the query differently. This is just an example, I'm going to have lot's of such queries in my application, and I want to know the best way to perform such filtering.

SELECT *
FROM
    (SELECT expand(in('hasPermission'))
     FROM Permission
     WHERE type IN ['USER'])
WHERE
    login >="admin"
ORDER BY
    login ASC
LIMIT 3

SELECT *
FROM User
WHERE login >= "admin"
  AND out("hasPermission").type IN ["USER"]
ORDER BY login ASC
LIMIT 3


问:
Add Line Number to existing HTML
I'm trying to add line numbers to existing html with unequal line height - many types of font size and also images.
each line look like -

```<code><div id="1"><right><span>line 1</span></right></div>
<div id="2"><right><span>line 2</span></right></div>
<div id="3"><right><span>line 3</span></right></div>
</code>```

is there simple way to add line numbers that will be vertically align?
thanks

答:
div {
  position: relative;
}

div>span:first-of-type {
  width: 120px;
  display: inline-block;
}

div>span:nth-of-type(2) {
  position: absolute;
  transform: translate(0, -50%);
  top: 50%;
}

td,
div {
  border-bottom: 1px solid;
}

td {
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>Some str length<br/>Some str length</td>
    <td>105</td>
  </tr>
  <tr>
    <td>shorter</td>
    <td>102</td>
  </tr>
</table>

<br/>
<br/>

<div>
  <span>Some str length<br/>Some str length</span>
  <span>105</span>
</div>
<div>
  <span>shorter</span>
  <span>102</span>
</div></code>```

Title: Add Line Number to existing HTML

Body:
I'm trying to add line numbers to existing html with unequal line height - many types of font size and also images.
each line look like -

<right>line 1</right>

<right>line 2</right>

<right>line 3</right>

is there simple way to add line numbers that will be vertically align?
thanks

Body:
div {
  position: relative;
}

div>span:first-of-type {
  width: 120px;
  display: inline-block;
}

div>span:nth-of-type(2) {
  position: absolute;
  transform: translate(0, -50%);
  top: 50%;
}

td,
div {
  border-bottom: 1px solid;
}

td {
  vertical-align: middle;
}

<table>
  <tr>
    <td>Some str length<br/>Some str length</td>
    <td>105</td>
  </tr>
  <tr>
    <td>shorter</td>
    <td>102</td>
  </tr>
</table>

<br/>
<br/>

<div>
  <span>Some str length<br/>Some str length</span>
  <span>105</span>
</div>
<div>
  <span>shorter</span>
  <span>102</span>
</div>


答:
Have you tried inserting into the variable?

Also declare the columns on your table to match the function:

```<code>DECLARE @mt TABLE (Column1 INT, Column2 Int...)

INSERT INTO @mt
SELECT Column1, Column2, ... FROM ufnGetTVP(@input)
</code>```

Title: how to assign a function return value in storedprocedure?

Body:
Have you tried inserting into the variable?

Also declare the columns on your table to match the function:

DECLARE @mt TABLE (Column1 INT, Column2 Int...)

INSERT INTO @mt
SELECT Column1, Column2, ... FROM ufnGetTVP(@input)


问:
Get User SID of remote computer
I'm learning and can't figure out how to get the below code to work on a remote computer.

I want to retrieve the SID of a particular user on a remote computer

The below snippet works to retrieve the SID of the logged in user on the local computer.  I am searching for a way to use this to find a specific SID for a remote system.  Any help is appreciated.

```<code>$currentusersid = Get-WmiObject -Class win32_computersystem |
Select-Object -ExpandProperty Username |
ForEach-Object { ([System.Security.Principal.NTAccount]$_).Translate([System.Security.Principal.SecurityIdentifier]).Value }
</code>```

答:
This should give you:

```<code>[wmi] "win32_userAccount.Domain='domainname',Name='username'"
</code>```

Remotely:

```<code>Get-WmiObject win32_useraccount -ComputerName remotecomputer -Filter "name = 'username' AND domain = 'domainname'" -Credential $cred
</code>```

Oldschool method:

```<code>wmic useraccount where (name='username' and domain='domainname') get name,sid
</code>```

Title: Get User SID of remote computer

Body:
I'm learning and can't figure out how to get the below code to work on a remote computer.

I want to retrieve the SID of a particular user on a remote computer

The below snippet works to retrieve the SID of the logged in user on the local computer.  I am searching for a way to use this to find a specific SID for a remote system.  Any help is appreciated.

$currentusersid = Get-WmiObject -Class win32_computersystem |
Select-Object -ExpandProperty Username |
ForEach-Object { ([System.Security.Principal.NTAccount]$_).Translate([System.Security.Principal.SecurityIdentifier]).Value }

Body:
This should give you:

[wmi] "win32_userAccount.Domain='domainname',Name='username'"

Remotely:

Get-WmiObject win32_useraccount -ComputerName remotecomputer -Filter "name = 'username' AND domain = 'domainname'" -Credential $cred

Oldschool method:

wmic useraccount where (name='username' and domain='domainname') get name,sid


问:
Drawing a right triangle (Python 3)
I'm having a bit of an issue. I'm trying to make this program output a right triangle based on the height and symbol that is specified by the user, but whenever I enter the symbol and height desired the program will output the correct shape, but upside-down. I've been having some difficulties getting a firm grasp of loops and through trial and error, this is the best I could come up with thus far. Could someone help a brother out, please. Thank yous in advance.

```<code>triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')

for i in range (len(triangle_char)):
    for j in range (triangle_height):
        print((triangle_char) * triangle_height )
        triangle_height -= 1
</code>```

This code will return this output when character is '*' and height is 5:

```<code>*****
****
***
**
*
</code>```

The expected output when those values are entered should be:

```<code>*
**
***
****
*****
</code>```

答:
You can also do like this : </p>

```<code>triangle_char = input('Enter a character: ')
triangle_height = int(input('Enter triangle height: '))
print('')

j = 0;

while j <= triangle_height :
    print triangle_char * j
    j += 1
</code>```

Title: Drawing a right triangle (Python 3)

Body:
I'm having a bit of an issue. I'm trying to make this program output a right triangle based on the height and symbol that is specified by the user, but whenever I enter the symbol and height desired the program will output the correct shape, but upside-down. I've been having some difficulties getting a firm grasp of loops and through trial and error, this is the best I could come up with thus far. Could someone help a brother out, please. Thank yous in advance.

triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')

for i in range (len(triangle_char)):
    for j in range (triangle_height):
        print((triangle_char) * triangle_height )
        triangle_height -= 1

This code will return this output when character is '*' and height is 5:

*****
****
***
**
*

The expected output when those values are entered should be:

*
**
***
****
*****

Body:
You can also do like this :

triangle_char = input('Enter a character: ')
triangle_height = int(input('Enter triangle height: '))
print('')

j = 0;

while j <= triangle_height :
    print triangle_char * j
    j += 1


问:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=131074, result=-1, data=Intent { (has extras) }} to activity
hi am trying to upload image using camera or from gallery where my below code is working perfectly on lollipop devices but getting an error in jelly bean. its showing  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=131074, result=-1, data=Intent { (has extras) }} to activity

the below is my code in onActivity result

```<code>@
Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_CANCELED) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_FILE) {
                fileUri = data.getData();
                Log.d("gallery", "" + data.getData());
                performcropg(fileUri);
            } else if (requestCode == REQUEST_CAMERA) {
                fileUri = data.getData();
                performcrop(fileUri);
            } else if (requestCode == PIC_CROP) {
                if (data != null) {
                    Bundle extras = data.getExtras();
                    // get the cropped bitmap
                    Bitmap selectedBitmap = extras.getParcelable("data");
                    saveToInternalStorage(selectedBitmap);
                    Bitmap circleBitmap = Bitmap.createBitmap(selectedBitmap.getWidth(), selectedBitmap.getHeight(), Bitmap.Config.ARGB_8888);

                    BitmapShader shader = new BitmapShader(selectedBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
                    Paint paint = new Paint();
                    paint.setShader(shader);
                    paint.setAntiAlias(true);
                    Canvas c = new Canvas(circleBitmap);
                    c.drawCircle(selectedBitmap.getWidth() / 2, selectedBitmap.getHeight() / 2, selectedBitmap.getWidth() / 2, paint);

                    img_role.setImageBitmap(circleBitmap);

                }
            } else if (requestCode == pic_crop) {
                if (data != null) {

                    Bundle extras = data.getExtras();
                    // get the cropped bitmap
                    Bitmap selectedBitmap = extras.getParcelable("data");
                    saveToInternalStorage(selectedBitmap);
                    Bitmap circleBitmap = Bitmap.createBitmap(selectedBitmap.getWidth(), selectedBitmap.getHeight(), Bitmap.Config.ARGB_8888);

                    BitmapShader shader = new BitmapShader(selectedBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
                    Paint paint = new Paint();
                    paint.setShader(shader);
                    paint.setAntiAlias(true);
                    Canvas c = new Canvas(circleBitmap);
                    c.drawCircle(selectedBitmap.getWidth() / 2, selectedBitmap.getHeight() / 2, selectedBitmap.getWidth() / 2, paint);

                    img_role.setImageBitmap(circleBitmap);
                }
            }

        }
    }
}
</code>```

答:
Comment out camera permission in your manifest</p>

```<code><!--<uses-permission android:name="android.permission.CAMERA" />-->
</code>```

Body:
hi am trying to upload image using camera or from gallery where my below code is working perfectly on lollipop devices but getting an error in jelly bean. its showing  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=131074, result=-1, data=Intent { (has extras) }} to activity

the below is my code in onActivity result

@
Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_CANCELED) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_FILE) {
                fileUri = data.getData();
                Log.d("gallery", "" + data.getData());
                performcropg(fileUri);
            } else if (requestCode == REQUEST_CAMERA) {
                fileUri = data.getData();
                performcrop(fileUri);
            } else if (requestCode == PIC_CROP) {
                if (data != null) {
                    Bundle extras = data.getExtras();
                    // get the cropped bitmap
                    Bitmap selectedBitmap = extras.getParcelable("data");
                    saveToInternalStorage(selectedBitmap);
                    Bitmap circleBitmap = Bitmap.createBitmap(selectedBitmap.getWidth(), selectedBitmap.getHeight(), Bitmap.Config.ARGB_8888);

                    BitmapShader shader = new BitmapShader(selectedBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
                    Paint paint = new Paint();
                    paint.setShader(shader);
                    paint.setAntiAlias(true);
                    Canvas c = new Canvas(circleBitmap);
                    c.drawCircle(selectedBitmap.getWidth() / 2, selectedBitmap.getHeight() / 2, selectedBitmap.getWidth() / 2, paint);

                    img_role.setImageBitmap(circleBitmap);

                }
            } else if (requestCode == pic_crop) {
                if (data != null) {

                    Bundle extras = data.getExtras();
                    // get the cropped bitmap
                    Bitmap selectedBitmap = extras.getParcelable("data");
                    saveToInternalStorage(selectedBitmap);
                    Bitmap circleBitmap = Bitmap.createBitmap(selectedBitmap.getWidth(), selectedBitmap.getHeight(), Bitmap.Config.ARGB_8888);

                    BitmapShader shader = new BitmapShader(selectedBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
                    Paint paint = new Paint();
                    paint.setShader(shader);
                    paint.setAntiAlias(true);
                    Canvas c = new Canvas(circleBitmap);
                    c.drawCircle(selectedBitmap.getWidth() / 2, selectedBitmap.getHeight() / 2, selectedBitmap.getWidth() / 2, paint);

                    img_role.setImageBitmap(circleBitmap);
                }
            }

        }
    }
}

Body:
Comment out camera permission in your manifest

<!--<uses-permission android:name="android.permission.CAMERA" />-->